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 store there vital ** statistics in tables[]. */ @@ -697,7 +697,7 @@ if( diff > 0 ) /* If we are past it. */ { tables[x].length = 0; - diff = 0; + diff = 0; } else if( diff < 0 ) /* If we haven't hit it yet. */ { @@ -711,12 +711,12 @@ tables[x].length = getULONG( ptr + 12 ); nextoffset += ( ((tables[x].length + 3) / 4) * 4 ); count++; - ptr += 16; + ptr += 16; } } while(diff != 0); - + } /* end of for loop which passes over the table directory */ - + /* Begin the sfnts array. */ sfnts_start(stream); @@ -724,10 +724,10 @@ /* Start by copying the TrueType version number. */ ptr = font->offset_table; for(x=0; x < 4; x++) - { + { sfnts_pputBYTE( stream, *(ptr++) ); } - + /* Now, generate those silly numTables numbers. */ sfnts_pputUSHORT(stream, count); /* number of tables */ if( count == 9 ) @@ -735,11 +735,11 @@ sfnts_pputUSHORT(stream, 7); /* searchRange */ sfnts_pputUSHORT(stream, 3); /* entrySelector */ sfnts_pputUSHORT(stream, 81); /* rangeShift */ - } + } #ifdef DEBUG_TRUETYPE else { - debug("only %d tables selected",count); + debug("only %d tables selected",count); } #endif @@ -754,13 +754,13 @@ sfnts_pputBYTE( stream, table_names[x][1] ); sfnts_pputBYTE( stream, table_names[x][2] ); sfnts_pputBYTE( stream, table_names[x][3] ); - + /* Checksum */ sfnts_pputULONG( stream, tables[x].checksum ); /* Offset */ sfnts_pputULONG( stream, tables[x].newoffset + 12 + (count * 16) ); - + /* Length */ sfnts_pputULONG( stream, tables[x].length ); } @@ -770,7 +770,7 @@ { if( tables[x].length == 0 ) /* skip tables that aren't there */ continue; - + #ifdef DEBUG_TRUETYPE debug("emmiting table '%s'",table_names[x]); #endif @@ -783,22 +783,22 @@ else /* Other tables may not exceed */ { /* 65535 bytes in length. */ if( tables[x].length > 65535 ) - throw TTException("TrueType font has a table which is too long"); - + throw TTException("TrueType font has a table which is too long"); + /* Start new string if necessary. */ sfnts_new_table(stream, tables[x].length); /* Seek to proper position in the file. */ fseek( font->file, tables[x].oldoffset, SEEK_SET ); - + /* Copy the bytes of the table. */ for( y=0; y < tables[x].length; y++ ) { if( (c = fgetc(font->file)) == EOF ) throw TTException("TrueType font may be corrupt (reason 7)"); - + sfnts_pputBYTE(stream, c); - } + } } /* Padd it out to a four byte boundary. */ @@ -815,39 +815,39 @@ } /* End of loop for all tables */ /* Close the array. */ - sfnts_end_string(stream); + sfnts_end_string(stream); stream.putline("]def"); } /* end of ttfont_sfnts() */ - -/*-------------------------------------------------------------- -** Create the CharStrings dictionary which will translate -** PostScript character names to TrueType font character + +/*-------------------------------------------------------------- +** Create the CharStrings dictionary which will translate +** PostScript character names to TrueType font character ** indexes. ** ** If we are creating a type 3 instead of a type 42 font, ** this array will instead convert PostScript character names ** to executable proceedures. --------------------------------------------------------------*/ -const char *Apple_CharStrings[]={ -".notdef",".null","nonmarkingreturn","space","exclam","quotedbl","numbersign", -"dollar","percent","ampersand","quotesingle","parenleft","parenright", +const char *Apple_CharStrings[]={ +".notdef",".null","nonmarkingreturn","space","exclam","quotedbl","numbersign", +"dollar","percent","ampersand","quotesingle","parenleft","parenright", "asterisk","plus", "comma","hyphen","period","slash","zero","one","two", -"three","four","five","six","seven","eight","nine","colon","semicolon", +"three","four","five","six","seven","eight","nine","colon","semicolon", "less","equal","greater","question","at","A","B","C","D","E","F","G","H","I", "J","K", "L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z", "bracketleft","backslash","bracketright","asciicircum","underscore","grave", -"a","b","c","d","e","f","g","h","i","j","k", "l","m","n","o","p","q","r","s", +"a","b","c","d","e","f","g","h","i","j","k", "l","m","n","o","p","q","r","s", "t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde", "Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis", "aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla", -"eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex", +"eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex", "idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde", "uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent", "sterling","section","bullet","paragraph","germandbls","registered", "copyright","trademark","acute","dieresis","notequal","AE","Oslash", "infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff", "summation","product","pi","integral","ordfeminine","ordmasculine","Omega", -"ae","oslash","questiondown","exclamdown","logicalnot","radical","florin", +"ae","oslash","questiondown","exclamdown","logicalnot","radical","florin", "approxequal","Delta","guillemotleft","guillemotright","ellipsis", "nobreakspace","Agrave","Atilde","Otilde","OE","oe","endash","emdash", "quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge", @@ -861,7 +861,7 @@ "Yacute","yacute","Thorn","thorn","minus","multiply","onesuperior", "twosuperior","threesuperior","onehalf","onequarter","threequarters","franc", "Gbreve","gbreve","Idot","Scedilla","scedilla","Cacute","cacute","Ccaron", -"ccaron","dmacron","markingspace","capslock","shift","propeller","enter", +"ccaron","dmacron","markingspace","capslock","shift","propeller","enter", "markingtabrtol","markingtabltor","control","markingdeleteltor", "markingdeletertol","option","escape","parbreakltor","parbreakrtol", "newpage","checkmark","linebreakltor","linebreakrtol","markingnobreakspace", @@ -879,7 +879,7 @@ ULONG len; GlyphIndex = (int)getUSHORT( font->post_table + 34 + (charindex * 2) ); - + if( GlyphIndex <= 257 ) /* If a standard Apple name, */ { return Apple_CharStrings[GlyphIndex]; @@ -887,7 +887,7 @@ else /* Otherwise, use one */ { /* of the pascal strings. */ GlyphIndex -= 258; - + /* Set pointer to start of Pascal strings. */ ptr = (char*)(font->post_table + 34 + (font->numGlyphs * 2)); @@ -897,7 +897,7 @@ ptr += len; len = (ULONG)*(ptr++); } - + if( len >= sizeof(temp) ) throw TTException("TrueType font file contains a very long PostScript name"); @@ -914,16 +914,16 @@ void ttfont_CharStrings(TTStreamWriter& stream, struct TTFONT *font, std::vector<int>& glyph_ids) { Fixed post_format; - + /* The 'post' table format number. */ post_format = getFixed( font->post_table ); - + if( post_format.whole != 2 || post_format.fraction != 0 ) throw TTException("TrueType fontdoes not have a format 2.0 'post' table"); /* Emmit the start of the PostScript code to define the dictionary. */ stream.printf("/CharStrings %d dict dup begin\n", glyph_ids.size()); - + /* Emmit one key-value pair for each glyph. */ for(std::vector<int>::const_iterator i = glyph_ids.begin(); i != glyph_ids.end(); ++i) @@ -935,13 +935,13 @@ else /* type 3 */ { stream.printf("/%s{",ttfont_CharStrings_getname(font, *i)); - + tt_type3_charproc(stream, font, *i); - + stream.putline("}_d"); /* "} bind def" */ } } - + stream.putline("end readonly def"); } /* end of ttfont_CharStrings() */ @@ -971,8 +971,8 @@ stream.putline("/BuildChar {"); stream.putline(" 1 index /Encoding get exch get"); stream.putline(" 1 index /BuildGlyph get exec"); - stream.putline("}_d"); - + stream.putline("}_d"); + stream.putchar('\n'); } @@ -999,7 +999,7 @@ stream.putline("{/TrueDict where{pop}{(%%[ Error: no TrueType rasterizer ]%%)= flush}ifelse"); /* Since we are expected to use Apple's TrueDict TrueType */ - /* reasterizer, change the font type to 3. */ + /* reasterizer, change the font type to 3. */ stream.putline("/FontType 3 def"); /* Define a string to hold the state of the Apple */ @@ -1035,7 +1035,7 @@ /* Exchange the CharStrings dictionary and the charname, */ /* but if the answer was false, replace the character name */ - /* with ".notdef". */ + /* with ".notdef". */ stream.putline(" {exch}{exch pop /.notdef}ifelse"); /* stack: CharStrings charname */ @@ -1060,7 +1060,7 @@ stream.putline(" /BuildChar{"); stream.putline(" 1 index /Encoding get exch get"); stream.putline(" 1 index /BuildGlyph get exec"); - stream.putline(" }bind def"); + stream.putline(" }bind def"); /* Here we close the condition which is true */ /* if the printer has no built-in TrueType */ @@ -1071,7 +1071,7 @@ stream.putline("FontName currentdict end definefont pop"); stream.putline("%%EOF"); - } /* end of ttfont_trailer() */ + } /* end of ttfont_trailer() */ /*------------------------------------------------------------------ ** This is the externally callable routine which inserts the font. @@ -1080,7 +1080,7 @@ void read_font(const char *filename, font_type_enum target_type, std::vector<int>& glyph_ids, TTFONT& font) { BYTE *ptr; - + /* Decide what type of PostScript font we will be generating. */ font.target_type = target_type; @@ -1094,24 +1094,24 @@ /* Allocate space for the unvarying part of the offset table. */ assert(font.offset_table == NULL); font.offset_table = (BYTE*)calloc( 12, sizeof(BYTE) ); - + /* Read the first part of the offset table. */ if( fread( font.offset_table, sizeof(BYTE), 12, font.file ) != 12 ) throw TTException("TrueType font may be corrupt (reason 1)"); - + /* Determine how many directory entries there are. */ font.numTables = getUSHORT( font.offset_table + 4 ); #ifdef DEBUG_TRUETYPE debug("numTables=%d",(int)font.numTables); #endif - + /* Expand the memory block to hold the whole thing. */ font.offset_table = (BYTE*)realloc( font.offset_table, sizeof(BYTE) * (12 + font.numTables * 16) ); - + /* Read the rest of the table directory. */ if( fread( font.offset_table + 12, sizeof(BYTE), (font.numTables*16), font.file ) != (font.numTables*16) ) throw TTException("TrueType font may be corrupt (reason 2)"); - + /* Extract information from the "Offset" table. */ font.TTVersion = getFixed( font.offset_table ); @@ -1133,7 +1133,7 @@ throw TTException("TrueType font is unusable because indexToLocFormat != 0"); if( getSHORT(ptr+52) != 0 ) throw TTException("TrueType font is unusable because glyphDataFormat != 0"); - } catch (TTException& e) { + } catch (TTException& ) { free(ptr); throw; } @@ -1177,7 +1177,7 @@ } /* end of insert_ttfont() */ -void insert_ttfont(const char *filename, TTStreamWriter& stream, +void insert_ttfont(const char *filename, TTStreamWriter& stream, font_type_enum target_type, std::vector<int>& glyph_ids) { struct TTFONT font; @@ -1233,9 +1233,9 @@ } TTFONT::TTFONT() : - file(NULL), + file(NULL), PostName(NULL), - FullName(NULL), + FullName(NULL), FamilyName(NULL), Style(NULL), Copyright(NULL), This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
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 = np.array((0,0,1)) zfront,zback = -self.dist,self.dist viewM = proj3d.view_transformation(E,R,V) perspM = proj3d.persp_transformation(zfront,zback) - M0 = npy.dot(viewM,worldM) - M = npy.dot(perspM,M0) + M0 = np.dot(viewM,worldM) + M = np.dot(perspM,M0) return M def mouse_init(self): @@ -382,8 +382,8 @@ # scale the z value to match x0,y0,z0 = p0 x1,y1,z1 = p1 - d0 = npy.hypot(x0-xd,y0-yd) - d1 = npy.hypot(x1-xd,y1-yd) + d0 = np.hypot(x0-xd,y0-yd) + d1 = np.hypot(x1-xd,y1-yd) dt = d0+d1 z = d1/dt * z0 + d0/dt * z1 #print 'mid', edgei, d0, d1, z0, z1, z @@ -503,14 +503,14 @@ had_data = self.has_data() rows, cols = Z.shape - tX,tY,tZ = npy.transpose(X), npy.transpose(Y), npy.transpose(Z) + tX,tY,tZ = np.transpose(X), np.transpose(Y), np.transpose(Z) rstride = cbook.popd(kwargs, 'rstride', 10) cstride = cbook.popd(kwargs, 'cstride', 10) # polys = [] boxes = [] - for rs in npy.arange(0,rows-1,rstride): - for cs in npy.arange(0,cols-1,cstride): + for rs in np.arange(0,rows-1,rstride): + for cs in np.arange(0,cols-1,cstride): ps = [] corners = [] for a,ta in [(X,tX),(Y,tY),(Z,tZ)]: @@ -521,9 +521,9 @@ zright = ta[cs][rs:min(rows,rs+rstride+1):] zright = zright[::-1] corners.append([ztop[0],ztop[-1],zbase[0],zbase[-1]]) - z = npy.concatenate((ztop,zleft,zbase,zright)) + z = np.concatenate((ztop,zleft,zbase,zright)) ps.append(z) - boxes.append(map(npy.array,zip(*corners))) + boxes.append(map(np.array,zip(*corners))) polys.append(zip(*ps)) # lines = [] @@ -532,10 +532,10 @@ n = proj3d.cross(box[0]-box[1], box[0]-box[2]) n = n/proj3d.mod(n)*5 - shade.append(npy.dot(n,[-1,-1,0.5])) + shade.append(np.dot(n,[-1,-1,0.5])) lines.append((box[0],n+box[0])) # - color = npy.array([0,0,1,1]) + color = np.array([0,0,1,1]) norm = Normalize(min(shade),max(shade)) colors = [color * (0.5+norm(v)*0.5) for v in shade] for c in colors: c[3] = 1 @@ -553,7 +553,7 @@ had_data = self.has_data() rows,cols = Z.shape - tX,tY,tZ = npy.transpose(X), npy.transpose(Y), npy.transpose(Z) + tX,tY,tZ = np.transpose(X), np.transpose(Y), np.transpose(Z) rii = [i for i in range(0,rows,rstride)]+[rows-1] cii = [i for i in range(0,cols,cstride)]+[cols-1] @@ -718,8 +718,8 @@ def get_test_data(delta=0.05): from mlab import bivariate_normal - x = y = npy.arange(-3.0, 3.0, delta) - X, Y = npy.meshgrid(x,y) + x = y = np.arange(-3.0, 3.0, delta) + X, Y = np.meshgrid(x,y) Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1) @@ -764,8 +764,8 @@ def test_plot(): ax = Axes3D() - xs = npy.arange(0,4*npy.pi+0.1,0.1) - ys = npy.sin(xs) + xs = np.arange(0,4*np.pi+0.1,0.1) + ys = np.sin(xs) ax.plot(xs,ys, label='zl') ax.plot(xs,ys+max(xs),label='zh') ax.plot(xs,ys,dir='x', label='xl') @@ -785,7 +785,7 @@ cc = lambda arg: colorConverter.to_rgba(arg, alpha=0.6) ax = Axes3D() - xs = npy.arange(0,10,0.4) + xs = np.arange(0,10,0.4) verts = [] zs = [0.0,1.0,2.0,3.0] for z in zs: @@ -817,7 +817,7 @@ ax = Axes3D() for c,z in zip(['r','g','b','y'],[30,20,10,0]): - xs = npy.arange(20) + xs = np.arange(20) ys = [random.random() for x in xs] ax.bar(xs,ys,z=z,dir='y',color=c) #ax.plot(xs,ys) Modified: trunk/matplotlib/lib/matplotlib/axis3d.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axis3d.py 2008-04-29 14:22:48 UTC (rev 5097) +++ trunk/matplotlib/lib/matplotlib/axis3d.py 2008-04-29 15:14:36 UTC (rev 5098) @@ -13,7 +13,7 @@ import art3d import proj3d -import numpy as npy +import numpy as np def norm_angle(a): """Return angle between -180 and +180""" @@ -51,8 +51,8 @@ # Compute the dash end points # The 'c' prefix is for canvas coordinates - cxy = npy.array(transform.xy_tup((x, y))) - cd = npy.array([cos_theta, sin_theta]) + cxy = np.array(transform.xy_tup((x, y))) + cd = np.array([cos_theta, sin_theta]) c1 = cxy+dashpush*cd c2 = cxy+(dashpush+dashlength)*cd (x1, y1) = transform.inverse_xy_tup(tuple(c1)) @@ -75,9 +75,9 @@ # well enough yet. we = self._mytext.get_window_extent(renderer=renderer) w, h = we.width(), we.height() - off = npy.array([cos_theta*(w/2+2)-1,sin_theta*(h+1)-1]) - off = npy.array([cos_theta*(w/2),sin_theta*(h/2)]) - dir = npy.array([cos_theta,sin_theta])*dashpad + off = np.array([cos_theta*(w/2+2)-1,sin_theta*(h+1)-1]) + off = np.array([cos_theta*(w/2),sin_theta*(h/2)]) + dir = np.array([cos_theta,sin_theta])*dashpad cw = c2 + off +dir self._mytext.set_position(transform.inverse_xy_tup(tuple(cw))) Modified: trunk/matplotlib/lib/matplotlib/backend_bases.py =================================================================== --- trunk/matplotlib/lib/matplotlib/backend_bases.py 2008-04-29 14:22:48 UTC (rev 5097) +++ trunk/matplotlib/lib/matplotlib/backend_bases.py 2008-04-29 15:14:36 UTC (rev 5098) @@ -6,7 +6,7 @@ from __future__ import division import os -import numpy as npy +import numpy as np import matplotlib.cbook as cbook import matplotlib.colors as colors import matplotlib._image as _image @@ -122,10 +122,10 @@ meshWidth, meshHeight, coordinates) if showedges: - edgecolors = npy.array([[0.0, 0.0, 0.0, 1.0]], npy.float_) + edgecolors = np.array([[0.0, 0.0, 0.0, 1.0]], np.float_) else: edgecolors = facecolors - linewidths = npy.array([1.0], npy.float_) + linewidths = np.array([1.0], np.float_) return self.draw_path_collection( master_transform, cliprect, clippath, clippath_trans, @@ -1569,7 +1569,7 @@ a.set_ylim((y0, y1)) elif self._button_pressed == 3: if a.get_xscale()=='log': - alpha=npy.log(Xmax/Xmin)/npy.log(x1/x0) + alpha=np.log(Xmax/Xmin)/np.log(x1/x0) rx1=pow(Xmin/x0,alpha)*Xmin rx2=pow(Xmax/x0,alpha)*Xmin else: @@ -1577,7 +1577,7 @@ rx1=alpha*(Xmin-x0)+Xmin rx2=alpha*(Xmax-x0)+Xmin if a.get_yscale()=='log': - alpha=npy.log(Ymax/Ymin)/npy.log(y1/y0) + alpha=np.log(Ymax/Ymin)/np.log(y1/y0) ry1=pow(Ymin/y0,alpha)*Ymin ry2=pow(Ymax/y0,alpha)*Ymin else: Modified: trunk/matplotlib/lib/matplotlib/cbook.py =================================================================== --- trunk/matplotlib/lib/matplotlib/cbook.py 2008-04-29 14:22:48 UTC (rev 5097) +++ trunk/matplotlib/lib/matplotlib/cbook.py 2008-04-29 15:14:36 UTC (rev 5098) @@ -5,7 +5,7 @@ from __future__ import generators import re, os, errno, sys, StringIO, traceback, locale import time, datetime -import numpy as npy +import numpy as np try: set = set @@ -856,7 +856,7 @@ class MemoryMonitor: def __init__(self, nmax=20000): self._nmax = nmax - self._mem = npy.zeros((self._nmax,), npy.int32) + self._mem = np.zeros((self._nmax,), np.int32) self.clear() def clear(self): @@ -892,7 +892,7 @@ print "Warning: array size was too small for the number of calls." def xy(self, i0=0, isub=1): - x = npy.arange(i0, self._n, isub) + x = np.arange(i0, self._n, isub) return x, self._mem[i0:self._n:isub] def plot(self, i0=0, isub=1, fig=None): @@ -1051,11 +1051,11 @@ def simple_linear_interpolation(a, steps): - steps = npy.floor(steps) + steps = np.floor(steps) new_length = ((len(a) - 1) * steps) + 1 new_shape = list(a.shape) new_shape[0] = new_length - result = npy.zeros(new_shape, a.dtype) + result = np.zeros(new_shape, a.dtype) result[0] = a[0] a0 = a[0:-1] Modified: trunk/matplotlib/lib/matplotlib/cm.py =================================================================== --- trunk/matplotlib/lib/matplotlib/cm.py 2008-04-29 14:22:48 UTC (rev 5097) +++ trunk/matplotlib/lib/matplotlib/cm.py 2008-04-29 15:14:36 UTC (rev 5098) @@ -2,7 +2,7 @@ This module contains the instantiations of color mapping classes """ -import numpy as npy +import numpy as np from numpy import ma import matplotlib as mpl import matplotlib.colors as colors @@ -56,18 +56,18 @@ try: if x.ndim == 3: if x.shape[2] == 3: - if x.dtype == npy.uint8: - alpha = npy.array(alpha*255, npy.uint8) + if x.dtype == np.uint8: + alpha = np.array(alpha*255, np.uint8) m, n = x.shape[:2] - xx = npy.empty(shape=(m,n,4), dtype = x.dtype) + xx = np.empty(shape=(m,n,4), dtype = x.dtype) xx[:,:,:3] = x xx[:,:,3] = alpha elif x.shape[2] == 4: xx = x else: raise ValueError("third dimension must be 3 or 4") - if bytes and xx.dtype != npy.uint8: - xx = (xx * 255).astype(npy.uint8) + if bytes and xx.dtype != np.uint8: + xx = (xx * 255).astype(np.uint8) return xx except AttributeError: pass Modified: trunk/matplotlib/lib/matplotlib/collections.py =================================================================== --- trunk/matplotlib/lib/matplotlib/collections.py 2008-04-29 14:22:48 UTC (rev 5097) +++ trunk/matplotlib/lib/matplotlib/collections.py 2008-04-29 15:14:36 UTC (rev 5098) @@ -8,7 +8,7 @@ line segemnts) """ import math, warnings -import numpy as npy +import numpy as np import matplotlib as mpl import matplotlib.cbook as cbook import matplotlib.colors as _colors # avoid conflict with kwarg @@ -51,7 +51,7 @@ draw time a call to scalar mappable will be made to set the face colors. """ - _offsets = npy.array([], npy.float_) + _offsets = np.array([], np.float_) _transOffset = transforms.IdentityTransform() _transforms = [] @@ -84,11 +84,11 @@ self.set_antialiased(antialiaseds) self._uniform_offsets = None - self._offsets = npy.array([], npy.float_) + self._offsets = np.array([], np.float_) if offsets is not None: - offsets = npy.asarray(offsets, npy.float_) + offsets = np.asarray(offsets, np.float_) if len(offsets.shape) == 1: - offsets = offsets[npy.newaxis,:] # Make it Nx2. + offsets = offsets[np.newaxis,:] # Make it Nx2. if transOffset is not None: Affine2D = transforms.Affine2D self._offsets = offsets @@ -137,7 +137,7 @@ if not transOffset.is_affine: offsets = transOffset.transform_non_affine(offsets) transOffset = transOffset.get_affine() - offsets = npy.asarray(offsets, npy.float_) + offsets = np.asarray(offsets, np.float_) result = mpath.get_path_collection_extents( transform.frozen(), paths, self.get_transforms(), @@ -166,7 +166,7 @@ ys = self.convert_yunits(self._offsets[:1]) offsets = zip(xs, ys) - offsets = npy.asarray(offsets, npy.float_) + offsets = np.asarray(offsets, np.float_) self.update_scalarmappable() @@ -206,7 +206,7 @@ ind = mpath.point_in_path_collection( mouseevent.x, mouseevent.y, self._pickradius, transform.frozen(), paths, self.get_transforms(), - npy.asarray(self._offsets, npy.float_), + np.asarray(self._offsets, np.float_), self._transOffset.frozen(), len(self._facecolors)) return len(ind)>0,dict(ind=ind) @@ -424,7 +424,7 @@ # By converting to floats now, we can avoid that on every draw. self._coordinates = self._coordinates.reshape((meshHeight + 1, meshWidth + 1, 2)) - self._coordinates = npy.array(self._coordinates, npy.float_) + self._coordinates = np.array(self._coordinates, np.float_) def get_paths(self, dataTrans=None): if self._paths is None: @@ -439,11 +439,11 @@ c = coordinates # We could let the Path constructor generate the codes for us, # but this is faster, since we know they'll always be the same - codes = npy.array( + codes = np.array( [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY], Path.code_type) - points = npy.concatenate(( + points = np.concatenate(( c[0:-1, 0:-1], c[0:-1, 1: ], c[1: , 1: ], @@ -470,7 +470,7 @@ ys = self.convert_yunits(self._offsets[:1]) offsets = zip(xs, ys) - offsets = npy.asarray(offsets, npy.float_) + offsets = np.asarray(offsets, np.float_) if self.check_update('array'): self.update_scalarmappable() @@ -556,8 +556,8 @@ Example: see examples/dynamic_collection.py for complete example - offsets = npy.random.rand(20,2) - facecolors = [cm.jet(x) for x in npy.random.rand(20)] + offsets = np.random.rand(20,2) + facecolors = [cm.jet(x) for x in np.random.rand(20)] black = (0,0,0,1) collection = RegularPolyCollection( @@ -584,7 +584,7 @@ # in points^2 self._transforms = [ transforms.Affine2D().rotate(-self._rotation).scale( - (npy.sqrt(x) * renderer.dpi / 72.0) / npy.sqrt(npy.pi)) + (np.sqrt(x) * renderer.dpi / 72.0) / np.sqrt(np.pi)) for x in self._sizes] return Collection.draw(self, renderer) @@ -679,7 +679,7 @@ pickradius=pickradius, **kwargs) - self._facecolors = npy.array([]) + self._facecolors = np.array([]) self.set_segments(segments) def get_paths(self): @@ -687,7 +687,7 @@ def set_segments(self, segments): if segments is None: return - segments = [npy.asarray(seg, npy.float_) for seg in segments] + segments = [np.asarray(seg, np.float_) for seg in segments] if self._uniform_offsets is not None: segments = self._add_offsets(segments) self._paths = [mpath.Path(seg) for seg in segments] Modified: trunk/matplotlib/lib/matplotlib/colorbar.py =================================================================== --- trunk/matplotlib/lib/matplotlib/colorbar.py 2008-04-29 14:22:48 UTC (rev 5097) +++ trunk/matplotlib/lib/matplotlib/colorbar.py 2008-04-29 15:14:36 UTC (rev 5098) @@ -15,7 +15,7 @@ ''' -import numpy as npy +import numpy as np import matplotlib as mpl import matplotlib.colors as colors import matplotlib.cm as cm @@ -185,7 +185,7 @@ self._process_values() self._find_range() X, Y = self._mesh() - C = self._values[:,npy.newaxis] + C = self._values[:,np.newaxis] self._config_axes(X, Y) if self.filled: self._add_solids(X, Y, C) @@ -248,13 +248,13 @@ ''' N = X.shape[0] ii = [0, 1, N-2, N-1, 2*N-1, 2*N-2, N+1, N, 0] - x = npy.take(npy.ravel(npy.transpose(X)), ii) - y = npy.take(npy.ravel(npy.transpose(Y)), ii) + x = np.take(np.ravel(np.transpose(X)), ii) + y = np.take(np.ravel(np.transpose(Y)), ii) x = x.reshape((len(x), 1)) y = y.reshape((len(y), 1)) if self.orientation == 'horizontal': - return npy.hstack((y, x)) - return npy.hstack((x, y)) + return np.hstack((y, x)) + return np.hstack((x, y)) def _edges(self, X, Y): ''' @@ -276,7 +276,7 @@ if self.orientation == 'vertical': args = (X, Y, C) else: - args = (npy.transpose(Y), npy.transpose(X), npy.transpose(C)) + args = (np.transpose(Y), np.transpose(X), np.transpose(C)) kw = {'cmap':self.cmap, 'norm':self.norm, 'shading':'flat', 'alpha':self.alpha} # Save, set, and restore hold state to keep pcolor from @@ -303,8 +303,8 @@ dummy, y = self._locate(levels) if len(y) <> N: raise ValueError("levels are outside colorbar range") - x = npy.array([0.0, 1.0]) - X, Y = npy.meshgrid(x,y) + x = np.array([0.0, 1.0]) + X, Y = np.meshgrid(x,y) if self.orientation == 'vertical': xy = [zip(X[i], Y[i]) for i in range(N)] else: @@ -348,7 +348,7 @@ locator.set_data_interval(*intv) formatter.set_view_interval(*intv) formatter.set_data_interval(*intv) - b = npy.array(locator()) + b = np.array(locator()) b, ticks = self._locate(b) formatter.set_locs(b) ticklabels = [formatter(t, i) for i, t in enumerate(b)] @@ -364,32 +364,32 @@ if b is None: b = self.boundaries if b is not None: - self._boundaries = npy.asarray(b, dtype=float) + self._boundaries = np.asarray(b, dtype=float) if self.values is None: self._values = 0.5*(self._boundaries[:-1] + self._boundaries[1:]) if isinstance(self.norm, colors.NoNorm): - self._values = (self._values + 0.00001).astype(npy.int16) + self._values = (self._values + 0.00001).astype(np.int16) return - self._values = npy.array(self.values) + self._values = np.array(self.values) return if self.values is not None: - self._values = npy.array(self.values) + self._values = np.array(self.values) if self.boundaries is None: - b = npy.zeros(len(self.values)+1, 'd') + b = np.zeros(len(self.values)+1, 'd') b[1:-1] = 0.5*(self._values[:-1] - self._values[1:]) b[0] = 2.0*b[1] - b[2] b[-1] = 2.0*b[-2] - b[-3] self._boundaries = b return - self._boundaries = npy.array(self.boundaries) + self._boundaries = np.array(self.boundaries) return # Neither boundaries nor values are specified; # make reasonable ones based on cmap and norm. if isinstance(self.norm, colors.NoNorm): b = self._uniform_y(self.cmap.N+1) * self.cmap.N - 0.5 - v = npy.zeros((len(b)-1,), dtype=npy.int16) - v[self._inside] = npy.arange(self.cmap.N, dtype=npy.int16) + v = np.zeros((len(b)-1,), dtype=np.int16) + v[self._inside] = np.arange(self.cmap.N, dtype=np.int16) if self.extend in ('both', 'min'): v[0] = -1 if self.extend in ('both', 'max'): @@ -403,8 +403,8 @@ b = [b[0]-1] + b if self.extend in ('both', 'max'): b = b + [b[-1] + 1] - b = npy.array(b) - v = npy.zeros((len(b)-1,), dtype=float) + b = np.array(b) + v = np.zeros((len(b)-1,), dtype=float) bi = self.norm.boundaries v[self._inside] = 0.5*(bi[:-1] + bi[1:]) if self.extend in ('both', 'min'): @@ -461,19 +461,19 @@ spaced boundaries, plus ends if required. ''' if self.extend == 'neither': - y = npy.linspace(0, 1, N) + y = np.linspace(0, 1, N) else: if self.extend == 'both': - y = npy.zeros(N + 2, 'd') + y = np.zeros(N + 2, 'd') y[0] = -0.05 y[-1] = 1.05 elif self.extend == 'min': - y = npy.zeros(N + 1, 'd') + y = np.zeros(N + 1, 'd') y[0] = -0.05 else: - y = npy.zeros(N + 1, 'd') + y = np.zeros(N + 1, 'd') y[-1] = 1.05 - y[self._inside] = npy.linspace(0, 1, N) + y[self._inside] = np.linspace(0, 1, N) return y def _proportional_y(self): @@ -503,13 +503,13 @@ transposition for a horizontal colorbar are done outside this function. ''' - x = npy.array([0.0, 1.0]) + x = np.array([0.0, 1.0]) if self.spacing == 'uniform': y = self._uniform_y(self._central_N()) else: y = self._proportional_y() self._y = y - X, Y = npy.meshgrid(x,y) + X, Y = np.meshgrid(x,y) if self.extend in ('min', 'both'): X[0,:] = 0.5 if self.extend in ('max', 'both'): @@ -535,19 +535,19 @@ # floating point errors. xn = self.norm(x, clip=False).filled() in_cond = (xn > -0.001) & (xn < 1.001) - xn = npy.compress(in_cond, xn) - xout = npy.compress(in_cond, x) + xn = np.compress(in_cond, xn) + xout = np.compress(in_cond, x) # The rest is linear interpolation with clipping. y = self._y N = len(b) - ii = npy.minimum(npy.searchsorted(b, xn), N-1) - i0 = npy.maximum(ii - 1, 0) + ii = np.minimum(np.searchsorted(b, xn), N-1) + i0 = np.maximum(ii - 1, 0) #db = b[ii] - b[i0] - db = npy.take(b, ii) - npy.take(b, i0) - db = npy.where(i0==ii, 1.0, db) + db = np.take(b, ii) - np.take(b, i0) + db = np.where(i0==ii, 1.0, db) #dy = y[ii] - y[i0] - dy = npy.take(y, ii) - npy.take(y, i0) - z = npy.take(y, i0) + (xn-npy.take(b,i0))*dy/db + dy = np.take(y, ii) - np.take(y, i0) + z = np.take(y, i0) + (xn-np.take(b,i0))*dy/db return xout, z def set_alpha(self, alpha): Modified: trunk/matplotlib/lib/matplotlib/colors.py =================================================================== --- trunk/matplotlib/lib/matplotlib/colors.py 2008-04-29 14:22:48 UTC (rev 5097) +++ trunk/matplotlib/lib/matplotlib/colors.py 2008-04-29 15:14:36 UTC (rev 5098) @@ -34,7 +34,7 @@ 'chartreuse' are supported. """ import re -import numpy as npy +import numpy as np from numpy import ma import matplotlib.cbook as cbook @@ -320,23 +320,23 @@ """ try: if c.lower() == 'none': - return npy.zeros((0,4), dtype=npy.float_) + return np.zeros((0,4), dtype=np.float_) except AttributeError: pass if len(c) == 0: - return npy.zeros((0,4), dtype=npy.float_) + return np.zeros((0,4), dtype=np.float_) try: result = [self.to_rgba(c, alpha)] except ValueError: # If c is a list it must be maintained as the same list # with modified items so that items can be appended to # it. This is needed for examples/dynamic_collections.py. - if not isinstance(c, (list, npy.ndarray)): # specific; don't need duck-typing + if not isinstance(c, (list, np.ndarray)): # specific; don't need duck-typing c = list(c) for i, cc in enumerate(c): c[i] = self.to_rgba(cc, alpha) # change in place result = c - return npy.asarray(result, npy.float_) + return np.asarray(result, np.float_) colorConverter = ColorConverter() @@ -358,7 +358,7 @@ gives the closest value for values of x between 0 and 1. """ try: - adata = npy.array(data) + adata = np.array(data) except: raise TypeError("data must be convertable to an array") shape = adata.shape @@ -372,21 +372,21 @@ if x[0] != 0. or x[-1] != 1.0: raise ValueError( "data mapping points must start with x=0. and end with x=1") - if npy.sometrue(npy.sort(x)-x): + if np.sometrue(np.sort(x)-x): raise ValueError( "data mapping points must have x in increasing order") # begin generation of lookup table x = x * (N-1) - lut = npy.zeros((N,), npy.float) - xind = npy.arange(float(N)) - ind = npy.searchsorted(x, xind)[1:-1] + lut = np.zeros((N,), np.float) + xind = np.arange(float(N)) + ind = np.searchsorted(x, xind)[1:-1] lut[1:-1] = ( ((xind[1:-1] - x[ind-1]) / (x[ind] - x[ind-1])) * (y0[ind] - y1[ind-1]) + y1[ind-1]) lut[0] = y1[0] lut[-1] = y0[-1] # ensure that the lut is confined to values between 0 and 1 by clipping it - npy.clip(lut, 0.0, 1.0) + np.clip(lut, 0.0, 1.0) #lut = where(lut > 1., 1., lut) #lut = where(lut < 0., 0., lut) return lut @@ -437,26 +437,26 @@ mask_bad = None if not cbook.iterable(X): vtype = 'scalar' - xa = npy.array([X]) + xa = np.array([X]) else: vtype = 'array' xma = ma.asarray(X) xa = xma.filled(0) mask_bad = ma.getmask(xma) - if xa.dtype.char in npy.typecodes['Float']: - npy.putmask(xa, xa==1.0, 0.9999999) #Treat 1.0 as slightly less than 1. + if xa.dtype.char in np.typecodes['Float']: + np.putmask(xa, xa==1.0, 0.9999999) #Treat 1.0 as slightly less than 1. xa = (xa * self.N).astype(int) # Set the over-range indices before the under-range; # otherwise the under-range values get converted to over-range. - npy.putmask(xa, xa>self.N-1, self._i_over) - npy.putmask(xa, xa<0, self._i_under) + np.putmask(xa, xa>self.N-1, self._i_over) + np.putmask(xa, xa<0, self._i_under) if mask_bad is not None and mask_bad.shape == xa.shape: - npy.putmask(xa, mask_bad, self._i_bad) + np.putmask(xa, mask_bad, self._i_bad) if bytes: - lut = (self._lut * 255).astype(npy.uint8) + lut = (self._lut * 255).astype(np.uint8) else: lut = self._lut - rgba = npy.empty(shape=xa.shape+(4,), dtype=lut.dtype) + rgba = np.empty(shape=xa.shape+(4,), dtype=lut.dtype) lut.take(xa, axis=0, mode='clip', out=rgba) # twice as fast as lut[xa]; # using the clip or wrap mode and providing an @@ -501,8 +501,8 @@ raise NotImplementedError("Abstract class only") def is_gray(self): - return (npy.alltrue(self._lut[:,0] == self._lut[:,1]) - and npy.alltrue(self._lut[:,0] == self._lut[:,2])) + return (np.alltrue(self._lut[:,0] == self._lut[:,1]) + and np.alltrue(self._lut[:,0] == self._lut[:,2])) class LinearSegmentedColormap(Colormap): @@ -527,7 +527,7 @@ self._segmentdata = segmentdata def _init(self): - self._lut = npy.ones((self.N + 3, 4), npy.float) + self._lut = np.ones((self.N + 3, 4), np.float) self._lut[:-3, 0] = makeMappingArray(self.N, self._segmentdata['red']) self._lut[:-3, 1] = makeMappingArray(self.N, self._segmentdata['green']) self._lut[:-3, 2] = makeMappingArray(self.N, self._segmentdata['blue']) @@ -579,9 +579,9 @@ def _init(self): - rgb = npy.array([colorConverter.to_rgb(c) - for c in self.colors], npy.float) - self._lut = npy.zeros((self.N + 3, 4), npy.float) + rgb = np.array([colorConverter.to_rgb(c) + for c in self.colors], np.float) + self._lut = np.zeros((self.N + 3, 4), np.float) self._lut[:-3, :-1] = rgb self._lut[:-3, -1] = 1 self._isinit = True @@ -615,10 +615,10 @@ if cbook.iterable(value): vtype = 'array' - val = ma.asarray(value).astype(npy.float) + val = ma.asarray(value).astype(np.float) else: vtype = 'scalar' - val = ma.array([value]).astype(npy.float) + val = ma.array([value]).astype(np.float) self.autoscale_None(val) vmin, vmax = self.vmin, self.vmax @@ -629,7 +629,7 @@ else: if clip: mask = ma.getmask(val) - val = ma.array(npy.clip(val.filled(vmax), vmin, vmax), + val = ma.array(np.clip(val.filled(vmax), vmin, vmax), mask=mask) result = (val-vmin) * (1.0/(vmax-vmin)) if vtype == 'scalar': @@ -674,10 +674,10 @@ if cbook.iterable(value): vtype = 'array' - val = ma.asarray(value).astype(npy.float) + val = ma.asarray(value).astype(np.float) else: vtype = 'scalar' - val = ma.array([value]).astype(npy.float) + val = ma.array([value]).astype(np.float) self.autoscale_None(val) vmin, vmax = self.vmin, self.vmax @@ -690,9 +690,9 @@ else: if clip: mask = ma.getmask(val) - val = ma.array(npy.clip(val.filled(vmax), vmin, vmax), + val = ma.array(np.clip(val.filled(vmax), vmin, vmax), mask=mask) - result = (ma.log(val)-npy.log(vmin))/(npy.log(vmax)-npy.log(vmin)) + result = (ma.log(val)-np.log(vmin))/(np.log(vmax)-np.log(vmin)) if vtype == 'scalar': result = result[0] return result @@ -737,7 +737,7 @@ self.clip = clip self.vmin = boundari... [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. |