You can subscribe to this list here.
| 2007 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
(115) |
Aug
(120) |
Sep
(137) |
Oct
(170) |
Nov
(461) |
Dec
(263) |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2008 |
Jan
(120) |
Feb
(74) |
Mar
(35) |
Apr
(74) |
May
(245) |
Jun
(356) |
Jul
(240) |
Aug
(115) |
Sep
(78) |
Oct
(225) |
Nov
(98) |
Dec
(271) |
| 2009 |
Jan
(132) |
Feb
(84) |
Mar
(74) |
Apr
(56) |
May
(90) |
Jun
(79) |
Jul
(83) |
Aug
(296) |
Sep
(214) |
Oct
(76) |
Nov
(82) |
Dec
(66) |
| 2010 |
Jan
(46) |
Feb
(58) |
Mar
(51) |
Apr
(77) |
May
(58) |
Jun
(126) |
Jul
(128) |
Aug
(64) |
Sep
(50) |
Oct
(44) |
Nov
(48) |
Dec
(54) |
| 2011 |
Jan
(68) |
Feb
(52) |
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(1) |
| 2018 |
Jan
|
Feb
|
Mar
|
Apr
|
May
(1) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
|
From: <jd...@us...> - 2008-05-25 13:03:02
|
Revision: 5261
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5261&view=rev
Author: jdh2358
Date: 2008-05-25 06:02:59 -0700 (Sun, 25 May 2008)
Log Message:
-----------
Merged revisions 5258-5259 via svnmerge from
https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/v0_91_maint
........
r5258 | jdh2358 | 2008-05-25 07:51:50 -0500 (Sun, 25 May 2008) | 1 line
added pil support to imread
........
r5259 | jdh2358 | 2008-05-25 08:00:49 -0500 (Sun, 25 May 2008) | 1 line
fixed a npy np mixup in image
........
Property Changed:
----------------
trunk/matplotlib/
Property changes on: trunk/matplotlib
___________________________________________________________________
Name: svnmerge-integrated
- /branches/v0_91_maint:1-5257
+ /branches/v0_91_maint:1-5260
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-05-25 13:01:44
|
Revision: 5260
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5260&view=rev
Author: jdh2358
Date: 2008-05-25 06:01:42 -0700 (Sun, 25 May 2008)
Log Message:
-----------
Merged revisions 5239 via svnmerge from
https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/v0_91_maint
........
r5239 | sameerd | 2008-05-23 14:27:23 -0500 (Fri, 23 May 2008) | 3 lines
Getting mlab.py in sync with the trunk
........
Property Changed:
----------------
trunk/matplotlib/
Property changes on: trunk/matplotlib
___________________________________________________________________
Name: svnmerge-integrated
- /branches/v0_91_maint:1-5215
+ /branches/v0_91_maint:1-5257
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-05-25 13:00:52
|
Revision: 5259
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5259&view=rev
Author: jdh2358
Date: 2008-05-25 06:00:49 -0700 (Sun, 25 May 2008)
Log Message:
-----------
fixed a npy np mixup in image
Modified Paths:
--------------
branches/v0_91_maint/lib/matplotlib/image.py
Modified: branches/v0_91_maint/lib/matplotlib/image.py
===================================================================
--- branches/v0_91_maint/lib/matplotlib/image.py 2008-05-25 12:51:50 UTC (rev 5258)
+++ branches/v0_91_maint/lib/matplotlib/image.py 2008-05-25 13:00:49 UTC (rev 5259)
@@ -648,6 +648,6 @@
raise RuntimeError('Unknown image mode')
x_str = im.tostring('raw',im.mode,0,-1)
- x = np.fromstring(x_str,np.uint8)
+ x = npy.fromstring(x_str,npy.uint8)
x.shape = im.size[1], im.size[0], 4
return x
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-05-25 12:51:52
|
Revision: 5258
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5258&view=rev
Author: jdh2358
Date: 2008-05-25 05:51:50 -0700 (Sun, 25 May 2008)
Log Message:
-----------
added pil support to imread
Modified Paths:
--------------
branches/v0_91_maint/lib/matplotlib/image.py
Modified: branches/v0_91_maint/lib/matplotlib/image.py
===================================================================
--- branches/v0_91_maint/lib/matplotlib/image.py 2008-05-25 12:50:29 UTC (rev 5257)
+++ branches/v0_91_maint/lib/matplotlib/image.py 2008-05-25 12:51:50 UTC (rev 5258)
@@ -609,13 +609,29 @@
Return value is a MxNx4 array of 0-1 normalized floats
+ matplotlib can only read PNGs natively, but if PIL is installed,
+ it will use it to load the image and return an RGBA if possible
+ which can be used with imshow
"""
+
+ def pilread():
+ 'try to load the image with PIL or return None'
+ try: import Image
+ except ImportError: return None
+ image = Image.open( fname )
+ return pil_to_array(image)
+
+
handlers = {'png' :_image.readpng,
}
basename, ext = os.path.splitext(fname)
ext = ext.lower()[1:]
+
if ext not in handlers.keys():
- raise ValueError('Only know how to handled extensions: %s' % handlers.keys())
+ im = pilread()
+ if im is None:
+ raise ValueError('Only know how to handle extensions: %s; with PIL installed matplotlib can handle more images' % handlers.keys())
+ return im
handler = handlers[ext]
return handler(fname)
@@ -632,6 +648,6 @@
raise RuntimeError('Unknown image mode')
x_str = im.tostring('raw',im.mode,0,-1)
- x = npy.fromstring(x_str,npy.uint8)
+ x = np.fromstring(x_str,np.uint8)
x.shape = im.size[1], im.size[0], 4
return x
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-05-25 12:50:30
|
Revision: 5257
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5257&view=rev
Author: jdh2358
Date: 2008-05-25 05:50:29 -0700 (Sun, 25 May 2008)
Log Message:
-----------
experimenting with log toggle
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/backend_bases.py
Modified: trunk/matplotlib/lib/matplotlib/backend_bases.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backend_bases.py 2008-05-25 01:30:32 UTC (rev 5256)
+++ trunk/matplotlib/lib/matplotlib/backend_bases.py 2008-05-25 12:50:29 UTC (rev 5257)
@@ -4,7 +4,7 @@
"""
from __future__ import division
-import os
+import os, warnings
import numpy as np
import matplotlib.cbook as cbook
@@ -1201,8 +1201,17 @@
event.inaxes.grid()
self.canvas.draw()
elif event.key == 'l':
- event.inaxes.toggle_log_lineary()
- self.canvas.draw()
+ warnings.warn('log scale toggling under construction')
+ if 0:
+ ax = event.inaxes
+ scale = ax.get_yscale()
+ if scale=='log':
+ ax.set_yscale('linear')
+ ax.figure.canvas.draw()
+ elif scale=='linear':
+ ax.set_yscale('log')
+ ax.figure.canvas.draw()
+
elif event.key is not None and (event.key.isdigit() and event.key!='0') or event.key=='a':
# 'a' enables all axes
if event.key!='a':
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-05-25 01:30:33
|
Revision: 5256
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5256&view=rev
Author: jdh2358
Date: 2008-05-24 18:30:32 -0700 (Sat, 24 May 2008)
Log Message:
-----------
added tonys wx loan icon patch
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/backends/backend_wx.py
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_wx.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_wx.py 2008-05-24 21:05:14 UTC (rev 5255)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_wx.py 2008-05-25 01:30:32 UTC (rev 5256)
@@ -1383,9 +1383,6 @@
matplotlib library is installed. The filename parameter should not
contain any path information as this is determined automatically.
- Bitmaps should be in XPM format, and of size 16x16 (unless you change
- the code!). I have converted the stock GTK2 16x16 icons to XPM format.
-
Returns a wx.Bitmap object
"""
@@ -1395,27 +1392,9 @@
if not os.path.exists(bmpFilename):
raise IOError('Could not find bitmap file "%s"; dying'%bmpFilename)
- bmp =wx.Bitmap(bmpFilename, wx.BITMAP_TYPE_XPM)
+ bmp = wx.Bitmap(bmpFilename)
return bmp
-def _load_pngicon(filename):
- """
- Load a png icon file from the backends/images subdirectory in which the
- matplotlib library is installed. The filename parameter should not
- contain any path information as this is determined automatically.
-
- Returns a wx.Bitmap object
- """
-
- basedir = os.path.join(rcParams['datapath'],'images')
-
- pngFilename = os.path.normpath(os.path.join(basedir, filename))
- if not os.path.exists(pngFilename):
- raise IOError('Could not find bitmap file "%s"; dying'%pngFilename)
-
- png =wx.Bitmap(pngFilename, wx.BITMAP_TYPE_PNG)
- return png
-
class MenuButtonWx(wx.Button):
"""
wxPython does not permit a menu to be incorporated directly into a toolbar.
@@ -1576,24 +1555,24 @@
self.SetToolBitmapSize(wx.Size(24,24))
- self.AddSimpleTool(_NTB2_HOME, _load_pngicon('home.png'),
+ self.AddSimpleTool(_NTB2_HOME, _load_bitmap('home.png'),
'Home', 'Reset original view')
- self.AddSimpleTool(self._NTB2_BACK, _load_pngicon('back.png'),
+ self.AddSimpleTool(self._NTB2_BACK, _load_bitmap('back.png'),
'Back', 'Back navigation view')
- self.AddSimpleTool(self._NTB2_FORWARD, _load_pngicon('forward.png'),
+ self.AddSimpleTool(self._NTB2_FORWARD, _load_bitmap('forward.png'),
'Forward', 'Forward navigation view')
# todo: get new bitmap
- self.AddCheckTool(self._NTB2_PAN, _load_pngicon('move.png'),
+ self.AddCheckTool(self._NTB2_PAN, _load_bitmap('move.png'),
shortHelp='Pan',
longHelp='Pan with left, zoom with right')
- self.AddCheckTool(self._NTB2_ZOOM, _load_pngicon('zoom_to_rect.png'),
+ self.AddCheckTool(self._NTB2_ZOOM, _load_bitmap('zoom_to_rect.png'),
shortHelp='Zoom', longHelp='Zoom to rectangle')
self.AddSeparator()
- self.AddSimpleTool(_NTB2_SUBPLOT, _load_pngicon('subplots.png'),
+ self.AddSimpleTool(_NTB2_SUBPLOT, _load_bitmap('subplots.png'),
'Configure subplots', 'Configure subplot parameters')
- self.AddSimpleTool(_NTB2_SAVE, _load_pngicon('filesave.png'),
+ self.AddSimpleTool(_NTB2_SAVE, _load_bitmap('filesave.png'),
'Save', 'Save plot contents to file')
if wx.VERSION_STRING >= '2.5':
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-05-24 21:05:15
|
Revision: 5255
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5255&view=rev
Author: jdh2358
Date: 2008-05-24 14:05:14 -0700 (Sat, 24 May 2008)
Log Message:
-----------
removed old doc dir
Removed Paths:
-------------
trunk/matplotlib/doc/
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-05-24 21:04:51
|
Revision: 5254
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5254&view=rev
Author: jdh2358
Date: 2008-05-24 14:04:44 -0700 (Sat, 24 May 2008)
Log Message:
-----------
fixed the latex build
Modified Paths:
--------------
trunk/matplotlib/docs/conf.py
trunk/matplotlib/docs/make.py
Modified: trunk/matplotlib/docs/conf.py
===================================================================
--- trunk/matplotlib/docs/conf.py 2008-05-24 20:49:31 UTC (rev 5253)
+++ trunk/matplotlib/docs/conf.py 2008-05-24 21:04:44 UTC (rev 5254)
@@ -139,10 +139,12 @@
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, document class [howto/manual]).
+
latex_documents = [
- ('index', 'Matplotlib.tex', 'Matplotlib', 'John Hunter, Darren Dale', 'Michael Droettboom', 'manual'),
+ ('index', 'Matplotlib.tex', 'Matplotlib', 'John Hunter, Darren Dale, Michael Droettboom', 'manual'),
]
+
# The name of an image file (relative to this directory) to place at the top of
# the title page.
latex_logo = None
Modified: trunk/matplotlib/docs/make.py
===================================================================
--- trunk/matplotlib/docs/make.py 2008-05-24 20:49:31 UTC (rev 5253)
+++ trunk/matplotlib/docs/make.py 2008-05-24 21:04:44 UTC (rev 5254)
@@ -30,11 +30,11 @@
os.chdir('build/latex')
# Copying the makefile produced by sphinx...
- os.system('pdflatex Matplotlib_Users_Guide.tex')
- os.system('pdflatex Matplotlib_Users_Guide.tex')
- os.system('makeindex -s python.ist Matplotlib_Users_Guide.idx')
- os.system('makeindex -s python.ist modMatplotlib_Users_Guide.idx')
- os.system('pdflatex Matplotlib_Users_Guide.tex')
+ os.system('pdflatex Matplotlib.tex')
+ os.system('pdflatex Matplotlib.tex')
+ os.system('makeindex -s python.ist Matplotlib.idx')
+ os.system('makeindex -s python.ist modMatplotlib.idx')
+ os.system('pdflatex Matplotlib.tex')
os.chdir('../..')
else:
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-05-24 20:49:35
|
Revision: 5253
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5253&view=rev
Author: jdh2358
Date: 2008-05-24 13:49:31 -0700 (Sat, 24 May 2008)
Log Message:
-----------
added new docs dir
Added Paths:
-----------
trunk/matplotlib/docs/
trunk/matplotlib/docs/_static/
trunk/matplotlib/docs/_templates/
trunk/matplotlib/docs/api/
trunk/matplotlib/docs/api/artist_api.rst
trunk/matplotlib/docs/api/index.rst
trunk/matplotlib/docs/conf.py
trunk/matplotlib/docs/devel/
trunk/matplotlib/docs/devel/add_new_projection.rst
trunk/matplotlib/docs/devel/coding_guide.rst
trunk/matplotlib/docs/devel/documenting_mpl.rst
trunk/matplotlib/docs/devel/index.rst
trunk/matplotlib/docs/index.rst
trunk/matplotlib/docs/make.py
trunk/matplotlib/docs/mpl_data
trunk/matplotlib/docs/mpl_examples
trunk/matplotlib/docs/sphinxext/
trunk/matplotlib/docs/sphinxext/ipython_console_highlighting.py
trunk/matplotlib/docs/sphinxext/mathml.py
trunk/matplotlib/docs/sphinxext/mathpng.py
trunk/matplotlib/docs/users/
trunk/matplotlib/docs/users/artists.rst
trunk/matplotlib/docs/users/customizing.rst
trunk/matplotlib/docs/users/event_handling.rst
trunk/matplotlib/docs/users/figures/
trunk/matplotlib/docs/users/figures/dollar_ticks.py
trunk/matplotlib/docs/users/figures/fig_axes_customize_simple.py
trunk/matplotlib/docs/users/figures/fig_axes_labels_simple.py
trunk/matplotlib/docs/users/figures/fig_x.py
trunk/matplotlib/docs/users/figures/make.py
trunk/matplotlib/docs/users/figures/pyplot_formatstr.py
trunk/matplotlib/docs/users/figures/pyplot_mathtext.py
trunk/matplotlib/docs/users/figures/pyplot_simple.py
trunk/matplotlib/docs/users/figures/pyplot_text.py
trunk/matplotlib/docs/users/figures/pyplot_three.py
trunk/matplotlib/docs/users/figures/pyplot_two_subplots.py
trunk/matplotlib/docs/users/index.rst
trunk/matplotlib/docs/users/navigation_toolbar.rst
trunk/matplotlib/docs/users/pyplot_tutorial.rst
Added: trunk/matplotlib/docs/api/artist_api.rst
===================================================================
--- trunk/matplotlib/docs/api/artist_api.rst (rev 0)
+++ trunk/matplotlib/docs/api/artist_api.rst 2008-05-24 20:49:31 UTC (rev 5253)
@@ -0,0 +1,31 @@
+******************
+matplotlib artists
+******************
+
+:mod:`matplotlib.artist`
+=============================
+
+.. automodule:: matplotlib.artist
+ :members:
+ :undoc-members:
+
+:mod:`matplotlib.lines`
+=============================
+
+.. automodule:: matplotlib.lines
+ :members:
+ :undoc-members:
+
+:mod:`matplotlib.patches`
+=============================
+
+.. automodule:: matplotlib.patches
+ :members:
+ :undoc-members:
+
+:mod:`matplotlib.text`
+=============================
+
+.. automodule:: matplotlib.text
+ :members:
+ :undoc-members:
Added: trunk/matplotlib/docs/api/index.rst
===================================================================
--- trunk/matplotlib/docs/api/index.rst (rev 0)
+++ trunk/matplotlib/docs/api/index.rst 2008-05-24 20:49:31 UTC (rev 5253)
@@ -0,0 +1,15 @@
+.. _api-index:
+
+####################
+ The Matplotlib API
+####################
+
+:Release: |version|
+:Date: |today|
+
+Introduction to developer's guide here **TODO**.
+
+.. toctree::
+
+ artist_api.rst
+
Added: trunk/matplotlib/docs/conf.py
===================================================================
--- trunk/matplotlib/docs/conf.py (rev 0)
+++ trunk/matplotlib/docs/conf.py 2008-05-24 20:49:31 UTC (rev 5253)
@@ -0,0 +1,159 @@
+# -*- coding: utf-8 -*-
+#
+# Matplotlib documentation build configuration file, created by
+# sphinx-quickstart on Fri May 2 12:33:25 2008.
+#
+# This file is execfile()d with the current directory set to its containing dir.
+#
+# The contents of this file are pickled, so don't put values in the namespace
+# that aren't pickleable (module imports are okay, they're removed automatically).
+#
+# All configuration values have a default value; values that are commented out
+# serve to show the default value.
+
+import sys, os
+
+# If your extensions are in another directory, add it here. If the directory
+# is relative to the documentation root, use os.path.abspath to make it
+# absolute, like shown here.
+sys.path.append(os.path.abspath('sphinxext'))
+
+# Import support for ipython console session syntax highlighting (lives
+# in the sphinxext directory defined above)
+import ipython_console_highlighting
+
+# General configuration
+# ---------------------
+
+# Add any Sphinx extension module names here, as strings. They can be extensions
+# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
+extensions = ['mathpng', 'sphinx.ext.autodoc']
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['_templates']
+
+# The suffix of source filenames.
+source_suffix = '.rst'
+
+# The master toctree document.
+master_doc = 'index'
+
+# General substitutions.
+project = 'Matplotlib'
+copyright = '2008, John Hunter, Darren Dale, Michael Droettboom'
+
+# The default replacements for |version| and |release|, also used in various
+# other places throughout the built documents.
+#
+# The short X.Y version.
+version = '0.98'
+# The full version, including alpha/beta/rc tags.
+release = '0.98pre'
+
+# There are two options for replacing |today|: either, you set today to some
+# non-false value, then it is used:
+#today = ''
+# Else, today_fmt is used as the format for a strftime call.
+today_fmt = '%B %d, %Y'
+
+# List of documents that shouldn't be included in the build.
+unused_docs = []
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+#add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+#add_module_names = True
+
+# If true, sectionauthor and moduleauthor directives will be shown in the
+# output. They are ignored by default.
+#show_authors = False
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = 'sphinx'
+
+
+# Options for HTML output
+# -----------------------
+
+# The style sheet to use for HTML and HTML Help pages. A file of that name
+# must exist either in Sphinx' static/ path, or in one of the custom paths
+# given in html_static_path.
+html_style = 'default.css'
+
+# The name for this set of Sphinx documents. If None, it defaults to
+# "<project> v<release> documentation".
+#html_title = None
+
+# The name of an image file (within the static path) to place at the top of
+# the sidebar.
+#html_logo = 'logo.png'
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+html_static_path = ['_static']
+
+# If nonempty, this is the file name suffix for generated HTML files. The
+# default is ``".html"``.
+#html_file_suffix = '.xhtml'
+
+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
+# using the given strftime format.
+html_last_updated_fmt = '%b %d, %Y'
+
+# If true, SmartyPants will be used to convert quotes and dashes to
+# typographically correct entities.
+#html_use_smartypants = True
+
+# Custom sidebar templates, maps document names to template names.
+#html_sidebars = {}
+
+# Additional templates that should be rendered to pages, maps page names to
+# template names.
+#html_additional_pages = {}
+
+# If false, no module index is generated.
+#html_use_modindex = True
+
+# If true, the reST sources are included in the HTML build as _sources/<name>.
+#html_copy_source = True
+
+# If true, an OpenSearch description file will be output, and all pages will
+# contain a <link> tag referring to it.
+html_use_opensearch = 'False'
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = 'Matplotlibdoc'
+
+
+# Options for LaTeX output
+# ------------------------
+
+# The paper size ('letter' or 'a4').
+latex_paper_size = 'letter'
+
+# The font size ('10pt', '11pt' or '12pt').
+latex_font_size = '11pt'
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title, author, document class [howto/manual]).
+latex_documents = [
+ ('index', 'Matplotlib.tex', 'Matplotlib', 'John Hunter, Darren Dale', 'Michael Droettboom', 'manual'),
+]
+
+# The name of an image file (relative to this directory) to place at the top of
+# the title page.
+latex_logo = None
+
+# Additional stuff for the LaTeX preamble.
+latex_preamble = ''
+
+# Documents to append as an appendix to all manuals.
+latex_appendices = []
+
+# If false, no module index is generated.
+latex_use_modindex = True
+
+latex_use_parts = True
Added: trunk/matplotlib/docs/devel/add_new_projection.rst
===================================================================
--- trunk/matplotlib/docs/devel/add_new_projection.rst (rev 0)
+++ trunk/matplotlib/docs/devel/add_new_projection.rst 2008-05-24 20:49:31 UTC (rev 5253)
@@ -0,0 +1,105 @@
+***********************************************
+Adding new scales and projections to matplotlib
+***********************************************
+
+.. ::author Michael Droettboom
+
+Matplotlib supports the addition of custom procedures that transform
+the data before it is displayed.
+
+There is an important distinction between two kinds of
+transformations. Separable transformations, working on a single
+dimension, are called "scales", and non-separable transformations,
+that handle data in two or more dimensions at a time, are called
+"projections".
+
+From the user's perspective, the scale of a plot can be set with
+:meth:`~matplotlib.axes.Axes.set_xscale` and
+:meth:`~matplotlib.axes.Axes.set_xscale`. Projections can be chosen
+using the ``projection`` keyword argument to the
+:func:`~matplotlib.pylab.plot` or :func:`~matplotlib.pylab.subplot`
+functions, e.g.::
+
+ plot(x, y, projection="custom")
+
+This document is intended for developers and advanced users who need
+to create new scales and projections for matplotlib. The necessary
+code for scales and projections can be included anywhere: directly
+within a plot script, in third-party code, or in the matplotlib source
+tree itself.
+
+
+Creating a new scale
+====================
+
+Adding a new scale consists of defining a subclass of
+:class:`matplotlib.scale.ScaleBase`, that includes the following
+elements:
+
+ - A transformation from data coordinates into display coordinates.
+
+ - An inverse of that transformation. This is used, for example, to
+ convert mouse positions from screen space back into data space.
+
+ - A function to limit the range of the axis to acceptable values
+ (``limit_range_for_scale()``). A log scale, for instance, would
+ prevent the range from including values less than or equal to
+ zero.
+
+ - Locators (major and minor) that determine where to place ticks in
+ the plot, and optionally, how to adjust the limits of the plot to
+ some "good" values. Unlike ``limit_range_for_scale()``, which is
+ always enforced, the range setting here is only used when
+ automatically setting the range of the plot.
+
+ - Formatters (major and minor) that specify how the tick labels
+ should be drawn.
+
+Once the class is defined, it must be registered with matplotlib so
+that the user can select it.
+
+A full-fledged and heavily annotated example is in
+:file:`examples/api/custom_scale_example.py`. There are also some classes
+in :mod:`matplotlib.scale` that may be used as starting points.
+
+
+Creating a new projection
+=========================
+
+Adding a new projection consists of defining a subclass of
+:class:`matplotlib.axes.Axes`, that includes the following elements:
+
+ - A transformation from data coordinates into display coordinates.
+
+ - An inverse of that transformation. This is used, for example, to
+ convert mouse positions from screen space back into data space.
+
+ - Transformations for the gridlines, ticks and ticklabels. Custom
+ projections will often need to place these elements in special
+ locations, and matplotlib has a facility to help with doing so.
+
+ - Setting up default values (overriding
+ :meth:`~matplotlib.axes.Axes.cla`), since the defaults for a
+ rectilinear axes may not be appropriate.
+
+ - Defining the shape of the axes, for example, an elliptical axes,
+ that will be used to draw the background of the plot and for
+ clipping any data elements.
+
+ - Defining custom locators and formatters for the projection. For
+ example, in a geographic projection, it may be more convenient to
+ display the grid in degrees, even if the data is in radians.
+
+ - Set up interactive panning and zooming. This is left as an
+ "advanced" feature left to the reader, but there is an example of
+ this for polar plots in :mod:`matplotlib.projections.polar`.
+
+ - Any additional methods for additional convenience or features.
+
+Once the class is defined, it must be registered with matplotlib
+so that the user can select it.
+
+A full-fledged and heavily annotated example is in
+:file:`examples/api/custom_projection_example.py`. The polar plot
+functionality in :mod:`matplotlib.projections.polar` may also be of
+interest.
Added: trunk/matplotlib/docs/devel/coding_guide.rst
===================================================================
--- trunk/matplotlib/docs/devel/coding_guide.rst (rev 0)
+++ trunk/matplotlib/docs/devel/coding_guide.rst 2008-05-24 20:49:31 UTC (rev 5253)
@@ -0,0 +1,317 @@
+***************
+Version Control
+***************
+
+svn checkouts
+=============
+
+Checking out everything in the trunk (matplotlib and toolkits)::
+
+ svn co https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/trunk \
+ matplotlib --username=youruser --password=yourpass
+
+Checking out the main source::
+
+ svn co https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/trunk/\
+ matplotlib matplotlib --username=youruser --password=yourpass
+
+Branch checkouts, eg the maintenance branch::
+
+ svn co https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/\
+ v0_91_maint mplv0_91_maint
+
+Committing changes
+==================
+
+When committing changes to matplotlib, there are a few things to bear
+in mind.
+
+* if your changes are non-trivial, please make an entry in the
+ CHANGELOG
+* if you change the API, please document it in API_CHANGES, and
+ consider posting to mpl-devel
+* Are your changes python2.3 compatible? We are still trying to
+ support 2.3, so avoid 2.4 only features like decorators until we
+ remove 2.3 support
+* Can you pass examples/backend_driver.py? This is our poor man's
+ unit test.
+* If you have altered extension code, do you pass
+ unit/memleak_hawaii.py?
+* if you have added new files or directories, or reorganized
+ existing ones, are the new files included in the match patterns in
+ MANIFEST.in. This file determines what goes into the src
+ distribution of the mpl build.
+* Keep the maintenance branch and trunk in sync where it makes sense.
+ If there is a bug on both that needs fixing, use svnmerge.py to
+ keep them in sync. http://www.orcaware.com/svn/wiki/Svnmerge.py. The
+ basic procedure is:
+
+ * install svnmerge.py in your PATH::
+
+ wget http://svn.collab.net/repos/svn/trunk/contrib/client-side/\
+ svnmerge/svnmerge.py
+
+ * get a svn copy of the maintenance branch and the trunk (see above)
+ * Michael advises making the change on the branch and committing
+ it. Make sure you svn upped on the trunk and have no local
+ modifications, and then from the svn trunk do::
+
+ > svnmerge.py merge -rNNN1,NNN2
+
+ where the NNN* are the revision numbers. Ranges arealso acceptable.
+ svnmergy.py automatically creates a file containing the commit messages,
+ so you are ready to make the commit::
+
+ > svn commit -F svnmerge-commit-message.txt
+
+***********
+Style Guide
+***********
+
+Importing and name spaces
+=========================
+
+For numpy, use::
+
+ import numpy as np
+ a = np.array([1,2,3])
+
+For masked arrays, use::
+
+ from numpy import ma
+
+(The earlier recommendation, 'import matplotlib.numerix.npyma as ma',
+was needed temporarily during the development of the maskedarray
+implementation as a separate package. As of numpy 1.1, it replaces the
+old implementation. Note: "from numpy import ma" works with numpy < 1.1
+*and* with numpy >= 1.1. "import numpy.ma as ma" works *only* with
+numpy >= 1.1, so for now we must not use it.)
+
+For matplotlib main module, use::
+
+ import matplotlib as mpl
+ mpl.rcParams['xtick.major.pad'] = 6
+
+For matplotlib modules (or any other modules), use::
+
+ import matplotlib.cbook as cbook
+
+ if cbook.iterable(z):
+ pass
+
+We prefer this over the equivalent 'from matplotlib import cbook'
+because the latter is ambiguous whether cbook is a module or a
+function to the new developer. The former makes it explcit that
+you are importing a module or package.
+
+Naming, spacing, and formatting conventions
+===========================================
+
+In general, we want to hew as closely as possible to the standard
+coding guidelines for python written by Guido in
+http://www.python.org/dev/peps/pep-0008, though we do not do this
+throughout.
+
+* functions and class methods: lower or lower_underscore_separated
+
+* attributes and variables: lower or lowerUpper
+
+* classes: Upper or MixedCase
+
+Personally, I prefer the shortest names that are still readable.
+
+Also, use an editor that does not put tabs in files. Four spaces
+should be used for indentation everywhere and if there is a file with
+tabs or more or less spaces it is a bug -- please fix it.
+
+Please avoid spurious invisible spaces at the ends of lines.
+(Tell your editor to strip whitespace from line ends when saving
+a file.)
+
+Keep docstrings uniformly indented as in the example below, with
+nothing to the left of the triple quotes. The dedent() function
+is needed to remove excess indentation only if something will be
+interpolated into the docstring, again as in the example above.
+
+Limit line length to 80 characters. If a logical line needs to be
+longer, use parentheses to break it; do not use an escaped
+newline. It may be preferable to use a temporary variable
+to replace a single long line with two shorter and more
+readable lines.
+
+Please do not commit lines with trailing white space, as it causes
+noise in svn diffs. If you are an emacs user, the following in your
+.emacs will cause emacs to strip trailing white space on save for
+python, C and C++::
+
+ ; and similarly for c++-mode-hook and c-mode-hook
+ (add-hook 'python-mode-hook
+ (lambda ()
+ (add-hook 'write-file-functions 'delete-trailing-whitespace)))
+
+for older versions of emacs (emacs<22) you need to do::
+
+ (add-hook 'python-mode-hook
+ (lambda ()
+ (add-hook 'local-write-file-hooks 'delete-trailing-whitespace)))
+
+Keyword argument processing
+===========================
+
+Matplotlib makes extensive use of ``**kwargs`` for pass through
+customizations from one function to another. A typical example is in
+pylab.text, The definition of the pylab text function is a simple
+pass-through to axes.Axes.text::
+
+ # in pylab.py
+ def text(*args, **kwargs):
+ ret = gca().text(*args, **kwargs)
+ draw_if_interactive()
+ return ret
+
+axes.Axes.text in simplified form looks like this, ie it just passes
+them on to text.Text.__init__::
+
+ # in axes.py
+ def text(self, x, y, s, fontdict=None, withdash=False, **kwargs):
+ t = Text(x=x, y=y, text=s, **kwargs)
+
+and Text.__init__ (again with liberties for illustration) just passes
+them on to the artist.Artist.update method::
+
+ # in text.py
+ def __init__(self, x=0, y=0, text='', **kwargs):
+ Artist.__init__(self)
+ self.update(kwargs)
+
+'update' does the work looking for methods named like 'set_property'
+if 'property' is a keyword argument. Ie, noone looks at the keywords,
+they just get passed through the API to the artist constructor which
+looks for suitably named methods and calls them with the value.
+
+As a general rule, the use of ``**kwargs`` should be reserved for
+pass-through keyword arguments, as in the examaple above. If I intend
+for all the keyword args to be used in some function and not passed
+on, I just use the key/value keyword args in the function definition
+rather than the ``**kwargs`` idiom.
+
+In some cases I want to consume some keys and pass through the others,
+in which case I pop the ones I want to use locally and pass on the
+rest, eg I pop scalex and scaley in Axes.plot and assume the rest are
+Line2D keyword arguments. As an example of a pop, passthrough
+usage, see Axes.plot::
+
+ # in axes.py
+ def plot(self, *args, **kwargs):
+ scalex = kwargs.pop('scalex', True)
+ scaley = kwargs.pop('scaley', True)
+ if not self._hold: self.cla()
+ lines = []
+ for line in self._get_lines(*args, **kwargs):
+ self.add_line(line)
+ lines.append(line)
+
+The matplotlib.cbook function popd() is rendered
+obsolete by the pop() dictionary method introduced in Python 2.3,
+so it should not be used for new code.
+
+Note there is a use case when kwargs are meant to be used locally in
+the function (not passed on), but you still need the ``**kwargs`` idiom.
+That is when you want to use ``*args`` to allow variable numbers of
+non-keyword args. In this case, python will not allow you to use
+named keyword args after the ``*args`` usage, so you will be forced to use
+``**kwargs``. An example is matplotlib.contour.ContourLabeler.clabel::
+
+ # in contour.py
+ def clabel(self, *args, **kwargs):
+ fontsize = kwargs.get('fontsize', None)
+ inline = kwargs.get('inline', 1)
+ self.fmt = kwargs.get('fmt', '%1.3f')
+ colors = kwargs.get('colors', None)
+ if len(args) == 0:
+ levels = self.levels
+ indices = range(len(self.levels))
+ elif len(args) == 1:
+ ...etc...
+
+Documentation and Docstrings
+============================
+
+matplotlib uses artist instrospection of docstrings to support
+properties. All properties that you want to support through setp and
+getp should have a set_property and get_property method in the Artist
+class. Yes, this is not ideal given python properties or enthought
+traits, but it is a historical legacy for now. The setter methods use
+the docstring with the ACCEPTS token to indicate the type of argument
+the method accepts. Eg in matplotlib.lines.Line2D::
+
+ # in lines.py
+ def set_linestyle(self, linestyle):
+ """
+ Set the linestyle of the line
+
+ ACCEPTS: [ '-' | '--' | '-.' | ':' | 'steps' | 'None' | ' ' | '' ]
+ """
+
+Since matplotlib uses a lot of pass through kwargs, eg in every
+function that creates a line (plot, semilogx, semilogy, etc...), it
+can be difficult for the new user to know which kwargs are supported.
+I have developed a docstring interpolation scheme to support
+documentation of every function that takes a ``**kwargs``. The
+requirements are:
+
+1. single point of configuration so changes to the properties don't
+ require multiple docstring edits
+
+2. as automated as possible so that as properties change the docs
+ are updated automagically.
+
+I have added a matplotlib.artist.kwdocd and kwdoc() to faciliate this.
+They combines python string interpolation in the docstring with the
+matplotlib artist introspection facility that underlies setp and getp.
+The kwdocd is a single dictionary that maps class name to a docstring
+of kwargs. Here is an example from matplotlib.lines::
+
+ # in lines.py
+ artist.kwdocd['Line2D'] = artist.kwdoc(Line2D)
+
+Then in any function accepting Line2D passthrough kwargs, eg
+matplotlib.axes.Axes.plot::
+
+ # in axes.py
+ def plot(self, *args, **kwargs):
+ """
+ Some stuff omitted
+
+ The kwargs are Line2D properties:
+ %(Line2D)s
+
+ kwargs scalex and scaley, if defined, are passed on
+ to autoscale_view to determine whether the x and y axes are
+ autoscaled; default True. See Axes.autoscale_view for more
+ information
+ """
+ pass
+ plot.__doc__ = cbook.dedent(plot.__doc__) % artist.kwdocd
+
+Note there is a problem for Artist __init__ methods, eg Patch.__init__
+which supports Patch kwargs, since the artist inspector cannot work
+until the class is fully defined and we can't modify the
+Patch.__init__.__doc__ docstring outside the class definition. I have
+made some manual hacks in this case which violates the "single entry
+point" requirement above; hopefully we'll find a more elegant solution
+before too long
+
+********
+Licenses
+********
+
+Matplotlib only uses BSD compatible code. If you bring in code from
+another project make sure it has a PSF, BSD, MIT or compatible
+license. If not, you may consider contacting the author and asking
+them to relicense it. GPL and LGPL code are not acceptible in the
+main code base, though we are considering an alternative way of
+distributing L/GPL code through an separate channel, possibly a
+toolkit. If you include code, make sure you include a copy of that
+code's license in the license directory if the code's license requires
+you to distribute the license with it.
\ No newline at end of file
Added: trunk/matplotlib/docs/devel/documenting_mpl.rst
===================================================================
--- trunk/matplotlib/docs/devel/documenting_mpl.rst (rev 0)
+++ trunk/matplotlib/docs/devel/documenting_mpl.rst 2008-05-24 20:49:31 UTC (rev 5253)
@@ -0,0 +1,76 @@
+**********************
+Documenting Matplotlib
+**********************
+
+The documentation for matplotlib is generated from ReStructured Text
+using the Sphinx_ documentation generation tool. Sphinx-0.4 or later
+is required. Currently this means we need to install from the svn
+repository by doing::
+
+ svn co http://svn.python.org/projects/doctools/trunk sphinx
+ cd sphinx
+ python setup.py install
+
+.. _Sphinx: http://sphinx.pocoo.org/
+
+The documentation sources are found in the doc/ directory in the trunk.
+To build the users guid in html format, cd into doc/users_guide and do::
+
+ python make.py html
+
+you can also pass a ``latex`` flag to make.py to build a pdf, or pass no
+arguments to build everything. The same procedure can be followed for
+the sources in doc/api_reference.
+
+The actual ReStructured Text files are kept in doc/users_guide/source
+and doc/api_reference/source. The main entry point is index.rst.
+Additional files can be added by including their base file name
+(dropping the .rst extension) in the table of contents. It is also
+possible to include other documents through the use of an include
+statement. For example, in the Developers Guide, index.rst lists
+coding_guide, which automatically inserts coding_guide.rst.
+
+Mathematical expressions can be rendered as png images in html, and in
+the usual way by latex. For example:
+
+``math:`sin(x_n^2)`` yields: :math:`sin(x_n^2)`, and::
+
+ .. math::
+
+ \int_{-\infty}^{\infty}\frac{e^{i\phi}}{1+x^2\frac{e^{i\phi}}{1+x^2}}``
+
+yields:
+
+.. math::
+
+ \int_{-\infty}^{\infty}\frac{e^{i\phi}}{1+x^2\frac{e^{i\phi}}{1+x^2}}
+
+The output produced by Sphinx can be configured by editing the conf.py
+files located in the documentation source directories.
+
+The Sphinx website contains plenty of documentation_ concerning ReST
+markup and working with Sphinx in general.
+
+.. _documentation: http://sphinx.pocoo.org/contents.html
+
+Referring to mpl documents
+==========================
+
+In the documentation, you may want to include to a document in the
+matplotlib src, eg a license file, an image file from ``mpl-data``, or an
+example. When you include these files, include them using a symbolic
+link from the documentation parent directory. This way, if we
+relocate the mpl documentation directory, all of the internal pointers
+to files will not have to change, just the top level symlinks. For
+example, In the top level doc directory we have symlinks pointing to
+the mpl ``examples`` and ``mpl-data``::
+
+ home:~/mpl/doc2> ls -l mpl_*
+ mpl_data -> ../lib/matplotlib/mpl-data
+ mpl_examples -> ../examples
+
+
+In the ``users`` subdirectory, if I want to refer to a file in the mpl-data directory, I use the symlink direcotry. For example, from ``customizing.rst``::
+
+ .. literalinclude:: ../mpl_data/matplotlibrc
+
Added: trunk/matplotlib/docs/devel/index.rst
===================================================================
--- trunk/matplotlib/docs/devel/index.rst (rev 0)
+++ trunk/matplotlib/docs/devel/index.rst 2008-05-24 20:49:31 UTC (rev 5253)
@@ -0,0 +1,16 @@
+.. _developers_guide-index:
+
+###################################
+ The Matplotlib Developers's Guide
+###################################
+
+:Release: |version|
+:Date: |today|
+
+Introduction to developer's guide here **TODO**.
+
+.. toctree::
+
+ coding_guide.rst
+ documenting_mpl.rst
+ add_new_projection.rst
Added: trunk/matplotlib/docs/index.rst
===================================================================
--- trunk/matplotlib/docs/index.rst (rev 0)
+++ trunk/matplotlib/docs/index.rst 2008-05-24 20:49:31 UTC (rev 5253)
@@ -0,0 +1,23 @@
+.. matplotlib documentation master file, created by sphinx-quickstart on Sat May 24 15:37:00 2008.
+ You can adapt this file completely to your liking, but it should at least
+ contain the root `toctree` directive.
+
+Welcome to matplotlib's documentation!
+======================================
+
+Contents:
+
+.. toctree::
+ :maxdepth: 2
+
+ users/index.rst
+ devel/index.rst
+ api/index.rst
+
+Indices and tables
+==================
+
+* :ref:`genindex`
+* :ref:`modindex`
+* :ref:`search`
+
Added: trunk/matplotlib/docs/make.py
===================================================================
--- trunk/matplotlib/docs/make.py (rev 0)
+++ trunk/matplotlib/docs/make.py 2008-05-24 20:49:31 UTC (rev 5253)
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+import fileinput
+import glob
+import os
+import shutil
+import sys
+
+def check_build():
+ build_dirs = ['build', 'build/doctrees', 'build/html', 'build/latex',
+ '_static', '_templates']
+ for d in build_dirs:
+ try:
+ os.mkdir(d)
+ except OSError:
+ pass
+
+def figs():
+ os.system('cd users/figures/ && python make.py')
+
+def html():
+ check_build()
+ os.system('sphinx-build -b html -d build/doctrees . build/html')
+
+def latex():
+ if sys.platform != 'win32':
+ # LaTeX format.
+ os.system('sphinx-build -b latex -d build/doctrees . build/latex')
+
+ # Produce pdf.
+ os.chdir('build/latex')
+
+ # Copying the makefile produced by sphinx...
+ os.system('pdflatex Matplotlib_Users_Guide.tex')
+ os.system('pdflatex Matplotlib_Users_Guide.tex')
+ os.system('makeindex -s python.ist Matplotlib_Users_Guide.idx')
+ os.system('makeindex -s python.ist modMatplotlib_Users_Guide.idx')
+ os.system('pdflatex Matplotlib_Users_Guide.tex')
+
+ os.chdir('../..')
+ else:
+ print 'latex build has not been tested on windows'
+
+def clean():
+ shutil.rmtree('build')
+
+def all():
+ figs()
+ html()
+ latex()
+
+
+funcd = {'figs':figs,
+ 'html':html,
+ 'latex':latex,
+ 'clean':clean,
+ 'all':all,
+ }
+
+
+if len(sys.argv)>1:
+ for arg in sys.argv[1:]:
+ func = funcd.get(arg)
+ if func is None:
+ raise SystemExit('Do not know how to handle %s; valid args are'%(
+ arg, funcd.keys()))
+ func()
+else:
+ all()
Property changes on: trunk/matplotlib/docs/make.py
___________________________________________________________________
Name: svn:executable
+ *
Added: trunk/matplotlib/docs/mpl_data
===================================================================
--- trunk/matplotlib/docs/mpl_data (rev 0)
+++ trunk/matplotlib/docs/mpl_data 2008-05-24 20:49:31 UTC (rev 5253)
@@ -0,0 +1 @@
+link ../lib/matplotlib/mpl-data/
\ No newline at end of file
Property changes on: trunk/matplotlib/docs/mpl_data
___________________________________________________________________
Name: svn:special
+ *
Added: trunk/matplotlib/docs/mpl_examples
===================================================================
--- trunk/matplotlib/docs/mpl_examples (rev 0)
+++ trunk/matplotlib/docs/mpl_examples 2008-05-24 20:49:31 UTC (rev 5253)
@@ -0,0 +1 @@
+link ../examples/
\ No newline at end of file
Property changes on: trunk/matplotlib/docs/mpl_examples
___________________________________________________________________
Name: svn:special
+ *
Added: trunk/matplotlib/docs/sphinxext/ipython_console_highlighting.py
===================================================================
--- trunk/matplotlib/docs/sphinxext/ipython_console_highlighting.py (rev 0)
+++ trunk/matplotlib/docs/sphinxext/ipython_console_highlighting.py 2008-05-24 20:49:31 UTC (rev 5253)
@@ -0,0 +1,75 @@
+from pygments.lexer import Lexer, do_insertions
+from pygments.lexers.agile import PythonConsoleLexer, PythonLexer, \
+ PythonTracebackLexer
+from pygments.token import Comment, Generic
+from sphinx import highlighting
+import re
+
+line_re = re.compile('.*?\n')
+
+class IPythonConsoleLexer(Lexer):
+ """
+ For IPython console output or doctests, such as:
+
+ Tracebacks are not currently supported.
+
+ .. sourcecode:: pycon
+
+ In [1]: a = 'foo'
+
+ In [2]: a
+ Out[2]: 'foo'
+
+ In [3]: print a
+ foo
+
+ In [4]: 1 / 0
+ """
+ name = 'IPython console session'
+ aliases = ['ipython']
+ mimetypes = ['text/x-ipython-console']
+ input_prompt = re.compile("(In \[[0-9]+\]: )|( \.\.\.+:)")
+ output_prompt = re.compile("(Out\[[0-9]+\]: )|( \.\.\.+:)")
+ continue_prompt = re.compile(" \.\.\.+:")
+ tb_start = re.compile("\-+")
+
+ def get_tokens_unprocessed(self, text):
+ pylexer = PythonLexer(**self.options)
+ tblexer = PythonTracebackLexer(**self.options)
+
+ curcode = ''
+ insertions = []
+ for match in line_re.finditer(text):
+ line = match.group()
+ input_prompt = self.input_prompt.match(line)
+ continue_prompt = self.continue_prompt.match(line.rstrip())
+ output_prompt = self.output_prompt.match(line)
+ if line.startswith("#"):
+ insertions.append((len(curcode),
+ [(0, Comment, line)]))
+ elif input_prompt is not None:
+ insertions.append((len(curcode),
+ [(0, Generic.Prompt, input_prompt.group())]))
+ curcode += line[input_prompt.end():]
+ elif continue_prompt is not None:
+ insertions.append((len(curcode),
+ [(0, Generic.Prompt, continue_prompt.group())]))
+ curcode += line[continue_prompt.end():]
+ elif output_prompt is not None:
+ insertions.append((len(curcode),
+ [(0, Generic.Output, output_prompt.group())]))
+ curcode += line[output_prompt.end():]
+ else:
+ if curcode:
+ for item in do_insertions(insertions,
+ pylexer.get_tokens_unprocessed(curcode)):
+ yield item
+ curcode = ''
+ insertions = []
+ yield match.start(), Generic.Output, line
+ if curcode:
+ for item in do_insertions(insertions,
+ pylexer.get_tokens_unprocessed(curcode)):
+ yield item
+
+highlighting.lexers['ipython'] = IPythonConsoleLexer()
Added: trunk/matplotlib/docs/sphinxext/mathml.py
===================================================================
--- trunk/matplotlib/docs/sphinxext/mathml.py (rev 0)
+++ trunk/matplotlib/docs/sphinxext/mathml.py 2008-05-24 20:49:31 UTC (rev 5253)
@@ -0,0 +1,552 @@
+from docutils import nodes
+from docutils.writers.html4css1 import HTMLTranslator
+from sphinx.latexwriter import LaTeXTranslator
+
+# Define LaTeX math node:
+class latex_math(nodes.General, nodes.Element):
+ pass
+
+def math_role(role, rawtext, text, lineno, inliner,
+ options={}, content=[]):
+ i = rawtext.find('`')
+ latex = rawtext[i+1:-1]
+ try:
+ mathml_tree = parse_latex_math(latex, inline=True)
+ except SyntaxError, msg:
+ msg = inliner.reporter.error(msg, line=lineno)
+ prb = inliner.problematic(rawtext, rawtext, msg)
+ return [prb], [msg]
+ node = latex_math(rawtext)
+ node['latex'] = latex
+ node['mathml_tree'] = mathml_tree
+ return [node], []
+
+
+try:
+ from docutils.parsers.rst import Directive
+except ImportError:
+ # Register directive the old way:
+ from docutils.parsers.rst.directives import _directives
+ def math_directive(name, arguments, options, content, lineno,
+ content_offset, block_text, state, state_machine):
+ latex = ''.join(content)
+ try:
+ mathml_tree = parse_latex_math(latex, inline=False)
+ except SyntaxError, msg:
+ error = state_machine.reporter.error(
+ msg, nodes.literal_block(block_text, block_text), line=lineno)
+ return [error]
+ node = latex_math(block_text)
+ node['latex'] = latex
+ node['mathml_tree'] = mathml_tree
+ return [node]
+ math_directive.arguments = None
+ math_directive.options = {}
+ math_directive.content = 1
+ _directives['math'] = math_directive
+else:
+ class math_directive(Directive):
+ has_content = True
+ def run(self):
+ latex = ' '.join(self.content)
+ try:
+ mathml_tree = parse_latex_math(latex, inline=False)
+ except SyntaxError, msg:
+ error = self.state_machine.reporter.error(
+ msg, nodes.literal_block(self.block_text, self.block_text),
+ line=self.lineno)
+ return [error]
+ node = latex_math(self.block_text)
+ node['latex'] = latex
+ node['mathml_tree'] = mathml_tree
+ return [node]
+ from docutils.parsers.rst import directives
+ directives.register_directive('math', math_directive)
+
+def setup(app):
+ app.add_node(latex_math)
+ app.add_role('math', math_role)
+
+ # Add visit/depart methods to HTML-Translator:
+ def visit_latex_math_html(self, node):
+ mathml = ''.join(node['mathml_tree'].xml())
+ self.body.append(mathml)
+ def depart_latex_math_html(self, node):
+ pass
+ HTMLTranslator.visit_latex_math = visit_latex_math_html
+ HTMLTranslator.depart_latex_math = depart_latex_math_html
+
+ # Add visit/depart methods to LaTeX-Translator:
+ def visit_latex_math_latex(self, node):
+ inline = isinstance(node.parent, nodes.TextElement)
+ if inline:
+ self.body.append('$%s$' % node['latex'])
+ else:
+ self.body.extend(['\\begin{equation}',
+ node['latex'],
+ '\\end{equation}'])
+ def depart_latex_math_latex(self, node):
+ pass
+ LaTeXTranslator.visit_latex_math = visit_latex_math_latex
+ LaTeXTranslator.depart_latex_math = depart_latex_math_latex
+
+
+# LaTeX to MathML translation stuff:
+class math:
+ """Base class for MathML elements."""
+
+ nchildren = 1000000
+ """Required number of children"""
+
+ def __init__(self, children=None, inline=None):
+ """math([children]) -> MathML element
+
+ children can be one child or a list of children."""
+
+ self.children = []
+ if children is not None:
+ if type(children) is list:
+ for child in children:
+ self.append(child)
+ else:
+ # Only one child:
+ self.append(children)
+
+ if inline is not None:
+ self.inline = inline
+
+ def __repr__(self):
+ if hasattr(self, 'children'):
+ return self.__class__.__name__ + '(%s)' % \
+ ','.join([repr(child) for child in self.children])
+ else:
+ return self.__class__.__name__
+
+ def full(self):
+ """Room for more children?"""
+
+ return len(self.children) >= self.nchildren
+
+ def append(self, child):
+ """append(child) -> element
+
+ Appends child and returns self if self is not full or first
+ non-full parent."""
+
+ assert not self.full()
+ self.children.append(child)
+ child.parent = self
+ node = self
+ while node.full():
+ node = node.parent
+ return node
+
+ def delete_child(self):
+ """delete_child() -> child
+
+ Delete last child and return it."""
+
+ child = self.children[-1]
+ del self.children[-1]
+ return child
+
+ def close(self):
+ """close() -> parent
+
+ Close element and return first non-full element."""
+
+ parent = self.parent
+ while parent.full():
+ parent = parent.parent
+ return parent
+
+ def xml(self):
+ """xml() -> xml-string"""
+
+ return self.xml_start() + self.xml_body() + self.xml_end()
+
+ def xml_start(self):
+ if not hasattr(self, 'inline'):
+ return ['<%s>' % self.__class__.__name__]
+ xmlns = 'http://www.w3.org/1998/Math/MathML'
+ if self.inline:
+ return ['<math xmlns="%s">' % xmlns]
+ else:
+ return ['<math xmlns="%s" mode="display">' % xmlns]
+
+ def xml_end(self):
+ return ['</%s>' % self.__class__.__name__]
+
+ def xml_body(self):
+ xml = []
+ for child in self.children:
+ xml.extend(child.xml())
+ return xml
+
+class mrow(math): pass
+class mtable(math): pass
+class mtr(mrow): pass
+class mtd(mrow): pass
+
+class mx(math):
+ """Base class for mo, mi, and mn"""
+
+ nchildren = 0
+ def __init__(self, data):
+ self.data = data
+
+ def xml_body(self):
+ return [self.data]
+
+class mo(mx):
+ translation = {'<': '<', '>': '>'}
+ def xml_body(self):
+ return [self.translation.get(self.data, self.data)]
+
+class mi(mx): pass
+class mn(mx): pass
+
+class msub(math):
+ nchildren = 2
+
+class msup(math):
+ nchildren = 2
+
+class msqrt(math):
+ nchildren = 1
+
+class mroot(math):
+ nchildren = 2
+
+class mfrac(math):
+ nchildren = 2
+
+class msubsup(math):
+ nchildren = 3
+ def __init__(self, children=None, reversed=False):
+ self.reversed = reversed
+ math.__init__(self, children)
+
+ def xml(self):
+ if self.reversed:
+## self.children[1:3] = self.children[2:0:-1]
+ self.children[1:3] = [self.children[2], self.children[1]]
+ self.reversed = False
+ return math.xml(self)
+
+class mfenced(math):
+ translation = {'\\{': '{', '\\langle': u'\u2329',
+ '\\}': '}', '\\rangle': u'\u232A',
+ '.': ''}
+ def __init__(self, par):
+ self.openpar = par
+ math.__init__(self)
+
+ def xml_start(self):
+ open = self.translation.get(self.openpar, self.openpar)
+ close = self.translation.get(self.closepar, self.closepar)
+ return ['<mfenced open="%s" close="%s">' % (open, close)]
+
+class mspace(math):
+ nchildren = 0
+
+class mstyle(math):
+ def __init__(self, children=None, nchildren=None, **kwargs):
+ if nchildren is not None:
+ self.nchildren = nchildren
+ math.__init__(self, children)
+ self.attrs = kwargs
+
+ def xml_start(self):
+ return ['<mstyle '] + ['%s="%s"' % item
+ for item in self.attrs.items()] + ['>']
+
+class mover(math):
+ nchildren = 2
+ def __init__(self, children=None, reversed=False):
+ self.reversed = reversed
+ math.__init__(self, children)
+
+ def xml(self):
+ if self.reversed:
+ self.children.reverse()
+ self.reversed = False
+ return math.xml(self)
+
+class munder(math):
+ nchildren = 2
+
+class munderover(math):
+ nchildren = 3
+ def __init__(self, children=None):
+ math.__init__(self, children)
+
+class mtext(math):
+ nchildren = 0
+ def __init__(self, text):
+ self.text = text
+
+ def xml_body(self):
+ return [self.text]
+
+
+over = {'tilde': '~',
+ 'hat': '^',
+ 'bar': '_',
+ 'vec': u'\u2192'}
+
+Greek = {
+ # Upper case greek letters:
+ 'Phi': u'\u03a6', 'Xi': u'\u039e', 'Sigma': u'\u03a3', 'Psi': u'\u03a8', 'Delta': u'\u0394', 'Theta': u'\u0398', 'Upsilon': u'\u03d2', 'Pi': u'\u03a0', 'Omega': u'\u03a9', 'Gamma': u'\u0393', 'Lambda': u'\u039b'}
+greek = {
+ # Lower case greek letters:
+ 'tau': u'\u03c4', 'phi': u'\u03d5', 'xi': u'\u03be', 'iota': u'\u03b9', 'epsilon': u'\u03f5', 'varrho': u'\u03f1', 'varsigma': u'\u03c2', 'beta': u'\u03b2', 'psi': u'\u03c8', 'rho': u'\u03c1', 'delta': u'\u03b4', 'alpha': u'\u03b1', 'zeta': u'\u03b6', 'omega': u'\u03c9', 'varepsilon': u'\u03b5', 'kappa': u'\u03ba', 'vartheta': u'\u03d1', 'chi': u'\u03c7', 'upsilon': u'\u03c5', 'sigma': u'\u03c3', 'varphi': u'\u03c6', 'varpi': u'\u03d6', 'mu': u'\u03bc', 'eta': u'\u03b7', 'theta': u'\u03b8', 'pi': u'\u03c0', 'varkappa': u'\u03f0', 'nu': u'\u03bd', 'gamma': u'\u03b3', 'lambda': u'\u03bb'}
+
+special = {
+ # Binary operation symbols:
+ 'wedge': u'\u2227', 'diamond': u'\u22c4', 'star': u'\u22c6', 'amalg': u'\u2a3f', 'ast': u'\u2217', 'odot': u'\u2299', 'triangleleft': u'\u25c1', 'bigtriangleup': u'\u25b3', 'ominus': u'\u2296', 'ddagger': u'\u2021', 'wr': u'\u2240', 'otimes': u'\u2297', 'sqcup': u'\u2294', 'oplus': u'\u2295', 'bigcirc': u'\u25cb', 'oslash': u'\u2298', 'sqcap': u'\u2293', 'bullet': u'\u2219', 'cup': u'\u222a', 'cdot': u'\u22c5', 'cap': u'\u2229', 'bigtriangledown': u'\u25bd', 'times': u'\xd7', 'setminus': u'\u2216', 'circ': u'\u2218', 'vee': u'\u2228', 'uplus': u'\u228e', 'mp': u'\u2213', 'dagger': u'\u2020', 'triangleright': u'\u25b7', 'div': u'\xf7', 'pm': u'\xb1',
+ # Relation symbols:
+ 'subset': u'\u2282', 'propto': u'\u221d', 'geq': u'\u2265', 'ge': u'\u2265', 'sqsubset': u'\u228f', 'Join': u'\u2a1d', 'frown': u'\u2322', 'models': u'\u22a7', 'supset': u'\u2283', 'in': u'\u2208', 'doteq': u'\u2250', 'dashv': u'\u22a3', 'gg': u'\u226b', 'leq': u'\u2264', 'succ': u'\u227b', 'vdash': u'\u22a2', 'cong': u'\u2245', 'simeq': u'\u2243', 'subseteq': u'\u2286', 'parallel': u'\u2225', 'equiv': u'\u2261', 'ni': u'\u220b', 'le': u'\u2264', 'approx': u'\u2248', 'precsim': u'\u227e', 'sqsupset': u'\u2290', 'll': u'\u226a', 'sqsupseteq': u'\u2292', 'mid': u'\u2223', 'prec': u'\u227a', 'succsim': u'\u227f', 'bowtie': u'\u22c8', 'perp': u'\u27c2', 'sqsubseteq': u'\u2291', 'asymp': u'\u224d', 'smile': u'\u2323', 'supseteq': u'\u2287', 'sim': u'\u223c', 'neq': u'\u2260',
+ # Arrow symbols:
+ 'searrow': u'\u2198', 'updownarrow': u'\u2195', 'Uparrow': u'\u21d1', 'longleftrightarrow': u'\u27f7', 'Leftarrow': u'\u21d0', 'longmapsto': u'\u27fc', 'Longleftarrow': u'\u27f8', 'nearrow': u'\u2197', 'hookleftarrow': u'\u21a9', 'downarrow': u'\u2193', 'Leftrightarrow': u'\u21d4', 'longrightarrow': u'\u27f6', 'rightharpoondown': u'\u21c1', 'longleftarrow': u'\u27f5', 'rightarrow': u'\u2192', 'Updownarrow': u'\u21d5', 'rightharpoonup': u'\u21c0', 'Longleftrightarrow': u'\u27fa', 'leftarrow': u'\u2190', 'mapsto': u'\u21a6', 'nwarrow': u'\u2196', 'uparrow': u'\u2191', 'leftharpoonup': u'\u21bc', 'leftharpoondown': u'\u21bd', 'Downarrow': u'\u21d3', 'leftrightarrow': u'\u2194', 'Longrightarrow': u'\u27f9', 'swarrow': u'\u2199', 'hookrightarrow': u'\u21aa', 'Rightarrow': u'\u21d2',
+ # Miscellaneous symbols:
+ 'infty': u'\u221e', 'surd': u'\u221a', 'partial': u'\u2202', 'ddots': u'\u22f1', 'exists': u'\u2203', 'flat': u'\u266d', 'diamondsuit': u'\u2662', 'wp': u'\u2118', 'spadesuit': u'\u2660', 'Re': u'\u211c', 'vdots': u'\u22ee', 'aleph': u'\u2135', 'clubsuit': u'\u2663', 'sharp': u'\u266f', 'angle': u'\u2220', 'prime': u'\u2032', 'natural': u'\u266e', 'ell': u'\u2113', 'neg': u'\xac', 'top': u'\u22a4', 'nabla': u'\u2207', 'bot': u'\u22a5', 'heartsuit': u'\u2661', 'cdots': u'\u22ef', 'Im': u'\u2111', 'forall': u'\u2200', 'imath': u'\u0131', 'hbar': u'\u210f', 'emptyset': u'\u2205',
+ # Variable-sized symbols:
+ 'bigotimes': u'\u2a02', 'coprod': u'\u2210', 'int': u'\u222b', 'sum': u'\u2211', 'bigodot': u'\u2a00', 'bigcup': u'\u22c3', 'biguplus': u'\u2a04', 'bigcap': u'\u22c2', 'bigoplus': u'\u2a01', 'oint': u'\u222e', 'bigvee': u'\u22c1', 'bigwedge': u'\u22c0', 'prod': u'\u220f',
+ # Braces:
+ 'langle': u'\u2329', 'rangle': u'\u232A'}
+
+sumintprod = ''.join([special[symbol] for symbol in
+ ['sum', 'int', 'oint', 'prod']])
+
+functions = ['arccos', 'arcsin', 'arctan', 'arg', 'cos', 'cosh',
+ 'cot', 'coth', 'csc', 'deg', 'det', 'dim',
+ 'exp', 'gcd', 'hom', 'inf', 'ker', 'lg',
+ 'lim', 'liminf', 'limsup', 'ln', 'log', 'max',
+ 'min', 'Pr', 'sec', 'sin', 'sinh', 'sup',
+ 'tan', 'tanh',
+ 'injlim', 'varinjlim', 'varlimsup',
+ 'projlim', 'varliminf', 'varprojlim']
+
+
+def parse_latex_math(string, inline=True):
+ """parse_latex_math(string [,inline]) -> MathML-tree
+
+ Returns a MathML-tree parsed from string. inline=True is for
+ inline math and inline=False is for displayed math.
+
+ tree is the whole tree and node is the current element."""
+
+ # Normalize white-space:
+ string = ' '.join(string.split())
+
+ if inline:
+ node = mrow()
+ tree = math(node, inline=True)
+ else:
+ node = mtd()
+ tree = math(mtable(mtr(node)), inline=False)
+
+ while len(string) > 0:
+ n = len(string)
+ c = string[0]
+ skip = 1 # number of characters consumed
+ if n > 1:
+ c2 = string[1]
+ else:
+ c2 = ''
+## print n, string, c, c2, node.__class__.__name__
+ if c == ' ':
+ pass
+ elif c == '\\':
+ if c2 in '{}':
+ node = node.append(mo(c2))
+ skip = 2
+ elif c2 == ' ':
+ node = node.append(mspace())
+ skip = 2
+ elif c2.isalpha():
+ # We have a LaTeX-name:
+ i = 2
+ while i < n and string[i].isalpha():
+ i += 1
+ name = string[1:i]
+ node, skip = handle_keyword(name, node, string[i:])
+ skip += i
+ elif c2 == '\\':
+ # End of a row:
+ entry = mtd()
+ row = mtr(entry)
+ node.close().close().append(row)
+ node = entry
+ skip = 2
+ else:
+ raise SyntaxError('Syntax error: "%s%s"' % (c, c2))
+ elif c.isalpha():
+ node = node.append(mi(c))
+ elif c.isdigit():
+ node = node.append(mn(c))
+ elif c in "+-/()[]|=<>,.!'":
+ node = node.append(mo(c))
+ elif c == '_':
+ child = node.delete_child()
+ if isinstance(child, msup):
+ sub = msubsup(child.children, reversed=True)
+ elif isinstance(child, mo) and child.data in sumintprod:
+ sub = munder(child)
+ else:
+ sub = msub(child)
+ node.append(sub)
+ node = sub
+ elif c == '^':
+ child = node.delete_child()
+ if isinstance(child, msub):
+ sup = msubsup(child.children)
+ elif isinstance(child, mo) and child.data in sumintprod:
+ sup = mover(child)
+ elif (isinstance(child, munder) and
+ child.children[0].data in sumintprod):
+ sup = munderover(child.children)
+ else:
+ sup = msup(child)
+ node.append(sup)
+ node = sup
+ elif c == '{':
+ row = mrow()
+ node.append(row)
+ node = row
+ elif c == '}':
+ node = node.close()
+ elif c == '&':
+ entry = mtd()
+ node.close().append(entry)
+ node = entry
+ else:
+ raise SyntaxError('Illegal character: "%s"' % c)
+ string = string[skip:]
+ return tree
+
+
+mathbb = {'A': u'\U0001D538',
+ 'B': u'\U0001D539',
+ 'C': u'\u2102',
+ 'D': u'\U0001D53B',
+ 'E': u'\U0001D53C',
+ 'F': u'\U0001D53D',
+ 'G': u'\U0001D53E',
+ 'H': u'\u210D',
+ 'I': u'\U0001D540',
+ 'J': u'\U0001D541',
+ 'K': u'\U0001D542',
+ 'L': u'\U0001D543',
+ 'M': u'\U0001D544',
+ 'N': u'\u2115',
+ 'O': u'\U0001D546',
+ 'P': u'\u2119',
+ 'Q': u'\u211A',
+ 'R': u'\u211D',
+ 'S': u'\U0001D54A',
+ 'T': u'\U0001D54B',
+ 'U': u'\U0001D54C',
+ 'V': u'\U0001D54D',
+ 'W': u'\U0001D54E',
+ 'X': u'\U0001D54F',
+ 'Y': u'\U0001D550',
+ 'Z': u'\u2124'}
+
+negatables = {'=': u'\u2260',
+ '\in': u'\u2209',
+ '\equiv': u'\u2262'}
+
+
+def handle_keyword(name, node, string):
+ skip = 0
+ if len(string) > 0 and string[0] == ' ':
+ string = string[1:]
+ skip = 1
+ if name == 'begin':
+ if not string.startswith('{matrix}'):
+ raise SyntaxError('Expected "\begin{matrix}"!')
+ skip += 8
+ entry = mtd()
+ table = mtable(mtr(entry))
+ node.append(table)
+ node = entry
+ elif name == 'end':
+ if not string.startswith('{matrix}'):
+ raise SyntaxError('Expected "\end{matrix}"!')
+ skip += 8
+ node = node.close().close().close()
+ elif name == 'text':
+ if string[0] != '{':
+ raise SyntaxError('Expected "\text{...}"!')
+ i = string.find('}')
+ if i == -1:
+ raise SyntaxError('Expected "\text{...}"!')
+ node = node.append(mtext(string[1:i]))
+ skip += i + 1
+ elif name == 'sqrt':
+ sqrt = msqrt()
+ node.append(sqrt)
+ node = sqrt
+ elif name == 'frac':
+ frac = mfrac()
+ node.append(frac)
+ node = frac
+ elif name == 'left':
+ for par in ['(', '[', '|', '\\{', '\\langle', '.']:
+ if string.startswith(par):
+ break
+ else:
+ raise SyntaxError('Missing left-brace!')
+ fenced = mfenced(par)
+ node.append(fenced)
+ row = mrow()
+ fenced.append(row)
+ node = row
+ skip += len(par)
+ elif name == 'right':
+ for par in [')', ']', '|', '\\}', '\\rangle', '.']:
+ if string.startswith(par):
+ break
+ else:
+ raise SyntaxError('Missing right-brace!')
+ node = node.close()
+ node.closepar = par
+ node = node.close()
+ skip += len(par)
+ elif name == 'not':
+ for operator in negatables:
+ if string.startswith(operator):
+ break
+ else:
+ raise SyntaxError('Expected something to negate: "\\not ..."!')
+ node = node.append(mo(negatables[operator]))
+ skip += len(operator)
+ elif name == 'mathbf':
+ style = mstyle(nchildren=1, fontweight='bold')
+ node.append(style)
+ node = style
+ elif name == 'mathbb':
+ if string[0] != '{' or not string[1].isupper() or string[2] != '}':
+ raise SyntaxError('Expected something like "\mathbb{A}"!')
+ node = node.append(mi(mathbb[string[1]]))
+ skip += 3
+ elif name in greek:
+ node = node.append(mi(greek[name]))
+ elif name in Greek:
+ node = node.append(mo(Greek[name]))
+ elif name in special:
+ node = node.append(mo(special[name]))
+ elif name in functions:
+ node = node.append(mo(name))
+ else:
+ chr = over.get(name)
+ if chr is not None:
+ ovr = mover(mo(chr), reversed=True)
+ node.append(ovr)
+ node = ovr
+ else:
+ raise SyntaxError('Unknown LaTeX command: ' + name)
+
+ return node, skip
Added: trunk/matplotlib/docs/sphinxext/mathpng.py
===================================================================
--- trunk/matplotlib/docs/sphinxext/mathpng.py (rev 0)
+++ trunk/matplotlib/docs/sphinxext/mathpng.py 2008-05-24 20:49:31 UTC (rev 5253)
@@ -0,0 +1,111 @@
+import os
+try:
+ from hashlib import md5
+except ImportError:
+ from md5 import md5
+
+from docutils import nodes
+from docutils.writers.html4css1 import HTMLTranslator
+from sphinx.latexwriter import LaTeXTranslator
+
+# Define LaTeX math node:
+class latex_math(nodes.General, nodes.Element):
+ pass
+
+def math_role(role, rawtext, text, lineno, inliner,
+ options={}, content=[]):
+ i = rawtext.find('`')
+ latex = rawtext[i+1:-1]
+ node = latex_math(rawtext)
+ node['latex'] = latex
+ return [node], []
+
+
+try:
+ from docutils.parsers.rst import Directive
+except ImportError:
+ # Register directive the old way:
+ from docutils.parsers.rst.directives import _directives
+ def math_directive(name, arguments, options, content, lineno,
+ content_offset, block_text, state, state_machine):
+ latex = ''.join(content)
+ node = latex_math(block_text)
+ node['latex'] = latex
+ return [node]
+ math_directive.arguments = None
+ math_directive.options = {}
+ math_directive.content = 1
+ _directives['math'] = math_directive
+else:
+ class math_directive(Directive):
+ has_content = True
+ def run(self):
+ latex = ' '.join(self.content)
+ node = latex_math(self.block_text)
+ node['latex'] = latex
+ return [node]
+ from docutils.parsers.rst import directives
+ directives.register_directive('math', math_directive)
+
+def setup(app):
+ app.add_node(latex_math)
+ app.add_role('math', math_role)
+
+ # Add visit/depart methods to HTML-Translator:
+ def visit_latex_math_html(self, node):
+ source = self.document.attributes['source']
+ self.body.append(latex2html(node, source))
+ def depart_latex_math_html(self, node):
+ pass
+ HTMLTranslator.visit_latex_math = visit_latex_math_html
+ HTMLTranslator.depart_latex_math = depart_latex_math_html
+
+ # Add visit/depart methods to LaTeX-Translator:
+ def visit_latex_math_latex(self, node):
+ inline = isinstance(node.parent, nodes.TextElement)
+ if inline:
+ self.body.append('$%s$' % node['latex'])
+ else:
+ self.body.extend(['\\begin{equation}',
+ node['latex'],
+ '\\end{equation}'])
+ def depart_latex_math_latex(self, node):
+ pass
+ LaTeXTranslator.visit_latex_math = visit_latex_math_latex
+ LaTeXTranslator.depart_latex_math = depart_latex_math_latex
+
+from os.path import isfile
+# LaTeX to HTML translation stuff:
+def latex2html(node, source):
+ inline = isinstance(node.parent, nodes.TextElement)
+ latex = node['latex']
+ print latex
+ name = 'math-' + md5(latex).hexdigest()[-10:]
+ if not isfile('_static/%s.png' % name):
+ f = open('math.tex', 'w')
+ f.write(r...
[truncated message content] |
|
From: <jd...@us...> - 2008-05-24 17:56:20
|
Revision: 5252
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5252&view=rev
Author: jdh2358
Date: 2008-05-24 10:55:54 -0700 (Sat, 24 May 2008)
Log Message:
-----------
fixed a wx bug and added PIL support to imread
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/backends/backend_wx.py
trunk/matplotlib/lib/matplotlib/image.py
trunk/matplotlib/lib/matplotlib/patches.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-05-24 07:43:13 UTC (rev 5251)
+++ trunk/matplotlib/CHANGELOG 2008-05-24 17:55:54 UTC (rev 5252)
@@ -1,3 +1,6 @@
+2008-05-24 Added PIL support for loading images to imread (if PIL is
+ available) - JDH
+
2008-05-23 Provided a function and a method for controlling the
plot color cycle. - EF
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_wx.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_wx.py 2008-05-24 07:43:13 UTC (rev 5251)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_wx.py 2008-05-24 17:55:54 UTC (rev 5252)
@@ -1234,7 +1234,7 @@
statbar = StatusBarWx(self)
self.SetStatusBar(statbar)
self.canvas = self.get_canvas(fig)
- self.canvas.SetInitialSize(wx.Size(fig.bbox.width(), fig.bbox.height()))
+ self.canvas.SetInitialSize(wx.Size(fig.bbox.width, fig.bbox.height))
self.sizer =wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.canvas, 1, wx.TOP | wx.LEFT | wx.EXPAND)
# By adding toolbar in sizer, we are able to put it at the bottom
Modified: trunk/matplotlib/lib/matplotlib/image.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/image.py 2008-05-24 07:43:13 UTC (rev 5251)
+++ trunk/matplotlib/lib/matplotlib/image.py 2008-05-24 17:55:54 UTC (rev 5252)
@@ -652,13 +652,29 @@
Return value is a MxNx4 array of 0-1 normalized floats
+ matplotlib can only read PNGs natively, but if PIL is installed,
+ it will use it to load the image and return an RGBA if possible
+ which can be used with imshow
"""
+
+ def pilread():
+ 'try to load the image with PIL or return None'
+ try: import Image
+ except ImportError: return None
+ image = Image.open( fname )
+ return pil_to_array(image)
+
+
handlers = {'png' :_image.readpng,
}
basename, ext = os.path.splitext(fname)
ext = ext.lower()[1:]
+
if ext not in handlers.keys():
- raise ValueError('Only know how to handled extensions: %s' % handlers.keys())
+ im = pilread()
+ if im is None:
+ raise ValueError('Only know how to handle extensions: %s; with PIL installed matplotlib can handle more images' % handlers.keys())
+ return im
handler = handlers[ext]
return handler(fname)
Modified: trunk/matplotlib/lib/matplotlib/patches.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/patches.py 2008-05-24 07:43:13 UTC (rev 5251)
+++ trunk/matplotlib/lib/matplotlib/patches.py 2008-05-24 17:55:54 UTC (rev 5252)
@@ -11,8 +11,8 @@
from matplotlib.path import Path
# these are not available for the object inspector until after the
-# class is build so we define an initial set here for the init
-# function and they will be overridden after object defn
+# class is built so we define an initial set here for the init
+# function and they will be overridden after object definition
artist.kwdocd['Patch'] = """\
alpha: float
animated: [True | False]
@@ -31,7 +31,6 @@
visible: [True | False]
zorder: any number
"""
-
class Patch(artist.Artist):
"""
A patch is a 2D thingy with a face color and an edge color
@@ -1109,7 +1108,6 @@
r.draw(renderer)
artist.kwdocd['Patch'] = patchdoc = artist.kwdoc(Patch)
-
for k in ('Rectangle', 'Circle', 'RegularPolygon', 'Polygon', 'Wedge', 'Arrow',
'FancyArrow', 'YAArrow', 'CirclePolygon', 'Ellipse'):
artist.kwdocd[k] = patchdoc
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2008-05-24 07:43:14
|
Revision: 5251
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5251&view=rev
Author: efiring
Date: 2008-05-24 00:43:13 -0700 (Sat, 24 May 2008)
Log Message:
-----------
Forgot to add the example on last commit
Added Paths:
-----------
trunk/matplotlib/examples/api/color_cycle.py
Added: trunk/matplotlib/examples/api/color_cycle.py
===================================================================
--- trunk/matplotlib/examples/api/color_cycle.py (rev 0)
+++ trunk/matplotlib/examples/api/color_cycle.py 2008-05-24 07:43:13 UTC (rev 5251)
@@ -0,0 +1,28 @@
+"""
+Illustrate the API for changing the cycle of colors used
+when plotting multiple lines on a single Axes.
+"""
+
+import numpy as np
+import matplotlib.pyplot as plt
+import matplotlib as mpl
+
+yy = np.arange(24)
+yy.shape = 6,4
+
+mpl.rc('lines', linewidth=4)
+
+fig = plt.figure()
+mpl.axes.set_default_color_cycle(['r', 'g', 'b', 'c'])
+ax = fig.add_subplot(2,1,1)
+ax.plot(yy)
+ax.set_title('Changed default color cycle to rgbc')
+
+ax = fig.add_subplot(2,1,2)
+ax.set_color_cycle(['c', 'm', 'y', 'k'])
+ax.plot(yy)
+ax.set_title('This axes only, cycle is cmyk')
+
+plt.show()
+
+
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2008-05-24 07:36:51
|
Revision: 5250
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5250&view=rev
Author: efiring
Date: 2008-05-24 00:36:47 -0700 (Sat, 24 May 2008)
Log Message:
-----------
Provide function and method to control the plot color cycle
Modified Paths:
--------------
trunk/matplotlib/API_CHANGES
trunk/matplotlib/CHANGELOG
trunk/matplotlib/examples/tests/backend_driver.py
trunk/matplotlib/lib/matplotlib/axes.py
Modified: trunk/matplotlib/API_CHANGES
===================================================================
--- trunk/matplotlib/API_CHANGES 2008-05-24 00:51:33 UTC (rev 5249)
+++ trunk/matplotlib/API_CHANGES 2008-05-24 07:36:47 UTC (rev 5250)
@@ -1,3 +1,7 @@
+ New axes function and Axes method provide control over the plot
+ color cycle: axes.set_default_color_cycle(clist) and
+ Axes.set_color_cycle(clist).
+
matplotlib now requires python2.4, so matplotlib.cbook will no
loner provide set, enumerate, reversed or izip compatability functions
@@ -2,3 +6,3 @@
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.
+ method "hist" now uses future numpy 1.3 semantic for histograms.
Providing binedges, the last value gives the upper-right edge now,
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-05-24 00:51:33 UTC (rev 5249)
+++ trunk/matplotlib/CHANGELOG 2008-05-24 07:36:47 UTC (rev 5250)
@@ -1,3 +1,6 @@
+2008-05-23 Provided a function and a method for controlling the
+ plot color cycle. - EF
+
2008-05-23 Major revision of hist(). Can handle 2D arrays and create
stacked histogram plots; keyword 'width' deprecated and
rwidth (relative width) introduced; align='edge' changed
Modified: trunk/matplotlib/examples/tests/backend_driver.py
===================================================================
--- trunk/matplotlib/examples/tests/backend_driver.py 2008-05-24 00:51:33 UTC (rev 5249)
+++ trunk/matplotlib/examples/tests/backend_driver.py 2008-05-24 07:36:47 UTC (rev 5250)
@@ -114,6 +114,7 @@
api_dir = os.path.join('..', 'api')
api_files = [
'colorbar_only.py',
+ 'color_cycle.py',
]
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2008-05-24 00:51:33 UTC (rev 5249)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2008-05-24 07:36:47 UTC (rev 5250)
@@ -135,6 +135,18 @@
return linestyle, marker, color
+def set_default_color_cycle(clist):
+ """
+ Change the default cycle of colors that will be used by the plot
+ command. This must be called before creating the Axes to which
+ it will apply; it will apply to all future Axes.
+
+ clist is a sequence of mpl color specifiers
+
+ """
+ _process_plot_var_args.defaultColors = clist[:]
+ rcParams['lines.color'] = clist[0]
+
class _process_plot_var_args:
"""
@@ -170,6 +182,12 @@
self.count = 0
+ def set_color_cycle(self, clist):
+ self.colors = clist[:]
+ self.firstColor = self.colors[0]
+ self.Ncolors = len(self.colors)
+ self.count = 0
+
def _get_next_cycle_color(self):
if self.count==0:
color = self.firstColor
@@ -828,6 +846,15 @@
'clear the axes'
self.cla()
+ def set_color_cycle(self, clist):
+ """
+ Set the color cycle for any future plot commands on this Axes.
+
+ clist is a list of mpl color specifiers.
+ """
+ self._get_lines.set_color_cycle(clist)
+
+
def ishold(self):
'return the HOLD status of the axes'
return self._hold
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2008-05-24 00:51:34
|
Revision: 5249
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5249&view=rev
Author: efiring
Date: 2008-05-23 17:51:33 -0700 (Fri, 23 May 2008)
Log Message:
-----------
Clean up debugging lines in mre_with_eeg.py
Modified Paths:
--------------
trunk/matplotlib/examples/pylab/mri_with_eeg.py
Modified: trunk/matplotlib/examples/pylab/mri_with_eeg.py
===================================================================
--- trunk/matplotlib/examples/pylab/mri_with_eeg.py 2008-05-23 23:17:57 UTC (rev 5248)
+++ trunk/matplotlib/examples/pylab/mri_with_eeg.py 2008-05-24 00:51:33 UTC (rev 5249)
@@ -27,7 +27,6 @@
im = take(im, nonzero(im)) # ignore the background
im = im/(2.0**15) # normalize
hist(im, 100)
- print im.shape
xticks([-1, -.5, 0, .5, 1])
yticks([])
xlabel('intensity')
@@ -85,7 +84,4 @@
xlabel('time (s)')
-if 1:
- savefig('mri_with_eeg')
-
show()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-05-23 23:18:02
|
Revision: 5248
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5248&view=rev
Author: jdh2358
Date: 2008-05-23 16:17:57 -0700 (Fri, 23 May 2008)
Log Message:
-----------
fixed a hist bug with 1xN inputs
Modified Paths:
--------------
trunk/matplotlib/examples/pylab/mri_with_eeg.py
trunk/matplotlib/lib/matplotlib/axes.py
Modified: trunk/matplotlib/examples/pylab/mri_with_eeg.py
===================================================================
--- trunk/matplotlib/examples/pylab/mri_with_eeg.py 2008-05-23 21:53:33 UTC (rev 5247)
+++ trunk/matplotlib/examples/pylab/mri_with_eeg.py 2008-05-23 23:17:57 UTC (rev 5248)
@@ -27,6 +27,7 @@
im = take(im, nonzero(im)) # ignore the background
im = im/(2.0**15) # normalize
hist(im, 100)
+ print im.shape
xticks([-1, -.5, 0, .5, 1])
yticks([])
xlabel('intensity')
@@ -84,6 +85,7 @@
xlabel('time (s)')
+if 1:
+ savefig('mri_with_eeg')
-#savefig('mri_with_eeg')
show()
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2008-05-23 21:53:33 UTC (rev 5247)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2008-05-23 23:17:57 UTC (rev 5248)
@@ -5484,8 +5484,15 @@
'hist now uses the rwidth to give relative width and not absolute width')
# todo: make hist() work with list of arrays with different lengths
- x = np.asarray(x)
+ x = np.asarray(x).copy()
+ if len(x.shape)==2 and min(x.shape)==1:
+ x.shape = max(x.shape),
+
+ if len(x.shape)==2 and x.shape[0]<x.shape[1]:
+ warnings.warn('2D hist should be nsamples x nvariables; this looks transposed')
+
if len(x.shape)==2:
+
n = []
for i in xrange(x.shape[1]):
# this will automatically overwrite bins,
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <js...@us...> - 2008-05-23 21:53:34
|
Revision: 5247
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5247&view=rev
Author: jswhit
Date: 2008-05-23 14:53:33 -0700 (Fri, 23 May 2008)
Log Message:
-----------
update pyproj to 1.8.5
Modified Paths:
--------------
trunk/toolkits/basemap/lib/mpl_toolkits/basemap/pyproj.py
trunk/toolkits/basemap/src/_proj.c
trunk/toolkits/basemap/src/_proj.pyx
trunk/toolkits/basemap/src/_pyproj.pxi
Modified: trunk/toolkits/basemap/lib/mpl_toolkits/basemap/pyproj.py
===================================================================
--- trunk/toolkits/basemap/lib/mpl_toolkits/basemap/pyproj.py 2008-05-23 21:53:01 UTC (rev 5246)
+++ trunk/toolkits/basemap/lib/mpl_toolkits/basemap/pyproj.py 2008-05-23 21:53:33 UTC (rev 5247)
@@ -66,7 +66,8 @@
A Proj class instance is initialized with proj map projection
control parameter key/value pairs. The key/value pairs can
- either be passed in a dictionary, or as keyword arguments. See
+ either be passed in a dictionary, or as keyword arguments,
+ or as a proj4 string (compatible with the proj command). See
http://www.remotesensing.org/geotiff/proj_list for examples of
key/value pairs defining different map projections.
@@ -97,7 +98,7 @@
Example usage:
>>> from pyproj import Proj
- >>> p = Proj(proj='utm',zone=10,ellps='WGS84')
+ >>> p = Proj(proj='utm',zone=10,ellps='WGS84') # use kwargs
>>> x,y = p(-120.108, 34.36116666)
>>> print 'x=%9.3f y=%11.3f' % (x,y)
x=765975.641 y=3805993.134
@@ -116,20 +117,35 @@
lons: -119.720 -118.400 -122.380
>>> print 'lats: %8.3f %8.3f %8.3f' % lats
lats: 36.770 33.930 37.620
+ >>> p2 = Proj('+proj=utm +zone=10 +ellps=WGS84') # use proj4 string
+ >>> x,y = p2(-120.108, 34.36116666)
+ >>> print 'x=%9.3f y=%11.3f' % (x,y)
+ x=765975.641 y=3805993.134
"""
# if projparams is None, use kwargs.
if projparams is None:
if len(kwargs) == 0:
raise RuntimeError('no projection control parameters specified')
else:
- projparams = kwargs
- # set units to meters.
- if not projparams.has_key('units'):
- projparams['units']='m'
- elif projparams['units'] != 'm':
- print 'resetting units to meters ...'
- projparams['units']='m'
- return _Proj.__new__(self, projparams)
+ projstring = _dict2string(kwargs)
+ elif type(projparams) == str:
+ # if projparams is a string, interpret as a proj4 init string.
+ projstring = projparams
+ else: # projparams a dict
+ projstring = _dict2string(projparams)
+ # make sure units are meters.
+ if not projstring.count('+units='):
+ projstring = '+units=m '+projstring
+ else:
+ kvpairs = []
+ for kvpair in projstring.split():
+ if kvpair.startswith('+units'):
+ k,v = kvpair.split('=')
+ kvpairs.append(k+'=m ')
+ else:
+ kvpairs.append(kvpair+' ')
+ projstring = ''.join(kvpairs)
+ return _Proj.__new__(self, projstring)
def __call__(self, *args, **kw):
#,lon,lat,inverse=False,radians=False,errcheck=False):
@@ -331,6 +347,13 @@
else:
return inx
+def _dict2string(projparams):
+ # convert a dict to a proj4 string.
+ pjargs = []
+ for key,value in projparams.iteritems():
+ pjargs.append('+'+key+"="+str(value)+' ')
+ return ''.join(pjargs)
+
class Geod(_Geod):
"""
performs forward and inverse geodetic, or Great Circle,
Modified: trunk/toolkits/basemap/src/_proj.c
===================================================================
--- trunk/toolkits/basemap/src/_proj.c 2008-05-23 21:53:01 UTC (rev 5246)
+++ trunk/toolkits/basemap/src/_proj.c 2008-05-23 21:53:33 UTC (rev 5247)
@@ -1,4 +1,4 @@
-/* Generated by Cython 0.9.6.14 on Tue May 20 09:59:26 2008 */
+/* Generated by Cython 0.9.6.14 on Fri May 23 15:52:15 2008 */
#define PY_SSIZE_T_CLEAN
#include "Python.h"
@@ -106,20 +106,6 @@
static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/
-static PyObject *__Pyx_UnpackItem(PyObject *, Py_ssize_t index); /*proto*/
-static int __Pyx_EndUnpack(PyObject *); /*proto*/
-
-static inline PyObject* __Pyx_PyObject_Append(PyObject* L, PyObject* x) {
- if (likely(PyList_CheckExact(L))) {
- if (PyList_Append(L, x) < 0) return NULL;
- Py_INCREF(Py_None);
- return Py_None; // this is just to have an accurate signature
- }
- else {
- return PyObject_CallMethod(L, "append", "(O)", x);
- }
-}
-
static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb); /*proto*/
static int __Pyx_InternStrings(__Pyx_InternTabEntry *t); /*proto*/
@@ -139,13 +125,12 @@
*
* cdef class Proj: # <<<<<<<<<<<<<<
* cdef projPJ projpj
- * cdef public object projparams
+ * cdef public object proj_version
*/
struct __pyx_obj_5_proj_Proj {
PyObject_HEAD
projPJ projpj;
- PyObject *projparams;
PyObject *proj_version;
char *pjinitstring;
PyObject *srs;
@@ -162,7 +147,7 @@
/* Implementation of _proj */
-static char __pyx_k_2[] = "1.8.4";
+static char __pyx_k_2[] = "1.8.5";
static PyObject *__pyx_n___cinit__;
static PyObject *__pyx_n___dealloc__;
@@ -218,187 +203,59 @@
return __pyx_r;
}
-/* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":19
+/* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":18
* cdef public object srs
*
- * def __new__(self, projparams): # <<<<<<<<<<<<<<
- * self.projparams = projparams
+ * def __new__(self, projstring): # <<<<<<<<<<<<<<
* # setup proj initialization string.
+ * self.srs = projstring
*/
-static PyObject *__pyx_n_iteritems;
-static PyObject *__pyx_n_append;
-static PyObject *__pyx_n_join;
static PyObject *__pyx_n_RuntimeError;
-static PyObject *__pyx_k_3p;
-static PyObject *__pyx_k_4p;
-static PyObject *__pyx_k_5p;
-static PyObject *__pyx_k_6p;
-
static PyObject *__pyx_builtin_RuntimeError;
-static char __pyx_k_3[] = "+";
-static char __pyx_k_4[] = "=";
-static char __pyx_k_5[] = " ";
-static char __pyx_k_6[] = "";
-
static int __pyx_pf_5_proj_4Proj___new__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static int __pyx_pf_5_proj_4Proj___new__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- PyObject *__pyx_v_projparams = 0;
- PyObject *__pyx_v_pjargs;
- PyObject *__pyx_v_key;
- PyObject *__pyx_v_value;
+ PyObject *__pyx_v_projstring = 0;
int __pyx_r;
- PyObject *__pyx_1 = 0;
- Py_ssize_t __pyx_2 = 0;
+ int __pyx_1;
+ PyObject *__pyx_2 = 0;
PyObject *__pyx_3 = 0;
- PyObject *__pyx_4 = 0;
- PyObject *__pyx_5 = 0;
- int __pyx_6;
- static char *__pyx_argnames[] = {"projparams",0};
+ static char *__pyx_argnames[] = {"projstring",0};
if (likely(!__pyx_kwds) && likely(PyTuple_GET_SIZE(__pyx_args) == 1)) {
- __pyx_v_projparams = PyTuple_GET_ITEM(__pyx_args, 0);
+ __pyx_v_projstring = PyTuple_GET_ITEM(__pyx_args, 0);
}
else {
- if (unlikely(!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O", __pyx_argnames, &__pyx_v_projparams))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L2;}
+ if (unlikely(!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O", __pyx_argnames, &__pyx_v_projstring))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L2;}
}
goto __pyx_L3;
__pyx_L2:;
__Pyx_AddTraceback("_proj.Proj.__cinit__");
return -1;
__pyx_L3:;
- __pyx_v_pjargs = Py_None; Py_INCREF(Py_None);
- __pyx_v_key = Py_None; Py_INCREF(Py_None);
- __pyx_v_value = Py_None; Py_INCREF(Py_None);
/* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":20
- *
- * def __new__(self, projparams):
- * self.projparams = projparams # <<<<<<<<<<<<<<
+ * def __new__(self, projstring):
* # setup proj initialization string.
- * pjargs = []
- */
- Py_INCREF(__pyx_v_projparams);
- Py_DECREF(((struct __pyx_obj_5_proj_Proj *)__pyx_v_self)->projparams);
- ((struct __pyx_obj_5_proj_Proj *)__pyx_v_self)->projparams = __pyx_v_projparams;
-
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":22
- * self.projparams = projparams
- * # setup proj initialization string.
- * pjargs = [] # <<<<<<<<<<<<<<
- * for key,value in projparams.iteritems():
- * pjargs.append('+'+key+"="+str(value)+' ')
- */
- __pyx_1 = PyList_New(0); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1;}
- Py_DECREF(__pyx_v_pjargs);
- __pyx_v_pjargs = ((PyObject *)__pyx_1);
- __pyx_1 = 0;
-
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":23
- * # setup proj initialization string.
- * pjargs = []
- * for key,value in projparams.iteritems(): # <<<<<<<<<<<<<<
- * pjargs.append('+'+key+"="+str(value)+' ')
- * self.srs = ''.join(pjargs)
- */
- __pyx_1 = PyObject_GetAttr(__pyx_v_projparams, __pyx_n_iteritems); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1;}
- __pyx_3 = PyObject_Call(__pyx_1, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1;}
- Py_DECREF(__pyx_1); __pyx_1 = 0;
- if (PyList_CheckExact(__pyx_3)) { __pyx_2 = 0; __pyx_1 = __pyx_3; Py_INCREF(__pyx_1); }
- else { __pyx_1 = PyObject_GetIter(__pyx_3); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1;} }
- Py_DECREF(__pyx_3); __pyx_3 = 0;
- for (;;) {
- if (PyList_CheckExact(__pyx_1)) { if (__pyx_2 >= PyList_GET_SIZE(__pyx_1)) break; __pyx_3 = PyList_GET_ITEM(__pyx_1, __pyx_2++); Py_INCREF(__pyx_3); }
- else {
- __pyx_3 = PyIter_Next(__pyx_1);
- if (!__pyx_3) {
- break;
- }
- }
- if (PyTuple_CheckExact(__pyx_3) && PyTuple_GET_SIZE(__pyx_3) == 2) {
- PyObject* tuple = __pyx_3;
- __pyx_5 = PyTuple_GET_ITEM(tuple, 0);
- Py_INCREF(__pyx_5);
- Py_DECREF(__pyx_v_key);
- __pyx_v_key = __pyx_5;
- __pyx_5 = 0;
- __pyx_5 = PyTuple_GET_ITEM(tuple, 1);
- Py_INCREF(__pyx_5);
- Py_DECREF(__pyx_v_value);
- __pyx_v_value = __pyx_5;
- __pyx_5 = 0;
- Py_DECREF(__pyx_3); __pyx_3 = 0;
- }
- else {
- __pyx_4 = PyObject_GetIter(__pyx_3); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1;}
- Py_DECREF(__pyx_3); __pyx_3 = 0;
- __pyx_5 = __Pyx_UnpackItem(__pyx_4, 0); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1;}
- Py_DECREF(__pyx_v_key);
- __pyx_v_key = __pyx_5;
- __pyx_5 = 0;
- __pyx_5 = __Pyx_UnpackItem(__pyx_4, 1); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1;}
- Py_DECREF(__pyx_v_value);
- __pyx_v_value = __pyx_5;
- __pyx_5 = 0;
- if (__Pyx_EndUnpack(__pyx_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1;}
- Py_DECREF(__pyx_4); __pyx_4 = 0;
- }
-
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":24
- * pjargs = []
- * for key,value in projparams.iteritems():
- * pjargs.append('+'+key+"="+str(value)+' ') # <<<<<<<<<<<<<<
- * self.srs = ''.join(pjargs)
+ * self.srs = projstring # <<<<<<<<<<<<<<
* self.pjinitstring = PyString_AsString(self.srs)
- */
- __pyx_5 = PyNumber_Add(__pyx_k_3p, __pyx_v_key); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1;}
- __pyx_3 = PyNumber_Add(__pyx_5, __pyx_k_4p); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1;}
- Py_DECREF(__pyx_5); __pyx_5 = 0;
- __pyx_4 = PyTuple_New(1); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1;}
- Py_INCREF(__pyx_v_value);
- PyTuple_SET_ITEM(__pyx_4, 0, __pyx_v_value);
- __pyx_5 = PyObject_Call(((PyObject*)&PyString_Type), ((PyObject *)__pyx_4), NULL); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1;}
- Py_DECREF(((PyObject *)__pyx_4)); __pyx_4 = 0;
- __pyx_4 = PyNumber_Add(__pyx_3, __pyx_5); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1;}
- Py_DECREF(__pyx_3); __pyx_3 = 0;
- Py_DECREF(__pyx_5); __pyx_5 = 0;
- __pyx_3 = PyNumber_Add(__pyx_4, __pyx_k_5p); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1;}
- Py_DECREF(__pyx_4); __pyx_4 = 0;
- __pyx_5 = __Pyx_PyObject_Append(__pyx_v_pjargs, __pyx_3); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1;}
- Py_DECREF(__pyx_3); __pyx_3 = 0;
- Py_DECREF(__pyx_5); __pyx_5 = 0;
- }
- Py_DECREF(__pyx_1); __pyx_1 = 0;
-
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":25
- * for key,value in projparams.iteritems():
- * pjargs.append('+'+key+"="+str(value)+' ')
- * self.srs = ''.join(pjargs) # <<<<<<<<<<<<<<
- * self.pjinitstring = PyString_AsString(self.srs)
* # initialize projection
*/
- __pyx_4 = PyObject_GetAttr(__pyx_k_6p, __pyx_n_join); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1;}
- __pyx_3 = PyTuple_New(1); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1;}
- Py_INCREF(__pyx_v_pjargs);
- PyTuple_SET_ITEM(__pyx_3, 0, __pyx_v_pjargs);
- __pyx_5 = PyObject_Call(__pyx_4, ((PyObject *)__pyx_3), NULL); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1;}
- Py_DECREF(__pyx_4); __pyx_4 = 0;
- Py_DECREF(((PyObject *)__pyx_3)); __pyx_3 = 0;
+ Py_INCREF(__pyx_v_projstring);
Py_DECREF(((struct __pyx_obj_5_proj_Proj *)__pyx_v_self)->srs);
- ((struct __pyx_obj_5_proj_Proj *)__pyx_v_self)->srs = __pyx_5;
- __pyx_5 = 0;
+ ((struct __pyx_obj_5_proj_Proj *)__pyx_v_self)->srs = __pyx_v_projstring;
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":26
- * pjargs.append('+'+key+"="+str(value)+' ')
- * self.srs = ''.join(pjargs)
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":21
+ * # setup proj initialization string.
+ * self.srs = projstring
* self.pjinitstring = PyString_AsString(self.srs) # <<<<<<<<<<<<<<
* # initialize projection
* self.projpj = pj_init_plus(self.pjinitstring)
*/
((struct __pyx_obj_5_proj_Proj *)__pyx_v_self)->pjinitstring = PyString_AsString(((struct __pyx_obj_5_proj_Proj *)__pyx_v_self)->srs);
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":28
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":23
* self.pjinitstring = PyString_AsString(self.srs)
* # initialize projection
* self.projpj = pj_init_plus(self.pjinitstring) # <<<<<<<<<<<<<<
@@ -407,65 +264,60 @@
*/
((struct __pyx_obj_5_proj_Proj *)__pyx_v_self)->projpj = pj_init_plus(((struct __pyx_obj_5_proj_Proj *)__pyx_v_self)->pjinitstring);
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":29
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":24
* # initialize projection
* self.projpj = pj_init_plus(self.pjinitstring)
* if pj_errno != 0: # <<<<<<<<<<<<<<
* raise RuntimeError(pj_strerrno(pj_errno))
* self.proj_version = PJ_VERSION/100.
*/
- __pyx_6 = (pj_errno != 0);
- if (__pyx_6) {
+ __pyx_1 = (pj_errno != 0);
+ if (__pyx_1) {
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":30
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":25
* self.projpj = pj_init_plus(self.pjinitstring)
* if pj_errno != 0:
* raise RuntimeError(pj_strerrno(pj_errno)) # <<<<<<<<<<<<<<
* self.proj_version = PJ_VERSION/100.
*
*/
- __pyx_1 = PyString_FromString(pj_strerrno(pj_errno)); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1;}
- __pyx_4 = PyTuple_New(1); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1;}
- PyTuple_SET_ITEM(__pyx_4, 0, __pyx_1);
- __pyx_1 = 0;
- __pyx_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_4), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1;}
- Py_DECREF(((PyObject *)__pyx_4)); __pyx_4 = 0;
- __Pyx_Raise(__pyx_3, 0, 0);
- Py_DECREF(__pyx_3); __pyx_3 = 0;
- {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1;}
- goto __pyx_L6;
+ __pyx_2 = PyString_FromString(pj_strerrno(pj_errno)); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_3 = PyTuple_New(1); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ PyTuple_SET_ITEM(__pyx_3, 0, __pyx_2);
+ __pyx_2 = 0;
+ __pyx_2 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_3), NULL); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ Py_DECREF(((PyObject *)__pyx_3)); __pyx_3 = 0;
+ __Pyx_Raise(__pyx_2, 0, 0);
+ Py_DECREF(__pyx_2); __pyx_2 = 0;
+ {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ goto __pyx_L4;
}
- __pyx_L6:;
+ __pyx_L4:;
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":31
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":26
* if pj_errno != 0:
* raise RuntimeError(pj_strerrno(pj_errno))
* self.proj_version = PJ_VERSION/100. # <<<<<<<<<<<<<<
*
* def __dealloc__(self):
*/
- __pyx_5 = PyFloat_FromDouble((PJ_VERSION / 100.)); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 31; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_3 = PyFloat_FromDouble((PJ_VERSION / 100.)); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1;}
Py_DECREF(((struct __pyx_obj_5_proj_Proj *)__pyx_v_self)->proj_version);
- ((struct __pyx_obj_5_proj_Proj *)__pyx_v_self)->proj_version = __pyx_5;
- __pyx_5 = 0;
+ ((struct __pyx_obj_5_proj_Proj *)__pyx_v_self)->proj_version = __pyx_3;
+ __pyx_3 = 0;
__pyx_r = 0;
goto __pyx_L0;
__pyx_L1:;
- Py_XDECREF(__pyx_1);
+ Py_XDECREF(__pyx_2);
Py_XDECREF(__pyx_3);
- Py_XDECREF(__pyx_4);
- Py_XDECREF(__pyx_5);
__Pyx_AddTraceback("_proj.Proj.__cinit__");
__pyx_r = -1;
__pyx_L0:;
- Py_DECREF(__pyx_v_pjargs);
- Py_DECREF(__pyx_v_key);
- Py_DECREF(__pyx_v_value);
return __pyx_r;
}
-/* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":33
+/* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":28
* self.proj_version = PJ_VERSION/100.
*
* def __dealloc__(self): # <<<<<<<<<<<<<<
@@ -477,7 +329,7 @@
static char __pyx_doc_5_proj_4Proj___dealloc__[] = "destroy projection definition";
static void __pyx_pf_5_proj_4Proj___dealloc__(PyObject *__pyx_v_self) {
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":35
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":30
* def __dealloc__(self):
* """destroy projection definition"""
* pj_free(self.projpj) # <<<<<<<<<<<<<<
@@ -488,12 +340,12 @@
}
-/* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":37
+/* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":32
* pj_free(self.projpj)
*
* def __reduce__(self): # <<<<<<<<<<<<<<
* """special method that allows pyproj.Proj instance to be pickled"""
- * return (self.__class__,(self.projparams,))
+ * return (self.__class__,(self.srs,))
*/
static PyObject *__pyx_n___class__;
@@ -506,18 +358,18 @@
PyObject *__pyx_2 = 0;
PyObject *__pyx_3 = 0;
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":39
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":34
* def __reduce__(self):
* """special method that allows pyproj.Proj instance to be pickled"""
- * return (self.__class__,(self.projparams,)) # <<<<<<<<<<<<<<
+ * return (self.__class__,(self.srs,)) # <<<<<<<<<<<<<<
*
* def _fwd(self, object lons, object lats, radians=False, errcheck=False):
*/
- __pyx_1 = PyObject_GetAttr(__pyx_v_self, __pyx_n___class__); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1;}
- __pyx_2 = PyTuple_New(1); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1;}
- Py_INCREF(((struct __pyx_obj_5_proj_Proj *)__pyx_v_self)->projparams);
- PyTuple_SET_ITEM(__pyx_2, 0, ((struct __pyx_obj_5_proj_Proj *)__pyx_v_self)->projparams);
- __pyx_3 = PyTuple_New(2); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_1 = PyObject_GetAttr(__pyx_v_self, __pyx_n___class__); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_2 = PyTuple_New(1); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ Py_INCREF(((struct __pyx_obj_5_proj_Proj *)__pyx_v_self)->srs);
+ PyTuple_SET_ITEM(__pyx_2, 0, ((struct __pyx_obj_5_proj_Proj *)__pyx_v_self)->srs);
+ __pyx_3 = PyTuple_New(2); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; __pyx_clineno = __LINE__; goto __pyx_L1;}
PyTuple_SET_ITEM(__pyx_3, 0, __pyx_1);
PyTuple_SET_ITEM(__pyx_3, 1, ((PyObject *)__pyx_2));
__pyx_1 = 0;
@@ -538,17 +390,17 @@
return __pyx_r;
}
-/* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":41
- * return (self.__class__,(self.projparams,))
+/* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":36
+ * return (self.__class__,(self.srs,))
*
* def _fwd(self, object lons, object lats, radians=False, errcheck=False): # <<<<<<<<<<<<<<
* """
* forward transformation - lons,lats to x,y (done in place).
*/
-static PyObject *__pyx_k_7p;
+static PyObject *__pyx_k_3p;
-static char __pyx_k_7[] = "Buffer lengths not the same";
+static char __pyx_k_3[] = "Buffer lengths not the same";
static PyObject *__pyx_pf_5_proj_4Proj__fwd(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static char __pyx_doc_5_proj_4Proj__fwd[] = "\n forward transformation - lons,lats to x,y (done in place).\n if radians=True, lons/lats are radians instead of degrees.\n if errcheck=True, an exception is raised if the forward transformation is invalid.\n if errcheck=False and the forward transformation is invalid, no exception is\n raised and 1.e30 is returned.\n ";
@@ -588,7 +440,7 @@
}
}
else {
- if (unlikely(!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "OO|OO", __pyx_argnames, &__pyx_v_lons, &__pyx_v_lats, &__pyx_v_radians, &__pyx_v_errcheck))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 41; __pyx_clineno = __LINE__; goto __pyx_L2;}
+ if (unlikely(!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "OO|OO", __pyx_argnames, &__pyx_v_lons, &__pyx_v_lats, &__pyx_v_radians, &__pyx_v_errcheck))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L2;}
}
goto __pyx_L3;
__pyx_L2:;
@@ -596,7 +448,7 @@
return NULL;
__pyx_L3:;
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":55
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":50
* cdef void *londata, *latdata
* # if buffer api is supported, get pointer to data buffers.
* if PyObject_AsWriteBuffer(lons, &londata, &buflenx) <> 0: # <<<<<<<<<<<<<<
@@ -606,7 +458,7 @@
__pyx_1 = (PyObject_AsWriteBuffer(__pyx_v_lons, (&__pyx_v_londata), (&__pyx_v_buflenx)) != 0);
if (__pyx_1) {
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":56
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":51
* # if buffer api is supported, get pointer to data buffers.
* if PyObject_AsWriteBuffer(lons, &londata, &buflenx) <> 0:
* raise RuntimeError # <<<<<<<<<<<<<<
@@ -614,12 +466,12 @@
* raise RuntimeError
*/
__Pyx_Raise(__pyx_builtin_RuntimeError, 0, 0);
- {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1;}
goto __pyx_L4;
}
__pyx_L4:;
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":57
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":52
* if PyObject_AsWriteBuffer(lons, &londata, &buflenx) <> 0:
* raise RuntimeError
* if PyObject_AsWriteBuffer(lats, &latdata, &bufleny) <> 0: # <<<<<<<<<<<<<<
@@ -629,7 +481,7 @@
__pyx_1 = (PyObject_AsWriteBuffer(__pyx_v_lats, (&__pyx_v_latdata), (&__pyx_v_bufleny)) != 0);
if (__pyx_1) {
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":58
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":53
* raise RuntimeError
* if PyObject_AsWriteBuffer(lats, &latdata, &bufleny) <> 0:
* raise RuntimeError # <<<<<<<<<<<<<<
@@ -637,12 +489,12 @@
* if buflenx != bufleny:
*/
__Pyx_Raise(__pyx_builtin_RuntimeError, 0, 0);
- {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1;}
goto __pyx_L5;
}
__pyx_L5:;
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":60
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":55
* raise RuntimeError
* # process data in buffer
* if buflenx != bufleny: # <<<<<<<<<<<<<<
@@ -652,42 +504,42 @@
__pyx_1 = (__pyx_v_buflenx != __pyx_v_bufleny);
if (__pyx_1) {
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":61
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":56
* # process data in buffer
* if buflenx != bufleny:
* raise RuntimeError("Buffer lengths not the same") # <<<<<<<<<<<<<<
* ndim = buflenx/_doublesize
* lonsdata = <double *>londata
*/
- __pyx_2 = PyTuple_New(1); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1;}
- Py_INCREF(__pyx_k_7p);
- PyTuple_SET_ITEM(__pyx_2, 0, __pyx_k_7p);
- __pyx_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_2), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_2 = PyTuple_New(1); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ Py_INCREF(__pyx_k_3p);
+ PyTuple_SET_ITEM(__pyx_2, 0, __pyx_k_3p);
+ __pyx_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_2), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1;}
Py_DECREF(((PyObject *)__pyx_2)); __pyx_2 = 0;
__Pyx_Raise(__pyx_3, 0, 0);
Py_DECREF(__pyx_3); __pyx_3 = 0;
- {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1;}
goto __pyx_L6;
}
__pyx_L6:;
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":62
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":57
* if buflenx != bufleny:
* raise RuntimeError("Buffer lengths not the same")
* ndim = buflenx/_doublesize # <<<<<<<<<<<<<<
* lonsdata = <double *>londata
* latsdata = <double *>latdata
*/
- __pyx_2 = PyInt_FromSsize_t(__pyx_v_buflenx); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1;}
- __pyx_3 = __Pyx_GetName(__pyx_m, __pyx_n__doublesize); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1;}
- __pyx_4 = PyNumber_Divide(__pyx_2, __pyx_3); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_2 = PyInt_FromSsize_t(__pyx_v_buflenx); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_3 = __Pyx_GetName(__pyx_m, __pyx_n__doublesize); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_4 = PyNumber_Divide(__pyx_2, __pyx_3); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1;}
Py_DECREF(__pyx_2); __pyx_2 = 0;
Py_DECREF(__pyx_3); __pyx_3 = 0;
- __pyx_5 = __pyx_PyIndex_AsSsize_t(__pyx_4); if (unlikely((__pyx_5 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_5 = __pyx_PyIndex_AsSsize_t(__pyx_4); if (unlikely((__pyx_5 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1;}
Py_DECREF(__pyx_4); __pyx_4 = 0;
__pyx_v_ndim = __pyx_5;
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":63
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":58
* raise RuntimeError("Buffer lengths not the same")
* ndim = buflenx/_doublesize
* lonsdata = <double *>londata # <<<<<<<<<<<<<<
@@ -696,7 +548,7 @@
*/
__pyx_v_lonsdata = ((double *)__pyx_v_londata);
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":64
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":59
* ndim = buflenx/_doublesize
* lonsdata = <double *>londata
* latsdata = <double *>latdata # <<<<<<<<<<<<<<
@@ -705,7 +557,7 @@
*/
__pyx_v_latsdata = ((double *)__pyx_v_latdata);
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":65
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":60
* lonsdata = <double *>londata
* latsdata = <double *>latdata
* for i from 0 <= i < ndim: # <<<<<<<<<<<<<<
@@ -714,17 +566,17 @@
*/
for (__pyx_v_i = 0; __pyx_v_i < __pyx_v_ndim; __pyx_v_i++) {
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":66
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":61
* latsdata = <double *>latdata
* for i from 0 <= i < ndim:
* if radians: # <<<<<<<<<<<<<<
* projlonlatin.u = lonsdata[i]
* projlonlatin.v = latsdata[i]
*/
- __pyx_1 = __Pyx_PyObject_IsTrue(__pyx_v_radians); if (unlikely(__pyx_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_1 = __Pyx_PyObject_IsTrue(__pyx_v_radians); if (unlikely(__pyx_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1;}
if (__pyx_1) {
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":67
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":62
* for i from 0 <= i < ndim:
* if radians:
* projlonlatin.u = lonsdata[i] # <<<<<<<<<<<<<<
@@ -733,7 +585,7 @@
*/
__pyx_v_projlonlatin.u = (__pyx_v_lonsdata[__pyx_v_i]);
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":68
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":63
* if radians:
* projlonlatin.u = lonsdata[i]
* projlonlatin.v = latsdata[i] # <<<<<<<<<<<<<<
@@ -745,41 +597,41 @@
}
/*else*/ {
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":70
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":65
* projlonlatin.v = latsdata[i]
* else:
* projlonlatin.u = _dg2rad*lonsdata[i] # <<<<<<<<<<<<<<
* projlonlatin.v = _dg2rad*latsdata[i]
* projxyout = pj_fwd(projlonlatin,self.projpj)
*/
- __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_n__dg2rad); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1;}
- __pyx_3 = PyFloat_FromDouble((__pyx_v_lonsdata[__pyx_v_i])); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1;}
- __pyx_4 = PyNumber_Multiply(__pyx_2, __pyx_3); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_n__dg2rad); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_3 = PyFloat_FromDouble((__pyx_v_lonsdata[__pyx_v_i])); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_4 = PyNumber_Multiply(__pyx_2, __pyx_3); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1;}
Py_DECREF(__pyx_2); __pyx_2 = 0;
Py_DECREF(__pyx_3); __pyx_3 = 0;
- __pyx_6 = __pyx_PyFloat_AsDouble(__pyx_4); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_6 = __pyx_PyFloat_AsDouble(__pyx_4); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1;}
Py_DECREF(__pyx_4); __pyx_4 = 0;
__pyx_v_projlonlatin.u = __pyx_6;
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":71
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":66
* else:
* projlonlatin.u = _dg2rad*lonsdata[i]
* projlonlatin.v = _dg2rad*latsdata[i] # <<<<<<<<<<<<<<
* projxyout = pj_fwd(projlonlatin,self.projpj)
* if errcheck and pj_errno != 0:
*/
- __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_n__dg2rad); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1;}
- __pyx_3 = PyFloat_FromDouble((__pyx_v_latsdata[__pyx_v_i])); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1;}
- __pyx_4 = PyNumber_Multiply(__pyx_2, __pyx_3); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_n__dg2rad); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_3 = PyFloat_FromDouble((__pyx_v_latsdata[__pyx_v_i])); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_4 = PyNumber_Multiply(__pyx_2, __pyx_3); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L1;}
Py_DECREF(__pyx_2); __pyx_2 = 0;
Py_DECREF(__pyx_3); __pyx_3 = 0;
- __pyx_6 = __pyx_PyFloat_AsDouble(__pyx_4); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_6 = __pyx_PyFloat_AsDouble(__pyx_4); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L1;}
Py_DECREF(__pyx_4); __pyx_4 = 0;
__pyx_v_projlonlatin.v = __pyx_6;
}
__pyx_L9:;
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":72
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":67
* projlonlatin.u = _dg2rad*lonsdata[i]
* projlonlatin.v = _dg2rad*latsdata[i]
* projxyout = pj_fwd(projlonlatin,self.projpj) # <<<<<<<<<<<<<<
@@ -788,7 +640,7 @@
*/
__pyx_v_projxyout = pj_fwd(__pyx_v_projlonlatin, ((struct __pyx_obj_5_proj_Proj *)__pyx_v_self)->projpj);
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":73
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":68
* projlonlatin.v = _dg2rad*latsdata[i]
* projxyout = pj_fwd(projlonlatin,self.projpj)
* if errcheck and pj_errno != 0: # <<<<<<<<<<<<<<
@@ -797,36 +649,36 @@
*/
__pyx_2 = __pyx_v_errcheck;
Py_INCREF(__pyx_2);
- __pyx_1 = __Pyx_PyObject_IsTrue(__pyx_2); if (unlikely(__pyx_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_1 = __Pyx_PyObject_IsTrue(__pyx_2); if (unlikely(__pyx_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1;}
if (__pyx_1) {
Py_DECREF(__pyx_2); __pyx_2 = 0;
- __pyx_2 = __Pyx_PyBool_FromLong((pj_errno != 0)); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_2 = __Pyx_PyBool_FromLong((pj_errno != 0)); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1;}
}
- __pyx_1 = __Pyx_PyObject_IsTrue(__pyx_2); if (unlikely(__pyx_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_1 = __Pyx_PyObject_IsTrue(__pyx_2); if (unlikely(__pyx_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1;}
Py_DECREF(__pyx_2); __pyx_2 = 0;
if (__pyx_1) {
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":74
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":69
* projxyout = pj_fwd(projlonlatin,self.projpj)
* if errcheck and pj_errno != 0:
* raise RuntimeError(pj_strerrno(pj_errno)) # <<<<<<<<<<<<<<
* # since HUGE_VAL can be 'inf',
* # change it to a real (but very large) number.
*/
- __pyx_3 = PyString_FromString(pj_strerrno(pj_errno)); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1;}
- __pyx_4 = PyTuple_New(1); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_3 = PyString_FromString(pj_strerrno(pj_errno)); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_4 = PyTuple_New(1); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1;}
PyTuple_SET_ITEM(__pyx_4, 0, __pyx_3);
__pyx_3 = 0;
- __pyx_2 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_4), NULL); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_2 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_4), NULL); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1;}
Py_DECREF(((PyObject *)__pyx_4)); __pyx_4 = 0;
__Pyx_Raise(__pyx_2, 0, 0);
Py_DECREF(__pyx_2); __pyx_2 = 0;
- {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1;}
goto __pyx_L10;
}
__pyx_L10:;
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":77
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":72
* # since HUGE_VAL can be 'inf',
* # change it to a real (but very large) number.
* if projxyout.u == HUGE_VAL: # <<<<<<<<<<<<<<
@@ -836,7 +688,7 @@
__pyx_1 = (__pyx_v_projxyout.u == HUGE_VAL);
if (__pyx_1) {
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":78
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":73
* # change it to a real (but very large) number.
* if projxyout.u == HUGE_VAL:
* lonsdata[i] = 1.e30 # <<<<<<<<<<<<<<
@@ -848,7 +700,7 @@
}
/*else*/ {
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":80
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":75
* lonsdata[i] = 1.e30
* else:
* lonsdata[i] = projxyout.u # <<<<<<<<<<<<<<
@@ -859,7 +711,7 @@
}
__pyx_L11:;
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":81
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":76
* else:
* lonsdata[i] = projxyout.u
* if projxyout.v == HUGE_VAL: # <<<<<<<<<<<<<<
@@ -869,7 +721,7 @@
__pyx_1 = (__pyx_v_projxyout.v == HUGE_VAL);
if (__pyx_1) {
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":82
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":77
* lonsdata[i] = projxyout.u
* if projxyout.v == HUGE_VAL:
* latsdata[i] = 1.e30 # <<<<<<<<<<<<<<
@@ -881,7 +733,7 @@
}
/*else*/ {
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":84
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":79
* latsdata[i] = 1.e30
* else:
* latsdata[i] = projxyout.v # <<<<<<<<<<<<<<
@@ -905,7 +757,7 @@
return __pyx_r;
}
-/* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":86
+/* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":81
* latsdata[i] = projxyout.v
*
* def _inv(self, object x, object y, radians=False, errcheck=False): # <<<<<<<<<<<<<<
@@ -913,9 +765,9 @@
* inverse transformation - x,y to lons,lats (done in place).
*/
-static PyObject *__pyx_k_8p;
+static PyObject *__pyx_k_4p;
-static char __pyx_k_8[] = "Buffer lengths not the same";
+static char __pyx_k_4[] = "Buffer lengths not the same";
static PyObject *__pyx_pf_5_proj_4Proj__inv(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static char __pyx_doc_5_proj_4Proj__inv[] = "\n inverse transformation - x,y to lons,lats (done in place).\n if radians=True, lons/lats are radians instead of degrees.\n if errcheck=True, an exception is raised if the inverse transformation is invalid.\n if errcheck=False and the inverse transformation is invalid, no exception is\n raised and 1.e30 is returned.\n ";
@@ -955,7 +807,7 @@
}
}
else {
- if (unlikely(!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "OO|OO", __pyx_argnames, &__pyx_v_x, &__pyx_v_y, &__pyx_v_radians, &__pyx_v_errcheck))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L2;}
+ if (unlikely(!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "OO|OO", __pyx_argnames, &__pyx_v_x, &__pyx_v_y, &__pyx_v_radians, &__pyx_v_errcheck))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L2;}
}
goto __pyx_L3;
__pyx_L2:;
@@ -963,7 +815,7 @@
return NULL;
__pyx_L3:;
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":100
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":95
* cdef double *xdatab, *ydatab
* # if buffer api is supported, get pointer to data buffers.
* if PyObject_AsWriteBuffer(x, &xdata, &buflenx) <> 0: # <<<<<<<<<<<<<<
@@ -973,7 +825,7 @@
__pyx_1 = (PyObject_AsWriteBuffer(__pyx_v_x, (&__pyx_v_xdata), (&__pyx_v_buflenx)) != 0);
if (__pyx_1) {
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":101
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":96
* # if buffer api is supported, get pointer to data buffers.
* if PyObject_AsWriteBuffer(x, &xdata, &buflenx) <> 0:
* raise RuntimeError # <<<<<<<<<<<<<<
@@ -981,12 +833,12 @@
* raise RuntimeError
*/
__Pyx_Raise(__pyx_builtin_RuntimeError, 0, 0);
- {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1;}
goto __pyx_L4;
}
__pyx_L4:;
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":102
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":97
* if PyObject_AsWriteBuffer(x, &xdata, &buflenx) <> 0:
* raise RuntimeError
* if PyObject_AsWriteBuffer(y, &ydata, &bufleny) <> 0: # <<<<<<<<<<<<<<
@@ -996,7 +848,7 @@
__pyx_1 = (PyObject_AsWriteBuffer(__pyx_v_y, (&__pyx_v_ydata), (&__pyx_v_bufleny)) != 0);
if (__pyx_1) {
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":103
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":98
* raise RuntimeError
* if PyObject_AsWriteBuffer(y, &ydata, &bufleny) <> 0:
* raise RuntimeError # <<<<<<<<<<<<<<
@@ -1004,12 +856,12 @@
* # (for numpy/regular python arrays).
*/
__Pyx_Raise(__pyx_builtin_RuntimeError, 0, 0);
- {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1;}
goto __pyx_L5;
}
__pyx_L5:;
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":106
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":101
* # process data in buffer
* # (for numpy/regular python arrays).
* if buflenx != bufleny: # <<<<<<<<<<<<<<
@@ -1019,42 +871,42 @@
__pyx_1 = (__pyx_v_buflenx != __pyx_v_bufleny);
if (__pyx_1) {
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":107
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":102
* # (for numpy/regular python arrays).
* if buflenx != bufleny:
* raise RuntimeError("Buffer lengths not the same") # <<<<<<<<<<<<<<
* ndim = buflenx/_doublesize
* xdatab = <double *>xdata
*/
- __pyx_2 = PyTuple_New(1); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L1;}
- Py_INCREF(__pyx_k_8p);
- PyTuple_SET_ITEM(__pyx_2, 0, __pyx_k_8p);
- __pyx_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_2), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_2 = PyTuple_New(1); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ Py_INCREF(__pyx_k_4p);
+ PyTuple_SET_ITEM(__pyx_2, 0, __pyx_k_4p);
+ __pyx_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_2), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L1;}
Py_DECREF(((PyObject *)__pyx_2)); __pyx_2 = 0;
__Pyx_Raise(__pyx_3, 0, 0);
Py_DECREF(__pyx_3); __pyx_3 = 0;
- {__pyx_filename = __pyx_f[0]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ {__pyx_filename = __pyx_f[0]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L1;}
goto __pyx_L6;
}
__pyx_L6:;
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":108
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":103
* if buflenx != bufleny:
* raise RuntimeError("Buffer lengths not the same")
* ndim = buflenx/_doublesize # <<<<<<<<<<<<<<
* xdatab = <double *>xdata
* ydatab = <double *>ydata
*/
- __pyx_2 = PyInt_FromSsize_t(__pyx_v_buflenx); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1;}
- __pyx_3 = __Pyx_GetName(__pyx_m, __pyx_n__doublesize); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1;}
- __pyx_4 = PyNumber_Divide(__pyx_2, __pyx_3); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_2 = PyInt_FromSsize_t(__pyx_v_buflenx); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_3 = __Pyx_GetName(__pyx_m, __pyx_n__doublesize); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_4 = PyNumber_Divide(__pyx_2, __pyx_3); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1;}
Py_DECREF(__pyx_2); __pyx_2 = 0;
Py_DECREF(__pyx_3); __pyx_3 = 0;
- __pyx_5 = __pyx_PyIndex_AsSsize_t(__pyx_4); if (unlikely((__pyx_5 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_5 = __pyx_PyIndex_AsSsize_t(__pyx_4); if (unlikely((__pyx_5 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1;}
Py_DECREF(__pyx_4); __pyx_4 = 0;
__pyx_v_ndim = __pyx_5;
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":109
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":104
* raise RuntimeError("Buffer lengths not the same")
* ndim = buflenx/_doublesize
* xdatab = <double *>xdata # <<<<<<<<<<<<<<
@@ -1063,7 +915,7 @@
*/
__pyx_v_xdatab = ((double *)__pyx_v_xdata);
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":110
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":105
* ndim = buflenx/_doublesize
* xdatab = <double *>xdata
* ydatab = <double *>ydata # <<<<<<<<<<<<<<
@@ -1072,7 +924,7 @@
*/
__pyx_v_ydatab = ((double *)__pyx_v_ydata);
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":111
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":106
* xdatab = <double *>xdata
* ydatab = <double *>ydata
* for i from 0 <= i < ndim: # <<<<<<<<<<<<<<
@@ -1081,7 +933,7 @@
*/
for (__pyx_v_i = 0; __pyx_v_i < __pyx_v_ndim; __pyx_v_i++) {
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":112
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":107
* ydatab = <double *>ydata
* for i from 0 <= i < ndim:
* projxyin.u = xdatab[i] # <<<<<<<<<<<<<<
@@ -1090,7 +942,7 @@
*/
__pyx_v_projxyin.u = (__pyx_v_xdatab[__pyx_v_i]);
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":113
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":108
* for i from 0 <= i < ndim:
* projxyin.u = xdatab[i]
* projxyin.v = ydatab[i] # <<<<<<<<<<<<<<
@@ -1099,7 +951,7 @@
*/
__pyx_v_projxyin.v = (__pyx_v_ydatab[__pyx_v_i]);
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":114
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":109
* projxyin.u = xdatab[i]
* projxyin.v = ydatab[i]
* projlonlatout = pj_inv(projxyin,self.projpj) # <<<<<<<<<<<<<<
@@ -1108,7 +960,7 @@
*/
__pyx_v_projlonlatout = pj_inv(__pyx_v_projxyin, ((struct __pyx_obj_5_proj_Proj *)__pyx_v_self)->projpj);
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":115
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":110
* projxyin.v = ydatab[i]
* projlonlatout = pj_inv(projxyin,self.projpj)
* if errcheck and pj_errno != 0: # <<<<<<<<<<<<<<
@@ -1117,36 +969,36 @@
*/
__pyx_2 = __pyx_v_errcheck;
Py_INCREF(__pyx_2);
- __pyx_1 = __Pyx_PyObject_IsTrue(__pyx_2); if (unlikely(__pyx_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_1 = __Pyx_PyObject_IsTrue(__pyx_2); if (unlikely(__pyx_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1;}
if (__pyx_1) {
Py_DECREF(__pyx_2); __pyx_2 = 0;
- __pyx_2 = __Pyx_PyBool_FromLong((pj_errno != 0)); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_2 = __Pyx_PyBool_FromLong((pj_errno != 0)); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1;}
}
- __pyx_1 = __Pyx_PyObject_IsTrue(__pyx_2); if (unlikely(__pyx_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_1 = __Pyx_PyObject_IsTrue(__pyx_2); if (unlikely(__pyx_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1;}
Py_DECREF(__pyx_2); __pyx_2 = 0;
if (__pyx_1) {
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":116
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":111
* projlonlatout = pj_inv(projxyin,self.projpj)
* if errcheck and pj_errno != 0:
* raise RuntimeError(pj_strerrno(pj_errno)) # <<<<<<<<<<<<<<
* # since HUGE_VAL can be 'inf',
* # change it to a real (but very large) number.
*/
- __pyx_3 = PyString_FromString(pj_strerrno(pj_errno)); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1;}
- __pyx_4 = PyTuple_New(1); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_3 = PyString_FromString(pj_strerrno(pj_errno)); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_4 = PyTuple_New(1); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1;}
PyTuple_SET_ITEM(__pyx_4, 0, __pyx_3);
__pyx_3 = 0;
- __pyx_2 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_4), NULL); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_2 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_4), NULL); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1;}
Py_DECREF(((PyObject *)__pyx_4)); __pyx_4 = 0;
__Pyx_Raise(__pyx_2, 0, 0);
Py_DECREF(__pyx_2); __pyx_2 = 0;
- {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1;}
goto __pyx_L9;
}
__pyx_L9:;
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":119
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":114
* # since HUGE_VAL can be 'inf',
* # change it to a real (but very large) number.
* if projlonlatout.u == HUGE_VAL: # <<<<<<<<<<<<<<
@@ -1156,7 +1008,7 @@
__pyx_1 = (__pyx_v_projlonlatout.u == HUGE_VAL);
if (__pyx_1) {
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":120
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":115
* # change it to a real (but very large) number.
* if projlonlatout.u == HUGE_VAL:
* xdatab[i] = 1.e30 # <<<<<<<<<<<<<<
@@ -1167,17 +1019,17 @@
goto __pyx_L10;
}
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":121
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":116
* if projlonlatout.u == HUGE_VAL:
* xdatab[i] = 1.e30
* elif radians: # <<<<<<<<<<<<<<
* xdatab[i] = projlonlatout.u
* else:
*/
- __pyx_1 = __Pyx_PyObject_IsTrue(__pyx_v_radians); if (unlikely(__pyx_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 121; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_1 = __Pyx_PyObject_IsTrue(__pyx_v_radians); if (unlikely(__pyx_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1;}
if (__pyx_1) {
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":122
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":117
* xdatab[i] = 1.e30
* elif radians:
* xdatab[i] = projlonlatout.u # <<<<<<<<<<<<<<
@@ -1189,25 +1041,25 @@
}
/*else*/ {
- /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":124
+ /* "/Volumes/User/jwhitaker/matplotlib/basemap/src/_proj.pyx":119
* xdatab[i] = projlonlatout.u
* else:
* xdatab[i] = _rad2dg*projlonlatout.u # <<<<<<<<<<<<<<
* if projlonlatout.v == HUGE_VAL:
* ydatab[i] = 1.e30
*/
- __pyx_3 = __Pyx_GetName(__pyx_m, __pyx_n__rad2dg); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1;}
- __pyx_4 = PyFloat_FromDouble(__pyx_v_projlonlatout.u); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1;}
- __pyx_2 = PyNumber_Multiply(__pyx_3, __pyx_4); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_3 = __Pyx_GetName(__pyx_m, __pyx_n__rad2dg); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1;}
+ __pyx_4 = PyFloat_FromDouble(__pyx_v_projlonlatout.u); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clinen...
[truncated message content] |
|
From: <ds...@us...> - 2008-05-23 21:53:11
|
Revision: 5246
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5246&view=rev
Author: dsdale
Date: 2008-05-23 14:53:01 -0700 (Fri, 23 May 2008)
Log Message:
-----------
updating docstrings
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/axes.py
trunk/matplotlib/lib/matplotlib/text.py
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2008-05-23 20:32:56 UTC (rev 5245)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2008-05-23 21:53:01 UTC (rev 5246)
@@ -2399,13 +2399,15 @@
def annotate(self, *args, **kwargs):
"""
- annotate(s, xy,
- xytext=None,
- xycoords='data',
- textcoords='data',
- arrowprops=None,
- **props)
+ call signature::
+ annotate(s, xy,
+ xytext=None,
+ xycoords='data',
+ textcoords='data',
+ arrowprops=None,
+ **props)
+
%(Annotation)s
"""
a = mtext.Annotation(*args, **kwargs)
@@ -2996,13 +2998,16 @@
def acorr(self, x, **kwargs):
"""
- ACORR(x, normed=False, detrend=mlab.detrend_none, usevlines=False,
- maxlags=None, **kwargs)
+ call signature::
+
+ acorr(x, normed=False, detrend=mlab.detrend_none, usevlines=False,
+ maxlags=None, **kwargs)
+
Plot the autocorrelation of x. If normed=True, normalize the
data but the autocorrelation at 0-th lag. x is detrended by
the detrend callable (default no normalization.
- data are plotted as plot(lags, c, **kwargs)
+ data are plotted as ``plot(lags, c, **kwargs)``
return value is lags, c, line where lags are a length
2*maxlags+1 lag vector, c is the 2*maxlags+1 auto correlation
@@ -3032,17 +3037,17 @@
def xcorr(self, x, y, normed=False, detrend=mlab.detrend_none, usevlines=False,
maxlags=None, **kwargs):
"""
- XCORR(x, y, normed=False, detrend=mlab.detrend_none, usevlines=False, **kwargs):
+ XCORR(x, y, normed=False, detrend=mlab.detrend_none, usevlines=False, \*\*kwargs):
Plot the cross correlation between x and y. If normed=True,
normalize the data but the cross correlation at 0-th lag. x
and y are detrended by the detrend callable (default no
normalization. x and y must be equal length
- data are plotted as plot(lags, c, **kwargs)
+ data are plotted as ``plot(lags, c, **kwargs)``
return value is lags, c, line where lags are a length
- 2*maxlags+1 lag vector, c is the 2*maxlags+1 auto correlation
+ ``2*maxlags+1`` lag vector, c is the ``2*maxlags+1`` auto correlation
vector, and line is a Line2D instance returned by plot. The
default linestyle is None and the default marker is 'o',
though these can be overridden with keyword args. The cross
@@ -3059,7 +3064,7 @@
if usevlines=False, kwargs are passed onto Axes.plot
maxlags is a positive integer detailing the number of lags to show.
- The default value of None will return all (2*len(x)-1) lags.
+ The default value of None will return all ``(2*len(x)-1)`` lags.
See the respective function for documentation on valid kwargs
"""
Modified: trunk/matplotlib/lib/matplotlib/text.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/text.py 2008-05-23 20:32:56 UTC (rev 5245)
+++ trunk/matplotlib/lib/matplotlib/text.py 2008-05-23 21:53:01 UTC (rev 5246)
@@ -990,36 +990,47 @@
(see matplotlib.lines.Line2D) for the arrow that connects
annotation to the point. Valid keys are
- - width : the width of the arrow in points
- - frac : the fraction of the arrow length occupied by the head
- - headwidth : the width of the base of the arrow head in points
- - shrink: often times it is convenient to have the arrowtip
- and base a bit away from the text and point being
- annotated. If d is the distance between the text and
- annotated point, shrink will shorten the arrow so the tip
- and base are shink percent of the distance d away from the
- endpoints. ie, shrink=0.05 is 5%%
- - any key for matplotlib.patches.polygon
+ ========= ===========================================================
+ Key Description
+ ========= ===========================================================
+ width the width of the arrow in points
+ frac the fraction of the arrow length occupied by the head
+ headwidth the width of the base of the arrow head in points
+ shrink often times it is convenient to have the arrowtip
+ and base a bit away from the text and point being
+ annotated. If d is the distance between the text and
+ annotated point, shrink will shorten the arrow so the tip
+ and base are shink percent of the distance d away from the
+ endpoints. ie, shrink=0.05 is 5%%
+ ? any key for matplotlib.patches.polygon
+ ========= ===========================================================
xycoords and textcoords are strings that indicate the
coordinates of xy and xytext.
- 'figure points' : points from the lower left corner of the figure
- 'figure pixels' : pixels from the lower left corner of the figure 'figure fraction' : 0,0 is lower left of figure and 1,1 is upper, right
- 'axes points' : points from lower left corner of axes
- 'axes pixels' : pixels from lower left corner of axes
- 'axes fraction' : 0,1 is lower left of axes and 1,1 is upper right
- 'data' : use the coordinate system of the object being annotated (default)
- 'offset points' : Specify an offset (in points) from the xy value
- 'polar' : you can specify theta, r for the annotation, even
- in cartesian plots. Note that if you
- are using a polar axes, you do not need
- to specify polar for the coordinate
- system since that is the native"data" coordinate system.
+ ================= ===================================================
+ Property Description
+ ================= ===================================================
+ 'figure points' points from the lower left corner of the figure
+ 'figure pixels' pixels from the lower left corner of the figure
+ 'figure fraction' 0,0 is lower left of figure and 1,1 is upper, right
+ 'axes points' points from lower left corner of axes
+ 'axes pixels' pixels from lower left corner of axes
+ 'axes fraction' 0,1 is lower left of axes and 1,1 is upper right
+ 'data' use the coordinate system of the object being
+ annotated (default)
+ 'offset points' Specify an offset (in points) from the xy value
+ 'polar' you can specify theta, r for the annotation, even
+ in cartesian plots. Note that if you
+ are using a polar axes, you do not need
+ to specify polar for the coordinate
+ system since that is the native"data" coordinate
+ system.
+ ================= ===================================================
If a points or pixels option is specified, values will be
added to the left, bottom and if negative, values will be
- subtracted from the top, right. Eg,
+ subtracted from the top, right. Eg::
# 10 points to the right of the left border of the axes and
# 5 points below the top border
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-05-23 20:33:08
|
Revision: 5245
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5245&view=rev
Author: jdh2358
Date: 2008-05-23 13:32:56 -0700 (Fri, 23 May 2008)
Log Message:
-----------
added customize
Modified Paths:
--------------
trunk/matplotlib/doc/users_guide/conf.py
trunk/matplotlib/doc/users_guide/pyplot_tutorial.txt
Added Paths:
-----------
trunk/matplotlib/doc/users_guide/customizing.txt
Modified: trunk/matplotlib/doc/users_guide/conf.py
===================================================================
--- trunk/matplotlib/doc/users_guide/conf.py 2008-05-23 20:25:00 UTC (rev 5244)
+++ trunk/matplotlib/doc/users_guide/conf.py 2008-05-23 20:32:56 UTC (rev 5245)
@@ -57,7 +57,7 @@
today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
-#unused_docs = []
+unused_docs = ['figures/README.txt']
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
@@ -88,7 +88,7 @@
# The name of an image file (within the static path) to place at the top of
# the sidebar.
-#html_logo = None
+#html_logo = 'logo.png'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
Added: trunk/matplotlib/doc/users_guide/customizing.txt
===================================================================
--- trunk/matplotlib/doc/users_guide/customizing.txt (rev 0)
+++ trunk/matplotlib/doc/users_guide/customizing.txt 2008-05-23 20:32:56 UTC (rev 5245)
@@ -0,0 +1,26 @@
+Customizing matplotlib
+======================
+
+matplotlib uses an configuration file ``matplotlibrc`` which is
+located in ``matplotlib/mpl-data/matplotlibrc``. Every time you
+install matplotlib, this file will be overwritten, so if you want your
+customizations to be saved, please move this file to your ``HOME/.matplotlib``
+directory.
+
+You can control the defaults of almost every property in matplotlib:
+figure size and dpi, line width, color and style, axes, axis and grid
+properties, text and font properties and so on.
+
+You can also dynamically change the defaults in a python script or
+interactively from the python shell using the :func:`matplotlib.rc`
+command. For example to change the default line properties, you could
+do::
+
+ import matplotlib
+ matplotlib.rc('lines', linewidth=2, color='r')
+
+
+A sample matplotlibrc file
+--------------------------
+
+.. literalinclude:: ../../lib/matplotlib/mpl-data/matplotlibrc
\ No newline at end of file
Modified: trunk/matplotlib/doc/users_guide/pyplot_tutorial.txt
===================================================================
--- trunk/matplotlib/doc/users_guide/pyplot_tutorial.txt 2008-05-23 20:25:00 UTC (rev 5244)
+++ trunk/matplotlib/doc/users_guide/pyplot_tutorial.txt 2008-05-23 20:32:56 UTC (rev 5245)
@@ -95,7 +95,7 @@
plt.setp(lines, 'color', 'r', 'linewidth', 2.0)
-Here are the available :class:`matplotlib.lines.Line2D` properties.
+Here are the available :class:`~matplotlib.lines.Line2D` properties.
====================== ==================================================
Property Value Type
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ds...@us...> - 2008-05-23 20:25:02
|
Revision: 5244
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5244&view=rev
Author: dsdale
Date: 2008-05-23 13:25:00 -0700 (Fri, 23 May 2008)
Log Message:
-----------
minor changes to rest docstrings for lines.py and artist.py
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/artist.py
trunk/matplotlib/lib/matplotlib/lines.py
Modified: trunk/matplotlib/lib/matplotlib/artist.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/artist.py 2008-05-23 20:10:18 UTC (rev 5243)
+++ trunk/matplotlib/lib/matplotlib/artist.py 2008-05-23 20:25:00 UTC (rev 5244)
@@ -514,9 +514,12 @@
def get_aliases(self):
"""
get a dict mapping fullname -> alias for each alias in o.
- Eg for lines: {'markerfacecolor': 'mfc',
- 'linewidth' : 'lw',
- }
+ Eg for lines::
+
+ {'markerfacecolor': 'mfc',
+ 'linewidth' : 'lw',
+ }
+
"""
names = [name for name in dir(self.o) if
(name.startswith('set_') or name.startswith('get_'))
Modified: trunk/matplotlib/lib/matplotlib/lines.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/lines.py 2008-05-23 20:10:18 UTC (rev 5243)
+++ trunk/matplotlib/lib/matplotlib/lines.py 2008-05-23 20:25:00 UTC (rev 5244)
@@ -40,18 +40,18 @@
y = ma.array(np.arange(5), mask = [0,0,1,0,0])
#ii = unmasked_index_ranges(y.mask())
ii = unmasked_index_ranges(ma.getmask(y))
- # returns [[0,2,] [2,4,]]
+ # returns [[0,2,] [2,4,]]
y.compressed().filled()[ii[1,0]:ii[1,1]]
- # returns np.array [3,4,]
- # (The 'filled()' method converts the masked np.array to a numerix np.array.)
+ # returns np.array [3,4,]
+ # (The 'filled()' method converts the masked np.array to a numerix np.array.)
#i0, i1 = unmasked_index_ranges(y.mask(), compressed=False)
i0, i1 = unmasked_index_ranges(ma.getmask(y), compressed=False)
- # returns [[0,3,] [2,5,]]
+ # returns [[0,3,] [2,5,]]
y.filled()[ii[1,0]:ii[1,1]]
- # returns np.array [3,4,]
+ # returns np.array [3,4,]
'''
m = np.concatenate(((1,), mask, (1,)))
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-05-23 20:10:19
|
Revision: 5243
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5243&view=rev
Author: jdh2358
Date: 2008-05-23 13:10:18 -0700 (Fri, 23 May 2008)
Log Message:
-----------
removed the pyplot mod because it appears the rest is broken
Modified Paths:
--------------
trunk/matplotlib/doc/users_guide/api.txt
Removed Paths:
-------------
trunk/matplotlib/doc/users_guide/api_pyplot.txt
Modified: trunk/matplotlib/doc/users_guide/api.txt
===================================================================
--- trunk/matplotlib/doc/users_guide/api.txt 2008-05-23 19:56:31 UTC (rev 5242)
+++ trunk/matplotlib/doc/users_guide/api.txt 2008-05-23 20:10:18 UTC (rev 5243)
@@ -8,6 +8,5 @@
:maxdepth: 3
api_introduction
- api_pyplot
api_artists
Deleted: trunk/matplotlib/doc/users_guide/api_pyplot.txt
===================================================================
--- trunk/matplotlib/doc/users_guide/api_pyplot.txt 2008-05-23 19:56:31 UTC (rev 5242)
+++ trunk/matplotlib/doc/users_guide/api_pyplot.txt 2008-05-23 20:10:18 UTC (rev 5243)
@@ -1,10 +0,0 @@
-****************
-matlotlib.pyplot
-****************
-
-:mod:`matplotlib.pyplot`
-=============================
-
-.. automodule:: matplotlib.pyplot
- :members:
- :undoc-members:
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-05-23 19:56:35
|
Revision: 5242
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5242&view=rev
Author: jdh2358
Date: 2008-05-23 12:56:31 -0700 (Fri, 23 May 2008)
Log Message:
-----------
midnamed the pyplot api file
Modified Paths:
--------------
trunk/matplotlib/doc/users_guide/figures/make.py
Added Paths:
-----------
trunk/matplotlib/doc/users_guide/api_pyplot.txt
Removed Paths:
-------------
trunk/matplotlib/doc/users_guide/api_pyplot.py
Deleted: trunk/matplotlib/doc/users_guide/api_pyplot.py
===================================================================
--- trunk/matplotlib/doc/users_guide/api_pyplot.py 2008-05-23 19:54:04 UTC (rev 5241)
+++ trunk/matplotlib/doc/users_guide/api_pyplot.py 2008-05-23 19:56:31 UTC (rev 5242)
@@ -1,10 +0,0 @@
-****************
-matlotlib.pyplot
-****************
-
-:mod:`matplotlib.pyplot`
-=============================
-
-.. automodule:: matplotlib.pyplot
- :members:
- :undoc-members:
Copied: trunk/matplotlib/doc/users_guide/api_pyplot.txt (from rev 5241, trunk/matplotlib/doc/users_guide/api_pyplot.py)
===================================================================
--- trunk/matplotlib/doc/users_guide/api_pyplot.txt (rev 0)
+++ trunk/matplotlib/doc/users_guide/api_pyplot.txt 2008-05-23 19:56:31 UTC (rev 5242)
@@ -0,0 +1,10 @@
+****************
+matlotlib.pyplot
+****************
+
+:mod:`matplotlib.pyplot`
+=============================
+
+.. automodule:: matplotlib.pyplot
+ :members:
+ :undoc-members:
Modified: trunk/matplotlib/doc/users_guide/figures/make.py
===================================================================
--- trunk/matplotlib/doc/users_guide/figures/make.py 2008-05-23 19:54:04 UTC (rev 5241)
+++ trunk/matplotlib/doc/users_guide/figures/make.py 2008-05-23 19:56:31 UTC (rev 5242)
@@ -20,7 +20,7 @@
continue
else:
print ' building %s'%fname
- plt.gcf().clf() # we need to clear between runs
+ plt.close('all') # we need to clear between runs
mplshell.magic_run(basename)
plt.savefig('%s.png'%basename)
print 'all figures made'
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-05-23 19:54:11
|
Revision: 5241
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5241&view=rev
Author: jdh2358
Date: 2008-05-23 12:54:04 -0700 (Fri, 23 May 2008)
Log Message:
-----------
added pyplot to api
Modified Paths:
--------------
trunk/matplotlib/doc/users_guide/api.txt
trunk/matplotlib/doc/users_guide/api_artists.txt
Added Paths:
-----------
trunk/matplotlib/doc/users_guide/api_pyplot.py
Modified: trunk/matplotlib/doc/users_guide/api.txt
===================================================================
--- trunk/matplotlib/doc/users_guide/api.txt 2008-05-23 19:36:24 UTC (rev 5240)
+++ trunk/matplotlib/doc/users_guide/api.txt 2008-05-23 19:54:04 UTC (rev 5241)
@@ -8,5 +8,6 @@
:maxdepth: 3
api_introduction
+ api_pyplot
api_artists
Modified: trunk/matplotlib/doc/users_guide/api_artists.txt
===================================================================
--- trunk/matplotlib/doc/users_guide/api_artists.txt 2008-05-23 19:36:24 UTC (rev 5240)
+++ trunk/matplotlib/doc/users_guide/api_artists.txt 2008-05-23 19:54:04 UTC (rev 5241)
@@ -7,8 +7,8 @@
.. automodule:: matplotlib.artist
:members:
+ :undoc-members:
-
:mod:`matplotlib.lines`
=============================
@@ -21,10 +21,11 @@
.. automodule:: matplotlib.patches
:members:
+ :undoc-members:
:mod:`matplotlib.text`
=============================
.. automodule:: matplotlib.text
:members:
-
+ :undoc-members:
Added: trunk/matplotlib/doc/users_guide/api_pyplot.py
===================================================================
--- trunk/matplotlib/doc/users_guide/api_pyplot.py (rev 0)
+++ trunk/matplotlib/doc/users_guide/api_pyplot.py 2008-05-23 19:54:04 UTC (rev 5241)
@@ -0,0 +1,10 @@
+****************
+matlotlib.pyplot
+****************
+
+:mod:`matplotlib.pyplot`
+=============================
+
+.. automodule:: matplotlib.pyplot
+ :members:
+ :undoc-members:
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ds...@us...> - 2008-05-23 19:36:33
|
Revision: 5240
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5240&view=rev
Author: dsdale
Date: 2008-05-23 12:36:24 -0700 (Fri, 23 May 2008)
Log Message:
-----------
include undocumented members of the lines module
Modified Paths:
--------------
trunk/matplotlib/doc/users_guide/api_artists.txt
Modified: trunk/matplotlib/doc/users_guide/api_artists.txt
===================================================================
--- trunk/matplotlib/doc/users_guide/api_artists.txt 2008-05-23 19:27:23 UTC (rev 5239)
+++ trunk/matplotlib/doc/users_guide/api_artists.txt 2008-05-23 19:36:24 UTC (rev 5240)
@@ -14,8 +14,8 @@
.. automodule:: matplotlib.lines
:members:
+ :undoc-members:
-
:mod:`matplotlib.patches`
=============================
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <sa...@us...> - 2008-05-23 19:27:45
|
Revision: 5239
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5239&view=rev
Author: sameerd
Date: 2008-05-23 12:27:23 -0700 (Fri, 23 May 2008)
Log Message:
-----------
Getting mlab.py in sync with the trunk
Modified Paths:
--------------
branches/v0_91_maint/lib/matplotlib/mlab.py
Modified: branches/v0_91_maint/lib/matplotlib/mlab.py
===================================================================
--- branches/v0_91_maint/lib/matplotlib/mlab.py 2008-05-23 19:05:51 UTC (rev 5238)
+++ branches/v0_91_maint/lib/matplotlib/mlab.py 2008-05-23 19:27:23 UTC (rev 5239)
@@ -45,7 +45,6 @@
this efficiently by caching the direct FFTs.
= record array helper functions =
-
* rec2txt : pretty print a record array
* rec2csv : store record array in CSV file
* csv2rec : import record array from CSV file with type inspection
@@ -55,7 +54,7 @@
* rec_groupby : summarize data by groups (similar to SQL GROUP BY)
* rec_summarize : helper code to filter rec array fields into new fields
-For the rec viewer clases (eg rec2csv), there are a bunch of Format
+For the rec viewer functions(e rec2csv), there are a bunch of Format
objects you can pass into the functions that will do things like color
negative values red, set percent formatting and scaling, etc.
@@ -84,10 +83,11 @@
"""
from __future__ import division
-import sys, datetime, csv, warnings, copy, os
+import csv, warnings, copy, os
-import numpy as npy
+import numpy as np
+
from matplotlib import nxutils
from matplotlib import cbook
@@ -100,28 +100,28 @@
def linspace(*args, **kw):
warnings.warn("use numpy.linspace", DeprecationWarning)
- return npy.linspace(*args, **kw)
+ return np.linspace(*args, **kw)
def meshgrid(x,y):
warnings.warn("use numpy.meshgrid", DeprecationWarning)
- return npy.meshgrid(x,y)
+ return np.meshgrid(x,y)
def mean(x, dim=None):
warnings.warn("Use numpy.mean(x) or x.mean()", DeprecationWarning)
if len(x)==0: return None
- return npy.mean(x, axis=dim)
+ return np.mean(x, axis=dim)
def logspace(xmin,xmax,N):
- return npy.exp(npy.linspace(npy.log(xmin), npy.log(xmax), N))
+ return np.exp(np.linspace(np.log(xmin), np.log(xmax), N))
def _norm(x):
"return sqrt(x dot x)"
- return npy.sqrt(npy.dot(x,x))
+ return np.sqrt(np.dot(x,x))
def window_hanning(x):
"return x times the hanning window of len(x)"
- return npy.hanning(len(x))*x
+ return np.hanning(len(x))*x
def window_none(x):
"No window function; simply return x"
@@ -131,7 +131,7 @@
def conv(x, y, mode=2):
'convolve x with y'
warnings.warn("Use numpy.convolve(x, y, mode='full')", DeprecationWarning)
- return npy.convolve(x,y,mode)
+ return np.convolve(x,y,mode)
def detrend(x, key=None):
if key is None or key=='constant':
@@ -141,10 +141,10 @@
def demean(x, axis=0):
"Return x minus its mean along the specified axis"
- x = npy.asarray(x)
+ x = np.asarray(x)
if axis:
ind = [slice(None)] * axis
- ind.append(npy.newaxis)
+ ind.append(np.newaxis)
return x - x.mean(axis)[ind]
return x - x.mean(axis)
@@ -159,8 +159,8 @@
def detrend_linear(y):
"Return y minus best fit line; 'linear' detrending "
# This is faster than an algorithm based on linalg.lstsq.
- x = npy.arange(len(y), dtype=npy.float_)
- C = npy.cov(x, y, bias=1)
+ x = np.arange(len(y), dtype=np.float_)
+ C = np.cov(x, y, bias=1)
b = C[0,1]/C[0,0]
a = y.mean() - b*x.mean()
return y - (b*x + a)
@@ -200,41 +200,41 @@
if NFFT % 2:
raise ValueError('NFFT must be even')
- x = npy.asarray(x) # make sure we're dealing with a numpy array
+ x = np.asarray(x) # make sure we're dealing with a numpy array
# zero pad x up to NFFT if it is shorter than NFFT
if len(x)<NFFT:
n = len(x)
- x = npy.resize(x, (NFFT,)) # Can't use resize method.
+ x = np.resize(x, (NFFT,)) # Can't use resize method.
x[n:] = 0
# for real x, ignore the negative frequencies
- if npy.iscomplexobj(x): numFreqs = NFFT
+ if np.iscomplexobj(x): numFreqs = NFFT
else: numFreqs = NFFT//2+1
if cbook.iterable(window):
assert(len(window) == NFFT)
windowVals = window
else:
- windowVals = window(npy.ones((NFFT,),x.dtype))
+ windowVals = window(np.ones((NFFT,),x.dtype))
step = NFFT-noverlap
ind = range(0,len(x)-NFFT+1,step)
n = len(ind)
- Pxx = npy.zeros((numFreqs,n), npy.float_)
+ Pxx = np.zeros((numFreqs,n), np.float_)
# do the ffts of the slices
for i in range(n):
thisX = x[ind[i]:ind[i]+NFFT]
thisX = windowVals * detrend(thisX)
- fx = npy.absolute(npy.fft.fft(thisX))**2
+ fx = np.absolute(np.fft.fft(thisX))**2
Pxx[:,i] = fx[:numFreqs]
if n>1:
Pxx = Pxx.mean(axis=1)
# Scale the spectrum by the norm of the window to compensate for
# windowing loss; see Bendat & Piersol Sec 11.5.2
- Pxx /= (npy.abs(windowVals)**2).sum()
+ Pxx /= (np.abs(windowVals)**2).sum()
- freqs = Fs/NFFT * npy.arange(numFreqs)
+ freqs = Fs/NFFT * np.arange(numFreqs)
return Pxx, freqs
@@ -267,32 +267,32 @@
if NFFT % 2:
raise ValueError, 'NFFT must be even'
- x = npy.asarray(x) # make sure we're dealing with a numpy array
- y = npy.asarray(y) # make sure we're dealing with a numpy array
+ x = np.asarray(x) # make sure we're dealing with a numpy array
+ y = np.asarray(y) # make sure we're dealing with a numpy array
# zero pad x and y up to NFFT if they are shorter than NFFT
if len(x)<NFFT:
n = len(x)
- x = npy.resize(x, (NFFT,))
+ x = np.resize(x, (NFFT,))
x[n:] = 0
if len(y)<NFFT:
n = len(y)
- y = npy.resize(y, (NFFT,))
+ y = np.resize(y, (NFFT,))
y[n:] = 0
# for real x, ignore the negative frequencies
- if npy.iscomplexobj(x): numFreqs = NFFT
+ if np.iscomplexobj(x): numFreqs = NFFT
else: numFreqs = NFFT//2+1
if cbook.iterable(window):
assert(len(window) == NFFT)
windowVals = window
else:
- windowVals = window(npy.ones((NFFT,), x.dtype))
+ windowVals = window(np.ones((NFFT,), x.dtype))
step = NFFT-noverlap
ind = range(0,len(x)-NFFT+1,step)
n = len(ind)
- Pxy = npy.zeros((numFreqs,n), npy.complex_)
+ Pxy = np.zeros((numFreqs,n), np.complex_)
# do the ffts of the slices
for i in range(n):
@@ -300,9 +300,9 @@
thisX = windowVals*detrend(thisX)
thisY = y[ind[i]:ind[i]+NFFT]
thisY = windowVals*detrend(thisY)
- fx = npy.fft.fft(thisX)
- fy = npy.fft.fft(thisY)
- Pxy[:,i] = npy.conjugate(fx[:numFreqs])*fy[:numFreqs]
+ fx = np.fft.fft(thisX)
+ fy = np.fft.fft(thisY)
+ Pxy[:,i] = np.conjugate(fx[:numFreqs])*fy[:numFreqs]
@@ -310,8 +310,8 @@
# windowing loss; see Bendat & Piersol Sec 11.5.2
if n>1:
Pxy = Pxy.mean(axis=1)
- Pxy /= (npy.abs(windowVals)**2).sum()
- freqs = Fs/NFFT*npy.arange(numFreqs)
+ Pxy /= (np.abs(windowVals)**2).sum()
+ freqs = Fs/NFFT*np.arange(numFreqs)
return Pxy, freqs
def specgram(x, NFFT=256, Fs=2, detrend=detrend_none,
@@ -342,9 +342,9 @@
segments.
"""
- x = npy.asarray(x)
+ x = np.asarray(x)
assert(NFFT>noverlap)
- #if npy.log(NFFT)/npy.log(2) != int(npy.log(NFFT)/npy.log(2)):
+ #if np.log(NFFT)/np.log(2) != int(np.log(NFFT)/np.log(2)):
# raise ValueError, 'NFFT must be a power of 2'
if NFFT % 2:
raise ValueError('NFFT must be even')
@@ -353,42 +353,42 @@
# zero pad x up to NFFT if it is shorter than NFFT
if len(x)<NFFT:
n = len(x)
- x = npy.resize(x, (NFFT,))
+ x = np.resize(x, (NFFT,))
x[n:] = 0
# for real x, ignore the negative frequencies
- if npy.iscomplexobj(x):
+ if np.iscomplexobj(x):
numFreqs=NFFT
else:
numFreqs = NFFT//2+1
if cbook.iterable(window):
assert(len(window) == NFFT)
- windowVals = npy.asarray(window)
+ windowVals = np.asarray(window)
else:
- windowVals = window(npy.ones((NFFT,),x.dtype))
+ windowVals = window(np.ones((NFFT,),x.dtype))
step = NFFT-noverlap
- ind = npy.arange(0,len(x)-NFFT+1,step)
+ ind = np.arange(0,len(x)-NFFT+1,step)
n = len(ind)
- Pxx = npy.zeros((numFreqs,n), npy.float_)
+ Pxx = np.zeros((numFreqs,n), np.float_)
# do the ffts of the slices
for i in range(n):
thisX = x[ind[i]:ind[i]+NFFT]
thisX = windowVals*detrend(thisX)
- fx = npy.absolute(npy.fft.fft(thisX))**2
+ fx = np.absolute(np.fft.fft(thisX))**2
Pxx[:,i] = fx[:numFreqs]
# Scale the spectrum by the norm of the window to compensate for
# windowing loss; see Bendat & Piersol Sec 11.5.2
- Pxx /= (npy.abs(windowVals)**2).sum()
+ Pxx /= (np.abs(windowVals)**2).sum()
t = 1/Fs*(ind+NFFT/2)
- freqs = Fs/NFFT*npy.arange(numFreqs)
+ freqs = Fs/NFFT*np.arange(numFreqs)
- if npy.iscomplexobj(x):
+ if np.iscomplexobj(x):
# center the frequency range at zero
- freqs = npy.concatenate((freqs[NFFT/2:]-Fs,freqs[:NFFT/2]))
- Pxx = npy.concatenate((Pxx[NFFT/2:,:],Pxx[:NFFT/2,:]),0)
+ freqs = np.concatenate((freqs[NFFT/2:]-Fs,freqs[:NFFT/2]))
+ Pxx = np.concatenate((Pxx[NFFT/2:,:],Pxx[:NFFT/2,:]),0)
return Pxx, freqs, t
@@ -420,7 +420,7 @@
Pyy, f = psd(y, NFFT, Fs, detrend, window, noverlap)
Pxy, f = csd(x, y, NFFT, Fs, detrend, window, noverlap)
- Cxy = npy.divide(npy.absolute(Pxy)**2, Pxx*Pyy)
+ Cxy = np.divide(np.absolute(Pxy)**2, Pxx*Pyy)
Cxy.shape = (len(f),)
return Cxy, f
@@ -440,7 +440,7 @@
"""
warnings.warn("Use numpy.corrcoef", DeprecationWarning)
kw = dict(rowvar=False)
- return npy.corrcoef(*args, **kw)
+ return np.corrcoef(*args, **kw)
def polyfit(*args, **kwargs):
@@ -483,7 +483,7 @@
"""
warnings.warn("use numpy.poyfit", DeprecationWarning)
- return npy.polyfit(*args, **kwargs)
+ return np.polyfit(*args, **kwargs)
@@ -505,7 +505,7 @@
"""
warnings.warn("use numpy.polyval", DeprecationWarning)
- return npy.polyval(*args, **kwargs)
+ return np.polyval(*args, **kwargs)
def vander(*args, **kwargs):
"""
@@ -517,7 +517,7 @@
"""
warnings.warn("Use numpy.vander()", DeprecationWarning)
- return npy.vander(*args, **kwargs)
+ return np.vander(*args, **kwargs)
def donothing_callback(*args):
@@ -596,7 +596,7 @@
# zero pad if X is too short
if numRows < NFFT:
tmp = X
- X = npy.zeros( (NFFT, numCols), X.dtype)
+ X = np.zeros( (NFFT, numCols), X.dtype)
X[:numRows,:] = tmp
del tmp
@@ -611,7 +611,7 @@
del seen
# for real X, ignore the negative frequencies
- if npy.iscomplexobj(X): numFreqs = NFFT
+ if np.iscomplexobj(X): numFreqs = NFFT
else: numFreqs = NFFT//2+1
# cache the FFT of every windowed, detrended NFFT length segement
@@ -621,7 +621,7 @@
assert(len(window) == NFFT)
windowVals = window
else:
- windowVals = window(npy.ones((NFFT,), typecode(X)))
+ windowVals = window(np.ones((NFFT,), typecode(X)))
ind = range(0, numRows-NFFT+1, NFFT-noverlap)
numSlices = len(ind)
FFTSlices = {}
@@ -631,7 +631,7 @@
normVal = norm(windowVals)**2
for iCol in allColumns:
progressCallback(i/Ncols, 'Cacheing FFTs')
- Slices = npy.zeros( (numSlices,numFreqs), dtype=npy.complex_)
+ Slices = np.zeros( (numSlices,numFreqs), dtype=np.complex_)
for iSlice in slices:
thisSlice = X[ind[iSlice]:ind[iSlice]+NFFT, iCol]
thisSlice = windowVals*detrend(thisSlice)
@@ -640,7 +640,7 @@
FFTSlices[iCol] = Slices
if preferSpeedOverMemory:
FFTConjSlices[iCol] = conjugate(Slices)
- Pxx[iCol] = npy.divide(npy.mean(absolute(Slices)**2), normVal)
+ Pxx[iCol] = np.divide(np.mean(absolute(Slices)**2), normVal)
del Slices, ind, windowVals
# compute the coherences and phases for all pairs using the
@@ -657,13 +657,13 @@
if preferSpeedOverMemory:
Pxy = FFTSlices[i] * FFTConjSlices[j]
else:
- Pxy = FFTSlices[i] * npy.conjugate(FFTSlices[j])
- if numSlices>1: Pxy = npy.mean(Pxy)
- Pxy = npy.divide(Pxy, normVal)
- Cxy[(i,j)] = npy.divide(npy.absolute(Pxy)**2, Pxx[i]*Pxx[j])
- Phase[(i,j)] = npy.arctan2(Pxy.imag, Pxy.real)
+ Pxy = FFTSlices[i] * np.conjugate(FFTSlices[j])
+ if numSlices>1: Pxy = np.mean(Pxy)
+ Pxy = np.divide(Pxy, normVal)
+ Cxy[(i,j)] = np.divide(np.absolute(Pxy)**2, Pxx[i]*Pxx[j])
+ Phase[(i,j)] = np.arctan2(Pxy.imag, Pxy.real)
- freqs = Fs/NFFT*npy.arange(numFreqs)
+ freqs = Fs/NFFT*np.arange(numFreqs)
if returnPxx:
return Cxy, Phase, freqs, Pxx
else:
@@ -684,16 +684,16 @@
Sanalytic = 0.5 * ( 1.0 + log(2*pi*sigma**2.0) )
"""
- n,bins = npy.histogram(y, bins)
- n = n.astype(npy.float_)
+ n,bins = np.histogram(y, bins)
+ n = n.astype(np.float_)
- n = npy.take(n, npy.nonzero(n)[0]) # get the positive
+ n = np.take(n, np.nonzero(n)[0]) # get the positive
- p = npy.divide(n, len(y))
+ p = np.divide(n, len(y))
delta = bins[1]-bins[0]
- S = -1.0*npy.sum(p*log(p)) + log(delta)
- #S = -1.0*npy.sum(p*log(p))
+ S = -1.0*np.sum(p*log(p)) + log(delta)
+ #S = -1.0*np.sum(p*log(p))
return S
def hist(y, bins=10, normed=0):
@@ -711,12 +711,12 @@
Credits: the Numeric 22 documentation
"""
warnings.warn("Use numpy.histogram()", DeprecationWarning)
- return npy.histogram(y, bins=bins, range=None, normed=normed)
+ return np.histogram(y, bins=bins, range=None, normed=normed)
def normpdf(x, *args):
"Return the normal pdf evaluated at x; args provides mu, sigma"
mu, sigma = args
- return 1/(npy.sqrt(2*npy.pi)*sigma)*npy.exp(-0.5 * (1/sigma*(x - mu))**2)
+ return 1/(np.sqrt(2*np.pi)*sigma)*np.exp(-0.5 * (1/sigma*(x - mu))**2)
def levypdf(x, gamma, alpha):
@@ -726,26 +726,26 @@
if N%2 != 0:
raise ValueError, 'x must be an event length array; try\n' + \
- 'x = npy.linspace(minx, maxx, N), where N is even'
+ 'x = np.linspace(minx, maxx, N), where N is even'
dx = x[1]-x[0]
- f = 1/(N*dx)*npy.arange(-N/2, N/2, npy.float_)
+ f = 1/(N*dx)*np.arange(-N/2, N/2, np.float_)
- ind = npy.concatenate([npy.arange(N/2, N, int),
- npy.arange(0, N/2, int)])
+ ind = np.concatenate([np.arange(N/2, N, int),
+ np.arange(0, N/2, int)])
df = f[1]-f[0]
- cfl = exp(-gamma*npy.absolute(2*pi*f)**alpha)
+ cfl = exp(-gamma*np.absolute(2*pi*f)**alpha)
- px = npy.fft.fft(npy.take(cfl,ind)*df).astype(npy.float_)
- return npy.take(px, ind)
+ px = np.fft.fft(np.take(cfl,ind)*df).astype(np.float_)
+ return np.take(px, ind)
def find(condition):
"Return the indices where ravel(condition) is true"
- res, = npy.nonzero(npy.ravel(condition))
+ res, = np.nonzero(np.ravel(condition))
return res
def trapz(x, y):
@@ -753,12 +753,12 @@
Trapezoidal integral of y(x).
"""
warnings.warn("Use numpy.trapz(y,x) instead of trapz(x,y)", DeprecationWarning)
- return npy.trapz(y, x)
+ return np.trapz(y, x)
#if len(x)!=len(y):
# raise ValueError, 'x and y must have the same length'
#if len(x)<2:
# raise ValueError, 'x and y must have > 1 element'
- #return npy.sum(0.5*npy.diff(x)*(y[1:]+y[:-1]))
+ #return np.sum(0.5*np.diff(x)*(y[1:]+y[:-1]))
@@ -769,23 +769,23 @@
If there are two equally long stretches, pick the first
"""
- x = npy.ravel(x)
+ x = np.ravel(x)
if len(x)==0:
- return npy.array([])
+ return np.array([])
ind = (x==0).nonzero()[0]
if len(ind)==0:
- return npy.arange(len(x))
+ return np.arange(len(x))
if len(ind)==len(x):
- return npy.array([])
+ return np.array([])
- y = npy.zeros( (len(x)+2,), x.dtype)
+ y = np.zeros( (len(x)+2,), x.dtype)
y[1:-1] = x
- dif = npy.diff(y)
+ dif = np.diff(y)
up = (dif == 1).nonzero()[0];
dn = (dif == -1).nonzero()[0];
i = (dn-up == max(dn - up)).nonzero()[0][0]
- ind = npy.arange(up[i], dn[i])
+ ind = np.arange(up[i], dn[i])
return ind
@@ -809,7 +809,7 @@
R13 Neural Network Toolbox but is not found in later versions;
its successor seems to be called "processpcs".
"""
- U,s,v = npy.linalg.svd(P)
+ U,s,v = np.linalg.svd(P)
varEach = s**2/P.shape[1]
totVar = varEach.sum()
fracVar = varEach/totVar
@@ -817,7 +817,7 @@
# select the components that are greater
Trans = U[:,ind].transpose()
# The transformed data
- Pcomponents = npy.dot(Trans,P)
+ Pcomponents = np.dot(Trans,P)
return Pcomponents, Trans, fracVar[ind]
def prctile(x, p = (0.0, 25.0, 50.0, 75.0, 100.0)):
@@ -830,16 +830,16 @@
"""
- x = npy.array(x).ravel() # we need a copy
+ x = np.array(x).ravel() # we need a copy
x.sort()
Nx = len(x)
if not cbook.iterable(p):
return x[int(p*Nx/100.0)]
- p = npy.asarray(p)* Nx/100.0
+ p = np.asarray(p)* Nx/100.0
ind = p.astype(int)
- ind = npy.where(ind>=Nx, Nx-1, ind)
+ ind = np.where(ind>=Nx, Nx-1, ind)
return x.take(ind)
def prctile_rank(x, p):
@@ -856,15 +856,15 @@
"""
if not cbook.iterable(p):
- p = npy.arange(100.0/p, 100.0, 100.0/p)
+ p = np.arange(100.0/p, 100.0, 100.0/p)
else:
- p = npy.asarray(p)
+ p = np.asarray(p)
if p.max()<=1 or p.min()<0 or p.max()>100:
raise ValueError('percentiles should be in range 0..100, not 0..1')
ptiles = prctile(x, p)
- return npy.searchsorted(ptiles, x)
+ return np.searchsorted(ptiles, x)
def center_matrix(M, dim=0):
"""
@@ -873,12 +873,12 @@
if dim=1 operate on columns instead of rows. (dim is opposite
to the numpy axis kwarg.)
"""
- M = npy.asarray(M, npy.float_)
+ M = np.asarray(M, np.float_)
if dim:
M = (M - M.mean(axis=0)) / M.std(axis=0)
else:
- M = (M - M.mean(axis=1)[:,npy.newaxis])
- M = M / M.std(axis=1)[:,npy.newaxis]
+ M = (M - M.mean(axis=1)[:,np.newaxis])
+ M = M / M.std(axis=1)[:,np.newaxis]
return M
@@ -922,25 +922,25 @@
try: Ny = len(y0)
except TypeError:
- yout = npy.zeros( (len(t),), npy.float_)
+ yout = np.zeros( (len(t),), np.float_)
else:
- yout = npy.zeros( (len(t), Ny), npy.float_)
+ yout = np.zeros( (len(t), Ny), np.float_)
yout[0] = y0
i = 0
- for i in npy.arange(len(t)-1):
+ for i in np.arange(len(t)-1):
thist = t[i]
dt = t[i+1] - thist
dt2 = dt/2.0
y0 = yout[i]
- k1 = npy.asarray(derivs(y0, thist))
- k2 = npy.asarray(derivs(y0 + dt2*k1, thist+dt2))
- k3 = npy.asarray(derivs(y0 + dt2*k2, thist+dt2))
- k4 = npy.asarray(derivs(y0 + dt*k3, thist+dt))
+ k1 = np.asarray(derivs(y0, thist))
+ k2 = np.asarray(derivs(y0 + dt2*k1, thist+dt2))
+ k3 = np.asarray(derivs(y0 + dt2*k2, thist+dt2))
+ k4 = np.asarray(derivs(y0 + dt*k3, thist+dt))
yout[i+1] = y0 + dt/6.0*(k1 + 2*k2 + 2*k3 + k4)
return yout
@@ -957,8 +957,8 @@
rho = sigmaxy/(sigmax*sigmay)
z = Xmu**2/sigmax**2 + Ymu**2/sigmay**2 - 2*rho*Xmu*Ymu/(sigmax*sigmay)
- denom = 2*npy.pi*sigmax*sigmay*npy.sqrt(1-rho**2)
- return npy.exp( -z/(2*(1-rho**2))) / denom
+ denom = 2*np.pi*sigmax*sigmay*np.sqrt(1-rho**2)
+ return np.exp( -z/(2*(1-rho**2))) / denom
@@ -970,22 +970,22 @@
where x and y are the indices into Z and z are the values of Z at
those indices. x,y,z are 1D arrays
"""
- X,Y = npy.indices(Z.shape)
+ X,Y = np.indices(Z.shape)
return X[Cond], Y[Cond], Z[Cond]
def get_sparse_matrix(M,N,frac=0.1):
'return a MxN sparse matrix with frac elements randomly filled'
- data = npy.zeros((M,N))*0.
+ data = np.zeros((M,N))*0.
for i in range(int(M*N*frac)):
- x = npy.random.randint(0,M-1)
- y = npy.random.randint(0,N-1)
- data[x,y] = npy.random.rand()
+ x = np.random.randint(0,M-1)
+ y = np.random.randint(0,N-1)
+ data[x,y] = np.random.rand()
return data
def dist(x,y):
'return the distance between two points'
d = x-y
- return npy.sqrt(npy.dot(d,d))
+ return np.sqrt(np.dot(d,d))
def dist_point_to_segment(p, s0, s1):
"""
@@ -996,17 +996,17 @@
This algorithm from
http://softsurfer.com/Archive/algorithm_0102/algorithm_0102.htm#Distance%20to%20Ray%20or%20Segment
"""
- p = npy.asarray(p, npy.float_)
- s0 = npy.asarray(s0, npy.float_)
- s1 = npy.asarray(s1, npy.float_)
+ p = np.asarray(p, np.float_)
+ s0 = np.asarray(s0, np.float_)
+ s1 = np.asarray(s1, np.float_)
v = s1 - s0
w = p - s0
- c1 = npy.dot(w,v);
+ c1 = np.dot(w,v);
if ( c1 <= 0 ):
return dist(p, s0);
- c2 = npy.dot(v,v)
+ c2 = np.dot(v,v)
if ( c2 <= c1 ):
return dist(p, s1);
@@ -1049,11 +1049,11 @@
x=window*detrend(x)
else:
x = window(detrend(x))
- z = npy.fft.fft(x)
- a = 2.*npy.pi*1j
- phase = a * npy.random.rand(len(x))
- z = z*npy.exp(phase)
- return npy.fft.ifft(z).real
+ z = np.fft.fft(x)
+ a = 2.*np.pi*1j
+ phase = a * np.random.rand(len(x))
+ z = z*np.exp(phase)
+ return np.fft.ifft(z).real
def liaupunov(x, fprime):
@@ -1066,7 +1066,7 @@
caveat emptor.
It also seems that this function's name is badly misspelled.
"""
- return npy.mean(npy.log(npy.absolute(fprime(x))))
+ return np.mean(np.log(np.absolute(fprime(x))))
class FIFOBuffer:
"""
@@ -1088,10 +1088,10 @@
"""
def __init__(self, nmax):
'buffer up to nmax points'
- self._xa = npy.zeros((nmax,), npy.float_)
- self._ya = npy.zeros((nmax,), npy.float_)
- self._xs = npy.zeros((nmax,), npy.float_)
- self._ys = npy.zeros((nmax,), npy.float_)
+ self._xa = np.zeros((nmax,), np.float_)
+ self._ya = np.zeros((nmax,), np.float_)
+ self._xs = np.zeros((nmax,), np.float_)
+ self._ys = np.zeros((nmax,), np.float_)
self._ind = 0
self._nmax = nmax
self.dataLim = None
@@ -1149,9 +1149,9 @@
def movavg(x,n):
'compute the len(n) moving average of x'
- w = npy.empty((n,), dtype=npy.float_)
+ w = np.empty((n,), dtype=np.float_)
w[:] = 1.0/n
- return npy.convolve(x, w, mode='valid')
+ return np.convolve(x, w, mode='valid')
def save(fname, X, fmt='%.18e',delimiter=' '):
"""
@@ -1185,7 +1185,7 @@
raise ValueError('fname must be a string or file handle')
- X = npy.asarray(X)
+ X = np.asarray(X)
origShape = None
if X.ndim == 1:
origShape = X.shape
@@ -1278,7 +1278,7 @@
thisLen = len(row)
X.append(row)
- X = npy.array(X, npy.float_)
+ X = np.array(X, np.float_)
r,c = X.shape
if r==1 or c==1:
X.shape = max(r,c),
@@ -1313,10 +1313,10 @@
Icelandic Meteorological Office, March 2006 halldor at vedur.is)
"""
# Cast key variables as float.
- x=npy.asarray(x, npy.float_)
- y=npy.asarray(y, npy.float_)
+ x=np.asarray(x, np.float_)
+ y=np.asarray(y, np.float_)
- yp=npy.zeros(y.shape, npy.float_)
+ yp=np.zeros(y.shape, np.float_)
dx=x[1:] - x[:-1]
dy=y[1:] - y[:-1]
@@ -1371,18 +1371,18 @@
"""
# Cast key variables as float.
- x=npy.asarray(x, npy.float_)
- y=npy.asarray(y, npy.float_)
+ x=np.asarray(x, np.float_)
+ y=np.asarray(y, np.float_)
assert x.shape == y.shape
N=len(y)
if yp is None:
yp = slopes(x,y)
else:
- yp=npy.asarray(yp, npy.float_)
+ yp=np.asarray(yp, np.float_)
- xi=npy.asarray(xi, npy.float_)
- yi=npy.zeros(xi.shape, npy.float_)
+ xi=np.asarray(xi, np.float_)
+ yi=np.zeros(xi.shape, np.float_)
# calculate linear slopes
dx = x[1:] - x[:-1]
@@ -1391,7 +1391,7 @@
# find the segment each xi is in
# this line actually is the key to the efficiency of this implementation
- idx = npy.searchsorted(x[1:-1], xi)
+ idx = np.searchsorted(x[1:-1], xi)
# now we have generally: x[idx[j]] <= xi[j] <= x[idx[j]+1]
# except at the boundaries, where it may be that xi[j] < x[0] or xi[j] > x[-1]
@@ -1412,7 +1412,7 @@
# does more calculations than necessary but exploiting the power
# of numpy, this is far more efficient than coding a loop by hand
# in Python
- yi = yo + dy1dy2 * npy.choose(npy.array(npy.sign(dy1dy2), npy.int32)+1,
+ yi = yo + dy1dy2 * np.choose(np.array(np.sign(dy1dy2), np.int32)+1,
((2*xi-xidx-xidxp1)/((dy1-dy2)*(xidxp1-xidx)),
0.0,
1/(dy1+dy2),))
@@ -1426,7 +1426,7 @@
return value is a sequence of indices into points for the points
that are inside the polygon
"""
- res, = npy.nonzero(nxutils.points_inside_poly(points, verts))
+ res, = np.nonzero(nxutils.points_inside_poly(points, verts))
return res
def poly_below(xmin, xs, ys):
@@ -1439,13 +1439,13 @@
xv, yv = poly_below(0, x, y)
ax.fill(xv, yv)
"""
- xs = npy.asarray(xs)
- ys = npy.asarray(ys)
+ xs = np.asarray(xs)
+ ys = np.asarray(ys)
Nx = len(xs)
Ny = len(ys)
assert(Nx==Ny)
- x = xmin*npy.ones(2*Nx)
- y = npy.ones(2*Nx)
+ x = xmin*np.ones(2*Nx)
+ y = np.ones(2*Nx)
x[:Nx] = xs
y[:Nx] = ys
y[Nx:] = ys[::-1]
@@ -1462,13 +1462,13 @@
"""
Nx = len(x)
if not cbook.iterable(ylower):
- ylower = ylower*npy.ones(Nx)
+ ylower = ylower*np.ones(Nx)
if not cbook.iterable(yupper):
- yupper = yupper*npy.ones(Nx)
+ yupper = yupper*np.ones(Nx)
- x = npy.concatenate( (x, x[::-1]) )
- y = npy.concatenate( (yupper, ylower[::-1]) )
+ x = np.concatenate( (x, x[::-1]) )
+ y = np.concatenate( (yupper, ylower[::-1]) )
return x,y
### the following code was written and submitted by Fernando Perez
@@ -1532,8 +1532,8 @@
floating point exception handling with access to the underlying
hardware."""
- if type(x) is npy.ndarray:
- return exp(npy.clip(x,exp_safe_MIN,exp_safe_MAX))
+ if type(x) is np.ndarray:
+ return exp(np.clip(x,exp_safe_MIN,exp_safe_MAX))
else:
return math.exp(x)
@@ -1543,14 +1543,14 @@
Works like map(), but it returns an array. This is just a convenient
shorthand for numpy.array(map(...))
"""
- return npy.array(map(fn,*args))
+ return np.array(map(fn,*args))
#from numpy import zeros_like
def zeros_like(a):
"""Return an array of zeros of the shape and typecode of a."""
warnings.warn("Use numpy.zeros_like(a)", DeprecationWarning)
- return npy.zeros_like(a)
+ return np.zeros_like(a)
#from numpy import sum as sum_flat
def sum_flat(a):
@@ -1558,32 +1558,32 @@
It uses a.flat, and if a is not contiguous, a call to ravel(a) is made."""
warnings.warn("Use numpy.sum(a) or a.sum()", DeprecationWarning)
- return npy.sum(a)
+ return np.sum(a)
#from numpy import mean as mean_flat
def mean_flat(a):
"""Return the mean of all the elements of a, flattened out."""
warnings.warn("Use numpy.mean(a) or a.mean()", DeprecationWarning)
- return npy.mean(a)
+ return np.mean(a)
def rms_flat(a):
"""Return the root mean square of all the elements of a, flattened out."""
- return npy.sqrt(npy.mean(npy.absolute(a)**2))
+ return np.sqrt(np.mean(np.absolute(a)**2))
def l1norm(a):
"""Return the l1 norm of a, flattened out.
Implemented as a separate function (not a call to norm() for speed)."""
- return npy.sum(npy.absolute(a))
+ return np.sum(np.absolute(a))
def l2norm(a):
"""Return the l2 norm of a, flattened out.
Implemented as a separate function (not a call to norm() for speed)."""
- return npy.sqrt(npy.sum(npy.absolute(a)**2))
+ return np.sqrt(np.sum(np.absolute(a)**2))
def norm_flat(a,p=2):
"""norm(a,p=2) -> l-p norm of a.flat
@@ -1595,9 +1595,9 @@
# This function was being masked by a more general norm later in
# the file. We may want to simply delete it.
if p=='Infinity':
- return npy.amax(npy.absolute(a))
+ return np.amax(np.absolute(a))
else:
- return (npy.sum(npy.absolute(a)**p))**(1.0/p)
+ return (np.sum(np.absolute(a)**p))**(1.0/p)
def frange(xini,xfin=None,delta=None,**kw):
"""frange([start,] stop[, step, keywords]) -> array of floats
@@ -1657,7 +1657,7 @@
# round finds the nearest, so the endpoint can be up to
# delta/2 larger than xfin.
- return npy.arange(npts)*delta+xini
+ return np.arange(npts)*delta+xini
# end frange()
#import numpy.diag as diagonal_matrix
@@ -1665,7 +1665,7 @@
"""Return square diagonal matrix whose non-zero elements are given by the
input array."""
warnings.warn("Use numpy.diag(d)", DeprecationWarning)
- return npy.diag(diag)
+ return np.diag(diag)
def identity(n, rank=2, dtype='l', typecode=None):
"""identity(n,r) returns the identity matrix of shape (n,n,...,n) (rank r).
@@ -1686,7 +1686,7 @@
warnings.warn("Use dtype kwarg instead of typecode",
DeprecationWarning)
dtype = typecode
- iden = npy.zeros((n,)*rank, dtype)
+ iden = np.zeros((n,)*rank, dtype)
for i in range(n):
idx = (i,)*rank
iden[idx] = 1
@@ -1761,7 +1761,7 @@
The function MyFunction() is responsible for handling the dictionary of
keywords it will receive."""
warnings.warn("Use numpy.fromfunction()", DeprecationWarning)
- return npy.fromfunction(function, dimensions, **kwargs)
+ return np.fromfunction(function, dimensions, **kwargs)
### end fperez numutils code
@@ -1792,7 +1792,7 @@
For negative numbers is equivalent to ceil and for positive to floor.
"""
warnings.warn("Use numpy.fix()", DeprecationWarning)
- return npy.fix(x)
+ return np.fix(x)
def rem(x,y):
"""
@@ -1802,10 +1802,10 @@
This also differs from numpy.remainder, which uses floor instead of
fix.
"""
- x,y = npy.asarray(x), npy.asarray(y)
- if npy.any(y == 0):
+ x,y = np.asarray(x), np.asarray(y)
+ if np.any(y == 0):
return None
- return x - y * npy.fix(x/y)
+ return x - y * np.fix(x/y)
def norm(x,y=2):
@@ -1830,28 +1830,28 @@
NORM(V,-inf) = min(abs(V)).
"""
- x = npy.asarray(x)
+ x = np.asarray(x)
if x.ndim == 2:
if y==2:
- return npy.max(npy.linalg.svd(x)[1])
+ return np.max(np.linalg.svd(x)[1])
elif y==1:
- return npy.max(npy.sum(npy.absolute((x)), axis=0))
+ return np.max(np.sum(np.absolute((x)), axis=0))
elif y=='inf':
- return npy.max(npy.sum(npy.absolute((npy.transpose(x))), axis=0))
+ return np.max(np.sum(np.absolute((np.transpose(x))), axis=0))
elif y=='fro':
- xx = npy.dot(x.transpose(), x)
- return npy.sqrt(npy.sum(npy.diag(xx), axis=0))
+ xx = np.dot(x.transpose(), x)
+ return np.sqrt(np.sum(np.diag(xx), axis=0))
else:
raise ValueError('Second argument not permitted for matrices')
else:
- xa = npy.absolute(x)
+ xa = np.absolute(x)
if y == 'inf':
- return npy.max(xa)
+ return np.max(xa)
elif y == '-inf':
- return npy.min(xa)
+ return np.min(xa)
else:
- return npy.power(npy.sum(npy.power(xa,y)),1/float(y))
+ return np.power(np.sum(np.power(xa,y)),1/float(y))
def orth(A):
@@ -1865,8 +1865,8 @@
rank of A.
"""
- A = npy.asarray(A)
- U,S,V = npy.linalg.svd(A)
+ A = np.asarray(A)
+ U,S,V = np.linalg.svd(A)
m,n = A.shape
if m > 1:
@@ -1876,9 +1876,9 @@
else:
s = 0
- tol = max(m,n) * npy.max(s) * _eps_approx
- r = npy.sum(s > tol)
- Q = npy.take(U,range(r),1)
+ tol = max(m,n) * np.max(s) * _eps_approx
+ r = np.sum(s > tol)
+ Q = np.take(U,range(r),1)
return Q
@@ -1891,12 +1891,12 @@
Note that numerix.mlab.rank() is not equivalent to Matlab's rank.
This function is!
"""
- x = npy.asarray(x)
- s = npy.linalg.svd(x, compute_uv=False)
- maxabs = npy.max(npy.absolute(s))
+ x = np.asarray(x)
+ s = np.linalg.svd(x, compute_uv=False)
+ maxabs = np.max(np.absolute(s))
maxdim = max(x.shape)
tol = maxabs * maxdim * _eps_approx
- return npy.sum(s > tol)
+ return np.sum(s > tol)
def sqrtm(x):
"""
@@ -1904,8 +1904,9 @@
This means that s=sqrtm(x) implies dot(s,s) = x.
Note that s and x are matrices.
"""
- return mfuncC(npy.sqrt, x)
+ return mfuncC(np.sqrt, x)
+
def mfuncC(f, x):
"""
mfuncC(f, x) : matrix function with possibly complex eigenvalues.
@@ -1913,12 +1914,12 @@
This function is needed by sqrtm and allows further functions.
"""
- x = npy.asarray(x)
- (v,uT) = npy.linalg.eig(x)
- V = npy.diag(f(v+0j))
+ x = np.asarray(x)
+ (v,uT) = np.linalg.eig(x)
+ V = np.diag(f(v+0j))
# todo: warning: this is not exactly what matlab does
# MATLAB "B/A is roughly the same as B*inv(A)"
- y = npy.dot(uT, npy.dot(V, npy.linalg.inv(uT)))
+ y = np.dot(uT, np.dot(V, np.linalg.inv(uT)))
return approx_real(y)
def approx_real(x):
@@ -1927,9 +1928,9 @@
approx_real(x) : returns x.real if |x.imag| < |x.real| * _eps_approx.
This function is needed by sqrtm and allows further functions.
"""
- ai = npy.absolute(x.imag)
- ar = npy.absolute(x.real)
- if npy.max(ai) <= npy.max(ar) * _eps_approx:
+ ai = np.absolute(x.imag)
+ ar = np.absolute(x.real)
+ if np.max(ai) <= np.max(ar) * _eps_approx:
return x.real
else:
return x
@@ -1940,29 +1941,52 @@
def safe_isnan(x):
'isnan for arbitrary types'
- try: b = npy.isnan(x)
+ try: b = np.isnan(x)
except NotImplementedError: return False
else: return b
-
def safe_isinf(x):
'isnan for arbitrary types'
- try: b = npy.isinf(x)
+ try: b = np.isinf(x)
except NotImplementedError: return False
else: return b
-
def rec_append_field(rec, name, arr, dtype=None):
'return a new record array with field name populated with data from array arr'
- arr = npy.asarray(arr)
- if dtype is None:
- dtype = arr.dtype
- newdtype = npy.dtype(rec.dtype.descr + [(name, dtype)])
- newrec = npy.empty(rec.shape, dtype=newdtype)
+ warnings.warn("use rec_append_fields", DeprecationWarning)
+ return rec_append_fields(rec, name, arr, dtype)
+
+def rec_append_fields(rec, names, arrs, dtypes=None):
+ """
+ return a new record array with field names populated with data
+ from arrays in arrs. If appending a single field then names, arrs
+ and dtypes do not have to be lists. They can just be the values themselves.
+ """
+ if (not cbook.is_string_like(names) and cbook.iterable(names) \
+ and len(names) and cbook.is_string_like(names[0])):
+ if len(names) != len(arrs):
+ raise ValueError, "number of arrays do not match number of names"
+ else: # we have only 1 name and 1 array
+ names = [names]
+ arrs = [arrs]
+ arrs = map(np.asarray, arrs)
+ if dtypes is None:
+ dtypes = [a.dtype for a in arrs]
+ elif not cbook.iterable(dtypes):
+ dtypes = [dtypes]
+ if len(arrs) != len(dtypes):
+ if len(dtypes) == 1:
+ dtypes = dtypes * len(arrs)
+ else:
+ raise ValueError, "dtypes must be None, a single dtype or a list"
+
+ newdtype = np.dtype(rec.dtype.descr + zip(names, dtypes))
+ newrec = np.empty(rec.shape, dtype=newdtype)
for field in rec.dtype.fields:
newrec[field] = rec[field]
- newrec[name] = arr
- return newrec.view(npy.recarray)
+ for name, arr in zip(names, arrs):
+ newrec[name] = arr
+ return newrec.view(np.recarray)
def rec_drop_fields(rec, names):
@@ -1971,88 +1995,17 @@
names = set(names)
Nr = len(rec)
- newdtype = npy.dtype([(name, rec.dtype[name]) for name in rec.dtype.names
+ newdtype = np.dtype([(name, rec.dtype[name]) for name in rec.dtype.names
if name not in names])
- newrec = npy.empty(Nr, dtype=newdtype)
+ newrec = np.empty(Nr, dtype=newdtype)
for field in newdtype.names:
newrec[field] = rec[field]
- return newrec.view(npy.recarray)
+ return newrec.view(np.recarray)
-def rec_join(key, r1, r2):
- """
- join record arrays r1 and r2 on key; key is a tuple of field
- names. if r1 and r2 have equal values on all the keys in the key
- tuple, then their fields will be merged into a new record array
- containing the intersection of the fields of r1 and r2
- """
- for name in key:
- if name not in r1.dtype.names:
- raise ValueError('r1 does not have key field %s'%name)
- if name not in r2.dtype.names:
- raise ValueError('r2 does not have key field %s'%name)
-
- def makekey(row):
- return tuple([row[name] for name in key])
-
-
- names = list(r1.dtype.names) + [name for name in r2.dtype.names if name not in set(r1.dtype.names)]
-
-
-
- r1d = dict([(makekey(row),i) for i,row in enumerate(r1)])
- r2d = dict([(makekey(row),i) for i,row in enumerate(r2)])
-
- r1keys = set(r1d.keys())
- r2keys = set(r2d.keys())
-
- keys = r1keys & r2keys
-
- r1ind = [r1d[k] for k in keys]
- r2ind = [r2d[k] for k in keys]
-
-
- r1 = r1[r1ind]
- r2 = r2[r2ind]
-
- r2 = rec_drop_fields(r2, r1.dtype.names)
-
-
- def key_desc(name):
- 'if name is a string key, use the larger size of r1 or r2 before merging'
- dt1 = r1.dtype[name]
- if dt1.type != npy.string_:
- return (name, dt1.descr[0][1])
-
- dt2 = r1.dtype[name]
- assert dt2==dt1
- if dt1.num>dt2.num:
- return (name, dt1.descr[0][1])
- else:
- return (name, dt2.descr[0][1])
-
-
-
- keydesc = [key_desc(name) for name in key]
-
- newdtype = npy.dtype(keydesc +
- [desc for desc in r1.dtype.descr if desc[0] not in key ] +
- [desc for desc in r2.dtype.descr if desc[0] not in key ] )
-
-
- newrec = npy.empty(len(r1), dtype=newdtype)
- for field in r1.dtype.names:
- newrec[field] = r1[field]
-
- for field in r2.dtype.names:
- newrec[field] = r2[field]
-
- return newrec.view(npy.recarray)
-
-
def rec_groupby(r, groupby, stats):
"""
r is a numpy record array
@@ -2063,7 +2016,7 @@
stats is a sequence of (attr, func, outname) which will call x =
func(attr) and assign x to the record array output with attribute
outname.
- Eg, stats = ( ('sales', len, 'numsales'), ('sales', npy.mean, 'avgsale') )
+ Eg, stats = ( ('sales', len, 'numsales'), ('sales', np.mean, 'avgsale') )
return record array has dtype names for each attribute name in in
the the 'groupby' argument, with the associated group values, and
@@ -2095,7 +2048,7 @@
attrs, funcs, outnames = zip(*stats)
names = list(groupby)
names.extend(outnames)
- return npy.rec.fromrecords(rows, names=names)
+ return np.rec.fromrecords(rows, names=names)
@@ -2114,16 +2067,23 @@
for attr, func, outname in summaryfuncs:
names.append(outname)
- arrays.append(npy.asarray(func(r[attr])))
+ arrays.append(np.asarray(func(r[attr])))
- return npy.rec.fromarrays(arrays, names=names)
+ return np.rec.fromarrays(arrays, names=names)
-def rec_join(key, r1, r2):
+
+def rec_join(key, r1, r2, jointype='inner', defaults=None):
"""
join record arrays r1 and r2 on key; key is a tuple of field
names. if r1 and r2 have equal values on all the keys in the key
tuple, then their fields will be merged into a new record array
containing the intersection of the fields of r1 and r2
+
+ The jointype keyword can be 'inner', 'outer', 'leftouter'.
+ To do a rightouter join just reverse r1 and r2.
+
+ The defaults keyword is a dictionary filled with
+ {column_name:default_value} pairs.
"""
for name in key:
@@ -2141,24 +2101,29 @@
r1keys = set(r1d.keys())
r2keys = set(r2d.keys())
- keys = r1keys & r2keys
+ common_keys = r1keys & r2keys
- r1ind = npy.array([r1d[k] for k in keys])
- r2ind = npy.array([r2d[k] for k in keys])
+ r1ind = np.array([r1d[k] for k in common_keys])
+ r2ind = np.array([r2d[k] for k in common_keys])
- # Make sure that the output rows have the same relative order as r1
- sortind = r1ind.argsort()
+ common_len = len(common_keys)
+ left_len = right_len = 0
+ if jointype == "outer" or jointype == "leftouter":
+ left_keys = r1keys.difference(r2keys)
+ left_ind = np.array([r1d[k] for k in left_keys])
+ left_len = len(left_ind)
+ if jointype == "outer":
+ right_keys = r2keys.difference(r1keys)
+ right_ind = np.array([r2d[k] for k in right_keys])
+ right_len = len(right_ind)
- r1 = r1[r1ind[sortind]]
- r2 = r2[r2ind[sortind]]
-
r2 = rec_drop_fields(r2, r1.dtype.names)
def key_desc(name):
'if name is a string key, use the larger size of r1 or r2 before merging'
dt1 = r1.dtype[name]
- if dt1.type != npy.string_:
+ if dt1.type != np.string_:
return (name, dt1.descr[0][1])
dt2 = r1.dtype[name]
@@ -2172,25 +2137,44 @@
keydesc = [key_desc(name) for name in key]
- newdtype = npy.dtype(keydesc +
+ newdtype = np.dtype(keydesc +
[desc for desc in r1.dtype.descr if desc[0] not in key ] +
[desc for desc in r2.dtype.descr if desc[0] not in key ] )
- newrec = npy.empty(len(r1), dtype=newdtype)
+ newrec = np.empty(common_len + left_len + right_len, dtype=newdtype)
+
+ if jointype != 'inner' and defaults is not None: # fill in the defaults enmasse
+ newrec_fields = newrec.dtype.fields.keys()
+ for k, v in defaults.items():
+ if k in newrec_fields:
+ newrec[k] = v
+
for field in r1.dtype.names:
- newrec[field] = r1[field]
+ newrec[field][:common_len] = r1[field][r1ind]
+ if jointype == "outer" or jointype == "leftouter":
+ newrec[field][common_len:(common_len+left_len)] = r1[field][left_ind]
for field in r2.dtype.names:
- newrec[field] = r2[field]
+ newrec[field][:common_len] = r2[field][r2ind]
+ if jointype == "outer":
+ newrec[field][-right_len:] = r2[field][right_ind[right_ind.argsort()]]
- return newrec.view(npy.recarray)
+ # sort newrec using the same order as r1
+ sort_indices = r1ind.copy()
+ if jointype == "outer" or jointype == "leftouter":
+ sort_indices = np.append(sort_indices, left_ind)
+ newrec[:(common_len+left_len)] = newrec[sort_indices.argsort()]
+
+ return newrec.view(np.recarray)
+
+
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
@@ -2211,18 +2195,29 @@
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
+ 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
@@ -2270,14 +2265,35 @@
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
+
+
+ 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
d = dateparser(x)
@@ -2285,16 +2301,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 = {mybool:myint,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
@@ -2310,7 +2326,7 @@
converters = None
for i, row in enumerate(reader):
if i==0:
- converters = [int]*len(row)
+ converters = [mybool]*len(row)
if checkrows and i>checkrows:
break
#print i, len(names), len(row)
@@ -2320,17 +2336,25 @@
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)
+ else:
+ # how should we handle custom converters and defaults?
+ func = with_default_value(func, None)
converters[j] = func
return converters
# Get header and remove invalid characters
needheader = names is None
if needheader:
- headers = reader.next()
+ for row in reader:
+ if len(row) and row[0].startswith(comments):
+ continue
+ headers = row
+ break
+
# remove these chars
delete = set("""~!@#$%^&*()-=+~\|]}[{';: /?.>,<""")
delete.add('"')
@@ -2346,7 +2370,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
@@ -2366,15 +2390,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 np.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 = np.rec.fromrecords(rows, names=names)
return r
@@ -2386,6 +2419,8 @@
def toval(self, x):
return str(x)
+ def fromstr(self, s):
+ return s
class FormatString(FormatObj):
def tostr(self, x):
@@ -2404,6 +2439,7 @@
if x is None: return 'None'
return self.fmt%self.toval(x)
+
class FormatFloat(FormatFormatStr):
def __init__(self, precision=4, scale=1.):
FormatFormatStr.__init__(self, '%%1.%df'%precision)
@@ -2415,10 +2451,24 @@
x = x * self.scale
return x
+ def fromstr(self, s):
+ return float(s)/self.scale
+
+
class FormatInt(FormatObj):
def toval(self, x):
return x
+ 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.)
@@ -2427,6 +2477,7 @@
def __init__(self, precision=4):
FormatFloat.__init__(self, precision, scale=1e-3)
+
class FormatMillions(FormatFloat):
def __init__(self, precision=4):
FormatFloat.__init__(self, precision, scale=1e-6)
@@ -2440,19 +2491,30 @@
if x is None: return 'None'
return x.strftime(self.fmt)
+ def fromstr(self, x):
+ import dateutil.parser
+ return dateutil.parser.parse(x).date()
+
class FormatDatetime(FormatDate):
def __init__(self, fmt='%Y-%m-%d %H:%M:%S'):
FormatDate.__init__(self, fmt)
+ def fromstr(self, x):
+ import dateutil.parser
+ return dateutil.parser.parse(x)
+
+
+
defaultformatd = {
- npy.int16 : FormatInt(),
- npy.int32 : FormatInt(),
- npy.int64 : FormatInt(),
- npy.float32 : FormatFloat(),
- npy.float64 : FormatFloat(),
- npy.object_ : FormatObj(),
- npy.string_ : FormatString(),
+ np.bool_ : FormatBool(),
+ np.int16 : FormatInt(),
+ np.int32 : FormatInt(),
+ np.int64 : FormatInt(),
+ np.float32 : FormatFloat(),
+ np.float64 : FormatFloat(),
+ np.object_ : FormatObj(),
+ np.string_ : FormatString(),
}
def get_formatd(r, formatd=None):
@@ -2510,20 +2572,20 @@
def get_justify(colname, column, precision):
ntype = type(column[0])
- if ntype==npy.str or ntype==npy.str_ or ntype==npy.string0 or ntype==npy.string_:
+ if ntype==np.str or ntype==np.str_ or ntype==np.string0 or ntype==np.string_:
length = max(len(colname),column.itemsize)
return 0, length+padding, "%s" # left justify
- if ntype==npy.int or ntype==npy.int16 or ntype==npy.int32 or ntype==npy.int64 or ntype==npy.int8 or ntype==npy.int_:
- length = max(len(colname),npy.max(map(len,map(str,column))))
+ if ntype==np.int or ntype==np.int16 or ntype==np.int32 or ntype==np.int64 or ntype==np.int8 or ntype==np.int_:
+ length = max(len(colname),np.max(map(len,map(str,column))))
return 1, length+padding, "%d" # right justify
- if ntype==npy.float or ntype==npy.float32 or ntype==npy.float64 or ntype==npy.float96 or ntype==npy.float_:
+ if ntype==np.float or ntype==np.float32 or ntype==np.float64 or ntype==np.float96 or ntype==np.float_:
fmt = "%." + str(precision) + "f"
- length = max(len(colname),npy.max(map(len,map(lambda x:fmt%x,column))))
+ length = max(len(colname),np.max(map(len,map(lambda x:fmt%x,column))))
return 1, length+padding, fmt # right justify
- return 0, max(len(colname),npy.max(map(len,map(str,column))))+padding, "%s"
+ return 0, max(len(colname),np.max(map(len,map(str,column))))+padding, "%s"
if header is None:
header = r.dtype.names
@@ -2566,29 +2628,61 @@
text = os.linesep.join(textl)
return text
-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()
-
-
-
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-05-23 19:06:07
|
Revision: 5238
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5238&view=rev
Author: jdh2358
Date: 2008-05-23 12:05:51 -0700 (Fri, 23 May 2008)
Log Message:
-----------
experimenting with including api docs
Added Paths:
-----------
trunk/matplotlib/doc/users_guide/api.txt
Added: trunk/matplotlib/doc/users_guide/api.txt
===================================================================
--- trunk/matplotlib/doc/users_guide/api.txt (rev 0)
+++ trunk/matplotlib/doc/users_guide/api.txt 2008-05-23 19:05:51 UTC (rev 5238)
@@ -0,0 +1,12 @@
+##############
+Matplotlib API
+##############
+
+.. _contents:
+
+.. toctree::
+ :maxdepth: 3
+
+ api_introduction
+ api_artists
+
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-05-23 19:02:31
|
Revision: 5237
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5237&view=rev
Author: jdh2358
Date: 2008-05-23 12:02:25 -0700 (Fri, 23 May 2008)
Log Message:
-----------
experimenting with including api docs
Added Paths:
-----------
trunk/matplotlib/doc/users_guide/api_artists.txt
trunk/matplotlib/doc/users_guide/api_introduction.txt
Added: trunk/matplotlib/doc/users_guide/api_artists.txt
===================================================================
--- trunk/matplotlib/doc/users_guide/api_artists.txt (rev 0)
+++ trunk/matplotlib/doc/users_guide/api_artists.txt 2008-05-23 19:02:25 UTC (rev 5237)
@@ -0,0 +1,30 @@
+******************
+matplotlib artists
+******************
+
+:mod:`matplotlib.artist`
+=============================
+
+.. automodule:: matplotlib.artist
+ :members:
+
+
+:mod:`matplotlib.lines`
+=============================
+
+.. automodule:: matplotlib.lines
+ :members:
+
+
+:mod:`matplotlib.patches`
+=============================
+
+.. automodule:: matplotlib.patches
+ :members:
+
+:mod:`matplotlib.text`
+=============================
+
+.. automodule:: matplotlib.text
+ :members:
+
Added: trunk/matplotlib/doc/users_guide/api_introduction.txt
===================================================================
--- trunk/matplotlib/doc/users_guide/api_introduction.txt (rev 0)
+++ trunk/matplotlib/doc/users_guide/api_introduction.txt 2008-05-23 19:02:25 UTC (rev 5237)
@@ -0,0 +1,5 @@
+************
+Introduction
+************
+
+blah
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|