|
From: <ef...@us...> - 2008-04-21 08:00:17
|
Revision: 5054
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5054&view=rev
Author: efiring
Date: 2008-04-21 01:00:03 -0700 (Mon, 21 Apr 2008)
Log Message:
-----------
Support 0-centered axis in MaxNLocator
Modified Paths:
--------------
trunk/matplotlib/API_CHANGES
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/ticker.py
Modified: trunk/matplotlib/API_CHANGES
===================================================================
--- trunk/matplotlib/API_CHANGES 2008-04-20 10:45:32 UTC (rev 5053)
+++ trunk/matplotlib/API_CHANGES 2008-04-21 08:00:03 UTC (rev 5054)
@@ -1,5 +1,8 @@
+ New kwarg, "symmetric", in MaxNLocator
+ allows one require an axis to be centered on zero.
+
toolkits must now be imported from mpl_toolkits (not matplotlib.toolkits)
-
+
TRANSFORMS REFACTORING
The primary goal of this refactoring was to make it easier to
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-04-20 10:45:32 UTC (rev 5053)
+++ trunk/matplotlib/CHANGELOG 2008-04-21 08:00:03 UTC (rev 5054)
@@ -1,3 +1,5 @@
+2008-04-20 Add support to MaxNLocator for symmetric axis autoscaling. - EF
+
2008-04-20 Fix double-zoom bug. - MM
2008-04-15 Speed up color mapping. - EF
Modified: trunk/matplotlib/lib/matplotlib/ticker.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/ticker.py 2008-04-20 10:45:32 UTC (rev 5053)
+++ trunk/matplotlib/lib/matplotlib/ticker.py 2008-04-21 08:00:03 UTC (rev 5054)
@@ -845,10 +845,14 @@
Select no more than N intervals at nice locations.
"""
- def __init__(self, nbins = 10, steps = None, trim = True, integer=False):
+ def __init__(self, nbins = 10, steps = None,
+ trim = True,
+ integer=False,
+ symmetric=False):
self._nbins = int(nbins)
self._trim = trim
self._integer = integer
+ self._symmetric = symmetric
if steps is None:
self._steps = [1, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10]
else:
@@ -890,6 +894,10 @@
def autoscale(self):
dmin, dmax = self.axis.get_data_interval()
+ if self._symmetric:
+ maxabs = max(abs(dmin), abs(dmax))
+ dmin = -maxabs
+ dmax = maxabs
dmin, dmax = mtransforms.nonsingular(dmin, dmax, expander = 0.05)
return npy.take(self.bin_boundaries(dmin, dmax), [0,-1])
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-04-22 14:59:43
|
Revision: 5057
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5057&view=rev
Author: mdboom
Date: 2008-04-22 07:59:03 -0700 (Tue, 22 Apr 2008)
Log Message:
-----------
Fix inconsistency between svg.embed_chars and svg.embed_char_paths
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/matplotlibrc.template
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-04-22 12:15:13 UTC (rev 5056)
+++ trunk/matplotlib/CHANGELOG 2008-04-22 14:59:03 UTC (rev 5057)
@@ -1,3 +1,5 @@
+2008-04-22 Use "svg.embed_char_paths" consistently everywhere - MGD
+
2008-04-20 Add support to MaxNLocator for symmetric axis autoscaling. - EF
2008-04-20 Fix double-zoom bug. - MM
Modified: trunk/matplotlib/matplotlibrc.template
===================================================================
--- trunk/matplotlib/matplotlibrc.template 2008-04-22 12:15:13 UTC (rev 5056)
+++ trunk/matplotlib/matplotlibrc.template 2008-04-22 14:59:03 UTC (rev 5057)
@@ -292,7 +292,7 @@
# svg backend params
#svg.image_inline : True # write raster image data directly into the svg file
#svg.image_noscale : False # suppress scaling of raster data embedded in SVG
-#svg.embed_chars : True # embed character outlines in the SVG file
+#svg.embed_char_paths : True # embed character outlines in the SVG file
# Set the verbose flags. This controls how much information
# matplotlib gives you at runtime and where it goes. The verbosity
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-04-22 15:10:42
|
Revision: 5061
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5061&view=rev
Author: mdboom
Date: 2008-04-22 08:09:24 -0700 (Tue, 22 Apr 2008)
Log Message:
-----------
Merged revisions 5039-5060 via svnmerge from
https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/v0_91_maint
........
r5046 | dsdale | 2008-04-18 11:20:03 -0400 (Fri, 18 Apr 2008) | 4 lines
dont remove repaint/update from draw(), or updates to the figure after
the initial draw will be ignored. We need a different solution for the
double drawing problem reported for the Wx and Qt* backends
........
r5050 | dsdale | 2008-04-19 10:22:11 -0400 (Sat, 19 Apr 2008) | 3 lines
improve conversion from str to char*, avoid deprecation warnings during
build
........
r5058 | mdboom | 2008-04-22 11:01:00 -0400 (Tue, 22 Apr 2008) | 2 lines
Fix inconsistency between svg.embed_chars and svg.embed_char_paths
........
r5060 | mdboom | 2008-04-22 11:06:01 -0400 (Tue, 22 Apr 2008) | 2 lines
Fix inconsistency between svg.embed_chars and svg.embed_char_paths
........
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
Property Changed:
----------------
trunk/matplotlib/
Property changes on: trunk/matplotlib
___________________________________________________________________
Name: svnmerge-integrated
- /branches/v0_91_maint:1-5038
+ /branches/v0_91_maint:1-5060
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-04-22 15:06:01 UTC (rev 5060)
+++ trunk/matplotlib/CHANGELOG 2008-04-22 15:09:24 UTC (rev 5061)
@@ -3437,3 +3437,4 @@
2003-11-21 - make a dash-dot dict for the GC
2003-12-15 - fix install path bug
+t
\ No newline at end of file
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-04-23 17:45:51
|
Revision: 5066
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5066&view=rev
Author: jdh2358
Date: 2008-04-23 10:44:15 -0700 (Wed, 23 Apr 2008)
Log Message:
-----------
added manuels scatter pie example
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/mlab.py
trunk/matplotlib/unit/mlab_unit.py
Added Paths:
-----------
trunk/matplotlib/examples/scatter_piecharts.py
Added: trunk/matplotlib/examples/scatter_piecharts.py
===================================================================
--- trunk/matplotlib/examples/scatter_piecharts.py (rev 0)
+++ trunk/matplotlib/examples/scatter_piecharts.py 2008-04-23 17:44:15 UTC (rev 5066)
@@ -0,0 +1,40 @@
+"""
+This example makes custom 'pie charts' as the markers for a scatter plotqu
+
+Thanks to Manuel Metz for the example
+"""
+import math
+import numpy as np
+import matplotlib.pyplot as plt
+
+# first define the ratios
+r1 = 0.2 # 20%
+r2 = r1 + 0.4 # 40%
+
+# define some sizes of the scatter marker
+sizes = [60,80,120]
+
+# calculate the points of the first pie marker
+#
+# these are just the origin (0,0) +
+# some points on a circle cos,sin
+x = [0] + np.cos(np.linspace(0, 2*math.pi*r1, 10)).tolist()
+y = [0] + np.sin(np.linspace(0, 2*math.pi*r1, 10)).tolist()
+xy1 = zip(x,y)
+
+# ...
+x = [0] + np.cos(np.linspace(2*math.pi*r1, 2*math.pi*r2, 10)).tolist()
+y = [0] + np.sin(np.linspace(2*math.pi*r1, 2*math.pi*r2, 10)).tolist()
+xy2 = zip(x,y)
+
+x = [0] + np.cos(np.linspace(2*math.pi*r2, 2*math.pi, 10)).tolist()
+y = [0] + np.sin(np.linspace(2*math.pi*r2, 2*math.pi, 10)).tolist()
+xy3 = zip(x,y)
+
+
+fig = plt.figure()
+ax = fig.add_subplot(111)
+ax.scatter( np.arange(3), np.arange(3), marker=(xy1,0), s=sizes, facecolor='blue' )
+ax.scatter( np.arange(3), np.arange(3), marker=(xy2,0), s=sizes, facecolor='green' )
+ax.scatter( np.arange(3), np.arange(3), marker=(xy3,0), s=sizes, facecolor='red' )
+plt.show()
Modified: trunk/matplotlib/lib/matplotlib/mlab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mlab.py 2008-04-23 16:54:21 UTC (rev 5065)
+++ trunk/matplotlib/lib/matplotlib/mlab.py 2008-04-23 17:44:15 UTC (rev 5066)
@@ -87,6 +87,7 @@
import numpy as npy
+
from matplotlib import nxutils
from matplotlib import cbook
@@ -2143,10 +2144,10 @@
def csv2rec(fname, comments='#', skiprows=0, checkrows=0, delimiter=',',
- converterd=None, names=None, missing=None):
+ converterd=None, names=None, missing='', missingd=None):
"""
Load data from comma/space/tab delimited file in fname into a
- numpy record array and return the record array.
+ numpy (m)record array and return the record array.
If names is None, a header row is required to automatically assign
the recarray names. The headers will be lower cased, spaces will
@@ -2172,13 +2173,24 @@
names, if not None, is a list of header names. In this case, no
header will be read from the file
+ missingd - is a dictionary mapping munged column names to field values
+ which signify that the field does not contain actual data and should
+ be masked, e.g. '0000-00-00' or 'unused'
+
+ missing - a string whose value signals a missing field regardless of
+ the column it appears in, e.g. 'unused'
+
if no rows are found, None is returned -- see examples/loadrec.py
"""
if converterd is None:
converterd = dict()
+ if missingd is None:
+ missingd = {}
+
import dateutil.parser
+ import datetime
parsedate = dateutil.parser.parse
@@ -2226,14 +2238,28 @@
process_skiprows(reader)
- dateparser = dateutil.parser.parse
+ def ismissing(name, val):
+ "Should the value val in column name be masked?"
- def myfloat(x):
- if x==missing:
- return npy.nan
+ if val == missing or val == missingd.get(name) or val == '':
+ return True
else:
- return float(x)
+ return False
+ def with_default_value(func, default):
+ def newfunc(name, val):
+ if ismissing(name, val):
+ return default
+ else:
+ return func(val)
+ return newfunc
+
+ dateparser = dateutil.parser.parse
+ mydateparser = with_default_value(dateparser, datetime.date(1,1,1))
+ myfloat = with_default_value(float, npy.nan)
+ myint = with_default_value(int, -1)
+ mystr = with_default_value(str, '')
+
def mydate(x):
# try and return a date object
d = dateparser(x)
@@ -2241,16 +2267,16 @@
if d.hour>0 or d.minute>0 or d.second>0:
raise ValueError('not a date')
return d.date()
+ mydate = with_default_value(mydate, datetime.date(1,1,1))
-
- def get_func(item, func):
+ def get_func(name, item, func):
# promote functions in this order
- funcmap = {int:myfloat, myfloat:mydate, mydate:dateparser, dateparser:str}
- try: func(item)
+ funcmap = {myint:myfloat, myfloat:mydate, mydate:mydateparser, mydateparser:mystr}
+ try: func(name, item)
except:
- if func==str:
+ if func==mystr:
raise ValueError('Could not find a working conversion function')
- else: return get_func(item, funcmap[func]) # recurse
+ else: return get_func(name, item, funcmap[func]) # recurse
else: return func
@@ -2266,7 +2292,7 @@
converters = None
for i, row in enumerate(reader):
if i==0:
- converters = [int]*len(row)
+ converters = [myint]*len(row)
if checkrows and i>checkrows:
break
#print i, len(names), len(row)
@@ -2276,10 +2302,10 @@
if func is None:
func = converterd.get(name)
if func is None:
- if not item.strip(): continue
+ #if not item.strip(): continue
func = converters[j]
if len(item.strip()):
- func = get_func(item, func)
+ func = get_func(name, item, func)
converters[j] = func
return converters
@@ -2307,7 +2333,7 @@
item = itemd.get(item, item)
cnt = seen.get(item, 0)
if cnt>0:
- names.append(item + '%d'%cnt)
+ names.append(item + '_%d'%cnt)
else:
names.append(item)
seen[item] = cnt+1
@@ -2327,15 +2353,24 @@
# iterate over the remaining rows and convert the data to date
# objects, ints, or floats as approriate
rows = []
+ rowmasks = []
for i, row in enumerate(reader):
if not len(row): continue
if row[0].startswith(comments): continue
- rows.append([func(val) for func, val in zip(converters, row)])
+ rows.append([func(name, val) for func, name, val in zip(converters, names, row)])
+ rowmasks.append([ismissing(name, val) for name, val in zip(names, row)])
fh.close()
if not len(rows):
return None
- r = npy.rec.fromrecords(rows, names=names)
+ if npy.any(rowmasks):
+ try: from numpy.ma import mrecords
+ except ImportError:
+ raise RuntimeError('numpy 1.05 or later is required for masked array support')
+ else:
+ r = mrecords.fromrecords(rows, names=names, mask=rowmasks)
+ else:
+ r = npy.rec.fromrecords(rows, names=names)
return r
@@ -2529,26 +2564,59 @@
-def rec2csv(r, fname, delimiter=',', formatd=None):
+def rec2csv(r, fname, delimiter=',', formatd=None, missing='',
+ missingd=None):
"""
- Save the data from numpy record array r into a comma/space/tab
+ Save the data from numpy (m)recarray r into a comma/space/tab
delimited file. The record array dtype names will be used for
column headers.
fname - can be a filename or a file handle. Support for gzipped
files is automatic, if the filename ends in .gz
+
+ See csv2rec and rec2csv for information about missing and
+ missingd, which can be used to fill in masked values into your CSV
+ file.
"""
+
+ if missingd is None:
+ missingd = dict()
+
+ def with_mask(func):
+ def newfunc(val, mask, mval):
+ if mask:
+ return mval
+ else:
+ return func(val)
+ return newfunc
+
formatd = get_formatd(r, formatd)
funcs = []
for i, name in enumerate(r.dtype.names):
- funcs.append(csvformat_factory(formatd[name]).tostr)
+ funcs.append(with_mask(csvformat_factory(formatd[name]).tostr))
fh, opened = cbook.to_filehandle(fname, 'w', return_opened=True)
writer = csv.writer(fh, delimiter=delimiter)
header = r.dtype.names
writer.writerow(header)
+
+ # Our list of specials for missing values
+ mvals = []
+ for name in header:
+ mvals.append(missingd.get(name, missing))
+
+ ismasked = False
+ if len(r):
+ row = r[0]
+ ismasked = hasattr(row, '_fieldmask')
+
for row in r:
- writer.writerow([func(val) for func, val in zip(funcs, row)])
+ if ismasked:
+ row, rowmask = row.item(), row._fieldmask.item()
+ else:
+ rowmask = [False] * len(row)
+ writer.writerow([func(val, mask, mval) for func, val, mask, mval
+ in zip(funcs, row, rowmask, mvals)])
if opened:
fh.close()
Modified: trunk/matplotlib/unit/mlab_unit.py
===================================================================
--- trunk/matplotlib/unit/mlab_unit.py 2008-04-23 16:54:21 UTC (rev 5065)
+++ trunk/matplotlib/unit/mlab_unit.py 2008-04-23 17:44:15 UTC (rev 5066)
@@ -55,5 +55,27 @@
print 'repr(dt.type)',repr(dt.type)
self.failUnless( numpy.all(ra[name] == ra2[name]) ) # should not fail with numpy 1.0.5
+ def test_csv2rec_masks(self):
+ # Make sure masked entries survive roundtrip
+
+ csv = """date,age,weight,name
+2007-01-01,12,32.2,"jdh1"
+0000-00-00,0,23,"jdh2"
+2007-01-03,,32.5,"jdh3"
+2007-01-04,12,NaN,"jdh4"
+2007-01-05,-1,NULL,"""
+ missingd = dict(date='0000-00-00', age='-1', weight='NULL')
+ fh = StringIO.StringIO(csv)
+ r1 = mlab.csv2rec(fh, missingd=missingd)
+ fh = StringIO.StringIO()
+ mlab.rec2csv(r1, fh, missingd=missingd)
+ fh.seek(0)
+ r2 = mlab.csv2rec(fh, missingd=missingd)
+
+ self.failUnless( numpy.all( r2['date'].mask == [0,1,0,0,0] ))
+ self.failUnless( numpy.all( r2['age'].mask == [0,0,1,0,1] ))
+ self.failUnless( numpy.all( r2['weight'].mask == [0,0,0,0,1] ))
+ self.failUnless( numpy.all( r2['name'].mask == [0,0,0,0,1] ))
+
if __name__=='__main__':
unittest.main()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-04-24 12:35:10
|
Revision: 5069
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5069&view=rev
Author: mdboom
Date: 2008-04-24 05:34:47 -0700 (Thu, 24 Apr 2008)
Log Message:
-----------
Merged revisions 5061-5068 via svnmerge from
https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/v0_91_maint
........
r5068 | mdboom | 2008-04-24 08:31:53 -0400 (Thu, 24 Apr 2008) | 2 lines
Fix sub/superscript placement when the size of font has been changed.
........
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/mathtext.py
Property Changed:
----------------
trunk/matplotlib/
Property changes on: trunk/matplotlib
___________________________________________________________________
Name: svnmerge-integrated
- /branches/v0_91_maint:1-5060
+ /branches/v0_91_maint:1-5068
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-04-24 12:31:53 UTC (rev 5068)
+++ trunk/matplotlib/CHANGELOG 2008-04-24 12:34:47 UTC (rev 5069)
@@ -1,3 +1,6 @@
+2008-04-24 Fix sub/superscripts when the size of the font has been
+ changed - MGD
+
2008-04-22 Use "svg.embed_char_paths" consistently everywhere - MGD
2008-04-20 Add support to MaxNLocator for symmetric axis autoscaling. - EF
Modified: trunk/matplotlib/lib/matplotlib/mathtext.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mathtext.py 2008-04-24 12:31:53 UTC (rev 5068)
+++ trunk/matplotlib/lib/matplotlib/mathtext.py 2008-04-24 12:34:47 UTC (rev 5069)
@@ -651,7 +651,7 @@
# Some fonts don't store the xHeight, so we do a poor man's xHeight
metrics = self.get_metrics(font, 'it', 'x', fontsize, dpi)
return metrics.iceberg
- xHeight = pclt['xHeight'] / 64.0
+ xHeight = (pclt['xHeight'] / 64.0) * (fontsize / 12.0)
return xHeight
def get_underline_thickness(self, font, fontsize, dpi):
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-04-24 12:54:30
|
Revision: 5070
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5070&view=rev
Author: mdboom
Date: 2008-04-24 05:54:25 -0700 (Thu, 24 Apr 2008)
Log Message:
-----------
Fix compilation issues on VS2003. (Thanks Martin Spacek)
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/src/_backend_agg.cpp
trunk/matplotlib/src/agg_py_path_iterator.h
trunk/matplotlib/src/mplutils.h
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-04-24 12:34:47 UTC (rev 5069)
+++ trunk/matplotlib/CHANGELOG 2008-04-24 12:54:25 UTC (rev 5070)
@@ -1,3 +1,6 @@
+2008-04-24 Fix compilation issues on VS2003 (Thanks Martin Spacek for
+ all the help) - MGD
+
2008-04-24 Fix sub/superscripts when the size of the font has been
changed - MGD
Modified: trunk/matplotlib/src/_backend_agg.cpp
===================================================================
--- trunk/matplotlib/src/_backend_agg.cpp 2008-04-24 12:34:47 UTC (rev 5069)
+++ trunk/matplotlib/src/_backend_agg.cpp 2008-04-24 12:54:25 UTC (rev 5070)
@@ -270,8 +270,8 @@
double l, b, r, t;
if (py_convert_bbox(cliprect.ptr(), l, b, r, t)) {
- rasterizer->clip_box(int(round(l)) + 1, height - int(round(b)),
- int(round(r)), height - int(round(t)));
+ rasterizer->clip_box(int(mpl_round(l)) + 1, height - int(mpl_round(b)),
+ int(mpl_round(r)), height - int(mpl_round(t)));
}
_VERBOSE("RendererAgg::set_clipbox done");
@@ -807,7 +807,7 @@
if (gc.linewidth != 0.0) {
double linewidth = gc.linewidth;
if (!gc.isaa) {
- linewidth = (linewidth < 0.5) ? 0.5 : round(linewidth);
+ linewidth = (linewidth < 0.5) ? 0.5 : mpl_round(linewidth);
}
if (gc.dashes.size() == 0) {
stroke_t stroke(path);
@@ -1576,7 +1576,7 @@
int newwidth = 0;
int newheight = 0;
Py::String data;
- if (xmin < xmax and ymin < ymax) {
+ if (xmin < xmax && ymin < ymax) {
// Expand the bounds by 1 pixel on all sides
xmin = std::max(0, xmin - 1);
ymin = std::max(0, ymin - 1);
Modified: trunk/matplotlib/src/agg_py_path_iterator.h
===================================================================
--- trunk/matplotlib/src/agg_py_path_iterator.h 2008-04-24 12:34:47 UTC (rev 5069)
+++ trunk/matplotlib/src/agg_py_path_iterator.h 2008-04-24 12:54:25 UTC (rev 5070)
@@ -6,12 +6,9 @@
#include "numpy/arrayobject.h"
#include "agg_path_storage.h"
#include "MPL_isnan.h"
+#include "mplutils.h"
#include <queue>
-static inline double my_round(double v) {
- return (double)(int)(v + ((v >= 0.0) ? 0.5 : -0.5));
-}
-
class PathIterator
{
PyArrayObject* m_vertices;
@@ -161,8 +158,8 @@
cmd = m_source->vertex(x, y);
if (m_quantize && agg::is_vertex(cmd))
{
- *x = my_round(*x) + 0.5;
- *y = my_round(*y) + 0.5;
+ *x = mpl_round(*x) + 0.5;
+ *y = mpl_round(*y) + 0.5;
}
return cmd;
}
@@ -218,8 +215,8 @@
// Do any quantization if requested
if (m_quantize && agg::is_vertex(cmd))
{
- *x = my_round(*x) + 0.5;
- *y = my_round(*y) + 0.5;
+ *x = mpl_round(*x) + 0.5;
+ *y = mpl_round(*y) + 0.5;
}
//if we are starting a new path segment, move to the first point
Modified: trunk/matplotlib/src/mplutils.h
===================================================================
--- trunk/matplotlib/src/mplutils.h 2008-04-24 12:34:47 UTC (rev 5069)
+++ trunk/matplotlib/src/mplutils.h 2008-04-24 12:54:25 UTC (rev 5070)
@@ -1,4 +1,4 @@
-/* mplutils.h --
+/* mplutils.h --
*
* $Header$
* $Log$
@@ -26,6 +26,10 @@
#undef MAX
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
+inline double mpl_round(double v) {
+ return (double)(int)(v + ((v >= 0.0) ? 0.5 : -0.5));
+}
+
class Printf
{
private :
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-04-24 13:23:48
|
Revision: 5071
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5071&view=rev
Author: mdboom
Date: 2008-04-24 06:23:05 -0700 (Thu, 24 Apr 2008)
Log Message:
-----------
Remove a bunch of compiler warnings.
Modified Paths:
--------------
trunk/matplotlib/CXX/WrapPython.h
trunk/matplotlib/agg24/src/agg_curves.cpp
trunk/matplotlib/src/_backend_agg.cpp
trunk/matplotlib/src/_gtkagg.cpp
trunk/matplotlib/src/_image.cpp
trunk/matplotlib/src/_path.cpp
trunk/matplotlib/src/_ttconv.cpp
trunk/matplotlib/src/ft2font.cpp
trunk/matplotlib/src/ft2font.h
trunk/matplotlib/ttconv/pprdrv_tt.cpp
Modified: trunk/matplotlib/CXX/WrapPython.h
===================================================================
--- trunk/matplotlib/CXX/WrapPython.h 2008-04-24 12:54:25 UTC (rev 5070)
+++ trunk/matplotlib/CXX/WrapPython.h 2008-04-24 13:23:05 UTC (rev 5071)
@@ -38,12 +38,13 @@
#ifndef __PyCXX_wrap_python_hxx__
#define __PyCXX_wrap_python_hxx__
+// pull in python definitions
+#include <Python.h>
+
// On some platforms we have to include time.h to get select defined
#if !defined(__WIN32__) && !defined(WIN32) && !defined(_WIN32) && !defined(_WIN64)
#include <sys/time.h>
#endif
-// pull in python definitions
-#include <Python.h>
#endif
Modified: trunk/matplotlib/agg24/src/agg_curves.cpp
===================================================================
--- trunk/matplotlib/agg24/src/agg_curves.cpp 2008-04-24 12:54:25 UTC (rev 5070)
+++ trunk/matplotlib/agg24/src/agg_curves.cpp 2008-04-24 13:23:05 UTC (rev 5071)
@@ -2,8 +2,8 @@
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
-// Permission to copy, use, modify, sell and distribute this software
-// is granted provided this copyright notice appears in all copies.
+// Permission to copy, use, modify, sell and distribute this software
+// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
@@ -29,20 +29,20 @@
//------------------------------------------------------------------------
- void curve3_inc::approximation_scale(double s)
- {
+ void curve3_inc::approximation_scale(double s)
+ {
m_scale = s;
}
//------------------------------------------------------------------------
- double curve3_inc::approximation_scale() const
- {
+ double curve3_inc::approximation_scale() const
+ {
return m_scale;
}
//------------------------------------------------------------------------
- void curve3_inc::init(double x1, double y1,
- double x2, double y2,
+ void curve3_inc::init(double x1, double y1,
+ double x2, double y2,
double x3, double y3)
{
m_start_x = x1;
@@ -55,13 +55,13 @@
double dx2 = x3 - x2;
double dy2 = y3 - y2;
- double len = sqrt(dx1 * dx1 + dy1 * dy1) + sqrt(dx2 * dx2 + dy2 * dy2);
+ double len = sqrt(dx1 * dx1 + dy1 * dy1) + sqrt(dx2 * dx2 + dy2 * dy2);
m_num_steps = uround(len * 0.25 * m_scale);
if(m_num_steps < 4)
{
- m_num_steps = 4;
+ m_num_steps = 4;
}
double subdivide_step = 1.0 / m_num_steps;
@@ -72,7 +72,7 @@
m_saved_fx = m_fx = x1;
m_saved_fy = m_fy = y1;
-
+
m_saved_dfx = m_dfx = tmpx + (x2 - x1) * (2.0 * subdivide_step);
m_saved_dfy = m_dfy = tmpy + (y2 - y1) * (2.0 * subdivide_step);
@@ -115,10 +115,10 @@
--m_step;
return path_cmd_line_to;
}
- m_fx += m_dfx;
+ m_fx += m_dfx;
m_fy += m_dfy;
- m_dfx += m_ddfx;
- m_dfy += m_ddfy;
+ m_dfx += m_ddfx;
+ m_dfy += m_ddfy;
*x = m_fx;
*y = m_fy;
--m_step;
@@ -126,8 +126,8 @@
}
//------------------------------------------------------------------------
- void curve3_div::init(double x1, double y1,
- double x2, double y2,
+ void curve3_div::init(double x1, double y1,
+ double x2, double y2,
double x3, double y3)
{
m_points.remove_all();
@@ -138,19 +138,19 @@
}
//------------------------------------------------------------------------
- void curve3_div::recursive_bezier(double x1, double y1,
- double x2, double y2,
+ void curve3_div::recursive_bezier(double x1, double y1,
+ double x2, double y2,
double x3, double y3,
unsigned level)
{
- if(level > curve_recursion_limit)
+ if(level > curve_recursion_limit)
{
return;
}
// Calculate all the mid-points of the line segments
//----------------------
- double x12 = (x1 + x2) / 2;
+ double x12 = (x1 + x2) / 2;
double y12 = (y1 + y2) / 2;
double x23 = (x2 + x3) / 2;
double y23 = (y2 + y3) / 2;
@@ -163,7 +163,7 @@
double da;
if(d > curve_collinearity_epsilon)
- {
+ {
// Regular case
//-----------------
if(d * d <= m_distance_tolerance_square * (dx*dx + dy*dy))
@@ -187,7 +187,7 @@
// Finally we can stop the recursion
//----------------------
m_points.add(point_d(x123, y123));
- return;
+ return;
}
}
}
@@ -222,13 +222,13 @@
// Continue subdivision
//----------------------
- recursive_bezier(x1, y1, x12, y12, x123, y123, level + 1);
- recursive_bezier(x123, y123, x23, y23, x3, y3, level + 1);
+ recursive_bezier(x1, y1, x12, y12, x123, y123, level + 1);
+ recursive_bezier(x123, y123, x23, y23, x3, y3, level + 1);
}
//------------------------------------------------------------------------
- void curve3_div::bezier(double x1, double y1,
- double x2, double y2,
+ void curve3_div::bezier(double x1, double y1,
+ double x2, double y2,
double x3, double y3)
{
m_points.add(point_d(x1, y1));
@@ -241,23 +241,25 @@
//------------------------------------------------------------------------
- void curve4_inc::approximation_scale(double s)
- {
+ void curve4_inc::approximation_scale(double s)
+ {
m_scale = s;
}
//------------------------------------------------------------------------
- double curve4_inc::approximation_scale() const
- {
+ double curve4_inc::approximation_scale() const
+ {
return m_scale;
}
//------------------------------------------------------------------------
+#if defined(_MSC_VER) && _MSC_VER <= 1200
static double MSC60_fix_ICE(double v) { return v; }
+#endif
//------------------------------------------------------------------------
- void curve4_inc::init(double x1, double y1,
- double x2, double y2,
+ void curve4_inc::init(double x1, double y1,
+ double x2, double y2,
double x3, double y3,
double x4, double y4)
{
@@ -273,8 +275,8 @@
double dx3 = x4 - x3;
double dy3 = y4 - y3;
- double len = (sqrt(dx1 * dx1 + dy1 * dy1) +
- sqrt(dx2 * dx2 + dy2 * dy2) +
+ double len = (sqrt(dx1 * dx1 + dy1 * dy1) +
+ sqrt(dx2 * dx2 + dy2 * dy2) +
sqrt(dx3 * dx3 + dy3 * dy3)) * 0.25 * m_scale;
#if defined(_MSC_VER) && _MSC_VER <= 1200
@@ -285,7 +287,7 @@
if(m_num_steps < 4)
{
- m_num_steps = 4;
+ m_num_steps = 4;
}
double subdivide_step = 1.0 / m_num_steps;
@@ -296,7 +298,7 @@
double pre2 = 3.0 * subdivide_step2;
double pre4 = 6.0 * subdivide_step2;
double pre5 = 6.0 * subdivide_step3;
-
+
double tmp1x = x1 - x2 * 2.0 + x3;
double tmp1y = y1 - y2 * 2.0 + y3;
@@ -357,10 +359,10 @@
m_fx += m_dfx;
m_fy += m_dfy;
- m_dfx += m_ddfx;
- m_dfy += m_ddfy;
- m_ddfx += m_dddfx;
- m_ddfy += m_dddfy;
+ m_dfx += m_ddfx;
+ m_dfy += m_ddfy;
+ m_ddfx += m_dddfx;
+ m_ddfy += m_dddfy;
*x = m_fx;
*y = m_fy;
@@ -372,8 +374,8 @@
//------------------------------------------------------------------------
- void curve4_div::init(double x1, double y1,
- double x2, double y2,
+ void curve4_div::init(double x1, double y1,
+ double x2, double y2,
double x3, double y3,
double x4, double y4)
{
@@ -385,13 +387,13 @@
}
//------------------------------------------------------------------------
- void curve4_div::recursive_bezier(double x1, double y1,
- double x2, double y2,
- double x3, double y3,
+ void curve4_div::recursive_bezier(double x1, double y1,
+ double x2, double y2,
+ double x3, double y3,
double x4, double y4,
unsigned level)
{
- if(level > curve_recursion_limit)
+ if(level > curve_recursion_limit)
{
return;
}
@@ -542,7 +544,7 @@
}
break;
- case 3:
+ case 3:
// Regular case
//-----------------
if((d2 + d3)*(d2 + d3) <= m_distance_tolerance_square * (dx*dx + dy*dy))
@@ -592,14 +594,14 @@
// Continue subdivision
//----------------------
- recursive_bezier(x1, y1, x12, y12, x123, y123, x1234, y1234, level + 1);
- recursive_bezier(x1234, y1234, x234, y234, x34, y34, x4, y4, level + 1);
+ recursive_bezier(x1, y1, x12, y12, x123, y123, x1234, y1234, level + 1);
+ recursive_bezier(x1234, y1234, x234, y234, x34, y34, x4, y4, level + 1);
}
//------------------------------------------------------------------------
- void curve4_div::bezier(double x1, double y1,
- double x2, double y2,
- double x3, double y3,
+ void curve4_div::bezier(double x1, double y1,
+ double x2, double y2,
+ double x3, double y3,
double x4, double y4)
{
m_points.add(point_d(x1, y1));
Modified: trunk/matplotlib/src/_backend_agg.cpp
===================================================================
--- trunk/matplotlib/src/_backend_agg.cpp 2008-04-24 12:54:25 UTC (rev 5070)
+++ trunk/matplotlib/src/_backend_agg.cpp 2008-04-24 13:23:05 UTC (rev 5071)
@@ -1,12 +1,22 @@
/* A rewrite of _backend_agg using PyCXX to handle ref counting, etc..
*/
+#include <png.h>
+// To remove a gcc warning
+#ifdef _POSIX_C_SOURCE
+#undef _POSIX_C_SOURCE
+#endif
+
+#include "ft2font.h"
+#include "_image.h"
+#include "_backend_agg.h"
+#include "mplutils.h"
+
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdio>
#include <stdexcept>
-#include <png.h>
#include <time.h>
#include <algorithm>
@@ -23,11 +33,6 @@
#include "agg_conv_shorten_path.h"
#include "util/agg_color_conv_rgb8.h"
-#include "ft2font.h"
-#include "_image.h"
-#include "_backend_agg.h"
-#include "mplutils.h"
-
#include "swig_runtime.h"
#include "MPL_isnan.h"
@@ -295,8 +300,8 @@
SnapData
SafeSnap::snap (const float& x, const float& y) {
- xsnap = (int)x + 0.5;
- ysnap = (int)y + 0.5;
+ xsnap = (int)(x + 0.5f);
+ ysnap = (int)(y + 0.5f);
if ( first || ( (xsnap!=lastxsnap) || (ysnap!=lastysnap) ) ) {
lastxsnap = xsnap;
@@ -737,8 +742,8 @@
args.verify_length(4, 6);
- float x = Py::Float(args[0]);
- float y = Py::Float(args[1]);
+ double x = Py::Float(args[0]);
+ double y = Py::Float(args[1]);
Image *image = static_cast<Image*>(args[2].ptr());
Py::Object box_obj = args[3];
Py::Object clippath;
Modified: trunk/matplotlib/src/_gtkagg.cpp
===================================================================
--- trunk/matplotlib/src/_gtkagg.cpp 2008-04-24 12:54:25 UTC (rev 5070)
+++ trunk/matplotlib/src/_gtkagg.cpp 2008-04-24 13:23:05 UTC (rev 5071)
@@ -1,3 +1,6 @@
+#include <pygobject.h>
+#include <pygtk/pygtk.h>
+
#include <cstring>
#include <cerrno>
#include <cstdio>
@@ -6,10 +9,6 @@
#include <utility>
#include <fstream>
-
-#include <pygobject.h>
-#include <pygtk/pygtk.h>
-
#include "agg_basics.h"
#include "_backend_agg.h"
#define PY_ARRAY_TYPES_PREFIX NumPy
Modified: trunk/matplotlib/src/_image.cpp
===================================================================
--- trunk/matplotlib/src/_image.cpp 2008-04-24 12:54:25 UTC (rev 5070)
+++ trunk/matplotlib/src/_image.cpp 2008-04-24 13:23:05 UTC (rev 5071)
@@ -1,3 +1,6 @@
+#include "Python.h" //after png.h due to setjmp bug
+#include <string>
+
#include <iostream>
#include <fstream>
#include <cmath>
@@ -4,9 +7,6 @@
#include <cstdio>
#include <png.h>
-#include "Python.h" //after png.h due to setjmp bug
-#include <string>
-
#define PY_ARRAY_TYPES_PREFIX NumPy
#include "numpy/arrayobject.h"
@@ -936,10 +936,10 @@
png_byte* ptr = (rgba) ? &(row[x*4]) : &(row[x*3]);
size_t offset = y*A->strides[0] + x*A->strides[1];
//if ((y<10)&&(x==10)) std::cout << "r = " << ptr[0] << " " << ptr[0]/255.0 << std::endl;
- *(float*)(A->data + offset + 0*A->strides[2]) = ptr[0]/255.0;
- *(float*)(A->data + offset + 1*A->strides[2]) = ptr[1]/255.0;
- *(float*)(A->data + offset + 2*A->strides[2]) = ptr[2]/255.0;
- *(float*)(A->data + offset + 3*A->strides[2]) = rgba ? ptr[3]/255.0 : 1.0;
+ *(float*)(A->data + offset + 0*A->strides[2]) = (float)(ptr[0]/255.0f);
+ *(float*)(A->data + offset + 1*A->strides[2]) = (float)(ptr[1]/255.0f);
+ *(float*)(A->data + offset + 2*A->strides[2]) = (float)(ptr[2]/255.0f);
+ *(float*)(A->data + offset + 3*A->strides[2]) = rgba ? (float)(ptr[3]/255.0f) : 1.0f;
}
}
@@ -1434,7 +1434,7 @@
while(xs2 != xl && xo > xm) {
xs1 = xs2;
xs2 = xs1+1;
- xm = 0.5*(*xs1 + *xs2);
+ xm = 0.5f*(*xs1 + *xs2);
j++;
}
*colstart = j - j_last;
@@ -1447,7 +1447,7 @@
while(ys2 != yl && yo > ym) {
ys1 = ys2;
ys2 = ys1+1;
- ym = 0.5*(*ys1 + *ys2);
+ ym = 0.5f*(*ys1 + *ys2);
j++;
}
*rowstart = j - j_last;
Modified: trunk/matplotlib/src/_path.cpp
===================================================================
--- trunk/matplotlib/src/_path.cpp 2008-04-24 12:54:25 UTC (rev 5070)
+++ trunk/matplotlib/src/_path.cpp 2008-04-24 13:23:05 UTC (rev 5071)
@@ -1,9 +1,9 @@
+#include "agg_py_path_iterator.h"
+#include "agg_py_transforms.h"
+
#include <limits>
#include <math.h>
-#include "agg_py_path_iterator.h"
-#include "agg_py_transforms.h"
-
#include "CXX/Extensions.hxx"
#include "agg_conv_curve.h"
Modified: trunk/matplotlib/src/_ttconv.cpp
===================================================================
--- trunk/matplotlib/src/_ttconv.cpp 2008-04-24 12:54:25 UTC (rev 5070)
+++ trunk/matplotlib/src/_ttconv.cpp 2008-04-24 13:23:05 UTC (rev 5071)
@@ -83,11 +83,11 @@
int fonttype;
std::vector<int> glyph_ids;
- static const char *kwlist[] = {
+ static const char *kwlist[] = {
"filename", "output", "fonttype", "glyph_ids", NULL };
if (! PyArg_ParseTupleAndKeywords
- (args, kwds,
- "sO&i|O&:convert_ttf_to_ps",
+ (args, kwds,
+ "sO&i|O&:convert_ttf_to_ps",
(char**)kwlist,
&filename,
fileobject_to_PythonFileWriter,
@@ -96,9 +96,9 @@
pyiterable_to_vector_int,
&glyph_ids))
return NULL;
-
+
if (fonttype != 3 && fonttype != 42) {
- PyErr_SetString(PyExc_ValueError,
+ PyErr_SetString(PyExc_ValueError,
"fonttype must be either 3 (raw Postscript) or 42 "
"(embedded Truetype)");
return NULL;
@@ -109,7 +109,7 @@
} catch (TTException& e) {
PyErr_SetString(PyExc_RuntimeError, e.getMessage());
return NULL;
- } catch (PythonExceptionOccurred& e) {
+ } catch (PythonExceptionOccurred& ) {
return NULL;
} catch (...) {
PyErr_SetString(PyExc_RuntimeError, "Unknown C++ exception");
@@ -144,8 +144,8 @@
static const char *kwlist[] = { "filename", "glyph_ids", NULL };
if (! PyArg_ParseTupleAndKeywords
- (args, kwds,
- "s|O&:convert_ttf_to_ps",
+ (args, kwds,
+ "s|O&:convert_ttf_to_ps",
(char **)kwlist,
&filename,
pyiterable_to_vector_int,
@@ -163,7 +163,7 @@
} catch (TTException& e) {
PyErr_SetString(PyExc_RuntimeError, e.getMessage());
return NULL;
- } catch (PythonExceptionOccurred& e) {
+ } catch (PythonExceptionOccurred& ) {
return NULL;
} catch (...) {
PyErr_SetString(PyExc_RuntimeError, "Unknown C++ exception");
@@ -174,7 +174,7 @@
}
static PyMethodDef ttconv_methods[] = {
- {"convert_ttf_to_ps", (PyCFunction)convert_ttf_to_ps, METH_KEYWORDS,
+ {"convert_ttf_to_ps", (PyCFunction)convert_ttf_to_ps, METH_KEYWORDS,
"convert_ttf_to_ps(filename, output, fonttype, glyph_ids)\n"
"\n"
"Converts the Truetype font into a Type 3 or Type 42 Postscript font, "
@@ -191,7 +191,7 @@
"then all glyphs will be included. If any of the glyphs specified are "
"composite glyphs, then the component glyphs will also be included."
},
- {"get_pdf_charprocs", (PyCFunction)py_get_pdf_charprocs, METH_KEYWORDS,
+ {"get_pdf_charprocs", (PyCFunction)py_get_pdf_charprocs, METH_KEYWORDS,
"get_pdf_charprocs(filename, glyph_ids)\n"
"\n"
"Given a Truetype font file, returns a dictionary containing the PDF Type 3\n"
@@ -211,7 +211,7 @@
#define PyMODINIT_FUNC void
#endif
PyMODINIT_FUNC
-initttconv(void)
+initttconv(void)
{
PyObject* m;
Modified: trunk/matplotlib/src/ft2font.cpp
===================================================================
--- trunk/matplotlib/src/ft2font.cpp 2008-04-24 12:54:25 UTC (rev 5070)
+++ trunk/matplotlib/src/ft2font.cpp 2008-04-24 13:23:05 UTC (rev 5071)
@@ -1,6 +1,6 @@
-#include <sstream>
#include "ft2font.h"
#include "mplutils.h"
+#include <sstream>
#define FIXED_MAJOR(val) (*((short *) &val+1))
#define FIXED_MINOR(val) (*((short *) &val+0))
Modified: trunk/matplotlib/src/ft2font.h
===================================================================
--- trunk/matplotlib/src/ft2font.h 2008-04-24 12:54:25 UTC (rev 5070)
+++ trunk/matplotlib/src/ft2font.h 2008-04-24 13:23:05 UTC (rev 5071)
@@ -1,6 +1,8 @@
/* A python interface to freetype2 */
#ifndef _FT2FONT_H
#define _FT2FONT_H
+#include "CXX/Extensions.hxx"
+#include "CXX/Objects.hxx"
#include <iostream>
#include <vector>
#include <string>
@@ -15,8 +17,6 @@
#include FT_TYPE1_TABLES_H
#include FT_TRUETYPE_TABLES_H
}
-#include "CXX/Extensions.hxx"
-#include "CXX/Objects.hxx"
// the freetype string rendered into a width, height buffer
Modified: trunk/matplotlib/ttconv/pprdrv_tt.cpp
===================================================================
--- trunk/matplotlib/ttconv/pprdrv_tt.cpp 2008-04-24 12:54:25 UTC (rev 5070)
+++ trunk/matplotlib/ttconv/pprdrv_tt.cpp 2008-04-24 13:23:05 UTC (rev 5071)
@@ -16,7 +16,7 @@
** documentation. This software is provided "as is" without express or
** implied warranty.
**
-** TrueType font support. These functions allow PPR to generate
+** TrueType font support. These functions allow PPR to generate
** PostScript fonts from Microsoft compatible TrueType font files.
**
** Last revised 19 December 1995.
@@ -31,7 +31,7 @@
#include <sstream>
/*==========================================================================
-** Convert the indicated Truetype font file to a type 42 or type 3
+** Convert the indicated Truetype font file to a type 42 or type 3
** PostScript font and insert it in the output stream.
**
** All the routines from here to the end of file file are involved
@@ -42,7 +42,7 @@
** Endian conversion routines.
** These routines take a BYTE pointer
** and return a value formed by reading
-** bytes starting at that point.
+** bytes starting at that point.
**
** These routines read the big-endian
** values which are used in TrueType
@@ -55,14 +55,14 @@
ULONG getULONG(BYTE *p)
{
int x;
- ULONG val=0;
+ ULONG val=0;
for(x=0; x<4; x++)
{
val *= 0x100;
- val += p[x];
+ val += p[x];
}
-
+
return val;
} /* end of ftohULONG() */
@@ -72,14 +72,14 @@
USHORT getUSHORT(BYTE *p)
{
int x;
- USHORT val=0;
+ USHORT val=0;
for(x=0; x<2; x++)
{
val *= 0x100;
- val += p[x];
+ val += p[x];
}
-
+
return val;
} /* end of getUSHORT() */
@@ -92,7 +92,7 @@
Fixed val={0,0};
val.whole = ((s[0] * 256) + s[1]);
- val.fraction = ((s[2] * 256) + s[3]);
+ val.fraction = ((s[2] * 256) + s[3]);
return val;
} /* end of getFixed() */
@@ -102,16 +102,16 @@
** The font's "file" and "offset_table" fields must be set before this
** routine is called.
**
-** This first argument is a TrueType font structure, the second
+** This first argument is a TrueType font structure, the second
** argument is the name of the table to retrieve. A table name
-** is always 4 characters, though the last characters may be
+** is always 4 characters, though the last characters may be
** padding spaces.
-----------------------------------------------------------------------*/
BYTE *GetTable(struct TTFONT *font, const char *name)
{
BYTE *ptr;
ULONG x;
-
+
#ifdef DEBUG_TRUETYPE
debug("GetTable(file,font,\"%s\")",name);
#endif
@@ -127,20 +127,20 @@
BYTE *table;
offset = getULONG( ptr + 8 );
- length = getULONG( ptr + 12 );
+ length = getULONG( ptr + 12 );
table = (BYTE*)calloc( sizeof(BYTE), length );
try {
#ifdef DEBUG_TRUETYPE
debug("Loading table \"%s\" from offset %d, %d bytes",name,offset,length);
#endif
-
+
if( fseek( font->file, (long)offset, SEEK_SET ) )
throw TTException("TrueType font may be corrupt (reason 3)");
-
+
if( fread(table,sizeof(BYTE),length,font->file) != (sizeof(BYTE) * length))
throw TTException("TrueType font may be corrupt (reason 4)");
- } catch (TTException& e) {
+ } catch (TTException& ) {
free(table);
throw;
}
@@ -156,7 +156,7 @@
} /* end of GetTable() */
/*--------------------------------------------------------------------
-** Load the 'name' table, get information from it,
+** Load the 'name' table, get information from it,
** and store that information in the font structure.
**
** The 'name' table contains information such as the name of
@@ -171,7 +171,7 @@
int platform,encoding; /* Current platform id, encoding id, */
int language,nameid; /* language id, name id, */
int offset,length; /* offset and length of string. */
-
+
#ifdef DEBUG_TRUETYPE
debug("Read_name()");
#endif
@@ -188,7 +188,7 @@
try {
numrecords = getUSHORT( table_ptr + 2 ); /* number of names */
strings = table_ptr + getUSHORT( table_ptr + 4 ); /* start of string storage */
-
+
ptr2 = table_ptr + 6;
for(x=0; x < numrecords; x++,ptr2+=12)
{
@@ -202,7 +202,7 @@
#ifdef DEBUG_TRUETYPE
debug("platform %d, encoding %d, language 0x%x, name %d, offset %d, length %d",
platform,encoding,language,nameid,offset,length);
-#endif
+#endif
/* Copyright notice */
if( platform == 1 && nameid == 0 )
@@ -211,14 +211,14 @@
strncpy(font->Copyright,(const char*)strings+offset,length);
font->Copyright[length]=(char)NULL;
replace_newlines_with_spaces(font->Copyright);
-
+
#ifdef DEBUG_TRUETYPE
debug("font->Copyright=\"%s\"",font->Copyright);
#endif
continue;
}
-
+
/* Font Family name */
if( platform == 1 && nameid == 1 )
{
@@ -226,7 +226,7 @@
strncpy(font->FamilyName,(const char*)strings+offset,length);
font->FamilyName[length]=(char)NULL;
replace_newlines_with_spaces(font->FamilyName);
-
+
#ifdef DEBUG_TRUETYPE
debug("font->FamilyName=\"%s\"",font->FamilyName);
#endif
@@ -241,14 +241,14 @@
strncpy(font->Style,(const char*)strings+offset,length);
font->Style[length]=(char)NULL;
replace_newlines_with_spaces(font->Style);
-
+
#ifdef DEBUG_TRUETYPE
debug("font->Style=\"%s\"",font->Style);
#endif
continue;
}
-
-
+
+
/* Full Font name */
if( platform == 1 && nameid == 4 )
{
@@ -256,14 +256,14 @@
strncpy(font->FullName,(const char*)strings+offset,length);
font->FullName[length]=(char)NULL;
replace_newlines_with_spaces(font->FullName);
-
+
#ifdef DEBUG_TRUETYPE
debug("font->FullName=\"%s\"",font->FullName);
#endif
continue;
}
-
-
+
+
/* Version string */
if( platform == 1 && nameid == 5 )
{
@@ -277,8 +277,8 @@
#endif
continue;
}
-
-
+
+
/* PostScript name */
if( platform == 1 && nameid == 6 )
{
@@ -292,8 +292,8 @@
#endif
continue;
}
-
-
+
+
/* Trademark string */
if( platform == 1 && nameid == 7 )
{
@@ -301,15 +301,15 @@
strncpy(font->Trademark,(const char*)strings+offset,length);
font->Trademark[length]=(char)NULL;
replace_newlines_with_spaces(font->Trademark);
-
+
#ifdef DEBUG_TRUETYPE
debug("font->Trademark=\"%s\"",font->Trademark);
#endif
continue;
}
-
+
}
- } catch (TTException& e) {
+ } catch (TTException& ) {
free(table_ptr);
throw;
}
@@ -443,20 +443,20 @@
/* Some information from the "post" table. */
ItalicAngle = getFixed( font->post_table + 4 );
stream.printf("/ItalicAngle %d.%d def\n",ItalicAngle.whole,ItalicAngle.fraction);
- stream.printf("/isFixedPitch %s def\n", getULONG( font->post_table + 12 ) ? "true" : "false" );
+ stream.printf("/isFixedPitch %s def\n", getULONG( font->post_table + 12 ) ? "true" : "false" );
stream.printf("/UnderlinePosition %d def\n", (int)getFWord( font->post_table + 8 ) );
- stream.printf("/UnderlineThickness %d def\n", (int)getFWord( font->post_table + 10 ) );
- stream.putline("end readonly def");
- } /* end of ttfont_FontInfo() */
+ stream.printf("/UnderlineThickness %d def\n", (int)getFWord( font->post_table + 10 ) );
+ stream.putline("end readonly def");
+ } /* end of ttfont_FontInfo() */
/*-------------------------------------------------------------------
** sfnts routines
-** These routines generate the PostScript "sfnts" array which
+** These routines generate the PostScript "sfnts" array which
** contains one or more strings which contain a reduced version
** of the TrueType font.
**
** A number of functions are required to accomplish this rather
-** complicated task.
+** complicated task.
-------------------------------------------------------------------*/
int string_len;
int line_len;
@@ -498,9 +498,9 @@
stream.putchar('\n');
line_len=0;
}
-
+
} /* end of sfnts_pputBYTE() */
-
+
/*
** Write a USHORT as a hexadecimal value as part of the sfnts array.
*/
@@ -516,7 +516,7 @@
void sfnts_pputULONG(TTStreamWriter& stream, ULONG n)
{
int x1,x2,x3;
-
+
x1 = n % 256;
n /= 256;
x2 = n % 256;
@@ -531,7 +531,7 @@
} /* end of sfnts_pputULONG() */
/*
-** This is called whenever it is
+** This is called whenever it is
** necessary to end a string in the sfnts array.
**
** (The array must be broken into strings which are
@@ -542,7 +542,7 @@
if(in_string)
{
string_len=0; /* fool sfnts_pputBYTE() */
-
+
#ifdef DEBUG_TRUETYPE_INLINE
puts("\n% dummy byte:\n");
#endif
@@ -562,7 +562,7 @@
*/
void sfnts_new_table(TTStreamWriter& stream, ULONG length)
{
- if( (string_len + length) > 65528 )
+ if( (string_len + length) > 65528 )
sfnts_end_string(stream);
} /* end of sfnts_new_table() */
@@ -615,7 +615,7 @@
/* Start new string if necessary. */
sfnts_new_table( stream, (int)length );
- /*
+ /*
** Make sure the glyph is padded out to a
** two byte boundary.
*/
@@ -627,16 +627,16 @@
{
if( (c = fgetc(font->file)) == EOF )
throw TTException("TrueType font may be corrupt (reason 6)");
-
+
sfnts_pputBYTE(stream, c);
total++; /* add to running total */
- }
+ }
}
free(font->loca_table);
font->loca_table = NULL;
-
+
/* Pad out to full length from table directory */
while( total < correct_total_length )
{
@@ -649,7 +649,7 @@
/*
** Here is the routine which ties it all together.
**
-** Create the array called "sfnts" which
+** Create the array called "sfnts" which
** holds the actual TrueType data.
*/
void ttfont_sfnts(TTStreamWriter& stream, struct TTFONT *font)
@@ -673,7 +673,7 @@
ULONG length;
ULONG checksum;
} tables[9];
-
+
BYTE *ptr; /* A pointer into the origional table directory. */
ULONG x,y; /* General use loop countes. */
int c; /* Input character. */
@@ -684,8 +684,8 @@
ptr = font->offset_table + 12;
nextoffset=0;
count=0;
-
- /*
+
+ /*
** Find the tables we want and s...
[truncated message content] |
|
From: <ef...@us...> - 2008-04-24 18:31:15
|
Revision: 5073
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5073&view=rev
Author: efiring
Date: 2008-04-24 11:31:10 -0700 (Thu, 24 Apr 2008)
Log Message:
-----------
Enforce numpy >= 1.1 and python >= 2.3 when importing matplotlib.
Numpy svn passes the test now.
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/__init__.py
trunk/matplotlib/lib/matplotlib/transforms.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-04-24 17:57:57 UTC (rev 5072)
+++ trunk/matplotlib/CHANGELOG 2008-04-24 18:31:10 UTC (rev 5073)
@@ -1,3 +1,7 @@
+
+2008-04-24 Make numpy 1.1 and python 2.3 required when importing
+ matplotlib - EF
+
2008-04-24 Fix compilation issues on VS2003 (Thanks Martin Spacek for
all the help) - MGD
@@ -3443,4 +3447,4 @@
2003-11-21 - make a dash-dot dict for the GC
2003-12-15 - fix install path bug
-t
\ No newline at end of file
+t
Modified: trunk/matplotlib/lib/matplotlib/__init__.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/__init__.py 2008-04-24 17:57:57 UTC (rev 5072)
+++ trunk/matplotlib/lib/matplotlib/__init__.py 2008-04-24 18:31:10 UTC (rev 5073)
@@ -112,10 +112,13 @@
#else: _have_pkg_resources = True
if not _python23:
- def enumerate(seq):
- for i in range(len(seq)):
- yield i, seq[i]
+ raise SystemExit('matplotlib requires Python 2.3 or later')
+import numpy
+nn = numpy.__version__.split('.')
+if not (int(nn[0]) >= 1 and int(nn[1]) >= 1):
+ raise SystemExit(
+ 'numpy >= 1.1 is required; you have %s' % numpy.__version__)
def is_string_like(obj):
if hasattr(obj, 'shape'): return 0
Modified: trunk/matplotlib/lib/matplotlib/transforms.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/transforms.py 2008-04-24 17:57:57 UTC (rev 5072)
+++ trunk/matplotlib/lib/matplotlib/transforms.py 2008-04-24 18:31:10 UTC (rev 5073)
@@ -693,10 +693,7 @@
if len(xy) == 0:
return
- try:
- xym = ma.masked_invalid(xy) # maybe add copy=False
- except AttributeError: # masked_invalid not exposed in npy 1.04
- xym = ma.masked_where(~npy.isfinite(xy), xy)
+ xym = ma.masked_invalid(xy) # maybe add copy=False
if (xym.count(axis=1)!=2).all():
return
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2008-04-25 16:45:36
|
Revision: 5075
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5075&view=rev
Author: efiring
Date: 2008-04-25 09:45:30 -0700 (Fri, 25 Apr 2008)
Log Message:
-----------
Enforce python 2.4 or later; some other version-related cleanup
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/__init__.py
trunk/matplotlib/setup.py
trunk/matplotlib/setupext.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-04-25 15:43:06 UTC (rev 5074)
+++ trunk/matplotlib/CHANGELOG 2008-04-25 16:45:30 UTC (rev 5075)
@@ -1,4 +1,7 @@
+2008-04-25 Enforce python >= 2.4; remove subprocess build - EF
+2008-04-25 Enforce the numpy requirement at build time - JDH
+
2008-04-24 Make numpy 1.1 and python 2.3 required when importing
matplotlib - EF
Modified: trunk/matplotlib/lib/matplotlib/__init__.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/__init__.py 2008-04-25 15:43:06 UTC (rev 5074)
+++ trunk/matplotlib/lib/matplotlib/__init__.py 2008-04-25 16:45:30 UTC (rev 5075)
@@ -95,10 +95,8 @@
from rcsetup import validate_cairo_format
major, minor1, minor2, s, tmp = sys.version_info
-_python23 = major>=2 and minor1>=3
+_python24 = major>=2 and minor1>=4
-_havemath = _python23
-
try:
import datetime
import dateutil
@@ -111,14 +109,14 @@
#except ImportError: _have_pkg_resources = False
#else: _have_pkg_resources = True
-if not _python23:
- raise SystemExit('matplotlib requires Python 2.3 or later')
+if not _python24:
+ raise SystemExit('matplotlib requires Python 2.4 or later')
import numpy
nn = numpy.__version__.split('.')
if not (int(nn[0]) >= 1 and int(nn[1]) >= 1):
raise SystemExit(
- 'numpy >= 1.1 is required; you have %s' % numpy.__version__)
+ 'numpy 1.1 or later is required; you have %s' % numpy.__version__)
def is_string_like(obj):
if hasattr(obj, 'shape'): return 0
Modified: trunk/matplotlib/setup.py
===================================================================
--- trunk/matplotlib/setup.py 2008-04-25 15:43:06 UTC (rev 5074)
+++ trunk/matplotlib/setup.py 2008-04-25 16:45:30 UTC (rev 5075)
@@ -20,28 +20,15 @@
import sys
major, minor1, minor2, s, tmp = sys.version_info
-if major==2 and minor1<=3:
- # setuptools monkeypatches distutils.core.Distribution to support
- # package_data
- try: import setuptools
- except ImportError:
- raise SystemExit("""\
-matplotlib requires setuptools for installation with python-2.3. Visit:
-http://cheeseshop.python.org/pypi/setuptools
-for installation instructions for the proper version of setuptools for your
-system. If this is your first time upgrading matplotlib with the new
-setuptools requirement, you must delete the old matplotlib install
-directory.""")
+if major==2 and minor1<4 or major<2:
+ raise SystemExit("""matplotlib requires Python 2.4 or later.""")
-if major==2 and minor1<3 or major<2:
- raise SystemExit("""matplotlib requires Python 2.3 or later.""")
-
import glob
from distutils.core import setup
from setupext import build_agg, build_gtkagg, build_tkagg, build_wxagg,\
build_ft2font, build_image, build_windowing, build_path, \
build_contour, build_nxutils, build_traits, build_gdk, \
- build_subprocess, build_ttconv, print_line, print_status, print_message, \
+ build_ttconv, print_line, print_status, print_message, \
print_raw, check_for_freetype, check_for_libpng, check_for_gtk, \
check_for_tk, check_for_wx, check_for_numpy, check_for_qt, check_for_qt4, \
check_for_cairo, check_provide_traits, check_provide_pytz, \
@@ -100,25 +87,8 @@
]}
if not check_for_numpy():
- sys.exit()
+ sys.exit(1)
-try: import subprocess
-except ImportError: havesubprocess = False
-else: havesubprocess = True
-
-if havesubprocess and sys.version < '2.4':
- # Python didn't come with subprocess, so let's make sure it's
- # not in some Python egg (e.g. an older version of matplotlib)
- # that may get removed.
- subprocess_dir = os.path.dirname(subprocess.__file__)
- if subprocess_dir.endswith('.egg/subprocess'):
- havesubprocess = False
-
-if not havesubprocess:
- packages.append('subprocess')
- if sys.platform == 'win32':
- build_subprocess(ext_modules, packages)
-
if not check_for_freetype():
sys.exit(1)
Modified: trunk/matplotlib/setupext.py
===================================================================
--- trunk/matplotlib/setupext.py 2008-04-25 15:43:06 UTC (rev 5074)
+++ trunk/matplotlib/setupext.py 2008-04-25 16:45:30 UTC (rev 5075)
@@ -532,21 +532,17 @@
return False
def check_for_numpy():
- gotit = False
try:
import numpy
except ImportError:
print_status("numpy", "no")
- print_message("You must install numpy to build matplotlib.")
- return False
-
- major, minor1, minor2 = map(int, numpy.__version__.split('.')[:3])
- if major<1 or (major==1 and minor1<1):
- print_status("numpy version", "no")
print_message("You must install numpy 1.1 or later to build matplotlib.")
-
return False
-
+ nn = numpy.__version__.split('.')
+ if not (int(nn[0]) >= 1 and int(nn[1]) >= 1):
+ print_message(
+ 'numpy 1.1 or later is required; you have %s' % numpy.__version__)
+ return False
module = Extension('test', [])
add_numpy_flags(module)
add_base_flags(module)
@@ -554,16 +550,13 @@
print_status("numpy", numpy.__version__)
if not find_include_file(module.include_dirs, os.path.join("numpy", "arrayobject.h")):
print_message("Could not find the headers for numpy. You may need to install the development package.")
+ return False
return True
def add_numpy_flags(module):
"Add the modules flags to build extensions which use numpy"
import numpy
- # TODO: Remove this try statement when it is no longer needed
- try:
- module.include_dirs.append(numpy.get_include())
- except AttributeError:
- module.include_dirs.append(numpy.get_numpy_include())
+ module.include_dirs.append(numpy.get_include())
def add_agg_flags(module):
'Add the module flags to build extensions which use agg'
@@ -1267,10 +1260,3 @@
BUILT_GDK = True
-def build_subprocess(ext_modules, packages):
- module = Extension(
- 'subprocess._subprocess',
- ['src/_subprocess.c', ],
- )
- add_base_flags(module)
- ext_modules.append(module)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-04-26 21:46:54
|
Revision: 5076
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5076&view=rev
Author: jdh2358
Date: 2008-04-26 14:46:52 -0700 (Sat, 26 Apr 2008)
Log Message:
-----------
fixed dpi figure title positioning problem
Modified Paths:
--------------
trunk/matplotlib/CODING_GUIDE
trunk/matplotlib/Makefile
trunk/matplotlib/examples/barchart_demo.py
trunk/matplotlib/lib/matplotlib/axes.py
trunk/matplotlib/lib/matplotlib/figure.py
trunk/matplotlib/lib/matplotlib/pyplot.py
trunk/matplotlib/lib/matplotlib/text.py
Modified: trunk/matplotlib/CODING_GUIDE
===================================================================
--- trunk/matplotlib/CODING_GUIDE 2008-04-25 16:45:30 UTC (rev 5075)
+++ trunk/matplotlib/CODING_GUIDE 2008-04-26 21:46:52 UTC (rev 5076)
@@ -45,8 +45,8 @@
For numpy, use:
- import numpy as npy
- a = npy.array([1,2,3])
+ import numpy as np
+ a = np.array([1,2,3])
For masked arrays, use:
Modified: trunk/matplotlib/Makefile
===================================================================
--- trunk/matplotlib/Makefile 2008-04-25 16:45:30 UTC (rev 5075)
+++ trunk/matplotlib/Makefile 2008-04-26 21:46:52 UTC (rev 5076)
@@ -10,7 +10,7 @@
RELEASE = matplotlib-${VERSION}
-clean:
+clean:
${PYTHON} setup.py clean;\
rm -f *.png *.ps *.eps *.svg *.jpg *.pdf
find . -name "_tmp*.py" | xargs rm -f;\
@@ -25,11 +25,12 @@
${PYTHON} license.py ${VERSION} license/LICENSE;\
${PYTHON} setup.py sdist --formats=gztar,zip;
-pyback:
- tar cvfz pyback.tar.gz *.py lib src examples/*.py unit/*.py
+pyback:
+ tar cvfz pyback.tar.gz *.py lib src examples/*.py unit/*.py
+build_osx105:
+ CFLAGS="-Os -arch i386 -arch ppc" LDFLAGS="-Os -arch i386 -arch ppc" python setup.py build
-
Modified: trunk/matplotlib/examples/barchart_demo.py
===================================================================
--- trunk/matplotlib/examples/barchart_demo.py 2008-04-25 16:45:30 UTC (rev 5075)
+++ trunk/matplotlib/examples/barchart_demo.py 2008-04-26 21:46:52 UTC (rev 5076)
@@ -1,24 +1,39 @@
+
#!/usr/bin/env python
# a bar plot with errorbars
-from pylab import *
+import numpy as np
+import matplotlib.pyplot as plt
N = 5
menMeans = (20, 35, 30, 35, 27)
menStd = (2, 3, 4, 1, 2)
-ind = arange(N) # the x locations for the groups
+ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars
-p1 = bar(ind, menMeans, width, color='r', yerr=menStd)
+fig = plt.figure()
+ax = fig.add_subplot(111)
+rects1 = ax.bar(ind, menMeans, width, color='r', yerr=menStd)
+
womenMeans = (25, 32, 34, 20, 25)
womenStd = (3, 5, 2, 3, 3)
-p2 = bar(ind+width, womenMeans, width, color='y', yerr=womenStd)
+rects2 = ax.bar(ind+width, womenMeans, width, color='y', yerr=womenStd)
-ylabel('Scores')
-title('Scores by group and gender')
-xticks(ind+width, ('G1', 'G2', 'G3', 'G4', 'G5') )
+# add some
+ax.set_ylabel('Scores')
+ax.set_title('Scores by group and gender')
+ax.set_xticks(ind+width, ('G1', 'G2', 'G3', 'G4', 'G5') )
-legend( (p1[0], p2[0]), ('Men', 'Women') )
+ax.legend( (rects1[0], rects2[0]), ('Men', 'Women') )
-#savefig('barchart_demo')
-show()
+def autolabel(rects):
+ # attach some text labels
+ for rect in rects:
+ height = rect.get_height()
+ ax.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%d'%int(height),
+ ha='center', va='bottom')
+
+autolabel(rects1)
+autolabel(rects2)
+#fig.savefig('barchart_demo')
+plt.show()
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2008-04-25 16:45:30 UTC (rev 5075)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2008-04-26 21:46:52 UTC (rev 5076)
@@ -780,7 +780,10 @@
self.grid(self._gridOn)
props = font_manager.FontProperties(size=rcParams['axes.titlesize'])
- self.titleOffsetTrans = mtransforms.Affine2D().translate(0.0, 10.0)
+
+
+ self.titleOffsetTrans = mtransforms.Affine2D().translate(
+ 0.0, 5.0*self.figure.dpi/72.)
self.title = mtext.Text(
x=0.5, y=1.0, text='',
fontproperties=props,
@@ -811,8 +814,17 @@
self.xaxis.set_clip_path(self.axesPatch)
self.yaxis.set_clip_path(self.axesPatch)
- self.titleOffsetTrans.clear().translate(0.0, 10.0)
+ self.titleOffsetTrans.clear().translate(
+ 0.0, 5.0*self.figure.dpi/72.)
+ def on_dpi_change(fig):
+ self.titleOffsetTrans.clear().translate(
+ 0.0, 5.0*fig.dpi/72.)
+
+ self.figure.callbacks.connect('dpi_changed', on_dpi_change)
+
+
+
def clear(self):
'clear the axes'
self.cla()
@@ -839,8 +851,10 @@
figure will be cleared on the next plot command
"""
- if b is None: self._hold = not self._hold
- else: self._hold = b
+ if b is None:
+ self._hold = not self._hold
+ else:
+ self._hold = b
def get_aspect(self):
return self._aspect
Modified: trunk/matplotlib/lib/matplotlib/figure.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/figure.py 2008-04-25 16:45:30 UTC (rev 5075)
+++ trunk/matplotlib/lib/matplotlib/figure.py 2008-04-26 21:46:52 UTC (rev 5076)
@@ -1,7 +1,7 @@
"""
Figure class -- add docstring here!
"""
-import numpy as npy
+import numpy as np
import time
import artist
@@ -20,6 +20,8 @@
from projections import projection_factory, get_projection_names, \
get_projection_class
+import matplotlib.cbook as cbook
+
class SubplotParams:
"""
A class to hold the parameters for a subplot
@@ -176,6 +178,13 @@
class Figure(Artist):
+ """
+ The Figure instance supports callbacks through a callbacks
+ attribute which is a cbook.CallbackRegistry instance. The events
+ you can connect to are 'dpi_changed', and the callback will be
+ called with func(fig) where fig is the Figure instance
+ """
+
def __str__(self):
return "Figure(%gx%g)" % tuple(self.bbox.size)
@@ -195,6 +204,8 @@
"""
Artist.__init__(self)
+ self.callbacks = cbook.CallbackRegistry(('dpi_changed', ))
+
if figsize is None : figsize = rcParams['figure.figsize']
if dpi is None : dpi = rcParams['figure.dpi']
if facecolor is None: facecolor = rcParams['figure.facecolor']
@@ -236,6 +247,7 @@
def _set_dpi(self, dpi):
self._dpi = dpi
self.dpi_scale_trans.clear().scale(dpi, dpi)
+ self.callbacks.process('dpi_changed', self)
dpi = property(_get_dpi, _set_dpi)
def enable_auto_layout(self, setting=True):
@@ -255,7 +267,7 @@
rotation: the rotation of the xtick labels
ha : the horizontal alignment of the xticklabels
"""
- allsubplots = npy.alltrue([hasattr(ax, 'is_last_row') for ax in self.axes])
+ allsubplots = np.alltrue([hasattr(ax, 'is_last_row') for ax in self.axes])
if len(self.axes)==1:
for label in ax.get_xticklabels():
label.set_ha(ha)
@@ -662,6 +674,9 @@
"""
Clear the figure
"""
+
+ self.callbacks = cbook.CallbackRegistry(('dpi_changed', ))
+
for ax in tuple(self.axes): # Iterate over the copy.
ax.cla()
self.delaxes(ax) # removes ax from self.axes
@@ -1022,8 +1037,8 @@
# min/max sizes to respect when autoscaling. If John likes the idea, they
# could become rc parameters, for now they're hardwired.
- figsize_min = npy.array((4.0,2.0)) # min length for width/height
- figsize_max = npy.array((16.0,16.0)) # max length for width/height
+ figsize_min = np.array((4.0,2.0)) # min length for width/height
+ figsize_max = np.array((16.0,16.0)) # max length for width/height
#figsize_min = rcParams['figure.figsize_min']
#figsize_max = rcParams['figure.figsize_max']
@@ -1038,7 +1053,7 @@
fig_height = rcParams['figure.figsize'][1]
# New size for the figure, keeping the aspect ratio of the caller
- newsize = npy.array((fig_height/arr_ratio,fig_height))
+ newsize = np.array((fig_height/arr_ratio,fig_height))
# Sanity checks, don't drop either dimension below figsize_min
newsize /= min(1.0,*(newsize/figsize_min))
@@ -1048,7 +1063,7 @@
# Finally, if we have a really funky aspect ratio, break it but respect
# the min/max dimensions (we don't want figures 10 feet tall!)
- newsize = npy.clip(newsize,figsize_min,figsize_max)
+ newsize = np.clip(newsize,figsize_min,figsize_max)
return newsize
artist.kwdocd['Figure'] = artist.kwdoc(Figure)
Modified: trunk/matplotlib/lib/matplotlib/pyplot.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/pyplot.py 2008-04-25 16:45:30 UTC (rev 5075)
+++ trunk/matplotlib/lib/matplotlib/pyplot.py 2008-04-26 21:46:52 UTC (rev 5076)
@@ -274,9 +274,9 @@
def ginput(*args, **kwargs):
"""
- Blocking call to interact with the figure.
+ Blocking call to interact with the figure.
- This will wait for n clicks from the user and return a list of the
+ This will wait for n clicks from the user and return a list of the
coordinates of each click.
If timeout is negative, does not timeout.
@@ -345,8 +345,17 @@
will be cleared on the next plot command
"""
- gcf().hold(b)
- gca().hold(b)
+ fig = gcf()
+ ax = fig.gca()
+
+ fig.hold(b)
+ ax.hold(b)
+
+ # b=None toggles the hold state, so let's get get the current hold
+ # state; but should pyplot hold toggle the rc setting - me thinks
+ # not
+ b = ax.ishold()
+
rc('axes', hold=b)
def ishold():
Modified: trunk/matplotlib/lib/matplotlib/text.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/text.py 2008-04-25 16:45:30 UTC (rev 5075)
+++ trunk/matplotlib/lib/matplotlib/text.py 2008-04-26 21:46:52 UTC (rev 5076)
@@ -4,7 +4,7 @@
from __future__ import division
import math
-import numpy as npy
+import numpy as np
from matplotlib import cbook
from matplotlib import rcParams
@@ -180,8 +180,8 @@
width, height = 0.0, 0.0
lines = self._text.split('\n')
- whs = npy.zeros((len(lines), 2))
- horizLayout = npy.zeros((len(lines), 4))
+ whs = np.zeros((len(lines), 2))
+ horizLayout = np.zeros((len(lines), 4))
# Find full vertical extent of font,
# including ascenders and descenders:
@@ -208,7 +208,7 @@
# get the rotation matrix
M = Affine2D().rotate_deg(self.get_rotation())
- offsetLayout = npy.zeros((len(lines), 2))
+ offsetLayout = np.zeros((len(lines), 2))
offsetLayout[:] = horizLayout[:, 0:2]
# now offset the individual text lines within the box
if len(lines)>1: # do the multiline aligment
@@ -219,9 +219,9 @@
offsetLayout[:, 0] += width - horizLayout[:, 2]
# the corners of the unrotated bounding box
- cornersHoriz = npy.array(
+ cornersHoriz = np.array(
[(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)],
- npy.float_)
+ np.float_)
# now rotate the bbox
cornersRotated = M.transform(cornersHoriz)
@@ -658,7 +658,7 @@
dashlength is the length of the dash in canvas units.
(default=0.0).
- dashdirection is one of 0 or 1, npy.where 0 draws the dash
+ dashdirection is one of 0 or 1, np.where 0 draws the dash
after the text and 1 before.
(default=0).
@@ -782,15 +782,15 @@
dashpush = self.get_dashpush()
angle = get_rotation(dashrotation)
- theta = npy.pi*(angle/180.0+dashdirection-1)
- cos_theta, sin_theta = npy.cos(theta), npy.sin(theta)
+ theta = np.pi*(angle/180.0+dashdirection-1)
+ cos_theta, sin_theta = np.cos(theta), np.sin(theta)
transform = self.get_transform()
# Compute the dash end points
# The 'c' prefix is for canvas coordinates
cxy = transform.transform_point((dashx, dashy))
- cd = npy.array([cos_theta, sin_theta])
+ cd = np.array([cos_theta, sin_theta])
c1 = cxy+dashpush*cd
c2 = cxy+(dashpush+dashlength)*cd
@@ -829,8 +829,8 @@
if dy > h or dy < -h:
dy = h
dx = h/tan_theta
- cwd = npy.array([dx, dy])/2
- cwd *= 1+dashpad/npy.sqrt(npy.dot(cwd,cwd))
+ cwd = np.array([dx, dy])/2
+ cwd *= 1+dashpad/np.sqrt(np.dot(cwd,cwd))
cw = c2+(dashdirection*2-1)*cwd
newx, newy = inverse.transform_point(tuple(cw))
@@ -840,7 +840,7 @@
# I'm not at all sure this is the right way to do this.
we = Text.get_window_extent(self, renderer=renderer)
self._twd_window_extent = we.frozen()
- self._twd_window_extent.update_from_data_xy(npy.array([c1]), False)
+ self._twd_window_extent.update_from_data_xy(np.array([c1]), False)
# Finally, make text align center
Text.set_horizontalalignment(self, 'center')
@@ -1094,8 +1094,8 @@
return x, y
elif s=='polar':
theta, r = x, y
- x = r*npy.cos(theta)
- y = r*npy.sin(theta)
+ x = r*np.cos(theta)
+ y = r*np.cosmsin(theta)
trans = self.axes.transData
return trans.transform_point((x,y))
elif s=='figure points':
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2008-04-28 07:25:12
|
Revision: 5084
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5084&view=rev
Author: efiring
Date: 2008-04-28 00:24:33 -0700 (Mon, 28 Apr 2008)
Log Message:
-----------
Added hexbin axes method and pyplot function by Michiel de Hoon.
Tracker 1952339.
Modified Paths:
--------------
trunk/matplotlib/API_CHANGES
trunk/matplotlib/CHANGELOG
trunk/matplotlib/boilerplate.py
trunk/matplotlib/lib/matplotlib/axes.py
trunk/matplotlib/lib/matplotlib/pyplot.py
Modified: trunk/matplotlib/API_CHANGES
===================================================================
--- trunk/matplotlib/API_CHANGES 2008-04-28 01:59:05 UTC (rev 5083)
+++ trunk/matplotlib/API_CHANGES 2008-04-28 07:24:33 UTC (rev 5084)
@@ -1,3 +1,7 @@
+ New axes method and pyplot function, hexbin, is an alternative
+ to scatter for large datasets. It makes something like a
+ pcolor of a 2-D histogram, but uses hexagonal bins.
+
New kwarg, "symmetric", in MaxNLocator
allows one require an axis to be centered on zero.
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-04-28 01:59:05 UTC (rev 5083)
+++ trunk/matplotlib/CHANGELOG 2008-04-28 07:24:33 UTC (rev 5084)
@@ -1,3 +1,6 @@
+2008-04-27 Applied patch by Michiel de Hoon to add hexbin
+ axes method and pyplot function - EF
+
2008-04-25 Enforce python >= 2.4; remove subprocess build - EF
2008-04-25 Enforce the numpy requirement at build time - JDH
Modified: trunk/matplotlib/boilerplate.py
===================================================================
--- trunk/matplotlib/boilerplate.py 2008-04-28 01:59:05 UTC (rev 5083)
+++ trunk/matplotlib/boilerplate.py 2008-04-28 07:24:33 UTC (rev 5084)
@@ -63,6 +63,7 @@
'csd',
'errorbar',
'fill',
+ 'hexbin',
'hist',
'hlines',
'imshow',
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2008-04-28 01:59:05 UTC (rev 5083)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2008-04-28 07:24:33 UTC (rev 5084)
@@ -4417,6 +4417,229 @@
scatter.__doc__ = cbook.dedent(scatter.__doc__) % martist.kwdocd
+ def hexbin(self, x, y, gridsize = 100, bins = None,
+ xscale = 'linear', yscale = 'linear',
+ cmap=None, norm=None, vmin=None, vmax=None,
+ alpha=1.0, linewidths=None, edgecolors='none',
+ **kwargs):
+ """
+ HEXBIN(x, y, gridsize = 100, bins = None,
+ xscale = 'linear', yscale = 'linear',
+ cmap=None, norm=None, vmin=None, vmax=None,
+ alpha=1.0, linewidths=None, edgecolors='none'
+ **kwargs)
+
+ Make a hexagonal binning plot of x versus y, where x, y are 1-D
+ sequences of the same length, N.
+
+ Either or both of x and y may be masked arrays, in which case all
+ masks will be combined and only unmasked points will be plotted.
+
+ * gridsize=100 : The number of hexagons in the x-direction. The
+ corresponding number of hexagons in the
+ y-direction is chosen such that the hexagons are
+ approximately regular.
+ Alternatively, gridsize can be a tuple with two
+ elements specifying the number of hexagons in
+ the x-direction and the y-direction.
+
+ * bins=None : If None, no binning is applied; the color of
+ each hexagon directly corresponds to its count
+ value.
+ bins='log' : Use a logarithmic scale for the color map.
+ Internally, log(count+1) is used to determine
+ the hexagon color.
+ bins=<integer> : Divide the counts in the specified number of
+ bins, and color the hexagons accordingly
+ bins=<a sequence of values> :
+ The values of the lower bound of the bins
+ to be used.
+
+ * xscale = 'linear' | 'log':
+ Use a logarithmic scale on the horizontal axis.
+
+ * yscale = 'linear' | 'log':
+ Use a logarithmic scale on the vertical axis.
+
+ Other keyword args; the color mapping and normalization arguments.
+
+ * cmap = cm.jet : a colors.Colormap instance from cm.
+ defaults to rc image.cmap
+
+ * norm = colors.Normalize() : colors.Normalize instance
+ is used to scale luminance data to 0,1.
+
+ * vmin=None and vmax=None : vmin and vmax are used in conjunction
+ with norm to normalize luminance data. If either are None, the
+ min and max of the color array C is used. Note if you pass a norm
+ instance, your settings for vmin and vmax will be ignored
+
+ * alpha =1.0 : the alpha value for the patches
+
+ * linewidths, if None, defaults to (lines.linewidth,). Note
+ that this is a tuple, and if you set the linewidths
+ argument you must set it as a sequence of floats, as
+ required by RegularPolyCollection -- see
+ collections.RegularPolyCollection for details
+
+ Optional kwargs control the Collection properties; in
+ particular:
+
+ edgecolors='none' : Draw the edges in the same color
+ as the fill color. This is the default, as
+ it avoids unsightly unpainted pixels
+ between the hexagons.
+ edgecolors=None : Draw the outlines in the default color.
+ edgecolors=<a matplotlib color arg or sequence of rgba tuples>
+ : Draw the outlines in the specified color.
+
+ Here are the standard descriptions of all the Collection kwargs:
+ %(Collection)s
+
+ The return value is a PolyCollection instance; use get_array() on
+ this PolyCollection to get the counts in each hexagon.
+ """
+
+ if not self._hold: self.cla()
+
+ self._process_unit_info(xdata=x, ydata=y, kwargs=kwargs)
+
+ x, y = delete_masked_points(x, y)
+
+ # Set the size of the hexagon grid
+ if iterable(gridsize):
+ nx, ny = gridsize
+ else:
+ nx = gridsize
+ ny = int(nx/math.sqrt(3))
+ # Count the number of data in each hexagon
+ x = npy.array(x, float)
+ y = npy.array(y, float)
+ if xscale=='log':
+ x = npy.log(x)
+ if yscale=='log':
+ y = npy.log(y)
+ xmin = min(x)
+ xmax = max(x)
+ ymin = min(y)
+ ymax = max(y)
+ # In the x-direction, the hexagons exactly cover the region from
+ # xmin to xmax. Need some padding to avoid roundoff errors.
+ width = xmax - xmin
+ padding = 1.e-9 * width
+ xmin -= padding
+ xmax += padding
+ sx = (xmax-xmin) / nx
+ sy = (ymax-ymin) / ny
+ x = (x-xmin)/sx
+ y = (y-ymin)/sy
+ ix1 = npy.round(x)
+ iy1 = npy.round(y)
+ ix2 = npy.floor(x)
+ iy2 = npy.floor(y)
+
+ nx1 = nx + 1
+ ny1 = ny + 1
+ nx2 = nx
+ ny2 = ny
+ n = nx1*ny1+nx2*ny2
+ counts = npy.zeros(n)
+ lattice1 = counts[:nx1*ny1]
+ lattice2 = counts[nx1*ny1:]
+ lattice1.shape = (nx1,ny1)
+ lattice2.shape = (nx2,ny2)
+
+ d1 = (x-ix1)**2 + 3.0 * (y-iy1)**2
+ d2 = (x-ix2-0.5)**2 + 3.0 * (y-iy2-0.5)**2
+
+ for i in xrange(len(x)):
+ if d1[i] < d2[i]:
+ lattice1[ix1[i], iy1[i]]+=1
+ else:
+ lattice2[ix2[i], iy2[i]]+=1
+
+ px = xmin + sx * npy.array([ 0.5, 0.5, 0.0, -0.5, -0.5, 0.0])
+ py = ymin + sy * npy.array([-0.5, 0.5 ,1.0, 0.5, -0.5, -1.0]) / 3.0
+
+ polygons = npy.zeros((6, n, 2), float)
+ polygons[:,:nx1*ny1,0] = npy.repeat(npy.arange(nx1), ny1)
+ polygons[:,:nx1*ny1,1] = npy.array(range(ny1) * nx1)
+ polygons[:,nx1*ny1:,0] = npy.repeat(npy.arange(nx2) + 0.5, ny2)
+ polygons[:,nx1*ny1:,1] = npy.array(range(ny2) * nx2) + 0.5
+
+ polygons = npy.transpose(polygons, axes=[1,0,2])
+ polygons[:,:,0] *= sx
+ polygons[:,:,1] *= sy
+ polygons[:,:,0] += px
+ polygons[:,:,1] += py
+
+ if xscale=='log':
+ polygons[:,:,0] = npy.exp(polygons[:,:,0])
+ xmin = math.exp(xmin)
+ xmax = math.exp(xmax)
+ self.set_xscale('log')
+ if yscale=='log':
+ polygons[:,:,1] = npy.exp(polygons[:,:,1])
+ ymin = math.exp(ymin)
+ ymax = math.exp(ymax)
+ self.set_yscale('log')
+
+ class HexagonBinCollection(mcoll.PolyCollection):
+ """A HexagonBinCollection is a PolyCollection where the edge
+ colors are always kept equal to the fill colors"""
+ def update_scalarmappable(self):
+ mcoll.PolyCollection.update_scalarmappable(self)
+ self._edgecolors = self._facecolors
+
+ if edgecolors=='none':
+ collection = HexagonBinCollection(
+ polygons,
+ linewidths = linewidths,
+ transOffset = self.transData,
+ )
+ else:
+ collection = mcoll.PolyCollection(
+ polygons,
+ edgecolors = edgecolors,
+ linewidths = linewidths,
+ transOffset = self.transData,
+ )
+
+ # Transform the counts if needed
+ if bins=='log':
+ counts = npy.log(counts+1)
+ elif bins!=None:
+ if not iterable(bins):
+ minimum, maximum = min(counts), max(counts)
+ bins-=1 # one less edge than bins
+ bins = minimum + (maximum-minimum)*npy.arange(bins)/bins
+ bins = npy.sort(bins)
+ counts = bins.searchsorted(counts)
+
+ if norm is not None: assert(isinstance(norm, mcolors.Normalize))
+ if cmap is not None: assert(isinstance(cmap, mcolors.Colormap))
+ collection.set_array(counts)
+ collection.set_cmap(cmap)
+ collection.set_norm(norm)
+ collection.set_alpha(alpha)
+ collection.update(kwargs)
+
+ if vmin is not None or vmax is not None:
+ collection.set_clim(vmin, vmax)
+ else:
+ collection.autoscale_None()
+
+ corners = ((xmin, ymin), (xmax, ymax))
+ self.update_datalim( corners)
+ self.autoscale_view()
+
+ # add the collection last
+ self.add_collection(collection)
+ return collection
+
+ hexbin.__doc__ = cbook.dedent(hexbin.__doc__) % martist.kwdocd
+
+
def arrow(self, x, y, dx, dy, **kwargs):
"""
Draws arrow on specified axis from (x,y) to (x+dx,y+dy).
Modified: trunk/matplotlib/lib/matplotlib/pyplot.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/pyplot.py 2008-04-28 01:59:05 UTC (rev 5083)
+++ trunk/matplotlib/lib/matplotlib/pyplot.py 2008-04-28 07:24:33 UTC (rev 5084)
@@ -1953,6 +1953,27 @@
# This function was autogenerated by boilerplate.py. Do not edit as
# changes will be lost
+def hexbin(*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().hexbin(*args, **kwargs)
+ draw_if_interactive()
+ except:
+ hold(b)
+ raise
+ gci._current = ret
+ hold(b)
+ return ret
+if Axes.hexbin.__doc__ is not None:
+ hexbin.__doc__ = dedent(Axes.hexbin.__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 semilogx(*args, **kwargs):
# allow callers to override the hold state by passing hold=True|False
b = ishold()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-04-28 14:19:25
|
Revision: 5091
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5091&view=rev
Author: mdboom
Date: 2008-04-28 07:19:06 -0700 (Mon, 28 Apr 2008)
Log Message:
-----------
Merged revisions 5069-5090 via svnmerge from
https://matplotlib.svn.sf.net/svnroot/matplotlib/branches/v0_91_maint
........
r5088 | mdboom | 2008-04-28 09:07:41 -0400 (Mon, 28 Apr 2008) | 2 lines
Fix SVG text rendering bug affecting Mozilla-based viewers.
........
r5089 | mdboom | 2008-04-28 09:41:28 -0400 (Mon, 28 Apr 2008) | 3 lines
Fix bug where fraction beams were too wide at lower dpi's. Fix
sub/superscript placement at different dpi's.
........
r5090 | mdboom | 2008-04-28 09:49:50 -0400 (Mon, 28 Apr 2008) | 2 lines
Oops in last commit -- left in debugging info.
........
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/backends/backend_svg.py
trunk/matplotlib/lib/matplotlib/mathtext.py
Property Changed:
----------------
trunk/matplotlib/
Property changes on: trunk/matplotlib
___________________________________________________________________
Name: svnmerge-integrated
- /branches/v0_91_maint:1-5068
+ /branches/v0_91_maint:1-5090
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-04-28 13:49:50 UTC (rev 5090)
+++ trunk/matplotlib/CHANGELOG 2008-04-28 14:19:06 UTC (rev 5091)
@@ -1,3 +1,6 @@
+2008-04-28 Fix bug in SVG text with Mozilla-based viewers (the symbol
+ tag is not supported) - MGD
+
2008-04-27 Applied patch by Michiel de Hoon to add hexbin
axes method and pyplot function - EF
@@ -11,6 +14,7 @@
2008-04-24 Fix compilation issues on VS2003 (Thanks Martin Spacek for
all the help) - MGD
+>>>>>>> .merge-right.r5090
2008-04-24 Fix sub/superscripts when the size of the font has been
changed - MGD
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_svg.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_svg.py 2008-04-28 13:49:50 UTC (rev 5090)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_svg.py 2008-04-28 14:19:06 UTC (rev 5091)
@@ -401,7 +401,7 @@
currx, curry = step[-2], -step[-1]
path_data = ''.join(path_data)
char_num = 'c_%s' % md5.new(path_data).hexdigest()
- path_element = '<symbol id="%s"><path d="%s"/></symbol>\n' % (char_num, ''.join(path_data))
+ path_element = '<path id="%s" d="%s"/>\n' % (char_num, ''.join(path_data))
self._char_defs[char_id] = char_num
return path_element
Modified: trunk/matplotlib/lib/matplotlib/mathtext.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mathtext.py 2008-04-28 13:49:50 UTC (rev 5090)
+++ trunk/matplotlib/lib/matplotlib/mathtext.py 2008-04-28 14:19:06 UTC (rev 5091)
@@ -651,12 +651,12 @@
# Some fonts don't store the xHeight, so we do a poor man's xHeight
metrics = self.get_metrics(font, 'it', 'x', fontsize, dpi)
return metrics.iceberg
- xHeight = (pclt['xHeight'] / 64.0) * (fontsize / 12.0)
+ xHeight = (pclt['xHeight'] / 64.0) * (fontsize / 12.0) * (dpi / 100.0)
return xHeight
def get_underline_thickness(self, font, fontsize, dpi):
cached_font = self._get_font(font)
- return max(1.0, cached_font.font.underline_thickness / 64.0 / fontsize * 10.0)
+ return cached_font.font.underline_thickness / 64.0 / fontsize * (10.0 * dpi / 100.0)
def get_kern(self, font1, fontclass1, sym1, fontsize1,
font2, fontclass2, sym2, fontsize2, dpi):
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2008-04-28 18:27:25
|
Revision: 5093
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5093&view=rev
Author: efiring
Date: 2008-04-28 11:26:08 -0700 (Mon, 28 Apr 2008)
Log Message:
-----------
Add hexbin_demo, and use log10 for log in hexbin
Modified Paths:
--------------
trunk/matplotlib/examples/backend_driver.py
trunk/matplotlib/lib/matplotlib/axes.py
Added Paths:
-----------
trunk/matplotlib/examples/hexbin_demo.py
Modified: trunk/matplotlib/examples/backend_driver.py
===================================================================
--- trunk/matplotlib/examples/backend_driver.py 2008-04-28 16:52:44 UTC (rev 5092)
+++ trunk/matplotlib/examples/backend_driver.py 2008-04-28 18:26:08 UTC (rev 5093)
@@ -49,6 +49,7 @@
'fill_demo.py',
'finance_demo.py',
'fonts_demo_kw.py',
+ 'hexbin_demo.py',
'histogram_demo.py',
'hline_demo.py',
'image_demo.py',
Added: trunk/matplotlib/examples/hexbin_demo.py
===================================================================
--- trunk/matplotlib/examples/hexbin_demo.py (rev 0)
+++ trunk/matplotlib/examples/hexbin_demo.py 2008-04-28 18:26:08 UTC (rev 5093)
@@ -0,0 +1,34 @@
+'''
+hexbin is an axes method or pyplot function that is essentially
+a pcolor of a 2-D histogram with hexagonal cells. It can be
+much more informative than a scatter plot; in the first subplot
+below, try substituting 'scatter' for 'hexbin'.
+'''
+
+from matplotlib.pyplot import *
+import numpy as np
+
+n = 100000
+x = np.random.standard_normal(n)
+y = 2.0 + 3.0 * x + 4.0 * np.random.standard_normal(n)
+xmin = x.min()
+xmax = x.max()
+ymin = y.min()
+ymax = y.max()
+
+subplot(121)
+hexbin(x,y)
+axis([xmin, xmax, ymin, ymax])
+title("Hexagon binning")
+cb = colorbar()
+cb.set_label('counts')
+
+subplot(122)
+hexbin(x,y,bins='log')
+axis([xmin, xmax, ymin, ymax])
+title("With a log color scale")
+cb = colorbar()
+cb.set_label('log10(N)')
+
+show()
+
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2008-04-28 16:52:44 UTC (rev 5092)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2008-04-28 18:26:08 UTC (rev 5093)
@@ -4447,7 +4447,7 @@
each hexagon directly corresponds to its count
value.
bins='log' : Use a logarithmic scale for the color map.
- Internally, log(count+1) is used to determine
+ Internally, log10(count+1) is used to determine
the hexagon color.
bins=<integer> : Divide the counts in the specified number of
bins, and color the hexagons accordingly
@@ -4456,10 +4456,10 @@
to be used.
* xscale = 'linear' | 'log':
- Use a logarithmic scale on the horizontal axis.
+ Use a log10 scale on the horizontal axis.
* yscale = 'linear' | 'log':
- Use a logarithmic scale on the vertical axis.
+ Use a log10 scale on the vertical axis.
Other keyword args; the color mapping and normalization arguments.
@@ -4516,9 +4516,9 @@
x = npy.array(x, float)
y = npy.array(y, float)
if xscale=='log':
- x = npy.log(x)
+ x = npy.log10(x)
if yscale=='log':
- y = npy.log(y)
+ y = npy.log10(y)
xmin = min(x)
xmax = max(x)
ymin = min(y)
@@ -4574,14 +4574,14 @@
polygons[:,:,1] += py
if xscale=='log':
- polygons[:,:,0] = npy.exp(polygons[:,:,0])
- xmin = math.exp(xmin)
- xmax = math.exp(xmax)
+ polygons[:,:,0] = 10**(polygons[:,:,0])
+ xmin = 10**xmin
+ xmax = 10**xmax
self.set_xscale('log')
if yscale=='log':
- polygons[:,:,1] = npy.exp(polygons[:,:,1])
- ymin = math.exp(ymin)
- ymax = math.exp(ymax)
+ polygons[:,:,1] = 10**(polygons[:,:,1])
+ ymin = 10**ymin
+ ymax = 10**ymax
self.set_yscale('log')
class HexagonBinCollection(mcoll.PolyCollection):
@@ -4607,7 +4607,7 @@
# Transform the counts if needed
if bins=='log':
- counts = npy.log(counts+1)
+ counts = npy.log10(counts+1)
elif bins!=None:
if not iterable(bins):
minimum, maximum = min(counts), max(counts)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mme...@us...> - 2008-04-29 13:35:52
|
Revision: 5096
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5096&view=rev
Author: mmetz_bn
Date: 2008-04-29 06:35:47 -0700 (Tue, 29 Apr 2008)
Log Message:
-----------
fixed bug in mlab.sqrtm; numpy.linalg.eig behaves different than Numeric did
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/mlab.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-04-29 13:21:48 UTC (rev 5095)
+++ trunk/matplotlib/CHANGELOG 2008-04-29 13:35:47 UTC (rev 5096)
@@ -1,3 +1,5 @@
+2008-04-29 Fix bug in mlab.sqrtm - MM
+
2008-04-28 Fix bug in SVG text with Mozilla-based viewers (the symbol
tag is not supported) - MGD
Modified: trunk/matplotlib/lib/matplotlib/mlab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mlab.py 2008-04-29 13:21:48 UTC (rev 5095)
+++ trunk/matplotlib/lib/matplotlib/mlab.py 2008-04-29 13:35:47 UTC (rev 5096)
@@ -1901,7 +1901,7 @@
def sqrtm(x):
"""
Returns the square root of a square matrix.
- This means that s=sqrtm(x) implies s*s = x.
+ This means that s=sqrtm(x) implies dot(s,s) = x.
Note that s and x are matrices.
"""
return mfuncC(npy.sqrt, x)
@@ -1914,9 +1914,10 @@
"""
x = npy.asarray(x)
- (v, u) = npy.linalg.eig(x)
- uT = u.transpose()
+ (v,uT) = npy.linalg.eig(x)
V = npy.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 = npy.dot(uT, npy.dot(V, npy.linalg.inv(uT)))
return approx_real(y)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-04-29 15:15:02
|
Revision: 5098
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5098&view=rev
Author: jdh2358
Date: 2008-04-29 08:14:36 -0700 (Tue, 29 Apr 2008)
Log Message:
-----------
changed numpy abbrev from npy to np
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/art3d.py
trunk/matplotlib/lib/matplotlib/axes.py
trunk/matplotlib/lib/matplotlib/axes3d.py
trunk/matplotlib/lib/matplotlib/axis3d.py
trunk/matplotlib/lib/matplotlib/backend_bases.py
trunk/matplotlib/lib/matplotlib/cbook.py
trunk/matplotlib/lib/matplotlib/cm.py
trunk/matplotlib/lib/matplotlib/collections.py
trunk/matplotlib/lib/matplotlib/colorbar.py
trunk/matplotlib/lib/matplotlib/colors.py
trunk/matplotlib/lib/matplotlib/contour.py
trunk/matplotlib/lib/matplotlib/dates.py
trunk/matplotlib/lib/matplotlib/dviread.py
trunk/matplotlib/lib/matplotlib/finance.py
trunk/matplotlib/lib/matplotlib/image.py
trunk/matplotlib/lib/matplotlib/legend.py
trunk/matplotlib/lib/matplotlib/lines.py
trunk/matplotlib/lib/matplotlib/mlab.py
trunk/matplotlib/lib/matplotlib/patches.py
trunk/matplotlib/lib/matplotlib/path.py
trunk/matplotlib/lib/matplotlib/proj3d.py
trunk/matplotlib/lib/matplotlib/pylab.py
trunk/matplotlib/lib/matplotlib/quiver.py
trunk/matplotlib/lib/matplotlib/scale.py
trunk/matplotlib/lib/matplotlib/texmanager.py
trunk/matplotlib/lib/matplotlib/ticker.py
trunk/matplotlib/lib/matplotlib/transforms.py
trunk/matplotlib/lib/matplotlib/widgets.py
trunk/matplotlib/setupext.py
trunk/matplotlib/src/_backend_agg.cpp
Modified: trunk/matplotlib/lib/matplotlib/art3d.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/art3d.py 2008-04-29 14:22:48 UTC (rev 5097)
+++ trunk/matplotlib/lib/matplotlib/art3d.py 2008-04-29 15:14:36 UTC (rev 5098)
@@ -11,7 +11,7 @@
from colors import Normalize
-import numpy as npy
+import numpy as np
import proj3d
class Wrap2D:
@@ -253,8 +253,8 @@
segis.append((si,ei))
si = ei
xs,ys,zs = zip(*points)
- ones = npy.ones(len(xs))
- self.vec = npy.array([xs,ys,zs,ones])
+ ones = np.ones(len(xs))
+ self.vec = np.array([xs,ys,zs,ones])
self.segis = segis
def draw3d(self, renderer):
@@ -326,7 +326,7 @@
source = image._A
w,h,p = source.shape
X,Y = meshgrid(arange(w),arange(h))
- Z = npy.zeros((w,h))
+ Z = np.zeros((w,h))
tX,tY,tZ = proj3d.transform(X.flat,Y.flat,Z.flat,M)
tX = reshape(tX,(w,h))
tY = reshape(tY,(w,h))
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2008-04-29 14:22:48 UTC (rev 5097)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2008-04-29 15:14:36 UTC (rev 5098)
@@ -1,7 +1,7 @@
from __future__ import division, generators
import math, warnings, new
-import numpy as npy
+import numpy as np
from numpy import ma
import matplotlib
@@ -212,16 +212,16 @@
def _xy_from_y(self, y):
if self.axes.yaxis is not None:
b = self.axes.yaxis.update_units(y)
- if b: return npy.arange(len(y)), y, False
+ if b: return np.arange(len(y)), y, False
if not ma.isMaskedArray(y):
- y = npy.asarray(y)
+ y = np.asarray(y)
if len(y.shape) == 1:
- y = y[:,npy.newaxis]
+ y = y[:,np.newaxis]
nr, nc = y.shape
- x = npy.arange(nr)
+ x = np.arange(nr)
if len(x.shape) == 1:
- x = x[:,npy.newaxis]
+ x = x[:,np.newaxis]
return x,y, True
def _xy_from_xy(self, x, y):
@@ -235,18 +235,18 @@
x = ma.asarray(x)
y = ma.asarray(y)
if len(x.shape) == 1:
- x = x[:,npy.newaxis]
+ x = x[:,np.newaxis]
if len(y.shape) == 1:
- y = y[:,npy.newaxis]
+ y = y[:,np.newaxis]
nrx, ncx = x.shape
nry, ncy = y.shape
assert nrx == nry, 'Dimensions of x and y are incompatible'
if ncx == ncy:
return x, y, True
if ncx == 1:
- x = npy.repeat(x, ncy, axis=1)
+ x = np.repeat(x, ncy, axis=1)
if ncy == 1:
- y = npy.repeat(y, ncx, axis=1)
+ y = np.repeat(y, ncx, axis=1)
assert x.shape == y.shape, 'Dimensions of x and y are incompatible'
return x, y, True
@@ -1231,7 +1231,7 @@
# Otherwise, it will compute the bounds of it's current data
# and the data in xydata
if not ma.isMaskedArray(xys):
- xys = npy.asarray(xys)
+ xys = np.asarray(xys)
self.dataLim.update_from_data_xy(xys, self.ignore_existing_data_limits)
self.ignore_existing_data_limits = False
@@ -2071,7 +2071,7 @@
dx = 0.5 * (dx + dy)
dy = dx
- alpha = npy.power(10.0, (dx, dy))
+ alpha = np.power(10.0, (dx, dy))
start = p.trans_inverse.transform_point((p.x, p.y))
lim_points = p.lim.get_points()
result = start + alpha * (lim_points - start)
@@ -2200,7 +2200,7 @@
def dist_x_y(p1, x, y):
'x and y are arrays; return the distance to the closest point'
x1, y1 = p1
- return min(npy.sqrt((x-x1)**2+(y-y1)**2))
+ return min(np.sqrt((x-x1)**2+(y-y1)**2))
def dist(a):
if isinstance(a, Text):
@@ -2217,7 +2217,7 @@
ydata = a.get_ydata(orig=False)
xt, yt = a.get_transform().numerix_x_y(xdata, ydata)
- return dist_x_y(xywin, npy.asarray(xt), npy.asarray(yt))
+ return dist_x_y(xywin, np.asarray(xt), np.asarray(yt))
artists = self.lines + self.patches + self.texts
if callable(among):
@@ -2601,14 +2601,14 @@
if not iterable(y): y = [y]
if not iterable(xmin): xmin = [xmin]
if not iterable(xmax): xmax = [xmax]
- y = npy.asarray(y)
- xmin = npy.asarray(xmin)
- xmax = npy.asarray(xmax)
+ y = np.asarray(y)
+ xmin = np.asarray(xmin)
+ xmax = np.asarray(xmax)
if len(xmin)==1:
- xmin = npy.resize( xmin, y.shape )
+ xmin = np.resize( xmin, y.shape )
if len(xmax)==1:
- xmax = npy.resize( xmax, y.shape )
+ xmax = np.resize( xmax, y.shape )
if len(xmin)!=len(y):
raise ValueError, 'xmin and y are unequal sized sequences'
@@ -2669,26 +2669,26 @@
if not iterable(x): x = [x]
if not iterable(ymin): ymin = [ymin]
if not iterable(ymax): ymax = [ymax]
- x = npy.asarray(x)
- ymin = npy.asarray(ymin)
- ymax = npy.asarray(ymax)
+ x = np.asarray(x)
+ ymin = np.asarray(ymin)
+ ymax = np.asarray(ymax)
if len(ymin)==1:
- ymin = npy.resize( ymin, x.shape )
+ ymin = np.resize( ymin, x.shape )
if len(ymax)==1:
- ymax = npy.resize( ymax, x.shape )
+ ymax = np.resize( ymax, x.shape )
if len(ymin)!=len(x):
raise ValueError, 'ymin and x are unequal sized sequences'
if len(ymax)!=len(x):
raise ValueError, 'ymax and x are unequal sized sequences'
- Y = npy.array([ymin, ymax]).T
+ Y = np.array([ymin, ymax]).T
verts = [ ((thisx, thisymin), (thisx, thisymax))
for thisx, (thisymin, thisymax) in zip(x,Y)]
#print 'creating line collection'
coll = mcoll.LineCollection(verts, colors=colors,
- linestyles=linestyles, label=label)
+ linestyles=linestyles, label=label)
self.add_collection(coll)
coll.update(kwargs)
@@ -3063,19 +3063,19 @@
if Nx!=len(y):
raise ValueError('x and y must be equal length')
- x = detrend(npy.asarray(x))
- y = detrend(npy.asarray(y))
+ x = detrend(np.asarray(x))
+ y = detrend(np.asarray(y))
- c = npy.correlate(x, y, mode=2)
+ c = np.correlate(x, y, mode=2)
- if normed: c/= npy.sqrt(npy.dot(x,x) * npy.dot(y,y))
+ if normed: c/= np.sqrt(np.dot(x,x) * np.dot(y,y))
if maxlags is None: maxlags = Nx - 1
if maxlags >= Nx or maxlags < 1:
raise ValueError('maglags must be None or strictly positive < %d'%Nx)
- lags = npy.arange(-maxlags,maxlags+1)
+ lags = np.arange(-maxlags,maxlags+1)
c = c[Nx-1-maxlags:Nx+maxlags]
@@ -3358,10 +3358,10 @@
# do not convert to array here as unit info is lost
- #left = npy.asarray(left)
- #height = npy.asarray(height)
- #width = npy.asarray(width)
- #bottom = npy.asarray(bottom)
+ #left = np.asarray(left)
+ #height = np.asarray(height)
+ #width = np.asarray(width)
+ #bottom = np.asarray(bottom)
if len(linewidth) == 1: linewidth = linewidth * nbars
@@ -3469,16 +3469,16 @@
if adjust_xlim:
xmin, xmax = self.dataLim.intervalx
- xmin = npy.amin(width)
+ xmin = np.amin(width)
if xerr is not None:
- xmin = xmin - npy.amax(xerr)
+ xmin = xmin - np.amax(xerr)
xmin = max(xmin*0.9, 1e-100)
self.dataLim.intervalx = (xmin, xmax)
if adjust_ylim:
ymin, ymax = self.dataLim.intervaly
- ymin = npy.amin(height)
+ ymin = np.amin(height)
if yerr is not None:
- ymin = ymin - npy.amax(yerr)
+ ymin = ymin - np.amax(yerr)
ymin = max(ymin*0.9, 1e-100)
self.dataLim.intervaly = (ymin, ymax)
self.autoscale_view()
@@ -3596,7 +3596,7 @@
l, = self.plot([thisx,thisx], [0, thisy], linefmt)
stemlines.append(l)
- baseline, = self.plot([npy.amin(x), npy.amax(x)], [0,0], basefmt)
+ baseline, = self.plot([np.amin(x), np.amax(x)], [0,0], basefmt)
self.hold(remember_hold)
@@ -3658,10 +3658,10 @@
"""
self.set_frame_on(False)
- x = npy.asarray(x).astype(npy.float32)
+ x = np.asarray(x).astype(np.float32)
sx = float(x.sum())
- if sx>1: x = npy.divide(x,sx)
+ if sx>1: x = np.divide(x,sx)
if labels is None: labels = ['']*len(x)
if explode is None: explode = [0]*len(x)
@@ -3841,17 +3841,17 @@
# arrays fine here, they are booleans and hence not units
if not iterable(lolims):
- lolims = npy.asarray([lolims]*len(x), bool)
- else: lolims = npy.asarray(lolims, bool)
+ lolims = np.asarray([lolims]*len(x), bool)
+ else: lolims = np.asarray(lolims, bool)
- if not iterable(uplims): uplims = npy.array([uplims]*len(x), bool)
- else: uplims = npy.asarray(uplims, bool)
+ if not iterable(uplims): uplims = np.array([uplims]*len(x), bool)
+ else: uplims = np.asarray(uplims, bool)
- if not iterable(xlolims): xlolims = npy.array([xlolims]*len(x), bool)
- else: xlolims = npy.asarray(xlolims, bool)
+ if not iterable(xlolims): xlolims = np.array([xlolims]*len(x), bool)
+ else: xlolims = np.asarray(xlolims, bool)
- if not iterable(xuplims): xuplims = npy.array([xuplims]*len(x), bool)
- else: xuplims = npy.asarray(xuplims, bool)
+ if not iterable(xuplims): xuplims = np.array([xuplims]*len(x), bool)
+ else: xuplims = np.asarray(xuplims, bool)
def xywhere(xs, ys, mask):
"""
@@ -4032,26 +4032,26 @@
distance = max(positions) - min(positions)
widths = min(0.15*max(distance,1.0), 0.5)
if isinstance(widths, float) or isinstance(widths, int):
- widths = npy.ones((col,), float) * widths
+ widths = np.ones((col,), float) * widths
# loop through columns, adding each to plot
self.hold(True)
for i,pos in enumerate(positions):
- d = npy.ravel(x[i])
+ d = np.ravel(x[i])
row = len(d)
# get median and quartiles
q1, med, q3 = mlab.prctile(d,[25,50,75])
# get high extreme
iq = q3 - q1
hi_val = q3 + whis*iq
- wisk_hi = npy.compress( d <= hi_val , d )
+ wisk_hi = np.compress( d <= hi_val , d )
if len(wisk_hi) == 0:
wisk_hi = q3
else:
wisk_hi = max(wisk_hi)
# get low extreme
lo_val = q1 - whis*iq
- wisk_lo = npy.compress( d >= lo_val, d )
+ wisk_lo = np.compress( d >= lo_val, d )
if len(wisk_lo) == 0:
wisk_lo = q1
else:
@@ -4062,16 +4062,16 @@
flier_hi_x = []
flier_lo_x = []
if len(sym) != 0:
- flier_hi = npy.compress( d > wisk_hi, d )
- flier_lo = npy.compress( d < wisk_lo, d )
- flier_hi_x = npy.ones(flier_hi.shape[0]) * pos
- flier_lo_x = npy.ones(flier_lo.shape[0]) * pos
+ flier_hi = np.compress( d > wisk_hi, d )
+ flier_lo = np.compress( d < wisk_lo, d )
+ flier_hi_x = np.ones(flier_hi.shape[0]) * pos
+ flier_lo_x = np.ones(flier_lo.shape[0]) * pos
# get x locations for fliers, whisker, whisker cap and box sides
box_x_min = pos - widths[i] * 0.5
box_x_max = pos + widths[i] * 0.5
- wisk_x = npy.ones(2) * pos
+ wisk_x = np.ones(2) * pos
cap_x_min = pos - widths[i] * 0.25
cap_x_max = pos + widths[i] * 0.25
@@ -4089,8 +4089,8 @@
med_x = [box_x_min, box_x_max]
# calculate 'notch' plot
else:
- notch_max = med + 1.57*iq/npy.sqrt(row)
- notch_min = med - 1.57*iq/npy.sqrt(row)
+ notch_max = med + 1.57*iq/np.sqrt(row)
+ notch_min = med - 1.57*iq/np.sqrt(row)
if notch_max > q3:
notch_max = q3
if notch_min < q1:
@@ -4267,7 +4267,7 @@
# mapping, not interpretation as rgb or rgba.
if not is_string_like(c):
- sh = npy.shape(c)
+ sh = np.shape(c)
if len(sh) == 1 and sh[0] == len(x):
colors = None # use cmap, norm after collection is created
else:
@@ -4324,7 +4324,7 @@
symstyle = marker[1]
else:
- verts = npy.asarray(marker[0])
+ verts = np.asarray(marker[0])
if sym is not None:
if symstyle==0:
@@ -4357,11 +4357,11 @@
else:
# MGDTODO: This has dpi problems
# rescale verts
- rescale = npy.sqrt(max(verts[:,0]**2+verts[:,1]**2))
+ rescale = np.sqrt(max(verts[:,0]**2+verts[:,1]**2))
verts /= rescale
- scales = npy.asarray(scales)
- scales = npy.sqrt(scales * self.figure.dpi / 72.)
+ scales = np.asarray(scales)
+ scales = np.sqrt(scales * self.figure.dpi / 72.)
if len(scales)==1:
verts = [scales[0]*verts]
else:
@@ -4382,7 +4382,7 @@
if colors is None:
if norm is not None: assert(isinstance(norm, mcolors.Normalize))
if cmap is not None: assert(isinstance(cmap, mcolors.Colormap))
- collection.set_array(npy.asarray(c))
+ collection.set_array(np.asarray(c))
collection.set_cmap(cmap)
collection.set_norm(norm)
@@ -4394,10 +4394,10 @@
temp_x = x
temp_y = y
- minx = npy.amin(temp_x)
- maxx = npy.amax(temp_x)
- miny = npy.amin(temp_y)
- maxy = npy.amax(temp_y)
+ minx = np.amin(temp_x)
+ maxx = np.amax(temp_x)
+ miny = np.amin(temp_y)
+ maxy = np.amax(temp_y)
w = maxx-minx
h = maxy-miny
@@ -4513,16 +4513,16 @@
nx = gridsize
ny = int(nx/math.sqrt(3))
# Count the number of data in each hexagon
- x = npy.array(x, float)
- y = npy.array(y, float)
+ x = np.array(x, float)
+ y = np.array(y, float)
if xscale=='log':
- x = npy.log10(x)
+ x = np.log10(x)
if yscale=='log':
- y = npy.log10(y)
- xmin = npy.amin(x)
- xmax = npy.amax(x)
- ymin = npy.amin(y)
- ymax = npy.amax(y)
+ y = np.log10(y)
+ xmin = np.amin(x)
+ xmax = np.amax(x)
+ ymin = np.amin(y)
+ ymax = np.amax(y)
# In the x-direction, the hexagons exactly cover the region from
# xmin to xmax. Need some padding to avoid roundoff errors.
padding = 1.e-9 * (xmax - xmin)
@@ -4532,17 +4532,17 @@
sy = (ymax-ymin) / ny
x = (x-xmin)/sx
y = (y-ymin)/sy
- ix1 = npy.round(x).astype(int)
- iy1 = npy.round(y).astype(int)
- ix2 = npy.floor(x).astype(int)
- iy2 = npy.floor(y).astype(int)
+ ix1 = np.round(x).astype(int)
+ iy1 = np.round(y).astype(int)
+ ix2 = np.floor(x).astype(int)
+ iy2 = np.floor(y).astype(int)
nx1 = nx + 1
ny1 = ny + 1
nx2 = nx
ny2 = ny
n = nx1*ny1+nx2*ny2
- counts = npy.zeros(n)
+ counts = np.zeros(n)
lattice1 = counts[:nx1*ny1]
lattice2 = counts[nx1*ny1:]
lattice1.shape = (nx1,ny1)
@@ -4558,16 +4558,16 @@
else:
lattice2[ix2[i], iy2[i]]+=1
- px = xmin + sx * npy.array([ 0.5, 0.5, 0.0, -0.5, -0.5, 0.0])
- py = ymin + sy * npy.array([-0.5, 0.5, 1.0, 0.5, -0.5, -1.0]) / 3.0
+ px = xmin + sx * np.array([ 0.5, 0.5, 0.0, -0.5, -0.5, 0.0])
+ py = ymin + sy * np.array([-0.5, 0.5, 1.0, 0.5, -0.5, -1.0]) / 3.0
- polygons = npy.zeros((6, n, 2), float)
- polygons[:,:nx1*ny1,0] = npy.repeat(npy.arange(nx1), ny1)
- polygons[:,:nx1*ny1,1] = npy.tile(npy.arange(ny1), nx1)
- polygons[:,nx1*ny1:,0] = npy.repeat(npy.arange(nx2) + 0.5, ny2)
- polygons[:,nx1*ny1:,1] = npy.tile(npy.arange(ny2), nx2) + 0.5
+ polygons = np.zeros((6, n, 2), float)
+ polygons[:,:nx1*ny1,0] = np.repeat(np.arange(nx1), ny1)
+ polygons[:,:nx1*ny1,1] = np.tile(np.arange(ny1), nx1)
+ polygons[:,nx1*ny1:,0] = np.repeat(np.arange(nx2) + 0.5, ny2)
+ polygons[:,nx1*ny1:,1] = np.tile(np.arange(ny2), nx2) + 0.5
- polygons = npy.transpose(polygons, axes=[1,0,2])
+ polygons = np.transpose(polygons, axes=[1,0,2])
polygons[:,:,0] *= sx
polygons[:,:,1] *= sy
polygons[:,:,0] += px
@@ -4607,13 +4607,13 @@
# Transform the counts if needed
if bins=='log':
- counts = npy.log10(counts+1)
+ counts = np.log10(counts+1)
elif bins!=None:
if not iterable(bins):
minimum, maximum = min(counts), max(counts)
bins-=1 # one less edge than bins
- bins = minimum + (maximum-minimum)*npy.arange(bins)/bins
- bins = npy.sort(bins)
+ bins = minimum + (maximum-minimum)*np.arange(bins)/bins
+ bins = np.sort(bins)
counts = bins.searchsorted(counts)
if norm is not None: assert(isinstance(norm, mcolors.Normalize))
@@ -4847,7 +4847,7 @@
if len(args)==1:
C = args[0]
numRows, numCols = C.shape
- X, Y = npy.meshgrid(npy.arange(numCols+1), npy.arange(numRows+1) )
+ X, Y = np.meshgrid(np.arange(numCols+1), np.arange(numRows+1) )
elif len(args)==3:
X, Y, C = args
else:
@@ -4936,8 +4936,8 @@
Similarly for meshgrid:
- x = npy.arange(5)
- y = npy.arange(3)
+ x = np.arange(5)
+ y = np.arange(3)
X, Y = meshgrid(x,y)
is equivalent to
@@ -4990,8 +4990,8 @@
# don't plot if C or any of the surrounding vertices are masked.
mask = ma.getmaskarray(C)[0:Ny-1,0:Nx-1]+xymask
- newaxis = npy.newaxis
- compress = npy.compress
+ newaxis = np.newaxis
+ compress = np.compress
ravelmask = (mask==0).ravel()
X1 = compress(ravelmask, ma.filled(X[0:-1,0:-1]).ravel())
@@ -5004,7 +5004,7 @@
Y4 = compress(ravelmask, ma.filled(Y[0:-1,1:]).ravel())
npoly = len(X1)
- xy = npy.concatenate((X1[:,newaxis], Y1[:,newaxis],
+ xy = np.concatenate((X1[:,newaxis], Y1[:,newaxis],
X2[:,newaxis], Y2[:,newaxis],
X3[:,newaxis], Y3[:,newaxis],
X4[:,newaxis], Y4[:,newaxis],
@@ -5043,10 +5043,10 @@
x = X.compressed()
y = Y.compressed()
- minx = npy.amin(x)
- maxx = npy.amax(x)
- miny = npy.amin(y)
- maxy = npy.amax(y)
+ minx = np.amin(x)
+ maxx = np.amax(x)
+ miny = np.amin(y)
+ maxy = np.amax(y)
corners = (minx, miny), (maxx, maxy)
self.update_datalim( corners)
@@ -5127,7 +5127,7 @@
X = X.ravel()
Y = Y.ravel()
- coords = npy.zeros(((Nx * Ny), 2), dtype=float)
+ coords = np.zeros(((Nx * Ny), 2), dtype=float)
coords[:, 0] = X
coords[:, 1] = Y
@@ -5151,10 +5151,10 @@
self.grid(False)
- minx = npy.amin(X)
- maxx = npy.amax(X)
- miny = npy.amin(Y)
- maxy = npy.amax(Y)
+ minx = np.amin(X)
+ maxx = np.amax(X)
+ miny = np.amin(Y)
+ maxy = np.amax(Y)
corners = (minx, miny), (maxx, maxy)
self.update_datalim( corners)
@@ -5250,16 +5250,16 @@
y = [0, nr]
elif len(args) == 3:
x, y = args[:2]
- x = npy.asarray(x)
- y = npy.asarray(y)
+ x = np.asarray(x)
+ y = np.asarray(y)
if x.ndim == 1 and y.ndim == 1:
if x.size == 2 and y.size == 2:
style = "image"
else:
- dx = npy.diff(x)
- dy = npy.diff(y)
- if (npy.ptp(dx) < 0.01*npy.abs(dx.mean()) and
- npy.ptp(dy) < 0.01*npy.abs(dy.mean())):
+ dx = np.diff(x)
+ dy = np.diff(y)
+ if (np.ptp(dx) < 0.01*np.abs(dx.mean()) and
+ np.ptp(dy) < 0.01*np.abs(dy.mean())):
style = "image"
else:
style = "pcolorimage"
@@ -5283,7 +5283,7 @@
# The following needs to be cleaned up; the renderer
# requires separate contiguous arrays for X and Y,
# but the QuadMesh class requires the 2D array.
- coords = npy.empty(((Nx * Ny), 2), npy.float64)
+ coords = np.empty(((Nx * Ny), 2), np.float64)
coords[:, 0] = X
coords[:, 1] = Y
@@ -5328,7 +5328,7 @@
ret.set_clim(vmin, vmax)
else:
ret.autoscale_None()
- self.update_datalim(npy.array([[xl, yb], [xr, yt]]))
+ self.update_datalim(np.array([[xl, yb], [xr, yt]]))
self.autoscale_view(tight=True)
return ret
@@ -5427,7 +5427,7 @@
# trapezoidal integration of the probability density function
pdf, bins, patches = ax.hist(...)
- print npy.trapz(pdf, bins)
+ print np.trapz(pdf, bins)
align = 'edge' | 'center'. Interprets bins either as edge
or center values
@@ -5445,7 +5445,7 @@
%(Rectangle)s
"""
if not self._hold: self.cla()
- n, bins = npy.histogram(x, bins, range=None, normed=normed)
+ n, bins = np.histogram(x, bins, range=None, normed=normed)
if width is None: width = 0.9*(bins[1]-bins[0])
if orientation == 'horizontal':
patches = self.barh(bins, n, height=width, left=bottom,
@@ -5498,7 +5498,7 @@
Returns the tuple Pxx, freqs
- For plotting, the power is plotted as 10*npy.log10(pxx) for decibels,
+ For plotting, the power is plotted as 10*np.log10(pxx) for decibels,
though pxx itself is returned
Refs:
@@ -5514,17 +5514,17 @@
pxx.shape = len(freqs),
freqs += Fc
- self.plot(freqs, 10*npy.log10(pxx), **kwargs)
+ self.plot(freqs, 10*np.log10(pxx), **kwargs)
self.set_xlabel('Frequency')
self.set_ylabel('Power Spectrum (dB)')
self.grid(True)
vmin, vmax = self.viewLim.intervaly
intv = vmax-vmin
- logi = int(npy.log10(intv))
+ logi = int(np.log10(intv))
if logi==0: logi=.1
step = 10*logi
#print vmin, vmax, step, intv, math.floor(vmin), math.ceil(vmax)+1
- ticks = npy.arange(math.floor(vmin), math.ceil(vmax)+1, step)
+ ticks = np.arange(math.floor(vmin), math.ceil(vmax)+1, step)
self.set_yticks(ticks)
return pxx, freqs
@@ -5546,7 +5546,7 @@
See the PSD help for a description of the optional parameters.
Returns the tuple Pxy, freqs. Pxy is the cross spectrum (complex
- valued), and 10*npy.log10(|Pxy|) is plotted
+ valued), and 10*np.log10(|Pxy|) is plotted
Refs:
Bendat & Piersol -- Random Data: Analysis and Measurement
@@ -5561,16 +5561,16 @@
# pxy is complex
freqs += Fc
- self.plot(freqs, 10*npy.log10(npy.absolute(pxy)), **kwargs)
+ self.plot(freqs, 10*np.log10(np.absolute(pxy)), **kwargs)
self.set_xlabel('Frequency')
self.set_ylabel('Cross Spectrum Magnitude (dB)')
self.grid(True)
vmin, vmax = self.viewLim.intervaly
intv = vmax-vmin
- step = 10*int(npy.log10(intv))
+ step = 10*int(np.log10(intv))
- ticks = npy.arange(math.floor(vmin), math.ceil(vmax)+1, step)
+ ticks = np.arange(math.floor(vmin), math.ceil(vmax)+1, step)
self.set_yticks(ticks)
return pxy, freqs
@@ -5655,10 +5655,10 @@
window, noverlap)
- Z = 10*npy.log10(Pxx)
- Z = npy.flipud(Z)
+ Z = 10*np.log10(Pxx)
+ Z = np.flipud(Z)
- if xextent is None: xextent = 0, npy.amax(bins)
+ if xextent is None: xextent = 0, np.amax(bins)
xmin, xmax = xextent
freqs += Fc
extent = xmin, xmax, freqs[0], freqs[-1]
@@ -5718,9 +5718,9 @@
if marker is None and markersize is None:
if hasattr(Z, 'tocoo'):
raise TypeError, "Image mode does not support scipy.sparse arrays"
- Z = npy.asarray(Z)
+ Z = np.asarray(Z)
if precision is None: mask = Z!=0.
- else: mask = npy.absolute(Z)>precision
+ else: mask = np.absolute(Z)>precision
if 'cmap' not in kwargs:
kwargs['cmap'] = mcolors.ListedColormap(['w', 'k'], name='binary')
@@ -5735,9 +5735,9 @@
x = c.col
z = c.data
else:
- Z = npy.asarray(Z)
+ Z = np.asarray(Z)
if precision is None: mask = Z!=0.
- else: mask = npy.absolute(Z)>precision
+ else: mask = np.absolute(Z)>precision
y,x,z = mlab.get_xyz_where(mask, mask)
if marker is None: marker = 's'
if markersize is None: markersize = 10
@@ -5780,7 +5780,7 @@
Returns: an image.AxesImage instance
'''
- Z = npy.asarray(Z)
+ Z = np.asarray(Z)
nr, nc = Z.shape
extent = [-0.5, nc-0.5, nr-0.5, -0.5]
kw = {'extent': extent,
Modified: trunk/matplotlib/lib/matplotlib/axes3d.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes3d.py 2008-04-29 14:22:48 UTC (rev 5097)
+++ trunk/matplotlib/lib/matplotlib/axes3d.py 2008-04-29 15:14:36 UTC (rev 5098)
@@ -15,7 +15,7 @@
import cbook
from transforms import unit_bbox
-import numpy as npy
+import numpy as np
from colors import Normalize
import art3d
@@ -184,7 +184,7 @@
pass
def auto_scale_xyz(self, X,Y,Z=None,had_data=None):
- x,y,z = map(npy.asarray, (X,Y,Z))
+ x,y,z = map(np.asarray, (X,Y,Z))
try:
x,y = X.flat,Y.flat
if Z is not None:
@@ -274,7 +274,7 @@
point.
"""
- relev,razim = npy.pi * self.elev/180, npy.pi * self.azim/180
+ relev,razim = np.pi * self.elev/180, np.pi * self.azim/180
xmin,xmax = self.get_w_xlim()
ymin,ymax = self.get_w_ylim()
@@ -286,29 +286,29 @@
zmin,zmax)
# look into the middle of the new coordinates
- R = npy.array([0.5,0.5,0.5])
+ R = np.array([0.5,0.5,0.5])
#
- xp = R[0] + npy.cos(razim)*npy.cos(relev)*self.dist
- yp = R[1] + npy.sin(razim)*npy.cos(relev)*self.dist
- zp = R[2] + npy.sin(relev)*self.dist
+ xp = R[0] + np.cos(razim)*np.cos(relev)*self.dist
+ yp = R[1] + np.sin(razim)*np.cos(relev)*self.dist
+ zp = R[2] + np.sin(relev)*self.dist
- E = npy.array((xp, yp, zp))
+ E = np.array((xp, yp, zp))
#
self.eye = E
self.vvec = R - E
self.vvec = self.vvec / proj3d.mod(self.vvec)
- if abs(relev) > npy.pi/2:
+ if abs(relev) > np.pi/2:
# upside down
- V = npy.array((0,0,-1))
+ V = np.array((0,0,-1))
else:
- V = npy.array((0,0,1))
+ V =...
[truncated message content] |
|
From: <jd...@us...> - 2008-04-30 19:53:25
|
Revision: 5100
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5100&view=rev
Author: jdh2358
Date: 2008-04-30 12:53:10 -0700 (Wed, 30 Apr 2008)
Log Message:
-----------
refinements to the rec editors plus examples
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/mlab.py
trunk/matplotlib/lib/mpl_toolkits/gtktools.py
Added Paths:
-----------
trunk/matplotlib/examples/data/demodata.csv
trunk/matplotlib/examples/date_demo.py
trunk/matplotlib/examples/rec_edit_gtk_custom.py
trunk/matplotlib/examples/rec_edit_gtk_simple.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-04-29 21:10:44 UTC (rev 5099)
+++ trunk/matplotlib/CHANGELOG 2008-04-30 19:53:10 UTC (rev 5100)
@@ -1,3 +1,6 @@
+2008-04-30 Added some record array editing widgets for gtk -- see
+ examples/rec_edit*.py - JDH
+
2008-04-29 Fix bug in mlab.sqrtm - MM
2008-04-28 Fix bug in SVG text with Mozilla-based viewers (the symbol
Added: trunk/matplotlib/examples/data/demodata.csv
===================================================================
--- trunk/matplotlib/examples/data/demodata.csv (rev 0)
+++ trunk/matplotlib/examples/data/demodata.csv 2008-04-30 19:53:10 UTC (rev 5100)
@@ -0,0 +1,11 @@
+clientid,date,weekdays,gains,prices,up
+0,2008-04-30,Wed,-0.52458192906686452,7791404.0091921333,False
+1,2008-05-01,Thu,0.076191536201738269,3167180.7366340165,True
+2,2008-05-02,Fri,-0.86850970062880861,9589766.9613829032,False
+3,2008-05-03,Sat,-0.42701083852713395,8949415.1867596991,False
+4,2008-05-04,Sun,0.2532553652693274,937163.44375252665,True
+5,2008-05-05,Mon,-0.68151636911081892,949579.88022264629,False
+6,2008-05-06,Tue,0.0071911579626532168,7268426.906552773,True
+7,2008-05-07,Wed,0.67449747200412147,7517014.782897247,True
+8,2008-05-08,Thu,-1.1841008656818983,1920959.5423492221,False
+9,2008-05-09,Fri,-1.5803692595811152,8456240.6198725495,False
Added: trunk/matplotlib/examples/date_demo.py
===================================================================
--- trunk/matplotlib/examples/date_demo.py (rev 0)
+++ trunk/matplotlib/examples/date_demo.py 2008-04-30 19:53:10 UTC (rev 5100)
@@ -0,0 +1,14 @@
+"""
+Simple example showing how to plot a time series with datetime objects
+"""
+import datetime
+import matplotlib.pyplot as plt
+
+today = datetime.date.today()
+dates = [today+datetime.timedelta(days=i) for i in range(10)]
+
+fig = plt.figure()
+ax = fig.add_subplot(111)
+ax.plot(dates, range(10))
+fig.autofmt_xdate()
+plt.show()
Added: trunk/matplotlib/examples/rec_edit_gtk_custom.py
===================================================================
--- trunk/matplotlib/examples/rec_edit_gtk_custom.py (rev 0)
+++ trunk/matplotlib/examples/rec_edit_gtk_custom.py 2008-04-30 19:53:10 UTC (rev 5100)
@@ -0,0 +1,37 @@
+"""
+generate an editable gtk treeview widget for record arrays with custom
+formatting of the cells and show how to limit string entries to a list
+of strings
+"""
+import gtk
+import numpy as np
+import matplotlib.mlab as mlab
+import mpl_toolkits.gtktools as gtktools
+
+r = mlab.csv2rec('data/demodata.csv', converterd={'weekdays':str})
+
+
+formatd = mlab.get_formatd(r)
+formatd['date'] = mlab.FormatDate('%Y-%m-%d')
+formatd['prices'] = mlab.FormatMillions(precision=1)
+formatd['gain'] = mlab.FormatPercent(precision=2)
+
+# use a drop down combo for weekdays
+stringd = dict(weekdays=['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'])
+constant = ['clientid'] # block editing of this field
+
+
+liststore = gtktools.RecListStore(r, formatd=formatd, stringd=stringd)
+treeview = gtktools.RecTreeView(liststore, constant=constant)
+
+def mycallback(liststore, rownum, colname, oldval, newval):
+ print 'verify: old=%s, new=%s, rec=%s'%(oldval, newval, liststore.r[rownum][colname])
+
+liststore.callbacks.connect('cell_changed', mycallback)
+
+win = gtk.Window()
+win.set_title('click to edit')
+win.add(treeview)
+win.show_all()
+win.connect('delete-event', lambda *args: gtk.main_quit())
+gtk.main()
Added: trunk/matplotlib/examples/rec_edit_gtk_simple.py
===================================================================
--- trunk/matplotlib/examples/rec_edit_gtk_simple.py (rev 0)
+++ trunk/matplotlib/examples/rec_edit_gtk_simple.py 2008-04-30 19:53:10 UTC (rev 5100)
@@ -0,0 +1,15 @@
+"""
+Load a CSV file into a record array and edit it in a gtk treeview
+"""
+
+import gtk
+import numpy as np
+import matplotlib.mlab as mlab
+import mpl_toolkits.gtktools as gtktools
+
+r = mlab.csv2rec('data/demodata.csv', converterd={'weekdays':str})
+
+liststore, treeview, win = gtktools.edit_recarray(r)
+win.set_title('click to edit')
+win.connect('delete-event', lambda *args: gtk.main_quit())
+gtk.main()
Modified: trunk/matplotlib/lib/matplotlib/mlab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mlab.py 2008-04-29 21:10:44 UTC (rev 5099)
+++ trunk/matplotlib/lib/matplotlib/mlab.py 2008-04-30 19:53:10 UTC (rev 5100)
@@ -2170,7 +2170,7 @@
data type. When set to zero all rows are validated.
converterd, if not None, is a dictionary mapping column number or
- munged column name to a converter function
+ munged column name to a converter function.
names, if not None, is a list of header names. In this case, no
header will be read from the file
@@ -2256,11 +2256,18 @@
return func(val)
return newfunc
+
+ def mybool(x):
+ if x=='True': return True
+ elif x=='False': return False
+ else: raise ValueError('invalid bool')
+
dateparser = dateutil.parser.parse
mydateparser = with_default_value(dateparser, datetime.date(1,1,1))
myfloat = with_default_value(float, np.nan)
myint = with_default_value(int, -1)
mystr = with_default_value(str, '')
+ mybool = with_default_value(mybool, None)
def mydate(x):
# try and return a date object
@@ -2273,7 +2280,7 @@
def get_func(name, item, func):
# promote functions in this order
- funcmap = {myint:myfloat, myfloat:mydate, mydate:mydateparser, mydateparser:mystr}
+ funcmap = {mybool:myint,myint:myfloat, myfloat:mydate, mydate:mydateparser, mydateparser:mystr}
try: func(name, item)
except:
if func==mystr:
@@ -2294,7 +2301,7 @@
converters = None
for i, row in enumerate(reader):
if i==0:
- converters = [myint]*len(row)
+ converters = [mybool]*len(row)
if checkrows and i>checkrows:
break
#print i, len(names), len(row)
@@ -2308,6 +2315,9 @@
func = converters[j]
if len(item.strip()):
func = get_func(name, item, func)
+ else:
+ # how should we handle custom converters and defaults?
+ func = with_default_value(func, None)
converters[j] = func
return converters
@@ -2427,6 +2437,13 @@
def fromstr(self, s):
return int(s)
+class FormatBool(FormatObj):
+ def toval(self, x):
+ return x
+
+ def fromstr(self, s):
+ return bool(s)
+
class FormatPercent(FormatFloat):
def __init__(self, precision=4):
FormatFloat.__init__(self, precision, scale=100.)
@@ -2465,6 +2482,7 @@
defaultformatd = {
+ np.bool_ : FormatBool(),
np.int16 : FormatInt(),
np.int32 : FormatInt(),
np.int64 : FormatInt(),
Modified: trunk/matplotlib/lib/mpl_toolkits/gtktools.py
===================================================================
--- trunk/matplotlib/lib/mpl_toolkits/gtktools.py 2008-04-29 21:10:44 UTC (rev 5099)
+++ trunk/matplotlib/lib/mpl_toolkits/gtktools.py 2008-04-30 19:53:10 UTC (rev 5100)
@@ -37,6 +37,49 @@
import matplotlib.cbook as cbook
import matplotlib.mlab as mlab
+
+def error_message(msg, parent=None, title=None):
+ """
+ create an error message dialog with string msg. Optionally set
+ the parent widget and dialog title
+ """
+
+ dialog = gtk.MessageDialog(
+ parent = None,
+ type = gtk.MESSAGE_ERROR,
+ buttons = gtk.BUTTONS_OK,
+ message_format = msg)
+ if parent is not None:
+ dialog.set_transient_for(parent)
+ if title is not None:
+ dialog.set_title(title)
+ else:
+ dialog.set_title('Error!')
+ dialog.show()
+ dialog.run()
+ dialog.destroy()
+ return None
+
+def simple_message(msg, parent=None, title=None):
+ """
+ create a simple message dialog with string msg. Optionally set
+ the parent widget and dialog title
+ """
+ dialog = gtk.MessageDialog(
+ parent = None,
+ type = gtk.MESSAGE_INFO,
+ buttons = gtk.BUTTONS_OK,
+ message_format = msg)
+ if parent is not None:
+ dialog.set_transient_for(parent)
+ if title is not None:
+ dialog.set_title(title)
+ dialog.show()
+ dialog.run()
+ dialog.destroy()
+ return None
+
+
def gtkformat_factory(format, colnum):
"""
copy the format, perform any overrides, and attach an gtk style attrs
@@ -313,6 +356,10 @@
* r - the record array with the edited values
+ * formatd - the list of mlab.FormatObj instances, with gtk attachments
+
+ * stringd - a dict mapping dtype names to a list of valid strings for the combo drop downs
+
* callbacks - a matplotlib.cbook.CallbackRegistry. Connect to the cell_changed with
def mycallback(liststore, rownum, colname, oldval, newval):
@@ -320,85 +367,265 @@
cid = liststore.callbacks.connect('cell_changed', mycallback)
- """
- def __init__(self, r, formatd=None):
+ """
+ def __init__(self, r, formatd=None, stringd=None):
+ """
+ r is a numpy record array
+
+ formatd is a dict mapping dtype name to mlab.FormatObj instances
+
+ stringd, if not None, is a dict mapping dtype names to a list of
+ valid strings for a combo drop down editor
+ """
+
+ if stringd is None:
+ stringd = dict()
+
if formatd is None:
formatd = mlab.get_formatd(r)
+ self.stringd = stringd
self.callbacks = cbook.CallbackRegistry(['cell_changed'])
self.r = r
- gtk.ListStore.__init__(self, *([gobject.TYPE_STRING]*len(r.dtype)))
+
self.headers = r.dtype.names
self.formats = [gtkformat_factory(formatd.get(name, mlab.FormatObj()),i)
for i,name in enumerate(self.headers)]
+
+ # use the gtk attached versions
+ self.formatd = formatd = dict(zip(self.headers, self.formats))
+ types = []
+ for format in self.formats:
+ if isinstance(format, mlab.FormatBool):
+ types.append(gobject.TYPE_BOOLEAN)
+ else:
+ types.append(gobject.TYPE_STRING)
+
+ self.combod = dict()
+ if len(stringd):
+ types.extend([gobject.TYPE_INT]*len(stringd))
+
+ keys = stringd.keys()
+ keys.sort()
+
+ valid = set(r.dtype.names)
+ for ikey, key in enumerate(keys):
+ assert(key in valid)
+ combostore = gtk.ListStore(gobject.TYPE_STRING)
+ for s in stringd[key]:
+ combostore.append([s])
+ self.combod[key] = combostore, len(self.headers)+ikey
+
+
+ gtk.ListStore.__init__(self, *types)
+
for row in r:
- self.append([func.tostr(val) for func, val in zip(self.formats, row)])
+ vals = []
+ for formatter, val in zip(self.formats, row):
+ if isinstance(formatter, mlab.FormatBool):
+ vals.append(val)
+ else:
+ vals.append(formatter.tostr(val))
+ if len(stringd):
+ # todo, get correct index here?
+ vals.extend([0]*len(stringd))
+ self.append(vals)
def position_edited(self, renderer, path, newtext, position):
- self[path][position] = newtext
- format = self.formats[int(position)]
+ position = int(position)
+ format = self.formats[position]
+
rownum = int(path)
- colname = self.headers[int(position)]
+ colname = self.headers[position]
oldval = self.r[rownum][colname]
- newval = format.fromstr(newtext)
+ try: newval = format.fromstr(newtext)
+ except ValueError:
+ msg = cbook.exception_to_str('Error converting "%s"'%newtext)
+ error_message(msg, title='Error')
+ return
self.r[rownum][colname] = newval
+
+ self[path][position] = format.tostr(newval)
+
+
self.callbacks.process('cell_changed', self, rownum, colname, oldval, newval)
-def editable_recarray(r, formatd=None):
+ def position_toggled(self, cellrenderer, path, position):
+ position = int(position)
+ format = self.formats[position]
+
+ newval = not cellrenderer.get_active()
+
+ rownum = int(path)
+ colname = self.headers[position]
+ oldval = self.r[rownum][colname]
+ self.r[rownum][colname] = newval
+
+ self[path][position] = newval
+
+ self.callbacks.process('cell_changed', self, rownum, colname, oldval, newval)
+
+
+
+
+
+class RecTreeView(gtk.TreeView):
"""
- return a (gtk.TreeView, RecListStore) from record array t and
- format dictionary formatd where the keys are record array dtype
- names and the values are matplotlib.mlab.FormatObj instances
+ An editable tree view widget for record arrays
+ """
+ def __init__(self, recliststore, constant=None):
+ """
+ build a gtk.TreeView to edit a RecListStore
- Example:
+ constant, if not None, is a list of dtype names which are not editable
+ """
+ self.recliststore = recliststore
+
+ gtk.TreeView.__init__(self, recliststore)
- formatd = mlab.get_formatd(r)
- formatd['date'] = mlab.FormatDate('%Y-%m-%d')
- formatd['volume'] = mlab.FormatMillions(precision=1)
+ combostrings = set(recliststore.stringd.keys())
- treeview, liststore = gtktools.editable_recarray(r, formatd=formatd)
+
+ if constant is None:
+ constant = []
- def mycallback(liststore, rownum, colname, oldval, newval):
- print 'verify: old=%s, new=%s, rec=%s'%(oldval, newval, liststore.r[rownum][colname])
+ constant = set(constant)
- liststore.callbacks.connect('cell_changed', mycallback)
+ for i, header in enumerate(recliststore.headers):
+ formatter = recliststore.formatd[header]
+ coltype = recliststore.get_column_type(i)
+ if coltype==gobject.TYPE_BOOLEAN:
+ renderer = gtk.CellRendererToggle()
+ if header not in constant:
+ renderer.connect("toggled", recliststore.position_toggled, i)
+ renderer.set_property('activatable', True)
+ elif header in combostrings:
+ renderer = gtk.CellRendererCombo()
+ renderer.connect("edited", recliststore.position_edited, i)
+ combostore, listind = recliststore.combod[header]
+ renderer.set_property("model", combostore)
+ renderer.set_property('editable', True)
+ else:
+ renderer = gtk.CellRendererText()
+ if header not in constant:
+ renderer.connect("edited", recliststore.position_edited, i)
+ renderer.set_property('editable', True)
+
+
+ if formatter is not None:
+ renderer.set_property('xalign', formatter.xalign)
+
+
+
+ tvcol = gtk.TreeViewColumn(header)
+ self.append_column(tvcol)
+ tvcol.pack_start(renderer, True)
+
+ if coltype == gobject.TYPE_STRING:
+ tvcol.add_attribute(renderer, 'text', i)
+ if header in combostrings:
+ combostore, listind = recliststore.combod[header]
+ tvcol.add_attribute(renderer, 'text-column', listind)
+ elif coltype == gobject.TYPE_BOOLEAN:
+ tvcol.add_attribute(renderer, 'active', i)
+
+
+ if formatter is not None and formatter.cell is not None:
+ tvcol.set_cell_data_func(renderer, formatter.cell)
+
+
+
+
+ self.connect("button-release-event", self.on_selection_changed)
+ self.set_grid_lines(gtk.TREE_VIEW_GRID_LINES_BOTH)
+ self.get_selection().set_mode(gtk.SELECTION_BROWSE)
+ self.get_selection().set_select_function(self.on_select)
+
+
+ def on_select(self, *args):
+ return False
+
+ def on_selection_changed(self, *args):
+ (path, col) = self.get_cursor()
+ ren = col.get_cell_renderers()[0]
+ if isinstance(ren, gtk.CellRendererText):
+ self.set_cursor_on_cell(path, col, ren, start_editing=True)
+
+def edit_recarray(r, formatd=None, stringd=None, constant=None, autowin=True):
+ """
+ create a RecListStore and RecTreeView and return them.
+
+ If autowin is True, create a gtk.Window, insert the treeview into
+ it, and return it (return value will be (liststore, treeview, win)
+
+ See RecListStore and RecTreeView for a description of the keyword args
+ """
+
+ liststore = RecListStore(r, formatd=formatd, stringd=stringd)
+ treeview = RecTreeView(liststore, constant=constant)
+
+ if autowin:
win = gtk.Window()
- win.show()
- win.connect('destroy', lambda x: gtk.main_quit())
win.add(treeview)
- gtk.main()
+ win.show_all()
+ return liststore, treeview, win
+ else:
+ return liststore, treeview
+
+
- """
- liststore = RecListStore(r, formatd=formatd)
- treeview = gtk.TreeView()
- if formatd is None:
- formatd = mlab.get_formatd(r)
- for i, header in enumerate(liststore.headers):
- renderer = gtk.CellRendererText()
- renderer.connect("edited", liststore.position_edited, i)
- renderer.set_property('editable', True)
- formatter = gtkformat_factory(formatd.get(header), i)
+if __name__=='__main__':
- if formatter is not None:
- renderer.set_property('xalign', formatter.xalign)
+ import datetime
+ import gtk
+ import numpy as np
+ import matplotlib.mlab as mlab
+ N = 10
+ today = datetime.date.today()
+ dates = [today+datetime.timedelta(days=i) for i in range(N)] # datetimes
+ weekdays = [d.strftime('%a') for d in dates] # strings
+ gains = np.random.randn(N) # floats
+ prices = np.random.rand(N)*1e7 # big numbers
+ up = gains>0 # bools
+ clientid = range(N) # ints
- tvcol = gtk.TreeViewColumn(header)
- treeview.append_column(tvcol)
- tvcol.pack_start(renderer, True)
- tvcol.add_attribute(renderer, 'text', i)
- if formatter is not None and formatter.cell is not None:
- tvcol.set_cell_data_func(renderer, formatter.cell)
+ r = np.rec.fromarrays([clientid, dates, weekdays, gains, prices, up],
+ names='clientid,date,weekdays,gains,prices,up')
+ # some custom formatters
+ formatd = mlab.get_formatd(r)
+ formatd['date'] = mlab.FormatDate('%Y-%m-%d')
+ formatd['prices'] = mlab.FormatMillions(precision=1)
+ formatd['gain'] = mlab.FormatPercent(precision=2)
- treeview.set_model(liststore)
- treeview.show()
- treeview.set_grid_lines(gtk.TREE_VIEW_GRID_LINES_BOTH)
+ # use a drop down combo for weekdays
+ stringd = dict(weekdays=['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'])
+ constant = ['clientid'] # block editing of this field
- return treeview, liststore
+ liststore = RecListStore(r, formatd=formatd, stringd=stringd)
+ treeview = RecTreeView(liststore, constant=constant)
+
+ def mycallback(liststore, rownum, colname, oldval, newval):
+ print 'verify: old=%s, new=%s, rec=%s'%(oldval, newval, liststore.r[rownum][colname])
+
+ liststore.callbacks.connect('cell_changed', mycallback)
+
+ win = gtk.Window()
+ win.set_title('with full customization')
+ win.add(treeview)
+ win.show_all()
+
+ # or you just use the defaults
+ r2 = r.copy()
+ ls, tv, win2 = edit_recarray(r2)
+ win2.set_title('with all defaults')
+
+ gtk.main()
+
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-05-01 18:26:57
|
Revision: 5102
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5102&view=rev
Author: mdboom
Date: 2008-05-01 11:24:54 -0700 (Thu, 01 May 2008)
Log Message:
-----------
Merged revisions 5091-5101 via svnmerge from
https://matplotlib.svn.sf.net/svnroot/matplotlib/branches/v0_91_maint
........
r5095 | mmetz_bn | 2008-04-29 09:21:48 -0400 (Tue, 29 Apr 2008) | 1 line
fixed bug in mlab.sqrtm; numpy.linalg.eig behaves different than Numeric did
........
r5101 | mdboom | 2008-05-01 14:20:13 -0400 (Thu, 01 May 2008) | 2 lines
Include stdio.h for gcc 4.3
........
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/mlab.py
trunk/matplotlib/ttconv/truetype.h
Property Changed:
----------------
trunk/matplotlib/
Property changes on: trunk/matplotlib
___________________________________________________________________
Name: svnmerge-integrated
- /branches/v0_91_maint:1-5090
+ /branches/v0_91_maint:1-5101
Modified: trunk/matplotlib/lib/matplotlib/mlab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mlab.py 2008-05-01 18:20:13 UTC (rev 5101)
+++ trunk/matplotlib/lib/matplotlib/mlab.py 2008-05-01 18:24:54 UTC (rev 5102)
@@ -2261,7 +2261,7 @@
if x=='True': return True
elif x=='False': return False
else: raise ValueError('invalid bool')
-
+
dateparser = dateutil.parser.parse
mydateparser = with_default_value(dateparser, datetime.date(1,1,1))
myfloat = with_default_value(float, np.nan)
Modified: trunk/matplotlib/ttconv/truetype.h
===================================================================
--- trunk/matplotlib/ttconv/truetype.h 2008-05-01 18:20:13 UTC (rev 5101)
+++ trunk/matplotlib/ttconv/truetype.h 2008-05-01 18:24:54 UTC (rev 5102)
@@ -4,6 +4,8 @@
* Michael Droettboom
*/
+#include <stdio.h>
+
/*
** ~ppr/src/include/typetype.h
**
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-05-02 17:00:22
|
Revision: 5106
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5106&view=rev
Author: mdboom
Date: 2008-05-02 10:00:01 -0700 (Fri, 02 May 2008)
Log Message:
-----------
Merged revisions 5102-5105 via svnmerge from
https://matplotlib.svn.sf.net/svnroot/matplotlib/branches/v0_91_maint
........
r5104 | mdboom | 2008-05-02 12:55:59 -0400 (Fri, 02 May 2008) | 3 lines
Update _subprocess.c from upstream Python 2.5.2 to get a few memory
and reference-counting-related bugfixes. See bug 1949978. - MGD
........
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/src/_subprocess.c
Property Changed:
----------------
trunk/matplotlib/
Property changes on: trunk/matplotlib
___________________________________________________________________
Name: svnmerge-integrated
- /branches/v0_91_maint:1-5101
+ /branches/v0_91_maint:1-5105
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-05-02 16:57:45 UTC (rev 5105)
+++ trunk/matplotlib/CHANGELOG 2008-05-02 17:00:01 UTC (rev 5106)
@@ -1,3 +1,7 @@
+2008-05-02 Update _subprocess.c from upstream Python 2.5.2 to get a
+ few memory and reference-counting-related bugfixes. See
+ bug 1949978. - MGD
+
2008-04-30 Added some record array editing widgets for gtk -- see
examples/rec_edit*.py - JDH
Modified: trunk/matplotlib/src/_subprocess.c
===================================================================
--- trunk/matplotlib/src/_subprocess.c 2008-05-02 16:57:45 UTC (rev 5105)
+++ trunk/matplotlib/src/_subprocess.c 2008-05-02 17:00:01 UTC (rev 5106)
@@ -104,12 +104,12 @@
{
if (self->handle != INVALID_HANDLE_VALUE)
CloseHandle(self->handle);
- PyMem_DEL(self);
+ PyObject_FREE(self);
}
static PyMethodDef sp_handle_methods[] = {
- {"Detach", (PyCFunction) sp_handle_detach, 1},
- {"Close", (PyCFunction) sp_handle_close, 1},
+ {"Detach", (PyCFunction) sp_handle_detach, METH_VARARGS},
+ {"Close", (PyCFunction) sp_handle_close, METH_VARARGS},
{NULL, NULL}
};
@@ -250,19 +250,23 @@
getint(PyObject* obj, char* name)
{
PyObject* value;
+ int ret;
value = PyObject_GetAttrString(obj, name);
if (! value) {
PyErr_Clear(); /* FIXME: propagate error? */
return 0;
}
- return (int) PyInt_AsLong(value);
+ ret = (int) PyInt_AsLong(value);
+ Py_DECREF(value);
+ return ret;
}
static HANDLE
gethandle(PyObject* obj, char* name)
{
sp_handle_object* value;
+ HANDLE ret;
value = (sp_handle_object*) PyObject_GetAttrString(obj, name);
if (! value) {
@@ -270,8 +274,11 @@
return NULL;
}
if (value->ob_type != &sp_handle_type)
- return NULL;
- return value->handle;
+ ret = NULL;
+ else
+ ret = value->handle;
+ Py_DECREF(value);
+ return ret;
}
static PyObject*
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-05-02 17:21:34
|
Revision: 5109
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5109&view=rev
Author: mdboom
Date: 2008-05-02 10:21:27 -0700 (Fri, 02 May 2008)
Log Message:
-----------
Merged revisions 5106-5108 via svnmerge from
https://matplotlib.svn.sf.net/svnroot/matplotlib/branches/v0_91_maint
........
r5107 | mdboom | 2008-05-02 13:05:19 -0400 (Fri, 02 May 2008) | 2 lines
Don't call sys.exit() when pyemf is not found.
........
r5108 | mdboom | 2008-05-02 13:20:38 -0400 (Fri, 02 May 2008) | 2 lines
Fix build error with PyQt <= 3.14 [1851364] - MGD
........
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/backends/backend_emf.py
trunk/matplotlib/setupext.py
Property Changed:
----------------
trunk/matplotlib/
Property changes on: trunk/matplotlib
___________________________________________________________________
Name: svnmerge-integrated
- /branches/v0_91_maint:1-5105
+ /branches/v0_91_maint:1-5108
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-05-02 17:20:38 UTC (rev 5108)
+++ trunk/matplotlib/CHANGELOG 2008-05-02 17:21:27 UTC (rev 5109)
@@ -1,3 +1,9 @@
+2008-05-02 On PyQt <= 3.14 there is no way to determine the underlying
+ Qt version. [1851364] - MGD
+
+2008-05-02 Don't call sys.exit() when pyemf is not found [1924199] -
+ MGD
+
2008-05-02 Update _subprocess.c from upstream Python 2.5.2 to get a
few memory and reference-counting-related bugfixes. See
bug 1949978. - MGD
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_emf.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_emf.py 2008-05-02 17:20:38 UTC (rev 5108)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_emf.py 2008-05-02 17:21:27 UTC (rev 5109)
@@ -8,9 +8,7 @@
try:
import pyemf
except ImportError:
- import sys
- print >>sys.stderr, 'You must first install pyemf from http://pyemf.sf.net'
- sys.exit()
+ raise ImportError('You must first install pyemf from http://pyemf.sf.net')
import os,sys,math,re
@@ -600,7 +598,7 @@
pass
filetypes = {'emf': 'Enhanced Metafile'}
-
+
def print_emf(self, filename, dpi=300, **kwargs):
width, height = self.figure.get_size_inches()
renderer = RendererEMF(filename,width,height,dpi)
@@ -609,7 +607,7 @@
def get_default_filetype(self):
return 'emf'
-
+
class FigureManagerEMF(FigureManagerBase):
"""
Wrap everything up into a window for the pylab interface
Modified: trunk/matplotlib/setupext.py
===================================================================
--- trunk/matplotlib/setupext.py 2008-05-02 17:20:38 UTC (rev 5108)
+++ trunk/matplotlib/setupext.py 2008-05-02 17:21:27 UTC (rev 5109)
@@ -351,8 +351,13 @@
print_status("Qt", "no")
return False
else:
+ try:
+ qt_version = pyqtconfig.Configuration().qt_version
+ qt_version = convert_qt_version(qt_version)
+ except AttributeError:
+ qt_version = "<unknown>"
print_status("Qt", "Qt: %s, PyQt: %s" %
- (convert_qt_version(pyqtconfig.Configuration().qt_version),
+ (qt_version,
pyqtconfig.Configuration().pyqt_version_str))
return True
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mme...@us...> - 2008-05-02 21:52:17
|
Revision: 5110
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5110&view=rev
Author: mmetz_bn
Date: 2008-05-02 14:52:05 -0700 (Fri, 02 May 2008)
Log Message:
-----------
Add step histograms
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/axes.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-05-02 17:21:27 UTC (rev 5109)
+++ trunk/matplotlib/CHANGELOG 2008-05-02 21:52:05 UTC (rev 5110)
@@ -1,3 +1,5 @@
+2008-05-02 Added step histograms, based on patch by Erik Tollerud. - MM
+
2008-05-02 On PyQt <= 3.14 there is no way to determine the underlying
Qt version. [1851364] - MGD
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2008-05-02 17:21:27 UTC (rev 5109)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2008-05-02 21:52:05 UTC (rev 5110)
@@ -5406,11 +5406,11 @@
#### Data analysis
- def hist(self, x, bins=10, normed=0, bottom=None,
+ def hist(self, x, bins=10, normed=0, bottom=None, histtype='bar',
align='edge', orientation='vertical', width=None,
log=False, **kwargs):
"""
- HIST(x, bins=10, normed=0, bottom=None,
+ HIST(x, bins=10, normed=0, bottom=None, histtype='bar',
align='edge', orientation='vertical', width=None,
log=False, **kwargs)
@@ -5429,6 +5429,10 @@
pdf, bins, patches = ax.hist(...)
print np.trapz(pdf, bins)
+ histtype = 'bar' | 'step'. The type of histogram to draw.
+ 'bar' is a traditional bar-type histogram, 'step' generates
+ a lineplot.
+
align = 'edge' | 'center'. Interprets bins either as edge
or center values
@@ -5436,7 +5440,7 @@
will be used and the "bottom" kwarg will be the left edges.
width: the width of the bars. If None, automatically compute
- the width.
+ the width. Ignored for 'step' histtype.
log: if True, the histogram axis will be set to a log scale
@@ -5446,15 +5450,44 @@
"""
if not self._hold: self.cla()
n, bins = np.histogram(x, bins, range=None, normed=normed)
- if width is None: width = 0.9*(bins[1]-bins[0])
- if orientation == 'horizontal':
- patches = self.barh(bins, n, height=width, left=bottom,
- align=align, log=log)
- elif orientation == 'vertical':
- patches = self.bar(bins, n, width=width, bottom=bottom,
- align=align, log=log)
+ if width is None:
+ if histtype == 'bar':
+ width = 0.9*(bins[1]-bins[0])
+ elif histtype == 'step':
+ width = bins[1]-bins[0]
+ else:
+ raise ValueError, 'invalid histtype: %s' % histtype
+
+ if histtype == 'bar':
+ if orientation == 'horizontal':
+ patches = self.barh(bins, n, height=width, left=bottom,
+ align=align, log=log)
+ elif orientation == 'vertical':
+ patches = self.bar(bins, n, width=width, bottom=bottom,
+ align=align, log=log)
+ else:
+ raise ValueError, 'invalid orientation: %s' % orientation
+
+ elif histtype == 'step':
+ binedges = np.concatenate((bins,bins[-1:]+width))
+ if align == 'center':
+ binedges -= 0.5*width
+ x = np.zeros( 2*len(binedges), np.float_ )
+ y = np.zeros( 2*len(binedges), np.float_ )
+
+ x[0:-1:2],x[1::2] = binedges, binedges
+ y[1:-1:2],y[2::2] = n, n
+
+ if orientation == 'horizontal':
+ x,y = y,x
+ elif orientation == 'vertical':
+ pass
+ else:
+ raise ValueError, 'invalid orientation: %s' % orientation
+ patches = self.fill(x,y)
else:
- raise ValueError, 'invalid orientation: %s' % orientation
+ raise ValueError, 'invalid histtype: %s' % histtype
+
for p in patches:
p.update(kwargs)
return n, bins, cbook.silent_list('Patch', patches)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-05-06 15:42:29
|
Revision: 5122
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5122&view=rev
Author: mdboom
Date: 2008-05-06 08:42:16 -0700 (Tue, 06 May 2008)
Log Message:
-----------
Merged revisions 5109-5121 via svnmerge from
https://matplotlib.svn.sf.net/svnroot/matplotlib/branches/v0_91_maint
........
r5119 | jdh2358 | 2008-05-06 10:34:32 -0400 (Tue, 06 May 2008) | 1 line
use pngs for wx icons
........
r5120 | mdboom | 2008-05-06 11:25:04 -0400 (Tue, 06 May 2008) | 2 lines
Fix blitting in Qt backends (which need ARGB, not RGBA)
........
r5121 | mdboom | 2008-05-06 11:30:09 -0400 (Tue, 06 May 2008) | 2 lines
Forgot CHANGELOG
........
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/backends/backend_qt4agg.py
trunk/matplotlib/lib/matplotlib/backends/backend_qtagg.py
trunk/matplotlib/src/_backend_agg.cpp
trunk/matplotlib/src/_backend_agg.h
Property Changed:
----------------
trunk/matplotlib/
Property changes on: trunk/matplotlib
___________________________________________________________________
Name: svnmerge-integrated
- /branches/v0_91_maint:1-5108
+ /branches/v0_91_maint:1-5121
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-05-06 15:30:09 UTC (rev 5121)
+++ trunk/matplotlib/CHANGELOG 2008-05-06 15:42:16 UTC (rev 5122)
@@ -1,3 +1,5 @@
+2008-05-06 Fix strange colors when blitting in QtAgg and Qt4Agg - MGD
+
2008-05-05 pass notify_axes_change to the figure's add_axobserver
in the qt backends, like we do for the other backends.
Thanks Glenn Jones for the report - DSD
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_qt4agg.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_qt4agg.py 2008-05-06 15:30:09 UTC (rev 5121)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_qt4agg.py 2008-05-06 15:42:16 UTC (rev 5122)
@@ -114,7 +114,7 @@
h = int(t) - int(b)
t = int(b) + h
reg = self.copy_from_bbox(bbox)
- stringBuffer = reg.to_string()
+ stringBuffer = reg.to_string_argb()
qImage = QtGui.QImage(stringBuffer, w, h, QtGui.QImage.Format_ARGB32)
pixmap = QtGui.QPixmap.fromImage(qImage)
p = QtGui.QPainter( self )
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_qtagg.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_qtagg.py 2008-05-06 15:30:09 UTC (rev 5121)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_qtagg.py 2008-05-06 15:42:16 UTC (rev 5122)
@@ -119,7 +119,7 @@
w = int(r) - int(l)
h = int(t) - int(b)
reg = self.copy_from_bbox(bbox)
- stringBuffer = reg.to_string()
+ stringBuffer = reg.to_string_argb()
qImage = qt.QImage(stringBuffer, w, h, 32, None, 0, qt.QImage.IgnoreEndian)
self.pixmap.convertFromImage(qImage, qt.QPixmap.Color)
p.drawPixmap(qt.QPoint(l, self.renderer.height-t), self.pixmap)
Modified: trunk/matplotlib/src/_backend_agg.cpp
===================================================================
--- trunk/matplotlib/src/_backend_agg.cpp 2008-05-06 15:30:09 UTC (rev 5121)
+++ trunk/matplotlib/src/_backend_agg.cpp 2008-05-06 15:42:16 UTC (rev 5122)
@@ -90,6 +90,34 @@
return Py::String(PyString_FromStringAndSize((const char*)data, height*stride), true);
}
+Py::Object BufferRegion::to_string_argb(const Py::Tuple &args) {
+ // owned=true to prevent memory leak
+ Py_ssize_t length;
+ char* pix;
+ char* begin;
+ char* end;
+ char tmp;
+
+ PyObject* str = PyString_FromStringAndSize((const char*)data, height*stride);
+ if (PyString_AsStringAndSize(str, &begin, &length)) {
+ throw Py::TypeError("Could not create memory for blit");
+ }
+
+ pix = begin;
+ end = begin + (height * stride);
+ while (pix != end) {
+ // Convert rgba to argb
+ tmp = pix[3];
+ pix[3] = pix[2];
+ pix[2] = pix[1];
+ pix[1] = pix[0];
+ pix[0] = pix[3];
+ pix += 4;
+ }
+
+ return Py::String(str, true);
+}
+
GCAgg::GCAgg(const Py::Object &gc, double dpi) :
dpi(dpi), isaa(true), linewidth(1.0), alpha(1.0),
dashOffset(0.0)
@@ -210,7 +238,6 @@
}
}
-
const size_t
RendererAgg::PIXELS_PER_INCH(96);
@@ -1707,6 +1734,8 @@
add_varargs_method("to_string", &BufferRegion::to_string,
"to_string()");
+ add_varargs_method("to_string_argb", &BufferRegion::to_string_argb,
+ "to_string_argb()");
}
Modified: trunk/matplotlib/src/_backend_agg.h
===================================================================
--- trunk/matplotlib/src/_backend_agg.h 2008-05-06 15:30:09 UTC (rev 5121)
+++ trunk/matplotlib/src/_backend_agg.h 2008-05-06 15:42:16 UTC (rev 5122)
@@ -103,6 +103,7 @@
bool freemem;
Py::Object to_string(const Py::Tuple &args);
+ Py::Object to_string_argb(const Py::Tuple &args);
static void init_type(void);
virtual ~BufferRegion() {
@@ -138,7 +139,7 @@
double dashOffset;
dash_t dashes;
- protected:
+protected:
agg::rgba get_color(const Py::Object& gc);
double points_to_pixels( const Py::Object& points);
void _set_linecap(const Py::Object& gc) ;
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-05-06 19:04:08
|
Revision: 5124
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5124&view=rev
Author: mdboom
Date: 2008-05-06 12:03:54 -0700 (Tue, 06 May 2008)
Log Message:
-----------
Merged revisions 5122-5123 via svnmerge from
https://matplotlib.svn.sf.net/svnroot/matplotlib/branches/v0_91_maint
........
r5123 | mdboom | 2008-05-06 14:56:47 -0400 (Tue, 06 May 2008) | 2 lines
Fixing bugs in recent changes to Qt blitting.
........
Modified Paths:
--------------
trunk/matplotlib/src/_backend_agg.cpp
Property Changed:
----------------
trunk/matplotlib/
Property changes on: trunk/matplotlib
___________________________________________________________________
Name: svnmerge-integrated
- /branches/v0_91_maint:1-5121
+ /branches/v0_91_maint:1-5123
Modified: trunk/matplotlib/src/_backend_agg.cpp
===================================================================
--- trunk/matplotlib/src/_backend_agg.cpp 2008-05-06 18:56:47 UTC (rev 5123)
+++ trunk/matplotlib/src/_backend_agg.cpp 2008-05-06 19:03:54 UTC (rev 5124)
@@ -93,26 +93,28 @@
Py::Object BufferRegion::to_string_argb(const Py::Tuple &args) {
// owned=true to prevent memory leak
Py_ssize_t length;
- char* pix;
- char* begin;
- char* end;
- char tmp;
+ unsigned char* pix;
+ unsigned char* begin;
+ unsigned char* end;
+ unsigned char tmp;
+ size_t i, j;
PyObject* str = PyString_FromStringAndSize((const char*)data, height*stride);
- if (PyString_AsStringAndSize(str, &begin, &length)) {
+ if (PyString_AsStringAndSize(str, (char**)&begin, &length)) {
throw Py::TypeError("Could not create memory for blit");
}
pix = begin;
end = begin + (height * stride);
- while (pix != end) {
- // Convert rgba to argb
- tmp = pix[3];
- pix[3] = pix[2];
- pix[2] = pix[1];
- pix[1] = pix[0];
- pix[0] = pix[3];
- pix += 4;
+ for (i = 0; i < (size_t)height; ++i) {
+ pix = begin + i * stride;
+ for (j = 0; j < (size_t)width; ++j) {
+ // Convert rgba to argb
+ tmp = pix[2];
+ pix[2] = pix[0];
+ pix[0] = tmp;
+ pix += 4;
+ }
}
return Py::String(str, true);
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mme...@us...> - 2008-05-07 10:41:46
|
Revision: 5126
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5126&view=rev
Author: mmetz_bn
Date: 2008-05-07 03:41:42 -0700 (Wed, 07 May 2008)
Log Message:
-----------
Switched to future numpy histogram semantic in hist
Modified Paths:
--------------
trunk/matplotlib/API_CHANGES
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/axes.py
Modified: trunk/matplotlib/API_CHANGES
===================================================================
--- trunk/matplotlib/API_CHANGES 2008-05-07 02:12:31 UTC (rev 5125)
+++ trunk/matplotlib/API_CHANGES 2008-05-07 10:41:42 UTC (rev 5126)
@@ -1,3 +1,9 @@
+ In numpy 1.0 bins are specified by the left edges only. The axes
+ method "hist" now uses future numpy 1.3 semantic for histograms.
+ Providing binedges, the last value gives the upper-right edge now,
+ which was implicitly set to +infinity in numpy 1.0. This also means
+ that the last bin doesn't contain upper outliers any more by default.
+
New axes method and pyplot function, hexbin, is an alternative
to scatter for large datasets. It makes something like a
pcolor of a 2-D histogram, but uses hexagonal bins.
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-05-07 02:12:31 UTC (rev 5125)
+++ trunk/matplotlib/CHANGELOG 2008-05-07 10:41:42 UTC (rev 5126)
@@ -1,3 +1,5 @@
+2008-05-07 Switched to future numpy histogram semantic in hist - MM
+
2008-05-06 Fix strange colors when blitting in QtAgg and Qt4Agg - MGD
2008-05-05 pass notify_axes_change to the figure's add_axobserver
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2008-05-07 02:12:31 UTC (rev 5125)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2008-05-07 10:41:42 UTC (rev 5126)
@@ -5406,11 +5406,11 @@
#### Data analysis
- def hist(self, x, bins=10, normed=0, bottom=None, histtype='bar',
+ def hist(self, x, bins=10, normed=False, bottom=None, histtype='bar',
align='edge', orientation='vertical', width=None,
log=False, **kwargs):
"""
- HIST(x, bins=10, normed=0, bottom=None, histtype='bar',
+ HIST(x, bins=10, normed=False, bottom=None, histtype='bar',
align='edge', orientation='vertical', width=None,
log=False, **kwargs)
@@ -5449,40 +5449,35 @@
%(Rectangle)s
"""
if not self._hold: self.cla()
- n, bins = np.histogram(x, bins, range=None, normed=normed)
- if width is None:
- if histtype == 'bar':
- width = 0.9*(bins[1]-bins[0])
- elif histtype == 'step':
- width = bins[1]-bins[0]
- else:
- raise ValueError, 'invalid histtype: %s' % histtype
+ n, bins = np.histogram(x, bins, range=None,
+ normed=bool(normed), new=True)
if histtype == 'bar':
+ if width is None:
+ width = 0.9*(bins[1]-bins[0])
+
if orientation == 'horizontal':
- patches = self.barh(bins, n, height=width, left=bottom,
+ patches = self.barh(bins[:-1], n, height=width, left=bottom,
align=align, log=log)
elif orientation == 'vertical':
- patches = self.bar(bins, n, width=width, bottom=bottom,
+ patches = self.bar(bins[:-1], n, width=width, bottom=bottom,
align=align, log=log)
else:
raise ValueError, 'invalid orientation: %s' % orientation
elif histtype == 'step':
- binedges = np.concatenate((bins,bins[-1:]+width))
+ x = np.zeros( 2*len(bins), np.float_ )
+ y = np.zeros( 2*len(bins), np.float_ )
+
+ x[0::2], x[1::2] = bins, bins
+ y[1:-1:2], y[2::2] = n, n
+
if align == 'center':
- binedges -= 0.5*width
- x = np.zeros( 2*len(binedges), np.float_ )
- y = np.zeros( 2*len(binedges), np.float_ )
+ x -= 0.5*(bins[1]-bins[0])
- x[0:-1:2],x[1::2] = binedges, binedges
- y[1:-1:2],y[2::2] = n, n
-
if orientation == 'horizontal':
x,y = y,x
- elif orientation == 'vertical':
- pass
- else:
+ elif orientation != 'vertical':
raise ValueError, 'invalid orientation: %s' % orientation
patches = self.fill(x,y)
else:
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-05-07 19:41:39
|
Revision: 5129
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5129&view=rev
Author: mdboom
Date: 2008-05-07 12:41:26 -0700 (Wed, 07 May 2008)
Log Message:
-----------
Merged revisions 5124-5128 via svnmerge from
https://matplotlib.svn.sf.net/svnroot/matplotlib/branches/v0_91_maint
........
r5128 | mdboom | 2008-05-07 15:39:58 -0400 (Wed, 07 May 2008) | 2 lines
[ 1922569 ] gcc 4.3 C++ compilation errors (Thanks, Jef Spaleta)
........
Modified Paths:
--------------
trunk/matplotlib/ttconv/pprdrv.h
trunk/matplotlib/ttconv/pprdrv_tt.cpp
trunk/matplotlib/ttconv/pprdrv_tt2.cpp
trunk/matplotlib/ttconv/ttutil.cpp
Property Changed:
----------------
trunk/matplotlib/
Property changes on: trunk/matplotlib
___________________________________________________________________
Name: svnmerge-integrated
- /branches/v0_91_maint:1-5123
+ /branches/v0_91_maint:1-5128
Modified: trunk/matplotlib/ttconv/pprdrv.h
===================================================================
--- trunk/matplotlib/ttconv/pprdrv.h 2008-05-07 19:39:58 UTC (rev 5128)
+++ trunk/matplotlib/ttconv/pprdrv.h 2008-05-07 19:41:26 UTC (rev 5129)
@@ -20,10 +20,10 @@
*/
#include <vector>
-#include <assert.h>
+#include <cassert>
/*
- * Encapsulates all of the output to write to an arbitrary output
+ * Encapsulates all of the output to write to an arbitrary output
* function. This both removes the hardcoding of output to go to stdout
* and makes output thread-safe. Michael Droettboom [06-07-07]
*/
@@ -36,7 +36,7 @@
public:
TTStreamWriter() { }
virtual ~TTStreamWriter() { }
-
+
virtual void write(const char*) = 0;
virtual void printf(const char* format, ...);
@@ -73,9 +73,9 @@
const char* getMessage() { return message; }
};
-/*
+/*
** No debug code will be included if this
-** is not defined:
+** is not defined:
*/
/* #define DEBUG 1 */
Modified: trunk/matplotlib/ttconv/pprdrv_tt.cpp
===================================================================
--- trunk/matplotlib/ttconv/pprdrv_tt.cpp 2008-05-07 19:39:58 UTC (rev 5128)
+++ trunk/matplotlib/ttconv/pprdrv_tt.cpp 2008-05-07 19:41:26 UTC (rev 5129)
@@ -23,9 +23,9 @@
*/
#include "global_defines.h"
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
#include "pprdrv.h"
#include "truetype.h"
#include <sstream>
Modified: trunk/matplotlib/ttconv/pprdrv_tt2.cpp
===================================================================
--- trunk/matplotlib/ttconv/pprdrv_tt2.cpp 2008-05-07 19:39:58 UTC (rev 5128)
+++ trunk/matplotlib/ttconv/pprdrv_tt2.cpp 2008-05-07 19:41:26 UTC (rev 5129)
@@ -16,14 +16,14 @@
** documentation. This software is provided "as is" without express or
** implied warranty.
**
-** TrueType font support. These functions allow PPR to generate
+** TrueType font support. These functions allow PPR to generate
** PostScript fonts from Microsoft compatible TrueType font files.
**
** The functions in this file do most of the work to convert a
** TrueType font to a type 3 PostScript font.
**
** Most of the material in this file is derived from a program called
-** "ttf2ps" which L. S. Ng posted to the usenet news group
+** "ttf2ps" which L. S. Ng posted to the usenet news group
** "comp.sources.postscript". The author did not provide a copyright
** notice or indicate any restrictions on use.
**
@@ -31,11 +31,11 @@
*/
#include "global_defines.h"
-#include <math.h>
-#include <stdlib.h>
-#include <string.h>
-#include <memory.h>
-#include "pprdrv.h"
+#include <cmath>
+#include <cstdlib>
+#include <cstring>
+#include <memory>
+#include "pprdrv.h"
#include "truetype.h"
#include <algorithm>
#include <stack>
@@ -59,7 +59,7 @@
int *ctrset; /* in contour index followed by out contour index */
int stack_depth; /* A book-keeping variable for keeping track of the depth of the PS stack */
-
+
bool pdf_mode;
void load_char(TTFONT* font, BYTE *glyph);
@@ -88,7 +88,7 @@
/*
** This routine is used to break the character
-** procedure up into a number of smaller
+** procedure up into a number of smaller
** procedures. This is necessary so as not to
** overflow the stack on certain level 1 interpreters.
**
@@ -131,21 +131,21 @@
** Find the area of a contour?
*/
double area(FWord *x, FWord *y, int n)
- {
+ {
int i;
double sum;
-
+
sum=x[n-1]*y[0]-y[n-1]*x[0];
for (i=0; i<=n-2; i++) sum += x[i]*y[i+1] - y[i]*x[i+1];
return sum;
- }
+ }
/*
** We call this routine to emmit the PostScript code
** for the character we have loaded with load_char().
*/
void GlyphToType3::PSConvert(TTStreamWriter& stream)
- {
+ {
int i,j,k,fst,start_offpt;
int end_offpt = 0;
@@ -162,10 +162,10 @@
check_ctr[0]=1;
area_ctr[0]=area(xcoor, ycoor, epts_ctr[0]+1);
- for (i=1; i<num_ctr; i++)
+ for (i=1; i<num_ctr; i++)
area_ctr[i]=area(xcoor+epts_ctr[i-1]+1, ycoor+epts_ctr[i-1]+1, epts_ctr[i]-epts_ctr[i-1]);
- for (i=0; i<num_ctr; i++)
+ for (i=0; i<num_ctr; i++)
{
if (area_ctr[i]>0)
{
@@ -254,26 +254,26 @@
{
int j;
- for(j=0; j<num_ctr; j++)
+ for(j=0; j<num_ctr; j++)
if (check_ctr[j]==0 && area_ctr[j] < 0) {
check_ctr[j]=1;
return j;
}
-
+
return NOMOREOUTCTR;
} /* end of nextoutctr() */
int GlyphToType3::nextinctr(int co, int ci)
{
int j;
-
+
for(j=0; j<num_ctr; j++)
- if (ctrset[2*j+1]==co)
+ if (ctrset[2*j+1]==co)
if (check_ctr[ctrset[2*j]]==0) {
check_ctr[ctrset[2*j]]=1;
return ctrset[2*j];
}
-
+
return NOMOREINCTR;
}
@@ -285,8 +285,8 @@
int k = 0; /* !!! is this right? */
int co;
double a, a1=0;
-
- for (co=0; co < num_ctr; co++)
+
+ for (co=0; co < num_ctr; co++)
{
if(area_ctr[co] < 0)
{
@@ -303,7 +303,7 @@
}
}
}
-
+
return k;
} /* end of nearout() */
@@ -312,14 +312,14 @@
int i, j, start, end;
double r1, r2, a;
FWord xi[3], yi[3];
-
+
j=start=(co==0)?0:(epts_ctr[co-1]+1);
end=epts_ctr[co];
i=(ci==0)?0:(epts_ctr[ci-1]+1);
xi[0] = xcoor[i];
yi[0] = ycoor[i];
r1=sqr(xcoor[start] - xi[0]) + sqr(ycoor[start] - yi[0]);
-
+
for (i=start; i<=end; i++) {
r2 = sqr(xcoor[i] - xi[0])+sqr(ycoor[i] - yi[0]);
if (r2 < r1) {
@@ -331,17 +331,17 @@
if (j==start) { xi[1]=xcoor[end]; yi[1]=ycoor[end]; }
if (j==end) { xi[2]=xcoor[start]; yi[2]=ycoor[start]; }
a=area(xi, yi, 3);
-
+
return a;
} /* end of intest() */
void GlyphToType3::PSMoveto(TTStreamWriter& stream, int x, int y) {
- stream.printf(pdf_mode ? "%d %d m\n" : "%d %d _m\n",
+ stream.printf(pdf_mode ? "%d %d m\n" : "%d %d _m\n",
x, y);
}
void GlyphToType3::PSLineto(TTStreamWriter& stream, int x, int y) {
- stream.printf(pdf_mode ? "%d %d l\n" : "%d %d _l\n",
+ stream.printf(pdf_mode ? "%d %d l\n" : "%d %d _l\n",
x, y);
}
@@ -369,8 +369,8 @@
cx[2] = (sx[2]+2*sx[1])/3;
cy[2] = (sy[2]+2*sy[1])/3;
- stream.printf(pdf_mode ?
- "%d %d %d %d %d %d c\n" :
+ stream.printf(pdf_mode ?
+ "%d %d %d %d %d %d c\n" :
"%d %d %d %d %d %d _c\n",
(int)cx[1], (int)cy[1], (int)cx[2], (int)cy[2],
(int)cx[3], (int)cy[3]);
@@ -513,22 +513,22 @@
USHORT yscale;
USHORT scale01;
USHORT scale10;
-
+
/* Once around this loop for each component. */
do {
- flags = getUSHORT(glyph); /* read the flags word */
+ flags = getUSHORT(glyph); /* read the flags word */
glyph += 2;
glyphIndex = getUSHORT(glyph); /* read the glyphindex word */
glyph += 2;
-
+
if(flags & ARG_1_AND_2_ARE_WORDS)
{ /* The tt spec. seems to say these are signed. */
arg1 = getSHORT(glyph);
glyph += 2;
arg2 = getSHORT(glyph);
glyph += 2;
- }
+ }
else /* The tt spec. does not clearly indicate */
{ /* whether these values are signed or not. */
arg1 = *(glyph++);
@@ -538,7 +538,7 @@
if(flags & WE_HAVE_A_SCALE)
{
xscale = yscale = getUSHORT(glyph);
- glyph += 2;
+ glyph += 2;
scale01 = scale10 = 0;
}
else if(flags & WE_HAVE_AN_X_AND_Y_SCALE)
@@ -548,7 +548,7 @@
yscale = getUSHORT(glyph);
glyph += 2;
scale01 = scale10 = 0;
- }
+ }
else if(flags & WE_HAVE_A_TWO_BY_TWO)
{
xscale = getUSHORT(glyph);
@@ -597,20 +597,20 @@
{
stream.printf("%% unimplemented shift, arg1=%d, arg2=%d\n",arg1,arg2);
}
-
+
/* Invoke the CharStrings procedure to print the component. */
stream.printf("false CharStrings /%s get exec\n",
ttfont_CharStrings_getname(font,glyphIndex));
-
+
/* If we translated the coordinate system, */
/* put it back the way it was. */
if( flags & ARGS_ARE_XY_VALUES && (arg1 != 0 || arg2 != 0) ) {
stream.puts("grestore ");
}
}
-
+
} while(flags & MORE_COMPONENTS);
-
+
} /* end of do_composite() */
/*
@@ -676,7 +676,7 @@
llx = getFWord(glyph + 2);
lly = getFWord(glyph + 4);
urx = getFWord(glyph + 6);
- ury = getFWord(glyph + 8);
+ ury = getFWord(glyph + 8);
/* Advance the pointer. */
glyph += 10;
@@ -691,7 +691,7 @@
/* Consult the horizontal metrics table to determine */
/* the character width. */
if( charindex < font->numberOfHMetrics )
- advance_width = getuFWord( font->hmtx_table + (charindex * 4) );
+ advance_width = getuFWord( font->hmtx_table + (charindex * 4) );
else
advance_width = getuFWord( font->hmtx_table + ((font->numberOfHMetrics-1) * 4) );
@@ -718,7 +718,7 @@
{
do_composite(stream, font, glyph);
}
-
+
stack_end(stream);
}
@@ -763,16 +763,16 @@
gind = (int)getUSHORT(glyph);
glyph += 2;
- std::vector<int>::iterator insertion =
+ std::vector<int>::iterator insertion =
std::lower_bound(glyph_ids.begin(), glyph_ids.end(), gind);
if (*insertion != gind) {
glyph_ids.insert(insertion, gind);
glyph_stack.push(gind);
}
-
+
if (flags & ARG_1_AND_2_ARE_WORDS)
glyph += 4;
- else
+ else
glyph += 2;
if (flags & WE_HAVE_A_SCALE)
Modified: trunk/matplotlib/ttconv/ttutil.cpp
===================================================================
--- trunk/matplotlib/ttconv/ttutil.cpp 2008-05-07 19:39:58 UTC (rev 5128)
+++ trunk/matplotlib/ttconv/ttutil.cpp 2008-05-07 19:41:26 UTC (rev 5129)
@@ -8,9 +8,9 @@
/* (c) Frank Siegert 1996 */
#include "global_defines.h"
-#include <stdio.h>
-#include <stdarg.h>
-#include <stdlib.h>
+#include <cstdio>
+#include <cstdarg>
+#include <cstdlib>
#include "pprdrv.h"
#if DEBUG_TRUETYPE
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-05-09 12:46:51
|
Revision: 5135
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5135&view=rev
Author: mdboom
Date: 2008-05-09 05:46:00 -0700 (Fri, 09 May 2008)
Log Message:
-----------
Merged revisions 5129-5134 via svnmerge from
https://matplotlib.svn.sf.net/svnroot/matplotlib/branches/v0_91_maint
........
r5130 | mdboom | 2008-05-08 12:45:55 -0400 (Thu, 08 May 2008) | 2 lines
Fix kerning in SVG.
........
r5134 | mdboom | 2008-05-09 08:39:25 -0400 (Fri, 09 May 2008) | 2 lines
Fix /singlequote (') in Ps backend.
........
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/backends/backend_ps.py
Property Changed:
----------------
trunk/matplotlib/
Property changes on: trunk/matplotlib
___________________________________________________________________
Name: svnmerge-integrated
- /branches/v0_91_maint:1-5128
+ /branches/v0_91_maint:1-5134
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-05-09 12:39:25 UTC (rev 5134)
+++ trunk/matplotlib/CHANGELOG 2008-05-09 12:46:00 UTC (rev 5135)
@@ -1,3 +1,7 @@
+2008-05-09 Fix /singlequote (') in Postscript backend - MGD
+
+2008-05-08 Fix kerning in SVG when embedding character outlines - MGD
+
2008-05-07 Switched to future numpy histogram semantic in hist - MM
2008-05-06 Fix strange colors when blitting in QtAgg and Qt4Agg - MGD
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_ps.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_ps.py 2008-05-09 12:39:25 UTC (rev 5134)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_ps.py 2008-05-09 12:46:00 UTC (rev 5135)
@@ -95,6 +95,7 @@
s=s.replace("\\", "\\\\")
s=s.replace("(", "\\(")
s=s.replace(")", "\\)")
+ s=s.replace("'", "\\251")
s=re.sub(r"[^ -~\n]", lambda x: r"\%03o"%ord(x.group()), s)
return s
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|