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: <ef...@us...> - 2008-11-17 23:08:23
|
Revision: 6412
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6412&view=rev
Author: efiring
Date: 2008-11-17 23:08:20 +0000 (Mon, 17 Nov 2008)
Log Message:
-----------
Use autoscale_view for contour plot autoscaling
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/contour.py
Modified: trunk/matplotlib/lib/matplotlib/contour.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/contour.py 2008-11-17 19:34:28 UTC (rev 6411)
+++ trunk/matplotlib/lib/matplotlib/contour.py 2008-11-17 23:08:20 UTC (rev 6412)
@@ -625,8 +625,7 @@
y0 = ma.minimum(y)
y1 = ma.maximum(y)
self.ax.update_datalim([(x0,y0), (x1,y1)])
- self.ax.set_xlim((x0, x1))
- self.ax.set_ylim((y0, y1))
+ self.ax.autoscale_view()
def changed(self):
tcolors = [ (tuple(rgba),) for rgba in
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-11-17 19:34:30
|
Revision: 6411
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6411&view=rev
Author: mdboom
Date: 2008-11-17 19:34:28 +0000 (Mon, 17 Nov 2008)
Log Message:
-----------
Fixed all Gtk memory leaks exercised by D2Hitman's recent thread.
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/backends/backend_gtk.py
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_gtk.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_gtk.py 2008-11-17 15:20:06 UTC (rev 6410)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_gtk.py 2008-11-17 19:34:28 UTC (rev 6411)
@@ -538,16 +538,6 @@
NavigationToolbar2.__init__(self, canvas)
self._idle_draw_id = 0
- self.connect("destroy", self.destroy)
-
- def destroy(self, *args):
- gtk.Toolbar.destroy(self)
- self.fileselect.destroy()
- self.tooltips.destroy()
- self.canvas.destroy()
- if self._idle_draw_id != 0:
- gobject.remove_source(self._idle_draw_id)
-
def set_message(self, s):
if self._idle_draw_id == 0:
self.message.set_label(s)
@@ -635,11 +625,6 @@
self.append_widget(self.message, None, None)
self.message.show()
- self.fileselect = FileSelection(title='Save the figure',
- parent=self.win,)
-
-
-
def _init_toolbar2_4(self):
basedir = os.path.join(matplotlib.rcParams['datapath'],'images')
self.tooltips = gtk.Tooltips()
@@ -670,15 +655,19 @@
self.show_all()
- self.fileselect = FileChooserDialog(
- title='Save the figure',
- parent=self.win,
- filetypes=self.canvas.get_supported_filetypes(),
- default_filetype=self.canvas.get_default_filetype())
+ def get_filechooser(self):
+ if gtk.pygtk_version >= (2,4,0):
+ return FileChooserDialog(
+ title='Save the figure',
+ parent=self.win,
+ filetypes=self.canvas.get_supported_filetypes(),
+ default_filetype=self.canvas.get_default_filetype())
+ else:
+ return FileSelection(title='Save the figure',
+ parent=self.win,)
-
def save_figure(self, button):
- fname, format = self.fileselect.get_filename_from_user()
+ fname, format = self.get_filechooser().get_filename_from_user()
if fname:
try:
self.canvas.print_figure(fname, format=format)
@@ -781,11 +770,6 @@
self.show_all()
self.update()
- def destroy(*args):
- self.fileselect.destroy()
- del self.fileselect
- self.connect("destroy", destroy)
-
def _create_toolitems_2_4(self):
# use the GTK+ 2.4 GtkToolbar API
iconSize = gtk.ICON_SIZE_SMALL_TOOLBAR
@@ -970,9 +954,19 @@
self.canvas.draw()
return True
+ def get_filechooser(self):
+ if gtk.pygtk_version >= (2,4,0):
+ return FileChooserDialog(
+ title='Save the figure',
+ parent=self.win,
+ filetypes=self.canvas.get_supported_filetypes(),
+ default_filetype=self.canvas.get_default_filetype())
+ else:
+ return FileSelection(title='Save the figure',
+ parent=self.win)
def save_figure(self, button):
- fname, format = self.fileselect.get_filename_from_user()
+ fname, format = self.get_filechooser().get_filename_from_user()
if fname:
try:
self.canvas.print_figure(fname, format=format)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-11-17 15:20:16
|
Revision: 6410
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6410&view=rev
Author: mdboom
Date: 2008-11-17 15:20:06 +0000 (Mon, 17 Nov 2008)
Log Message:
-----------
Further memory leak fixes for Gtk
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/backends/backend_gtk.py
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_gtk.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_gtk.py 2008-11-17 14:49:15 UTC (rev 6409)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_gtk.py 2008-11-17 15:20:06 UTC (rev 6410)
@@ -156,7 +156,7 @@
FigureCanvasBase.__init__(self, figure)
gtk.DrawingArea.__init__(self)
- self._idleID = 0
+ self._idle_draw_id = 0
self._need_redraw = True
self._pixmap_width = -1
self._pixmap_height = -1
@@ -177,11 +177,13 @@
self.set_flags(gtk.CAN_FOCUS)
self._renderer_init()
- self._idle_id = gobject.idle_add(self.idle_event)
+ self._idle_event_id = gobject.idle_add(self.idle_event)
def destroy(self):
- gtk.DrawingArea.destroy(self)
- gobject.source_remove(self._idle_id)
+ #gtk.DrawingArea.destroy(self)
+ gobject.source_remove(self._idle_event_id)
+ if self._idle_draw_id != 0:
+ gobject.source_remove(self._idle_draw_id)
def scroll_event(self, widget, event):
if _debug: print 'FigureCanvasGTK.%s' % fn_name()
@@ -280,10 +282,10 @@
def draw_idle(self):
def idle_draw(*args):
self.draw()
- self._idleID = 0
+ self._idle_draw_id = 0
return False
- if self._idleID == 0:
- self._idleID = gobject.idle_add(idle_draw)
+ if self._idle_draw_id == 0:
+ self._idle_draw_id = gobject.idle_add(idle_draw)
def _renderer_init(self):
@@ -534,7 +536,7 @@
self.win = window
gtk.Toolbar.__init__(self)
NavigationToolbar2.__init__(self, canvas)
- self._idleId = 0
+ self._idle_draw_id = 0
self.connect("destroy", self.destroy)
@@ -543,9 +545,11 @@
self.fileselect.destroy()
self.tooltips.destroy()
self.canvas.destroy()
+ if self._idle_draw_id != 0:
+ gobject.remove_source(self._idle_draw_id)
def set_message(self, s):
- if self._idleId == 0:
+ if self._idle_draw_id == 0:
self.message.set_label(s)
def set_cursor(self, cursor):
@@ -587,16 +591,15 @@
axrect = l,b,w,h
self._imageBack = axrect, drawable.get_image(*axrect)
drawable.draw_rectangle(gc, False, *rect)
- self._idleId = 0
+ self._idle_draw_id = 0
else:
def idle_draw(*args):
-
drawable.draw_image(gc, imageBack, 0, 0, *lastrect)
drawable.draw_rectangle(gc, False, *rect)
- self._idleId = 0
+ self._idle_draw_id = 0
return False
- if self._idleId == 0:
- self._idleId = gobject.idle_add(idle_draw)
+ if self._idle_draw_id == 0:
+ self._idle_draw_id = gobject.idle_add(idle_draw)
def _init_toolbar(self):
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-11-17 14:49:25
|
Revision: 6409
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6409&view=rev
Author: mdboom
Date: 2008-11-17 14:49:15 +0000 (Mon, 17 Nov 2008)
Log Message:
-----------
Reduce memory leakage in Gtk+-based backends. Still far from perfect.
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/backends/backend_gtk.py
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_gtk.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_gtk.py 2008-11-17 14:39:49 UTC (rev 6408)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_gtk.py 2008-11-17 14:49:15 UTC (rev 6409)
@@ -162,7 +162,7 @@
self._pixmap_height = -1
self._lastCursor = None
- self.connect('scroll_event', self.scroll_event)
+ self.connect('scroll_event', self.scroll_event)
self.connect('button_press_event', self.button_press_event)
self.connect('button_release_event', self.button_release_event)
self.connect('configure_event', self.configure_event)
@@ -177,8 +177,12 @@
self.set_flags(gtk.CAN_FOCUS)
self._renderer_init()
- gobject.idle_add(self.idle_event)
+ self._idle_id = gobject.idle_add(self.idle_event)
+ def destroy(self):
+ gtk.DrawingArea.destroy(self)
+ gobject.source_remove(self._idle_id)
+
def scroll_event(self, widget, event):
if _debug: print 'FigureCanvasGTK.%s' % fn_name()
x = event.x
@@ -466,14 +470,17 @@
def destroy(self, *args):
if _debug: print 'FigureManagerGTK.%s' % fn_name()
+ self.vbox.destroy()
self.window.destroy()
+ self.canvas.destroy()
+ self.toolbar.destroy()
+ self.__dict__.clear()
if Gcf.get_num_fig_managers()==0 and \
not matplotlib.is_interactive() and \
gtk.main_level() >= 1:
gtk.main_quit()
-
def show(self):
# show the figure window
self.window.show()
@@ -529,10 +536,14 @@
NavigationToolbar2.__init__(self, canvas)
self._idleId = 0
- def destroy(*args):
- self.fileselect.destroy()
- self.connect("destroy", destroy)
+ self.connect("destroy", self.destroy)
+ def destroy(self, *args):
+ gtk.Toolbar.destroy(self)
+ self.fileselect.destroy()
+ self.tooltips.destroy()
+ self.canvas.destroy()
+
def set_message(self, s):
if self._idleId == 0:
self.message.set_label(s)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-11-17 14:39:53
|
Revision: 6408
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6408&view=rev
Author: mdboom
Date: 2008-11-17 14:39:49 +0000 (Mon, 17 Nov 2008)
Log Message:
-----------
Turn off mixed-mode rendering when svg.image_noscale is True.
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/backends/backend_svg.py
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_svg.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_svg.py 2008-11-17 14:38:27 UTC (rev 6407)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_svg.py 2008-11-17 14:39:49 UTC (rev 6408)
@@ -269,9 +269,6 @@
transstr = ''
if rcParams['svg.image_noscale']:
trans = list(im.get_matrix())
- if im.get_interpolation() != 0:
- trans[4] += trans[0]
- trans[5] += trans[3]
trans[5] = -trans[5]
transstr = 'transform="matrix(%f %f %f %f %f %f)" '%tuple(trans)
assert trans[1] == 0
@@ -600,8 +597,11 @@
width, height = self.figure.get_size_inches()
w, h = width*72, height*72
- renderer = MixedModeRenderer(
- width, height, 72.0, RendererSVG(w, h, svgwriter, filename))
+ if rcParams['svg.image_noscale']:
+ renderer = RendererSVG(w, h, svgwriter, filename)
+ else:
+ renderer = MixedModeRenderer(
+ width, height, 72.0, RendererSVG(w, h, svgwriter, filename))
self.figure.draw(renderer)
renderer.finalize()
if fh_to_close is not None:
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-11-17 14:38:33
|
Revision: 6407
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6407&view=rev
Author: mdboom
Date: 2008-11-17 14:38:27 +0000 (Mon, 17 Nov 2008)
Log Message:
-----------
Fix minor bug in findfont -- None input should return default font.
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/font_manager.py
Modified: trunk/matplotlib/lib/matplotlib/font_manager.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/font_manager.py 2008-11-17 14:37:14 UTC (rev 6406)
+++ trunk/matplotlib/lib/matplotlib/font_manager.py 2008-11-17 14:38:27 UTC (rev 6407)
@@ -1180,6 +1180,8 @@
for a description of the font finding algorithm.
"""
debug = False
+ if prop is None:
+ return self.defaultFont
if is_string_like(prop):
prop = FontProperties(prop)
fname = prop.get_file()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-11-17 14:37:26
|
Revision: 6406
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6406&view=rev
Author: mdboom
Date: 2008-11-17 14:37:14 +0000 (Mon, 17 Nov 2008)
Log Message:
-----------
First pass formatting dates.py documentation.
Modified Paths:
--------------
trunk/matplotlib/doc/api/index.rst
trunk/matplotlib/lib/matplotlib/dates.py
Added Paths:
-----------
trunk/matplotlib/doc/api/dates_api.rst
Added: trunk/matplotlib/doc/api/dates_api.rst
===================================================================
--- trunk/matplotlib/doc/api/dates_api.rst (rev 0)
+++ trunk/matplotlib/doc/api/dates_api.rst 2008-11-17 14:37:14 UTC (rev 6406)
@@ -0,0 +1,14 @@
+****************
+matplotlib dates
+****************
+
+.. inheritance-diagram:: matplotlib.dates
+ :parts: 1
+
+:mod:`matplotlib.dates`
+=======================
+
+.. automodule:: matplotlib.dates
+ :members:
+ :undoc-members:
+ :show-inheritance:
Modified: trunk/matplotlib/doc/api/index.rst
===================================================================
--- trunk/matplotlib/doc/api/index.rst 2008-11-14 22:25:28 UTC (rev 6405)
+++ trunk/matplotlib/doc/api/index.rst 2008-11-17 14:37:14 UTC (rev 6406)
@@ -21,6 +21,7 @@
collections_api.rst
colorbar_api.rst
colors_api.rst
+ dates_api.rst
figure_api.rst
font_manager_api.rst
nxutils_api.rst
Modified: trunk/matplotlib/lib/matplotlib/dates.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/dates.py 2008-11-14 22:25:28 UTC (rev 6405)
+++ trunk/matplotlib/lib/matplotlib/dates.py 2008-11-17 14:37:14 UTC (rev 6406)
@@ -1,35 +1,37 @@
#!/usr/bin/env python
"""
-
Matplotlib provides sophisticated date plotting capabilities, standing
-on the shoulders of python datetime, the add-on modules pytz and
-dateutils. datetime objects are converted to floating point numbers
-which represent the number of days since 0001-01-01 UTC. The helper
-functions date2num, num2date and drange are used to facilitate easy
-conversion to and from datetime and numeric ranges.
+on the shoulders of python :mod:`datetime`, the add-on modules
+:mod:`pytz` and :mod:`dateutils`. :class:`datetime` objects are
+converted to floating point numbers which represent the number of days
+since 0001-01-01 UTC. The helper functions :func:`date2num`,
+:func:`num2date` and :func:`drange` are used to facilitate easy
+conversion to and from :mod:`datetime` and numeric ranges.
A wide range of specific and general purpose date tick locators and
formatters are provided in this module. See
-:module:`matplotlib.ticker` for general information on tick locators
+:mod:`matplotlib.ticker` for general information on tick locators
and formatters. These are described below.
All the matplotlib date converters, tickers and formatters are
timezone aware, and the default timezone is given by the timezone
-parameter in your matplotlibrc file. If you leave out a tz timezone
-instance, the default from your rc file will be assumed. If you want
-to use a custom time zone, pass a pytz.timezone instance
-with the tz keyword argument to num2date, plot_date, and any custom
-date tickers or locators you create. See http://pytz.sourceforge.net
-for information on pytz and timezone handling.
+parameter in your :file:`matplotlibrc` file. If you leave out a
+:class:`tz` timezone instance, the default from your rc file will be
+assumed. If you want to use a custom time zone, pass a
+:class:`pytz.timezone` instance with the tz keyword argument to
+:func:`num2date`, :func:`plot_date`, and any custom date tickers or
+locators you create. See `pytz <http://pytz.sourceforge.net>`_ for
+information on :mod:`pytz` and timezone handling.
-The dateutil module (http://labix.org/python-dateutil)
-provides additional code to handle
-date ticking, making it easy to place ticks on any kinds of dates -
-see examples below.
+The `dateutil module <http://labix.org/python-dateutil>`_ provides
+additional code to handle date ticking, making it easy to place ticks
+on any kinds of dates. See examples below.
-Date tickers -
+Date tickers
+------------
- Most of the date tickers can locate single or multiple values. Eg
+Most of the date tickers can locate single or multiple values. For
+example::
# tick on mondays every week
loc = WeekdayLocator(byweekday=MO, tz=tz)
@@ -37,44 +39,48 @@
# tick on mondays and saturdays
loc = WeekdayLocator(byweekday=(MO, SA))
- In addition, most of the constructors take an interval argument.
+In addition, most of the constructors take an interval argument::
# tick on mondays every second week
loc = WeekdayLocator(byweekday=MO, interval=2)
- The rrule locator allows completely general date ticking
+The rrule locator allows completely general date ticking::
# tick every 5th easter
rule = rrulewrapper(YEARLY, byeaster=1, interval=5)
loc = RRuleLocator(rule)
- Here are all the date tickers
+Here are all the date tickers:
- * MinuteLocator - locate minutes
+ * :class:`MinuteLocator`: locate minutes
- * HourLocator - locate hours
+ * :class:`HourLocator`: locate hours
- * DayLocator - locate specifed days of the month
+ * :class:`DayLocator`: locate specifed days of the month
- * WeekdayLocator - Locate days of the week, eg MO, TU
+ * :class:`WeekdayLocator`: Locate days of the week, eg MO, TU
- * MonthLocator - locate months, eg 7 for july
+ * :class:`MonthLocator`: locate months, eg 7 for july
- * YearLocator - locate years that are multiples of base
+ * :class:`YearLocator`: locate years that are multiples of base
- * RRuleLocator - locate using a matplotlib.dates.rrulewrapper.
- The rrulewrapper is a simple wrapper around a dateutils.rrule
- https://moin.conectiva.com.br/DateUtil which allow almost
- arbitrary date tick specifications. See
- examples/date_demo_rrule.py
+ * :class:`RRuleLocator`: locate using a
+ :class:`matplotlib.dates.rrulewrapper`. The
+ :class:`rrulewrapper` is a simple wrapper around a
+ :class:`dateutils.rrule` (`dateutil
+ <https://moin.conectiva.com.br/DateUtil>`_) which allow almost
+ arbitrary date tick specifications. See `rrule example
+ <../examples/pylab_examples/date_demo_rrule.html>`_.
-
Date formatters
+---------------
- DateFormatter - use strftime format strings
+Here all all the date formatters:
- DateIndexFormatter - date plots with implicit x indexing.
+ * :class:`DateFormatter`: use :func:`strftime` format strings
+ * :class:`IndexDateFormatter`: date plots with implicit *x*
+ indexing.
"""
import re, time, math, datetime
@@ -137,9 +143,9 @@
def _to_ordinalf(dt):
"""
- convert datetime to the Gregorian date as UTC float days,
- preserving hours, minutes, seconds and microseconds. return value
- is a float
+ Convert :mod:`datetime` to the Gregorian date as UTC float days,
+ preserving hours, minutes, seconds and microseconds. Return value
+ is a :func:`float`.
"""
if hasattr(dt, 'tzinfo') and dt.tzinfo is not None:
@@ -156,8 +162,8 @@
def _from_ordinalf(x, tz=None):
"""
- convert Gregorian float of the date, preserving hours, minutes,
- seconds and microseconds. return value is a datetime
+ Convert Gregorian float of the date, preserving hours, minutes,
+ seconds and microseconds. Return value is a :class:`datetime`.
"""
if tz is None: tz = _get_rc_timezone()
ix = int(x)
@@ -181,7 +187,7 @@
"""
Use this class to parse date strings to matplotlib datenums when
you know the date format string of the date you are parsing. See
- examples/load_demo.py
+ :file:`examples/load_demo.py`.
"""
def __init__(self, fmt):
""" fmt: any valid strptime format is supported """
@@ -195,8 +201,9 @@
def datestr2num(d):
"""
- Convert a date string to a datenum using dateutil.parser.parse
- d can be a single string or a sequence of strings
+ Convert a date string to a datenum using
+ :func:`dateutil.parser.parse`. *d* can be a single string or a
+ sequence of strings.
"""
if cbook.is_string_like(d):
dt = dateutil.parser.parse(d)
@@ -207,35 +214,36 @@
def date2num(d):
"""
- d is either a datetime instance or a sequence of datetimes
+ *d* is either a :class:`datetime` instance or a sequence of datetimes.
- return value is a floating point number (or sequence of floats)
+ Return value is a floating point number (or sequence of floats)
which gives number of days (fraction part represents hours,
- minutes, seconds) since 0001-01-01 00:00:00 UTC
+ minutes, seconds) since 0001-01-01 00:00:00 UTC.
"""
if not cbook.iterable(d): return _to_ordinalf(d)
else: return np.asarray([_to_ordinalf(val) for val in d])
def julian2num(j):
- 'convert a Julian date (or sequence) to a matplotlib date (or sequence)'
+ 'Convert a Julian date (or sequence) to a matplotlib date (or sequence).'
if cbook.iterable(j): j = np.asarray(j)
return j + 1721425.5
def num2julian(n):
- 'convert a matplotlib date (or seguence) to a Julian date (or sequence)'
+ 'Convert a matplotlib date (or sequence) to a Julian date (or sequence).'
if cbook.iterable(n): n = np.asarray(n)
return n - 1721425.5
def num2date(x, tz=None):
"""
- x is a float value which gives number of days (fraction part
- represents hours, minutes, seconds) since 0001-01-01 00:00:00 UTC
+ *x* is a float value which gives number of days (fraction part
+ represents hours, minutes, seconds) since 0001-01-01 00:00:00 UTC.
- Return value is a datetime instance in timezone tz (default to
- rcparams TZ value)
+ Return value is a :class:`datetime` instance in timezone *tz* (default to
+ rcparams TZ value).
- if x is a sequence, a sequence of datetimes will be returned
+ If *x* is a sequence, a sequence of :class:`datetime` objects will
+ be returned.
"""
if tz is None: tz = _get_rc_timezone()
if not cbook.iterable(x): return _from_ordinalf(x, tz)
@@ -243,8 +251,9 @@
def drange(dstart, dend, delta):
"""
- Return a date range as float gregorian ordinals. dstart and dend
- are datetime instances. delta is a datetime.timedelta instance
+ Return a date range as float Gregorian ordinals. *dstart* and
+ *dend* are :class:`datetime` instances. *delta* is a
+ :class:`datetime.timedelta` instance.
"""
step = (delta.days + delta.seconds/SECONDS_PER_DAY +
delta.microseconds/MUSECONDS_PER_DAY)
@@ -260,20 +269,21 @@
class DateFormatter(ticker.Formatter):
"""
- Tick location is seconds since the epoch. Use a strftime format
- string
+ Tick location is seconds since the epoch. Use a :func:`strftime`
+ format string.
- python only supports datetime strftime formatting for years
- greater than 1900. Thanks to Andrew Dalke, Dalke Scientific
- Software who contributed the strftime code below to include dates
- earlier than this year
+ Python only supports :mod:`datetime` :func:`strftime` formatting
+ for years greater than 1900. Thanks to Andrew Dalke, Dalke
+ Scientific Software who contributed the :func:`strftime` code
+ below to include dates earlier than this year.
"""
illegal_s = re.compile(r"((^|[^%])(%%)*%s)")
def __init__(self, fmt, tz=None):
"""
- fmt is an strftime format string; tz is the tzinfo instance
+ *fmt* is an :func:`strftime` format string; *tz* is the
+ :class:`tzinfo` instance.
"""
if tz is None: tz = _get_rc_timezone()
self.fmt = fmt
@@ -341,13 +351,13 @@
class IndexDateFormatter(ticker.Formatter):
"""
- Use with IndexLocator to cycle format strings by index.
+ Use with :class:`~matplotlib.ticker.IndexLocator` to cycle format
+ strings by index.
"""
def __init__(self, t, fmt, tz=None):
"""
- t is a sequence of dates floating point days). fmt is a
- strftime format string
-
+ *t* is a sequence of dates (floating point days). *fmt* is a
+ :func:`strftime` format string.
"""
if tz is None: tz = _get_rc_timezone()
self.t = t
@@ -355,7 +365,7 @@
self.tz = tz
def __call__(self, x, pos=0):
- 'Return the label for time x at position pos'
+ 'Return the label for time *x* at position *pos*'
ind = int(round(x))
if ind>=len(self.t) or ind<=0: return ''
@@ -366,8 +376,8 @@
class AutoDateFormatter(ticker.Formatter):
"""
- This class attempt to figure out the best format to use. This is
- most useful when used with the AutoDateLocator.
+ This class attempts to figure out the best format to use. This is
+ most useful when used with the :class:`AutoDateLocator`.
"""
# This can be improved by providing some user-level direction on
@@ -427,7 +437,7 @@
hms0d = {'byhour':0, 'byminute':0,'bysecond':0}
def __init__(self, tz=None):
"""
- tz is the tzinfo instance
+ *tz* is a :class:`tzinfo` instance.
"""
if tz is None: tz = _get_rc_timezone()
self.tz = tz
@@ -445,8 +455,8 @@
def _get_unit(self):
"""
- return how many days a unit of the locator is; use for
- intelligent autoscaling
+ Return how many days a unit of the locator is; used for
+ intelligent autoscaling.
"""
return 1
@@ -477,8 +487,8 @@
def _get_unit(self):
"""
- Return how many days a unit of the locator is; use for
- intelligent autoscaling
+ Return how many days a unit of the locator is; used for
+ intelligent autoscaling.
"""
freq = self.rule._rrule._freq
if ( freq == YEARLY ):
@@ -501,7 +511,7 @@
def autoscale(self):
"""
- Set the view limits to include the data range
+ Set the view limits to include the data range.
"""
dmin, dmax = self.datalim_to_dt()
if dmin>dmax:
@@ -526,8 +536,9 @@
class AutoDateLocator(DateLocator):
"""
- On autoscale this class picks the best MultipleDateLocator to set the
- view limits and the tick locs.
+ On autoscale, this class picks the best
+ :class:`MultipleDateLocator` to set the view limits and the tick
+ locations.
"""
def __init__(self, tz=None):
DateLocator.__init__(self, tz)
@@ -544,7 +555,7 @@
self._locator.set_axis(axis)
def refresh(self):
- 'refresh internal information based on current lim'
+ 'Refresh internal information based on current limits.'
dmin, dmax = self.viewlim_to_dt()
self._locator = self.get_locator(dmin, dmax)
@@ -568,13 +579,13 @@
return -1
def autoscale(self):
- 'Try to choose the view limits intelligently'
+ 'Try to choose the view limits intelligently.'
dmin, dmax = self.datalim_to_dt()
self._locator = self.get_locator(dmin, dmax)
return self._locator.autoscale()
def get_locator(self, dmin, dmax):
- 'pick the best locator based on a distance'
+ 'Pick the best locator based on a distance.'
delta = relativedelta(dmax, dmin)
@@ -682,19 +693,18 @@
"""
Make ticks on a given day of each year that is a multiple of base.
- Examples:
- # Tick every year on Jan 1st
- locator = YearLocator()
+ Examples::
- # Tick every 5 years on July 4th
- locator = YearLocator(5, month=7, day=4)
+ # Tick every year on Jan 1st
+ locator = YearLocator()
-
+ # Tick every 5 years on July 4th
+ locator = YearLocator(5, month=7, day=4)
"""
def __init__(self, base=1, month=1, day=1, tz=None):
"""
- mark years that are multiple of base on a given month and day
- (default jan 1)
+ Mark years that are multiple of base on a given month and day
+ (default jan 1).
"""
DateLocator.__init__(self, tz)
self.base = ticker.Base(base)
@@ -709,8 +719,8 @@
def _get_unit(self):
"""
- return how many days a unit of the locator is; use for
- intelligent autoscaling
+ Return how many days a unit of the locator is; used for
+ intelligent autoscaling.
"""
return 365
@@ -729,7 +739,7 @@
def autoscale(self):
"""
- Set the view limits to include the data range
+ Set the view limits to include the data range.
"""
dmin, dmax = self.datalim_to_dt()
@@ -744,15 +754,15 @@
class MonthLocator(RRuleLocator):
"""
- Make ticks on occurances of each month month, eg 1, 3, 12
+ Make ticks on occurances of each month month, eg 1, 3, 12.
"""
def __init__(self, bymonth=None, bymonthday=1, interval=1, tz=None):
"""
- mark every month in bymonth; bymonth can be an int or
- sequence. default is range(1,13), ie every month
+ Mark every month in *bymonth*; *bymonth* can be an int or
+ sequence. Default is ``range(1,13)``, i.e. every month.
- interval is the interval between each iteration. Eg, if
- interval=2, mark every second occurance
+ *interval* is the interval between each iteration. For
+ example, if ``interval=2``, mark every second occurance.
"""
if bymonth is None: bymonth=range(1,13)
o = rrulewrapper(MONTHLY, bymonth=bymonth, bymonthday=bymonthday,
@@ -761,28 +771,27 @@
def _get_unit(self):
"""
- return how many days a unit of the locator is; use for
- intelligent autoscaling
+ Return how many days a unit of the locator is; used for
+ intelligent autoscaling.
"""
return 30
class WeekdayLocator(RRuleLocator):
"""
- Make ticks on occurances of each weekday
+ Make ticks on occurances of each weekday.
"""
def __init__(self, byweekday=1, interval=1, tz=None):
"""
- mark every weekday in byweekday; byweekday can be a number or
- sequence
+ Mark every weekday in *byweekday*; *byweekday* can be a number or
+ sequence.
- elements of byweekday must be one of MO, TU, WE, TH, FR, SA,
- SU, the constants from dateutils.rrule
+ Elements of *byweekday* must be one of MO, TU, WE, TH, FR, SA,
+ SU, the constants from :mod:`dateutils.rrule`.
- interval specifies the number of weeks to skip. Ie interval=2
- plots every second week
-
+ *interval* specifies the number of weeks to skip. For example,
+ ``interval=2`` plots every second week.
"""
o = rrulewrapper(DAILY, byweekday=byweekday,
interval=interval, **self.hms0d)
@@ -790,21 +799,23 @@
def _get_unit(self):
"""
- return how many days a unit of the locator is; use for
- intelligent autoscaling
+ return how many days a unit of the locator is; used for
+ intelligent autoscaling.
"""
return 7
class DayLocator(RRuleLocator):
"""
- Make ticks on occurances of each day of the month, eg 1, 15, 30
+ Make ticks on occurances of each day of the month. For example,
+ 1, 15, 30.
"""
def __init__(self, bymonthday=None, interval=1, tz=None):
"""
- mark every day in bymonthday; bymonthday can be an int or sequence
+ Mark every day in *bymonthday*; *bymonthday* can be an int or
+ sequence.
- Default is to tick every day of the month - bymonthday=range(1,32)
+ Default is to tick every day of the month: ``bymonthday=range(1,32)``
"""
if bymonthday is None: bymonthday=range(1,32)
o = rrulewrapper(DAILY, bymonthday=bymonthday,
@@ -813,22 +824,22 @@
def _get_unit(self):
"""
- return how many days a unit of the locator is; use for
- intelligent autoscaling
+ Return how many days a unit of the locator is; used for
+ intelligent autoscaling.
"""
return 1
class HourLocator(RRuleLocator):
"""
- Make ticks on occurances of each hour
+ Make ticks on occurances of each hour.
"""
def __init__(self, byhour=None, interval=1, tz=None):
"""
- mark every hour in byhour; byhour can be an int or sequence.
- Default is to tick every hour - byhour=range(24)
+ Mark every hour in *byhour*; *byhour* can be an int or sequence.
+ Default is to tick every hour: ``byhour=range(24)``
- interval is the interval between each iteration. Eg, if
- interval=2, mark every second occurance
+ *interval* is the interval between each iteration. For
+ example, if ``interval=2``, mark every second occurrence.
"""
if byhour is None: byhour=range(24)
rule = rrulewrapper(HOURLY, byhour=byhour, interval=interval,
@@ -844,16 +855,15 @@
class MinuteLocator(RRuleLocator):
"""
- Make ticks on occurances of each minute
+ Make ticks on occurances of each minute.
"""
def __init__(self, byminute=None, interval=1, tz=None):
"""
- mark every minute in byminute; byminute can be an int or
- sequence. default is to tick every minute - byminute=range(60)
+ Mark every minute in *byminute*; *byminute* can be an int or
+ sequence. Default is to tick every minute: ``byminute=range(60)``
- interval is the interval between each iteration. Eg, if
- interval=2, mark every second occurance
-
+ *interval* is the interval between each iteration. For
+ example, if ``interval=2``, mark every second occurrence.
"""
if byminute is None: byminute=range(60)
rule = rrulewrapper(MINUTELY, byminute=byminute, interval=interval,
@@ -862,22 +872,22 @@
def _get_unit(self):
"""
- return how many days a unit of the locator is; use for
- intelligent autoscaling
+ Return how many days a unit of the locator is; used for
+ intelligent autoscaling.
"""
return 1./(24*60)
class SecondLocator(RRuleLocator):
"""
- Make ticks on occurances of each second
+ Make ticks on occurances of each second.
"""
def __init__(self, bysecond=None, interval=1, tz=None):
"""
- mark every second in bysecond; bysecond can be an int or
- sequence. Default is to tick every second bysecond = range(60)
+ Mark every second in *bysecond*; *bysecond* can be an int or
+ sequence. Default is to tick every second: ``bysecond = range(60)``
- interval is the interval between each iteration. Eg, if
- interval=2, mark every second occurance
+ *interval* is the interval between each iteration. For
+ example, if ``interval=2``, mark every second occurrence.
"""
if bysecond is None: bysecond=range(60)
@@ -886,44 +896,44 @@
def _get_unit(self):
"""
- return how many days a unit of the locator is; use for
- intelligent autoscaling
+ Return how many days a unit of the locator is; used for
+ intelligent autoscaling.
"""
return 1./(24*60*60)
def _close_to_dt(d1, d2, epsilon=5):
- 'assert that datetimes d1 and d2 are within epsilon microseconds'
+ 'Assert that datetimes *d1* and *d2* are within *epsilon* microseconds.'
delta = d2-d1
mus = abs(delta.days*MUSECONDS_PER_DAY + delta.seconds*1e6 +
delta.microseconds)
assert(mus<epsilon)
def _close_to_num(o1, o2, epsilon=5):
- 'assert that float ordinals o1 and o2 are within epsilon microseconds'
+ 'Assert that float ordinals *o1* and *o2* are within *epsilon* microseconds.'
delta = abs((o2-o1)*MUSECONDS_PER_DAY)
assert(delta<epsilon)
def epoch2num(e):
"""
- convert an epoch or sequence of epochs to the new date format,
- days since 0001
+ Convert an epoch or sequence of epochs to the new date format,
+ that is days since 0001.
"""
spd = 24.*3600.
return 719163 + np.asarray(e)/spd
def num2epoch(d):
"""
- convert days since 0001 to epoch. d can be a number or sequence
+ Convert days since 0001 to epoch. *d* can be a number or sequence.
"""
spd = 24.*3600.
return (np.asarray(d)-719163)*spd
def mx2num(mxdates):
"""
- Convert mx datetime instance (or sequence of mx instances) to the
- new date format,
+ Convert mx :class:`datetime` instance (or sequence of mx
+ instances) to the new date format.
"""
scalar = False
if not cbook.iterable(mxdates):
@@ -936,10 +946,8 @@
def date_ticker_factory(span, tz=None, numticks=5):
"""
- Create a date locator with numticks (approx) and a date formatter
- for span in days. Return value is (locator, formatter)
-
-
+ Create a date locator with *numticks* (approx) and a date formatter
+ for *span* in days. Return value is (locator, formatter).
"""
if span==0: span = 1/24.
@@ -979,19 +987,19 @@
def seconds(s):
- 'return seconds as days'
+ 'Return seconds as days.'
return float(s)/SEC_PER_DAY
def minutes(m):
- 'return minutes as days'
+ 'Return minutes as days.'
return float(m)/MINUTES_PER_DAY
def hours(h):
- 'return hours as days'
+ 'Return hours as days.'
return h/24.
def weeks(w):
- 'return weeks as days'
+ 'Return weeks as days.'
return w*7.
@@ -1016,7 +1024,7 @@
convert = staticmethod(convert)
def default_units(x):
- 'return the default unit for x or None'
+ 'Return the default unit for *x* or None'
return 'date'
default_units = staticmethod(default_units)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <pki...@us...> - 2008-11-14 22:25:37
|
Revision: 6405
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6405&view=rev
Author: pkienzle
Date: 2008-11-14 22:25:28 +0000 (Fri, 14 Nov 2008)
Log Message:
-----------
patches: use None rather than 0 for full wedge
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/patches.py
Modified: trunk/matplotlib/lib/matplotlib/patches.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/patches.py 2008-11-14 22:19:02 UTC (rev 6404)
+++ trunk/matplotlib/lib/matplotlib/patches.py 2008-11-14 22:25:28 UTC (rev 6405)
@@ -718,7 +718,7 @@
def __str__(self):
return "Wedge(%g,%g)"%(self.theta1,self.theta2)
- def __init__(self, center, r, theta1, theta2, width=0, **kwargs):
+ def __init__(self, center, r, theta1, theta2, width=None, **kwargs):
"""
Draw a wedge centered at *x*, *y* center with radius *r* that
sweeps *theta1* to *theta2* (in degrees). If *width* is given,
@@ -745,7 +745,7 @@
# Form the outer ring
arc = Path.arc(theta1,theta2)
- if width != 0:
+ if width is not None:
# Partial annulus needs to draw the outter ring
# followed by a reversed and scaled inner ring
v1 = arc.vertices
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <pki...@us...> - 2008-11-14 22:19:06
|
Revision: 6404
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6404&view=rev
Author: pkienzle
Date: 2008-11-14 22:19:02 +0000 (Fri, 14 Nov 2008)
Log Message:
-----------
patches: allow partial rings with Wedge
Modified Paths:
--------------
trunk/matplotlib/examples/api/patch_collection.py
trunk/matplotlib/lib/matplotlib/patches.py
Modified: trunk/matplotlib/examples/api/patch_collection.py
===================================================================
--- trunk/matplotlib/examples/api/patch_collection.py 2008-11-14 15:33:32 UTC (rev 6403)
+++ trunk/matplotlib/examples/api/patch_collection.py 2008-11-14 22:19:02 UTC (rev 6404)
@@ -25,12 +25,20 @@
wedge = Wedge((x1,y1), r, t1, t2)
patches.append(wedge)
+# Some limiting conditions on Wedge
+patches += [
+ Wedge((.3,.7), .1, 0, 360), # Full circle
+ Wedge((.7,.8), .2, 0, 360, width=0.05), # Full ring
+ Wedge((.8,.3), .2, 0, 45), # Full sector
+ Wedge((.8,.3), .2, 45, 90, width=0.10), # Ring sector
+]
+
for i in range(N):
polygon = Polygon(pylab.rand(N,2), True)
patches.append(polygon)
colors = 100*pylab.rand(len(patches))
-p = PatchCollection(patches, cmap=matplotlib.cm.jet)
+p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4)
p.set_array(pylab.array(colors))
ax.add_collection(p)
pylab.colorbar(p)
Modified: trunk/matplotlib/lib/matplotlib/patches.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/patches.py 2008-11-14 15:33:32 UTC (rev 6403)
+++ trunk/matplotlib/lib/matplotlib/patches.py 2008-11-14 22:19:02 UTC (rev 6404)
@@ -712,13 +712,18 @@
:meth:`~matplotlib.patches.Polygon.set_xy` instead.""")
class Wedge(Patch):
+ """
+ Wedge shaped patch.
+ """
def __str__(self):
return "Wedge(%g,%g)"%(self.theta1,self.theta2)
- def __init__(self, center, r, theta1, theta2, **kwargs):
+ def __init__(self, center, r, theta1, theta2, width=0, **kwargs):
"""
Draw a wedge centered at *x*, *y* center with radius *r* that
- sweeps *theta1* to *theta2* (in degrees).
+ sweeps *theta1* to *theta2* (in degrees). If *width* is given,
+ then a partial wedge is drawn from inner radius *r* - *width*
+ to outer radius *r*.
Valid kwargs are:
@@ -726,24 +731,43 @@
"""
Patch.__init__(self, **kwargs)
self.center = center
- self.r = r
- self.theta1 = theta1
- self.theta2 = theta2
+ self.r,self.width = r,width
+ self.theta1,self.theta2 = theta1,theta2
+
+ # Inner and outer rings are connected unless the annulus is complete
+ delta=theta2-theta1
+ if abs((theta2-theta1) - 360) <= 1e-12:
+ theta1,theta2 = 0,360
+ connector = Path.MOVETO
+ else:
+ connector = Path.LINETO
+
+ # Form the outer ring
+ arc = Path.arc(theta1,theta2)
+
+ if width != 0:
+ # Partial annulus needs to draw the outter ring
+ # followed by a reversed and scaled inner ring
+ v1 = arc.vertices
+ v2 = arc.vertices[::-1]*float(r-width)/r
+ v = np.vstack([v1,v2,v1[0,:],(0,0)])
+ c = np.hstack([arc.codes,arc.codes,connector,Path.CLOSEPOLY])
+ c[len(arc.codes)]=connector
+ else:
+ # Wedge doesn't need an inner ring
+ v = np.vstack([arc.vertices,[(0,0),arc.vertices[0,:],(0,0)]])
+ c = np.hstack([arc.codes,[connector,connector,Path.CLOSEPOLY]])
+
+ # Shift and scale the wedge to the final location.
+ v *= r
+ v += np.asarray(center)
+ self._path = Path(v,c)
self._patch_transform = transforms.IdentityTransform()
- self._path = Path.wedge(self.theta1, self.theta2)
__init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd
def get_path(self):
return self._path
- def get_patch_transform(self):
- x = self.convert_xunits(self.center[0])
- y = self.convert_yunits(self.center[1])
- rx = self.convert_xunits(self.r)
- ry = self.convert_yunits(self.r)
- self._patch_transform = transforms.Affine2D() \
- .scale(rx, ry).translate(x, y)
- return self._patch_transform
# COVERAGE NOTE: Not used internally or from examples
class Arrow(Patch):
@@ -3042,4 +3066,3 @@
self.fill = fill_orig
#renderer.close_group('patch')
-
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-11-14 15:33:39
|
Revision: 6403
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6403&view=rev
Author: jdh2358
Date: 2008-11-14 15:33:32 +0000 (Fri, 14 Nov 2008)
Log Message:
-----------
fixed a vlines/hlines doc bug
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/axes.py
trunk/matplotlib/lib/mpl_toolkits/gtktools.py
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2008-11-14 08:15:27 UTC (rev 6402)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2008-11-14 15:33:32 UTC (rev 6403)
@@ -2961,7 +2961,7 @@
"""
call signature::
- hlines(y, xmin, xmax, colors='k', linestyle='solid', **kwargs)
+ hlines(y, xmin, xmax, colors='k', linestyles='solid', **kwargs)
Plot horizontal lines at each *y* from *xmin* to *xmax*.
@@ -2984,7 +2984,7 @@
a line collections color argument, either a single color
or a ``len(y)`` list of colors
- *linestyle*:
+ *linestyles*:
[ 'solid' | 'dashed' | 'dashdot' | 'dotted' ]
**Example:**
@@ -3044,18 +3044,21 @@
"""
call signature::
- vlines(x, ymin, ymax, color='k')
+ vlines(x, ymin, ymax, color='k', linestyles='solid')
Plot vertical lines at each *x* from *ymin* to *ymax*. *ymin*
or *ymax* can be scalars or len(*x*) numpy arrays. If they are
scalars, then the respective values are constant, else the
heights of the lines are determined by *ymin* and *ymax*.
- *colors* is a line collections color args, either a single color
- or a len(*x*) list of colors
+ *colors*
+ a line collections color args, either a single color
+ or a len(*x*) list of colors
- *linestyle* is one of [ 'solid' | 'dashed' | 'dashdot' | 'dotted' ]
+ *linestyles*
+ one of [ 'solid' | 'dashed' | 'dashdot' | 'dotted' ]
+
Returns the :class:`matplotlib.collections.LineCollection`
that was added.
Modified: trunk/matplotlib/lib/mpl_toolkits/gtktools.py
===================================================================
--- trunk/matplotlib/lib/mpl_toolkits/gtktools.py 2008-11-14 08:15:27 UTC (rev 6402)
+++ trunk/matplotlib/lib/mpl_toolkits/gtktools.py 2008-11-14 15:33:32 UTC (rev 6403)
@@ -359,7 +359,7 @@
* formatd - the list of mlab.FormatObj instances, with gtk attachments
* stringd - a dict mapping dtype names to a list of valid strings for the combo drop downs
-
+
* callbacks - a matplotlib.cbook.CallbackRegistry. Connect to the cell_changed with
def mycallback(liststore, rownum, colname, oldval, newval):
@@ -377,10 +377,10 @@
stringd, if not None, is a dict mapping dtype names to a list of
valid strings for a combo drop down editor
"""
-
+
if stringd is None:
stringd = dict()
-
+
if formatd is None:
formatd = mlab.get_formatd(r)
@@ -408,7 +408,7 @@
keys = stringd.keys()
keys.sort()
-
+
valid = set(r.dtype.names)
for ikey, key in enumerate(keys):
assert(key in valid)
@@ -417,7 +417,7 @@
combostore.append([s])
self.combod[key] = combostore, len(self.headers)+ikey
-
+
gtk.ListStore.__init__(self, *types)
for row in r:
@@ -426,7 +426,7 @@
if isinstance(formatter, mlab.FormatBool):
vals.append(val)
else:
- vals.append(formatter.tostr(val))
+ vals.append(formatter.tostr(val))
if len(stringd):
# todo, get correct index here?
vals.extend([0]*len(stringd))
@@ -483,12 +483,12 @@
constant, if not None, is a list of dtype names which are not editable
"""
self.recliststore = recliststore
-
+
gtk.TreeView.__init__(self, recliststore)
combostrings = set(recliststore.stringd.keys())
-
+
if constant is None:
constant = []
@@ -509,7 +509,7 @@
renderer.connect("edited", recliststore.position_edited, i)
combostore, listind = recliststore.combod[header]
renderer.set_property("model", combostore)
- renderer.set_property('editable', True)
+ renderer.set_property('editable', True)
else:
renderer = gtk.CellRendererText()
if header not in constant:
@@ -530,7 +530,7 @@
tvcol.add_attribute(renderer, 'text', i)
if header in combostrings:
combostore, listind = recliststore.combod[header]
- tvcol.add_attribute(renderer, 'text-column', listind)
+ tvcol.add_attribute(renderer, 'text-column', listind)
elif coltype == gobject.TYPE_BOOLEAN:
tvcol.add_attribute(renderer, 'active', i)
@@ -542,7 +542,8 @@
self.connect("button-release-event", self.on_selection_changed)
- self.set_grid_lines(gtk.TREE_VIEW_GRID_LINES_BOTH)
+ #self.set_grid_lines(gtk.TREE_VIEW_GRID_LINES_BOTH)
+
self.get_selection().set_mode(gtk.SELECTION_BROWSE)
self.get_selection().set_select_function(self.on_select)
@@ -576,10 +577,10 @@
return liststore, treeview, win
else:
return liststore, treeview
-
-
+
+
if __name__=='__main__':
import datetime
@@ -628,4 +629,4 @@
win2.set_title('with all defaults')
gtk.main()
-
+
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mme...@us...> - 2008-11-14 08:15:34
|
Revision: 6402
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6402&view=rev
Author: mmetz_bn
Date: 2008-11-14 08:15:27 +0000 (Fri, 14 Nov 2008)
Log Message:
-----------
Added missing include, fixed debian bug #505618
Modified Paths:
--------------
trunk/matplotlib/src/mplutils.cpp
Modified: trunk/matplotlib/src/mplutils.cpp
===================================================================
--- trunk/matplotlib/src/mplutils.cpp 2008-11-13 08:11:13 UTC (rev 6401)
+++ trunk/matplotlib/src/mplutils.cpp 2008-11-14 08:15:27 UTC (rev 6402)
@@ -1,5 +1,6 @@
#include <iostream>
#include <cstdarg>
+#include <cstdio>
#include "mplutils.h"
void _VERBOSE(const std::string& s) {
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2008-11-13 08:11:20
|
Revision: 6401
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6401&view=rev
Author: efiring
Date: 2008-11-13 08:11:13 +0000 (Thu, 13 Nov 2008)
Log Message:
-----------
Fix autoscaling problems associated with axhline etc.
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/artist.py
trunk/matplotlib/lib/matplotlib/axes.py
trunk/matplotlib/lib/matplotlib/transforms.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-11-12 20:09:10 UTC (rev 6400)
+++ trunk/matplotlib/CHANGELOG 2008-11-13 08:11:13 UTC (rev 6401)
@@ -1,3 +1,9 @@
+2008-11-12 Add x_isdata and y_isdata attributes to Artist instances,
+ and use them to determine whether either or both
+ coordinates are used when updating dataLim. This is
+ used to fix autoscaling problems that had been triggered
+ by axhline, axhspan, axvline, axvspan. - EF
+
2008-11-11 Update the psd(), csd(), cohere(), and specgram() methods
of Axes and the csd() cohere(), and specgram() functions
in mlab to be in sync with the changes to psd().
Modified: trunk/matplotlib/lib/matplotlib/artist.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/artist.py 2008-11-12 20:09:10 UTC (rev 6400)
+++ trunk/matplotlib/lib/matplotlib/artist.py 2008-11-13 08:11:13 UTC (rev 6401)
@@ -51,6 +51,8 @@
self.axes = None
self._remove_method = None
self._url = None
+ self.x_isdata = True # False to avoid updating Axes.dataLim with x
+ self.y_isdata = True # with y
def remove(self):
"""
@@ -319,7 +321,7 @@
Returns the url
"""
return self._url
-
+
def set_url(self, url):
"""
Sets the url for the artist
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2008-11-12 20:09:10 UTC (rev 6400)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2008-11-13 08:11:13 UTC (rev 6401)
@@ -1312,8 +1312,7 @@
self._set_artist_props(line)
line.set_clip_path(self.patch)
- if line.get_transform() == self.transData:
- self._update_line_limits(line)
+ self._update_line_limits(line)
if not line.get_label():
line.set_label('_line%d'%len(self.lines))
self.lines.append(line)
@@ -1322,7 +1321,9 @@
def _update_line_limits(self, line):
p = line.get_path()
if p.vertices.size > 0:
- self.dataLim.update_from_path(p, self.ignore_existing_data_limits)
+ self.dataLim.update_from_path(p, self.ignore_existing_data_limits,
+ updatex=line.x_isdata,
+ updatey=line.y_isdata)
self.ignore_existing_data_limits = False
def add_patch(self, p):
@@ -1356,7 +1357,8 @@
transform = (patch.get_data_transform() +
self.transData.inverted())
xys = transform.transform(xys)
- self.update_datalim(xys)
+ self.update_datalim(xys, updatex=patch.x_isdata,
+ updatey=patch.y_isdata)
def add_table(self, tab):
@@ -1381,7 +1383,7 @@
for p in self.patches:
self._update_patch_limits(p)
- def update_datalim(self, xys):
+ def update_datalim(self, xys, updatex=True, updatey=True):
'Update the data lim bbox with seq of xy tups or equiv. 2-D array'
# if no data is set currently, the bbox will ignore its
# limits and set the bound to be the bounds of the xydata.
@@ -1391,7 +1393,8 @@
if iterable(xys) and not len(xys): return
if not ma.isMaskedArray(xys):
xys = np.asarray(xys)
- self.dataLim.update_from_data_xy(xys, self.ignore_existing_data_limits)
+ self.dataLim.update_from_data_xy(xys, self.ignore_existing_data_limits,
+ updatex=updatex, updatey=updatey)
self.ignore_existing_data_limits = False
def update_datalim_numerix(self, x, y):
@@ -2776,11 +2779,9 @@
trans = mtransforms.blended_transform_factory(
self.transAxes, self.transData)
l = mlines.Line2D([xmin,xmax], [y,y], transform=trans, **kwargs)
+ l.x_isdata = False
self.add_line(l)
- self.dataLim.y0 = min(self.dataLim.y0, yy)
- self.dataLim.y1 = max(self.dataLim.y1, yy)
self.autoscale_view(scalex=False, scaley=scaley)
-
return l
axhline.__doc__ = cbook.dedent(axhline.__doc__) % martist.kwdocd
@@ -2836,11 +2837,9 @@
trans = mtransforms.blended_transform_factory(
self.transData, self.transAxes)
l = mlines.Line2D([x,x], [ymin,ymax] , transform=trans, **kwargs)
+ l.y_isdata = False
self.add_line(l)
- self.dataLim.x0 = min(self.dataLim.x0, xx)
- self.dataLim.x1 = max(self.dataLim.x1, xx)
self.autoscale_view(scalex=scalex, scaley=False)
-
return l
axvline.__doc__ = cbook.dedent(axvline.__doc__) % martist.kwdocd
@@ -2858,7 +2857,7 @@
Draw a horizontal span (rectangle) from *ymin* to *ymax*.
With the default values of *xmin* = 0 and *xmax* = 1, this
- always span the xrange, regardless of the xlim settings, even
+ always spans the xrange, regardless of the xlim settings, even
if you change them, eg. with the :meth:`set_xlim` command.
That is, the horizontal extent is in axes coords: 0=left,
0.5=middle, 1.0=right but the *y* location is in data
@@ -2896,6 +2895,7 @@
verts = (xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)
p = mpatches.Polygon(verts, **kwargs)
p.set_transform(trans)
+ p.x_isdata = False
self.add_patch(p)
return p
axhspan.__doc__ = cbook.dedent(axhspan.__doc__) % martist.kwdocd
@@ -2913,7 +2913,7 @@
Draw a vertical span (rectangle) from *xmin* to *xmax*. With
the default values of *ymin* = 0 and *ymax* = 1, this always
- span the yrange, regardless of the ylim settings, even if you
+ spans the yrange, regardless of the ylim settings, even if you
change them, eg. with the :meth:`set_ylim` command. That is,
the vertical extent is in axes coords: 0=bottom, 0.5=middle,
1.0=top but the *y* location is in data coordinates.
@@ -2950,6 +2950,7 @@
verts = [(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)]
p = mpatches.Polygon(verts, **kwargs)
p.set_transform(trans)
+ p.y_isdata = False
self.add_patch(p)
return p
axvspan.__doc__ = cbook.dedent(axvspan.__doc__) % martist.kwdocd
Modified: trunk/matplotlib/lib/matplotlib/transforms.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/transforms.py 2008-11-12 20:09:10 UTC (rev 6400)
+++ trunk/matplotlib/lib/matplotlib/transforms.py 2008-11-13 08:11:13 UTC (rev 6401)
@@ -776,7 +776,8 @@
def update_from_data(self, x, y, ignore=None):
"""
Update the bounds of the :class:`Bbox` based on the passed in
- data.
+ data. After updating, the bounds will have positive *width*
+ and *height*; *x0* and *y0* will be the minimal values.
*x*: a numpy array of *x*-values
@@ -791,10 +792,11 @@
xy = np.hstack((x.reshape((len(x), 1)), y.reshape((len(y), 1))))
return self.update_from_data_xy(xy, ignore)
- def update_from_path(self, path, ignore=None):
+ def update_from_path(self, path, ignore=None, updatex=True, updatey=True):
"""
Update the bounds of the :class:`Bbox` based on the passed in
- data.
+ data. After updating, the bounds will have positive *width*
+ and *height*; *x0* and *y0* will be the minimal values.
*path*: a :class:`~matplotlib.path.Path` instance
@@ -802,6 +804,10 @@
- when True, ignore the existing bounds of the :class:`Bbox`.
- when False, include the existing bounds of the :class:`Bbox`.
- when None, use the last value passed to :meth:`ignore`.
+
+ *updatex*: when True, update the x values
+
+ *updatey*: when True, update the y values
"""
if ignore is None:
ignore = self._ignore
@@ -813,15 +819,20 @@
path, None, self._points, self._minpos, ignore)
if changed:
- self._points = points
- self._minpos = minpos
self.invalidate()
+ if updatex:
+ self._points[:,0] = points[:,0]
+ self._minpos[0] = minpos[0]
+ if updatey:
+ self._points[:,1] = points[:,1]
+ self._minpos[1] = minpos[1]
- def update_from_data_xy(self, xy, ignore=None):
+ def update_from_data_xy(self, xy, ignore=None, updatex=True, updatey=True):
"""
Update the bounds of the :class:`Bbox` based on the passed in
- data.
+ data. After updating, the bounds will have positive *width*
+ and *height*; *x0* and *y0* will be the minimal values.
*xy*: a numpy array of 2D points
@@ -829,12 +840,17 @@
- when True, ignore the existing bounds of the :class:`Bbox`.
- when False, include the existing bounds of the :class:`Bbox`.
- when None, use the last value passed to :meth:`ignore`.
+
+ *updatex*: when True, update the x values
+
+ *updatey*: when True, update the y values
"""
if len(xy) == 0:
return
path = Path(xy)
- self.update_from_path(path, ignore=ignore)
+ self.update_from_path(path, ignore=ignore,
+ updatex=updatex, updatey=updatey)
def _set_x0(self, val):
self._points[0, 0] = val
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-11-12 20:09:14
|
Revision: 6400
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6400&view=rev
Author: mdboom
Date: 2008-11-12 20:09:10 +0000 (Wed, 12 Nov 2008)
Log Message:
-----------
[ 2269684 ] mathtext broken in the cairo backend
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/font_manager.py
Modified: trunk/matplotlib/lib/matplotlib/font_manager.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/font_manager.py 2008-11-12 20:00:11 UTC (rev 6399)
+++ trunk/matplotlib/lib/matplotlib/font_manager.py 2008-11-12 20:09:10 UTC (rev 6400)
@@ -397,7 +397,7 @@
self.size = size
-def ttfFontProperty(fontpath, font):
+def ttfFontProperty(font):
"""
A function for populating the :class:`FontKey` by extracting
information from the TrueType font file.
@@ -489,7 +489,7 @@
# !!!! Incomplete
size_adjust = None
- return FontEntry(fontpath, name, style, variant, weight, stretch, size)
+ return FontEntry(font.fname, name, style, variant, weight, stretch, size)
def afmFontProperty(fontpath, font):
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-11-12 20:00:13
|
Revision: 6399
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6399&view=rev
Author: mdboom
Date: 2008-11-12 20:00:11 +0000 (Wed, 12 Nov 2008)
Log Message:
-----------
Add comment about minimum positive values.
Modified Paths:
--------------
trunk/matplotlib/src/_path.cpp
Modified: trunk/matplotlib/src/_path.cpp
===================================================================
--- trunk/matplotlib/src/_path.cpp 2008-11-11 22:02:34 UTC (rev 6398)
+++ trunk/matplotlib/src/_path.cpp 2008-11-12 20:00:11 UTC (rev 6399)
@@ -289,6 +289,8 @@
if (y < *y0) *y0 = y;
if (x > *x1) *x1 = x;
if (y > *y1) *y1 = y;
+ /* xm and ym are the minimum positive values in the data, used
+ by log scaling */
if (x > 0.0 && x < *xm) *xm = x;
if (y > 0.0 && y < *ym) *ym = y;
}
@@ -317,6 +319,8 @@
extents_data[1] = std::numeric_limits<double>::infinity();
extents_data[2] = -std::numeric_limits<double>::infinity();
extents_data[3] = -std::numeric_limits<double>::infinity();
+ /* xm and ym are the minimum positive values in the data, used
+ by log scaling */
xm = std::numeric_limits<double>::infinity();
ym = std::numeric_limits<double>::infinity();
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ry...@us...> - 2008-11-11 22:22:08
|
Revision: 6396
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6396&view=rev
Author: ryanmay
Date: 2008-11-11 21:32:29 +0000 (Tue, 11 Nov 2008)
Log Message:
-----------
Factor out common core of psd(), csd(), and specgram() into _spectral_helper() function. This allows all of them to have the same calling signature and capabilities and to have the code in a single location.
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/mlab.py
Modified: trunk/matplotlib/lib/matplotlib/mlab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mlab.py 2008-11-11 20:34:25 UTC (rev 6395)
+++ trunk/matplotlib/lib/matplotlib/mlab.py 2008-11-11 21:32:29 UTC (rev 6396)
@@ -238,29 +238,78 @@
a = y.mean() - b*x.mean()
return y - (b*x + a)
-def psd(x, NFFT=256, Fs=2, detrend=detrend_none,
+#This is a helper function that implements the commonality between the
+#psd, csd, and spectrogram. It is *NOT* meant to be used outside of mlab
+def _spectral_helper(x, y, NFFT=256, Fs=2, detrend=detrend_none,
window=window_hanning, noverlap=0, pad_to=None, sides='default'):
- """
- The power spectral density by Welch's average periodogram method.
- The vector *x* is divided into *NFFT* length blocks. Each block
- is detrended by the function *detrend* and windowed by the function
- *window*. *noverlap* gives the length of the overlap between blocks.
- The absolute(fft(block))**2 of each segment are averaged to compute
- *Pxx*, with a scaling to correct for power loss due to windowing.
+ #The checks for if y is x are so that we can use the same function to
+ #implement the core of psd(), csd(), and spectrogram() without doing
+ #extra calculations. We return the unaveraged Pxy, freqs, and t.
+
+ #Make sure we're dealing with a numpy array. If y and x were the same
+ #object to start with, keep them that way
+ same_data = y is x
- If len(*x*) < *NFFT*, it will be zero padded to *NFFT*.
+ x = np.asarray(x)
+ if not same_data:
+ y = np.asarray(y)
- *x*
- Array or sequence containing the data
- %(PSD)s
- Returns the tuple (*Pxx*, *freqs*).
+ # zero pad x and y up to NFFT if they are shorter than NFFT
+ if len(x)<NFFT:
+ n = len(x)
+ x = np.resize(x, (NFFT,))
+ x[n:] = 0
- Refs:
- Bendat & Piersol -- Random Data: Analysis and Measurement
- Procedures, John Wiley & Sons (1986)
- """
- return csd(x, x, NFFT, Fs, detrend, window, noverlap, pad_to, sides)
+ if not same_data and len(y)<NFFT:
+ n = len(y)
+ y = np.resize(y, (NFFT,))
+ y[n:] = 0
+ if pad_to is None:
+ pad_to = NFFT
+
+ # For real x, ignore the negative frequencies unless told otherwise
+ if (sides == 'default' and np.iscomplexobj(x)) or sides == 'twosided':
+ numFreqs = pad_to
+ elif sides in ('default', 'onesided'):
+ numFreqs = pad_to//2 + 1
+ else:
+ raise ValueError("sides must be one of: 'default', 'onesided', or "
+ "'twosided'")
+
+ if cbook.iterable(window):
+ assert(len(window) == NFFT)
+ windowVals = window
+ else:
+ windowVals = window(np.ones((NFFT,), x.dtype))
+
+ step = NFFT - noverlap
+ ind = np.arange(0, len(x) - NFFT + 1, step)
+ n = len(ind)
+ Pxy = np.zeros((numFreqs,n), np.complex_)
+
+ # do the ffts of the slices
+ for i in range(n):
+ thisX = x[ind[i]:ind[i]+NFFT]
+ thisX = windowVals * detrend(thisX)
+ fx = np.fft.fft(thisX, n=pad_to)
+
+ if same_data:
+ fy = fx
+ else:
+ thisY = y[ind[i]:ind[i]+NFFT]
+ thisY = windowVals * detrend(thisY)
+ fy = np.fft.fft(thisY, n=pad_to)
+ Pxy[:,i] = np.conjugate(fx[:numFreqs]) * fy[:numFreqs]
+
+ # Scale the spectrum by the norm of the window to compensate for
+ # windowing loss; see Bendat & Piersol Sec 11.5.2
+ Pxy /= (np.abs(windowVals)**2).sum()
+ t = 1./Fs * (ind + NFFT / 2.)
+ freqs = float(Fs) / pad_to * np.arange(numFreqs)
+
+ return Pxy, freqs, t
+
#Split out these keyword docs so that they can be used elsewhere
kwdocd = dict()
kwdocd['PSD'] ="""
@@ -315,6 +364,31 @@
for complex data. 'one' forces the return of a one-sided PSD, while
'both' forces two-sided.
"""
+
+def psd(x, NFFT=256, Fs=2, detrend=detrend_none,
+ window=window_hanning, noverlap=0, pad_to=None, sides='default'):
+ """
+ The power spectral density by Welch's average periodogram method.
+ The vector *x* is divided into *NFFT* length blocks. Each block
+ is detrended by the function *detrend* and windowed by the function
+ *window*. *noverlap* gives the length of the overlap between blocks.
+ The absolute(fft(block))**2 of each segment are averaged to compute
+ *Pxx*, with a scaling to correct for power loss due to windowing.
+
+ If len(*x*) < *NFFT*, it will be zero padded to *NFFT*.
+
+ *x*
+ Array or sequence containing the data
+ %(PSD)s
+ Returns the tuple (*Pxx*, *freqs*).
+
+ Refs:
+ Bendat & Piersol -- Random Data: Analysis and Measurement
+ Procedures, John Wiley & Sons (1986)
+ """
+ Pxx,freqs = csd(x, x, NFFT, Fs, detrend, window, noverlap, pad_to, sides)
+ return Pxx.real,freqs
+
psd.__doc__ = psd.__doc__ % kwdocd
def csd(x, y, NFFT=256, Fs=2, detrend=detrend_none,
@@ -340,93 +414,28 @@
Bendat & Piersol -- Random Data: Analysis and Measurement
Procedures, John Wiley & Sons (1986)
"""
+ Pxy, freqs, t = _spectral_helper(x, y, NFFT, Fs, detrend, window,
+ noverlap, pad_to, sides)
- #The checks for if y is x are so that we can use csd() to implement
- #psd() without doing extra work.
-
- #Make sure we're dealing with a numpy array. If y and x were the same
- #object to start with, keep them that way
- do_psd = y is x
-
- x = np.asarray(x)
- if not do_psd:
- y = np.asarray(y)
-
- # zero pad x and y up to NFFT if they are shorter than NFFT
- if len(x)<NFFT:
- n = len(x)
- x = np.resize(x, (NFFT,))
- x[n:] = 0
-
- if not do_psd and len(y)<NFFT:
- n = len(y)
- y = np.resize(y, (NFFT,))
- y[n:] = 0
-
- if pad_to is None:
- pad_to = NFFT
-
- # For real x, ignore the negative frequencies unless told otherwise
- if (sides == 'default' and np.iscomplexobj(x)) or sides == 'twosided':
- numFreqs = pad_to
- elif sides in ('default', 'onesided'):
- numFreqs = pad_to//2 + 1
- else:
- raise ValueError("sides must be one of: 'default', 'onesided', or "
- "'twosided'")
-
- if cbook.iterable(window):
- assert(len(window) == NFFT)
- windowVals = window
- else:
- windowVals = window(np.ones((NFFT,), x.dtype))
-
- step = NFFT - noverlap
- ind = range(0, len(x) - NFFT + 1, step)
- n = len(ind)
- Pxy = np.zeros((numFreqs,n), np.complex_)
-
- # do the ffts of the slices
- for i in range(n):
- thisX = x[ind[i]:ind[i]+NFFT]
- thisX = windowVals * detrend(thisX)
- fx = np.fft.fft(thisX, n=pad_to)
-
- if do_psd:
- fy = fx
- else:
- thisY = y[ind[i]:ind[i]+NFFT]
- thisY = windowVals * detrend(thisY)
- fy = np.fft.fft(thisY, n=pad_to)
- Pxy[:,i] = np.conjugate(fx[:numFreqs]) * fy[:numFreqs]
-
- # Scale the spectrum by the norm of the window to compensate for
- # windowing loss; see Bendat & Piersol Sec 11.5.2
- if n>1:
+ if len(Pxy.shape) == 2 and Pxy.shape[1]>1:
Pxy = Pxy.mean(axis=1)
-
- Pxy /= (np.abs(windowVals)**2).sum()
- freqs = float(Fs) / pad_to * np.arange(numFreqs)
return Pxy, freqs
csd.__doc__ = csd.__doc__ % kwdocd
def specgram(x, NFFT=256, Fs=2, detrend=detrend_none,
- window=window_hanning, noverlap=128):
+ window=window_hanning, noverlap=128, pad_to=None,
+ sides='default'):
"""
Compute a spectrogram of data in *x*. Data are split into *NFFT*
length segements and the PSD of each section is computed. The
windowing function *window* is applied to each segment, and the
amount of overlap of each segment is specified with *noverlap*.
- *window* can be a function or a vector of length *NFFT*. To create
- window vectors see :func:`numpy.blackman`, :func:`numpy.hamming`,
- :func:`numpy.bartlett`, :func:`scipy.signal`,
- :func:`scipy.signal.get_window` etc.
-
- If *x* is real (i.e. non-complex) only the positive spectrum is
- given. If *x* is complex then the complete spectrum is given.
-
+ If *x* is real (i.e. non-complex) only the spectrum of the positive
+ frequencie is returned. If *x* is complex then the complete
+ spectrum is returned.
+ %(PSD)s
Returns a tuple (*Pxx*, *freqs*, *t*):
- *Pxx*: 2-D array, columns are the periodograms of
@@ -444,56 +453,21 @@
the mean of the segment periodograms; and in not returning
times.
"""
- x = np.asarray(x)
- assert(NFFT>noverlap)
- #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')
+ assert(NFFT > noverlap)
+ Pxx, freqs, t = _spectral_helper(x, x, NFFT, Fs, detrend, window,
+ noverlap, pad_to, sides)
+ Pxx = Pxx.real #Needed since helper implements generically
- # zero pad x up to NFFT if it is shorter than NFFT
- if len(x)<NFFT:
- n = len(x)
- x = np.resize(x, (NFFT,))
- x[n:] = 0
-
-
- # for real x, ignore the negative frequencies
- if np.iscomplexobj(x):
- numFreqs=NFFT
- else:
- numFreqs = NFFT//2+1
-
- if cbook.iterable(window):
- assert(len(window) == NFFT)
- windowVals = np.asarray(window)
- else:
- windowVals = window(np.ones((NFFT,),x.dtype))
- step = NFFT-noverlap
- ind = np.arange(0,len(x)-NFFT+1,step)
- n = len(ind)
- 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 = 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 /= (np.abs(windowVals)**2).sum()
- t = 1/Fs*(ind+NFFT/2)
- freqs = Fs/NFFT*np.arange(numFreqs)
-
- if np.iscomplexobj(x):
+ if (np.iscomplexobj(x) and sides == 'default') or sides == 'twosided':
# center the frequency range at zero
freqs = np.concatenate((freqs[NFFT/2:]-Fs,freqs[:NFFT/2]))
Pxx = np.concatenate((Pxx[NFFT/2:,:],Pxx[:NFFT/2,:]),0)
return Pxx, freqs, t
+specgram.__doc__ = specgram.__doc__ % kwdocd
+
_coh_error = """Coherence is calculated by averaging over *NFFT*
length segments. Your signal is too short for your choice of *NFFT*.
"""
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ry...@us...> - 2008-11-11 22:02:38
|
Revision: 6398
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6398&view=rev
Author: ryanmay
Date: 2008-11-11 22:02:34 +0000 (Tue, 11 Nov 2008)
Log Message:
-----------
Update module docstring to include specgram().
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/mlab.py
Modified: trunk/matplotlib/lib/matplotlib/mlab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mlab.py 2008-11-11 21:45:15 UTC (rev 6397)
+++ trunk/matplotlib/lib/matplotlib/mlab.py 2008-11-11 22:02:34 UTC (rev 6398)
@@ -35,6 +35,8 @@
:func:`rk4`
A 4th order runge kutta integrator for 1D or ND systems
+:func:`specgram`
+ Spectrogram (power spectral density over segments of time)
Miscellaneous functions
-------------------------
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ry...@us...> - 2008-11-11 21:45:19
|
Revision: 6397
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6397&view=rev
Author: ryanmay
Date: 2008-11-11 21:45:15 +0000 (Tue, 11 Nov 2008)
Log Message:
-----------
Update specgram() to use the new keyword arguments and clean up docstring.
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/axes.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-11-11 21:32:29 UTC (rev 6396)
+++ trunk/matplotlib/CHANGELOG 2008-11-11 21:45:15 UTC (rev 6397)
@@ -1,7 +1,8 @@
-2008-11-11 Update the psd(), csd(), and cohere() methods of Axes
- and the csd() and cohere() functions in mlab to be in
- sync with the changes to psd(). In fact, under the
- hood, mlab.psd() now calls mlab.csd(). - RM
+2008-11-11 Update the psd(), csd(), cohere(), and specgram() methods
+ of Axes and the csd() cohere(), and specgram() functions
+ in mlab to be in sync with the changes to psd().
+ In fact, under the hood, these all call the same core
+ to do computations. - RM
2008-11-11 Add 'pad_to' and 'sides' parameters to mlab.psd() to
allow controlling of zero padding and returning of
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2008-11-11 21:32:29 UTC (rev 6396)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2008-11-11 21:45:15 UTC (rev 6397)
@@ -6719,17 +6719,16 @@
return cxy, freqs
cohere.__doc__ = cbook.dedent(cohere.__doc__) % psd_doc_dict
- del psd_doc_dict #So that this does not become an Axes attribute
def specgram(self, x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=128,
- cmap = None, xextent=None):
+ cmap=None, xextent=None, pad_to=None, sides='default'):
"""
call signature::
specgram(x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
- window = mlab.window_hanning, noverlap=128,
- cmap=None, xextent=None)
+ window=mlab.window_hanning, noverlap=128,
+ cmap=None, xextent=None, pad_to=None, sides='default')
Compute a spectrogram of data in *x*. Data are split into
*NFFT* length segments and the PSD of each section is
@@ -6737,16 +6736,22 @@
segment, and the amount of overlap of each segment is
specified with *noverlap*.
- Keyword arguments:
+ %(PSD)s
+ *Fc*: integer
+ The center frequency of *x* (defaults to 0), which offsets
+ the y extents of the plot to reflect the frequency range used
+ when a signal is acquired and then filtered and downsampled to
+ baseband.
+
*cmap*:
A :class:`matplotlib.cm.Colormap` instance; if *None* use
default determined by rc
*xextent*:
- The image extent in the xaxes xextent=xmin, xmax
- default 0, max(bins), 0, max(freqs) where bins is the return
- value from mlab.specgram
+ The image extent along the x-axis. xextent = (xmin,xmax)
+ The default is (0,max(bins)), where bins is the return
+ value from :func:`mlab.specgram`
Return value is (*Pxx*, *freqs*, *bins*, *im*):
@@ -6757,21 +6762,21 @@
Note: If *x* is real (i.e. non-complex), only the positive
spectrum is shown. If *x* is complex, both positive and
- negative parts of the spectrum are shown.
+ negative parts of the spectrum are shown. This can be
+ overridden using the *sides* keyword argument.
- .. seealso:
- :meth:`psd`
- For a description of the optional parameters.
+ **Example:**
+
+ .. plot:: mpl_examples/pylab_examples/specgram_demo.py
"""
if not self._hold: self.cla()
Pxx, freqs, bins = mlab.specgram(x, NFFT, Fs, detrend,
- window, noverlap)
+ window, noverlap, pad_to, sides)
+ Z = 10. * np.log10(Pxx)
+ Z = np.flipud(Z)
- Z = 10*np.log10(Pxx)
- Z = np.flipud(Z)
-
if xextent is None: xextent = 0, np.amax(bins)
xmin, xmax = xextent
freqs += Fc
@@ -6780,6 +6785,8 @@
self.axis('auto')
return Pxx, freqs, bins, im
+ specgram.__doc__ = cbook.dedent(specgram.__doc__) % psd_doc_dict
+ del psd_doc_dict #So that this does not become an Axes attribute
def spy(self, Z, precision=0, marker=None, markersize=None,
aspect='equal', **kwargs):
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ry...@us...> - 2008-11-11 20:34:29
|
Revision: 6395
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6395&view=rev
Author: ryanmay
Date: 2008-11-11 20:34:25 +0000 (Tue, 11 Nov 2008)
Log Message:
-----------
Update cohere() in mlab and Axes method to match new psd() and csd() parameters. Update docs.
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/axes.py
trunk/matplotlib/lib/matplotlib/mlab.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-11-11 20:20:27 UTC (rev 6394)
+++ trunk/matplotlib/CHANGELOG 2008-11-11 20:34:25 UTC (rev 6395)
@@ -1,15 +1,8 @@
-2008-11-11 Update the axes.csd() to match the new options added to
- mlab.csd(). Move some of the docs from axes.psd() to
- the common place in mlab. - RM
+2008-11-11 Update the psd(), csd(), and cohere() methods of Axes
+ and the csd() and cohere() functions in mlab to be in
+ sync with the changes to psd(). In fact, under the
+ hood, mlab.psd() now calls mlab.csd(). - RM
-2008-11-11 Update the mlab.csd() to match the new options added to
- mlab.psd(). Factor out the keyword argument docs so that
- they can be shared between the two functions. - RM
-
-2008-11-11 Update the axes.psd() method to reflect the new options
- available in mlab.psd. Add an example to show how the
- options change things. - RM
-
2008-11-11 Add 'pad_to' and 'sides' parameters to mlab.psd() to
allow controlling of zero padding and returning of
negative frequency components, respecitively. These are
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2008-11-11 20:20:27 UTC (rev 6394)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2008-11-11 20:34:25 UTC (rev 6395)
@@ -6663,15 +6663,16 @@
return pxy, freqs
csd.__doc__ = cbook.dedent(csd.__doc__) % psd_doc_dict
- del psd_doc_dict #So that this does not become an Axes attribute
def cohere(self, x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
- window=mlab.window_hanning, noverlap=0, **kwargs):
+ window=mlab.window_hanning, noverlap=0, pad_to=None,
+ sides='default', **kwargs):
"""
call signature::
cohere(x, y, NFFT=256, Fs=2, Fc=0, detrend = mlab.detrend_none,
- window = mlab.window_hanning, noverlap=0, **kwargs)
+ window = mlab.window_hanning, noverlap=0, pad_to=None,
+ sides='default', **kwargs)
cohere the coherence between *x* and *y*. Coherence is the normalized
cross spectral density:
@@ -6680,6 +6681,14 @@
C_{xy} = \\frac{|P_{xy}|^2}{P_{xx}P_{yy}}
+ %(PSD)s
+
+ *Fc*: integer
+ The center frequency of *x* (defaults to 0), which offsets
+ the x extents of the plot to reflect the frequency range used
+ when a signal is acquired and then filtered and downsampled to
+ baseband.
+
The return value is a tuple (*Cxy*, *f*), where *f* are the
frequencies of the coherence vector.
@@ -6698,10 +6707,6 @@
**Example:**
.. plot:: mpl_examples/pylab_examples/cohere_demo.py
-
- .. seealso:
- :meth:`psd`
- For a description of the optional parameters.
"""
if not self._hold: self.cla()
cxy, freqs = mlab.cohere(x, y, NFFT, Fs, detrend, window, noverlap)
@@ -6713,7 +6718,8 @@
self.grid(True)
return cxy, freqs
- cohere.__doc__ = cbook.dedent(cohere.__doc__) % martist.kwdocd
+ cohere.__doc__ = cbook.dedent(cohere.__doc__) % psd_doc_dict
+ del psd_doc_dict #So that this does not become an Axes attribute
def specgram(self, x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=128,
Modified: trunk/matplotlib/lib/matplotlib/mlab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mlab.py 2008-11-11 20:20:27 UTC (rev 6394)
+++ trunk/matplotlib/lib/matplotlib/mlab.py 2008-11-11 20:34:25 UTC (rev 6395)
@@ -313,7 +313,7 @@
Specifies which sides of the PSD to return. Default gives the
default behavior, which returns one-sided for real data and both
for complex data. 'one' forces the return of a one-sided PSD, while
- 'both' forces two-sided.
+ 'both' forces two-sided.
"""
psd.__doc__ = psd.__doc__ % kwdocd
@@ -494,13 +494,11 @@
return Pxx, freqs, t
-
-
_coh_error = """Coherence is calculated by averaging over *NFFT*
length segments. Your signal is too short for your choice of *NFFT*.
"""
def cohere(x, y, NFFT=256, Fs=2, detrend=detrend_none,
- window=window_hanning, noverlap=0):
+ window=window_hanning, noverlap=0, pad_to=None, sides='default'):
"""
The coherence between *x* and *y*. Coherence is the normalized
cross spectral density:
@@ -509,27 +507,30 @@
C_{xy} = \\frac{|P_{xy}|^2}{P_{xx}P_{yy}}
+ *x*, *y*
+ Array or sequence containing the data
+ %(PSD)s
The return value is the tuple (*Cxy*, *f*), where *f* are the
frequencies of the coherence vector.
.. seealso::
:func:`psd` and :func:`csd`:
- For information about the function arguments *NFFT*,
- *detrend*, *window*, *noverlap*, as well as the methods
- used to compute :math:`P_{xy}`, :math:`P_{xx}` and
- :math:`P_{yy}`.
+ For information about the methods used to compute
+ :math:`P_{xy}`, :math:`P_{xx}` and :math:`P_{yy}`.
"""
if len(x)<2*NFFT:
raise ValueError(_coh_error)
- Pxx, f = psd(x, NFFT, Fs, detrend, window, noverlap)
- Pyy, f = psd(y, NFFT, Fs, detrend, window, noverlap)
- Pxy, f = csd(x, y, NFFT, Fs, detrend, window, noverlap)
+ Pxx, f = psd(x, NFFT, Fs, detrend, window, noverlap, pad_to, sides)
+ Pyy, f = psd(y, NFFT, Fs, detrend, window, noverlap, pad_to, sides)
+ Pxy, f = csd(x, y, NFFT, Fs, detrend, window, noverlap, pad_to, sides)
Cxy = np.divide(np.absolute(Pxy)**2, Pxx*Pyy)
Cxy.shape = (len(f),)
return Cxy, f
+cohere.__doc__ = cohere.__doc__ % kwdocd
+
def corrcoef(*args):
"""
corrcoef(*X*) where *X* is a matrix returns a matrix of correlation
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ry...@us...> - 2008-11-11 20:20:30
|
Revision: 6394
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6394&view=rev
Author: ryanmay
Date: 2008-11-11 20:20:27 +0000 (Tue, 11 Nov 2008)
Log Message:
-----------
Make mlab.psd() call mlab.csd() instead of duplicating 95% of the code. Tweak csd() to check if x and y are the same and avoid duplicating the work if so.
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/mlab.py
Modified: trunk/matplotlib/lib/matplotlib/mlab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mlab.py 2008-11-11 19:28:38 UTC (rev 6393)
+++ trunk/matplotlib/lib/matplotlib/mlab.py 2008-11-11 20:20:27 UTC (rev 6394)
@@ -259,54 +259,8 @@
Bendat & Piersol -- Random Data: Analysis and Measurement
Procedures, John Wiley & Sons (1986)
"""
- x = np.asarray(x) # make sure we're dealing with a numpy array
+ return csd(x, x, NFFT, Fs, detrend, window, noverlap, pad_to, sides)
- # zero pad x up to NFFT if it is shorter than NFFT
- if len(x)<NFFT:
- n = len(x)
- x = np.resize(x, (NFFT,)) # Can't use resize method.
- x[n:] = 0
-
- if pad_to is None:
- pad_to = NFFT
-
- # For real x, ignore the negative frequencies unless told otherwise
- if (sides == 'default' and np.iscomplexobj(x)) or sides == 'twosided':
- numFreqs = pad_to
- elif sides in ('default', 'onesided'):
- numFreqs = pad_to//2 + 1
- else:
- raise ValueError("sides must be one of: 'default', 'onesided', or "
- "'twosided'")
-
- if cbook.iterable(window):
- assert(len(window) == NFFT)
- windowVals = window
- else:
- windowVals = window(np.ones((NFFT,), x.dtype))
-
- step = NFFT - noverlap
- ind = range(0, len(x) - NFFT + 1, step)
- n = len(ind)
- 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 = np.absolute(np.fft.fft(thisX, n=pad_to))**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 /= (np.abs(windowVals)**2).sum()
-
- freqs = float(Fs) / pad_to * np.arange(numFreqs)
-
- return Pxx, freqs
-
#Split out these keyword docs so that they can be used elsewhere
kwdocd = dict()
kwdocd['PSD'] ="""
@@ -387,15 +341,24 @@
Procedures, John Wiley & Sons (1986)
"""
- 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
+ #The checks for if y is x are so that we can use csd() to implement
+ #psd() without doing extra work.
+
+ #Make sure we're dealing with a numpy array. If y and x were the same
+ #object to start with, keep them that way
+ do_psd = y is x
+ x = np.asarray(x)
+ if not do_psd:
+ y = np.asarray(y)
+
# zero pad x and y up to NFFT if they are shorter than NFFT
if len(x)<NFFT:
n = len(x)
x = np.resize(x, (NFFT,))
x[n:] = 0
- if len(y)<NFFT:
+
+ if not do_psd and len(y)<NFFT:
n = len(y)
y = np.resize(y, (NFFT,))
y[n:] = 0
@@ -427,10 +390,14 @@
for i in range(n):
thisX = x[ind[i]:ind[i]+NFFT]
thisX = windowVals * detrend(thisX)
- thisY = y[ind[i]:ind[i]+NFFT]
- thisY = windowVals * detrend(thisY)
fx = np.fft.fft(thisX, n=pad_to)
- fy = np.fft.fft(thisY, n=pad_to)
+
+ if do_psd:
+ fy = fx
+ else:
+ thisY = y[ind[i]:ind[i]+NFFT]
+ thisY = windowVals * detrend(thisY)
+ fy = np.fft.fft(thisY, n=pad_to)
Pxy[:,i] = np.conjugate(fx[:numFreqs]) * fy[:numFreqs]
# Scale the spectrum by the norm of the window to compensate for
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ry...@us...> - 2008-11-11 19:28:41
|
Revision: 6393
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6393&view=rev
Author: ryanmay
Date: 2008-11-11 19:28:38 +0000 (Tue, 11 Nov 2008)
Log Message:
-----------
Update the axes.csd() to match the new options added to mlab.csd(). Move some of the docs from axes.psd() to the common place in mlab.
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/axes.py
trunk/matplotlib/lib/matplotlib/mlab.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-11-11 18:42:11 UTC (rev 6392)
+++ trunk/matplotlib/CHANGELOG 2008-11-11 19:28:38 UTC (rev 6393)
@@ -1,3 +1,7 @@
+2008-11-11 Update the axes.csd() to match the new options added to
+ mlab.csd(). Move some of the docs from axes.psd() to
+ the common place in mlab. - RM
+
2008-11-11 Update the mlab.csd() to match the new options added to
mlab.psd(). Factor out the keyword argument docs so that
they can be shared between the two functions. - RM
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2008-11-11 18:42:11 UTC (rev 6392)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2008-11-11 19:28:38 UTC (rev 6393)
@@ -6531,9 +6531,10 @@
call signature::
psd(x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
- window=mlab.window_hanning, noverlap=0, **kwargs)
+ window=mlab.window_hanning, noverlap=0, pad_to=None,
+ sides='default', **kwargs)
- The power spectral density by Welches average periodogram
+ The power spectral density by Welch's average periodogram
method. The vector *x* is divided into *NFFT* length
segments. Each segment is detrended by function *detrend* and
windowed by function *window*. *noverlap* gives the length of
@@ -6542,41 +6543,14 @@
scaling to correct for power loss due to windowing. *Fs* is the
sampling frequency.
- Keyword arguments:
+ %(PSD)s
- *NFFT*: integer
- The length of the fft segment, must be a power of 2
-
- *Fs*: integer
- The sampling frequency.
-
*Fc*: integer
The center frequency of *x* (defaults to 0), which offsets
the x extents of the plot to reflect the frequency range used
when a signal is acquired and then filtered and downsampled to
baseband.
- *detrend*:
- The function applied to each segment before fft-ing,
- designed to remove the mean or linear trend. Unlike in
- matlab, where the *detrend* parameter is a vector, in
- matplotlib is it a function. The :mod:`~matplotlib.pylab`
- module defines :func:`~matplotlib.pylab.detrend_none`,
- :func:`~matplotlib.pylab.detrend_mean`, and
- :func:`~matplotlib.pylab.detrend_linear`, but you can use
- a custom function as well.
-
- *window*:
- The function used to window the segments. *window* is a
- function, unlike in matlab where it is a vector.
- :mod:`~matplotlib.pylab` defines
- :func:`~matplotlib.pylab.window_none`, and
- :func:`~matplotlib.pylab.window_hanning`, but you can use
- a custom function as well.
-
- *noverlap*: integer
- Gives the length of the overlap between segments.
-
Returns the tuple (*Pxx*, *freqs*).
For plotting, the power is plotted as
@@ -6615,17 +6589,24 @@
self.set_yticks(ticks)
return pxx, freqs
- psd.__doc__ = cbook.dedent(psd.__doc__) % martist.kwdocd
+ psd_doc_dict = dict()
+ psd_doc_dict.update(martist.kwdocd)
+ psd_doc_dict.update(mlab.kwdocd)
+ psd_doc_dict['PSD'] = cbook.dedent(psd_doc_dict['PSD'])
+ psd.__doc__ = cbook.dedent(psd.__doc__) % psd_doc_dict
+
def csd(self, x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
- window=mlab.window_hanning, noverlap=0, **kwargs):
+ window=mlab.window_hanning, noverlap=0, pad_to=None,
+ sides='default', **kwargs):
"""
call signature::
csd(x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
- window=window_hanning, noverlap=0, **kwargs)
+ window=mlab.window_hanning, noverlap=0, pad_to=None,
+ sides='default', **kwargs)
- The cross spectral density :math:`P_{xy}` by Welches average
+ The cross spectral density :math:`P_{xy}` by Welch's average
periodogram method. The vectors *x* and *y* are divided into
*NFFT* length segments. Each segment is detrended by function
*detrend* and windowed by function *window*. The product of
@@ -6637,6 +6618,14 @@
(complex valued), and :math:`10\log_{10}|P_{xy}|` is
plotted.
+ %(PSD)s
+
+ *Fc*: integer
+ The center frequency of *x* (defaults to 0), which offsets
+ the x extents of the plot to reflect the frequency range used
+ when a signal is acquired and then filtered and downsampled to
+ baseband.
+
References:
Bendat & Piersol -- Random Data: Analysis and Measurement
Procedures, John Wiley & Sons (1986)
@@ -6654,7 +6643,8 @@
For a description of the optional parameters.
"""
if not self._hold: self.cla()
- pxy, freqs = mlab.csd(x, y, NFFT, Fs, detrend, window, noverlap)
+ pxy, freqs = mlab.csd(x, y, NFFT, Fs, detrend, window, noverlap,
+ pad_to, sides)
pxy.shape = len(freqs),
# pxy is complex
freqs += Fc
@@ -6672,7 +6662,8 @@
self.set_yticks(ticks)
return pxy, freqs
- csd.__doc__ = cbook.dedent(csd.__doc__) % martist.kwdocd
+ csd.__doc__ = cbook.dedent(csd.__doc__) % psd_doc_dict
+ del psd_doc_dict #So that this does not become an Axes attribute
def cohere(self, x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=0, **kwargs):
Modified: trunk/matplotlib/lib/matplotlib/mlab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mlab.py 2008-11-11 18:42:11 UTC (rev 6392)
+++ trunk/matplotlib/lib/matplotlib/mlab.py 2008-11-11 19:28:38 UTC (rev 6393)
@@ -310,48 +310,55 @@
#Split out these keyword docs so that they can be used elsewhere
kwdocd = dict()
kwdocd['PSD'] ="""
- *NFFT*
- The number of data points used in each block for the FFT.
- Must be even; a power 2 is most efficient. The default value is 256.
+ Keyword arguments:
- *Fs*
- The sampling frequency (samples per time unit). It is used
- to calculate the Fourier frequencies, freqs, in cycles per time
- unit. The default value is 2.
+ *NFFT*: integer
+ The number of data points used in each block for the FFT.
+ Must be even; a power 2 is most efficient. The default value is 256.
- *detrend*
- Any callable function (unlike in matlab where it is a vector).
- For examples, see :func:`detrend`, :func:`detrend_none`, and
- :func:`detrend_mean`. The default is :func:`detrend_none`.
+ *Fs*: scalar
+ The sampling frequency (samples per time unit). It is used
+ to calculate the Fourier frequencies, freqs, in cycles per time
+ unit. The default value is 2.
- *window*
- A function or a vector of length *NFFT*. To create window
- vectors see :func:`window_hanning`, :func:`window_none`,
- :func:`numpy.blackman`, :func:`numpy.hamming`,
- :func:`numpy.bartlett`, :func:`scipy.signal`,
- :func:`scipy.signal.get_window`, etc. The default is
- :func:`window_hanning`. If a function is passed as the
- argument, it must take a data segment as an argument and
- return the windowed version of the segment.
+ *detrend*: callable
+ The function applied to each segment before fft-ing,
+ designed to remove the mean or linear trend. Unlike in
+ matlab, where the *detrend* parameter is a vector, in
+ matplotlib is it a function. The :mod:`~matplotlib.pylab`
+ module defines :func:`~matplotlib.pylab.detrend_none`,
+ :func:`~matplotlib.pylab.detrend_mean`, and
+ :func:`~matplotlib.pylab.detrend_linear`, but you can use
+ a custom function as well.
- *noverlap*
- The number of points of overlap between blocks. The default value
- is 0 (no overlap).
+ *window*: callable or ndarray
+ A function or a vector of length *NFFT*. To create window
+ vectors see :func:`window_hanning`, :func:`window_none`,
+ :func:`numpy.blackman`, :func:`numpy.hamming`,
+ :func:`numpy.bartlett`, :func:`scipy.signal`,
+ :func:`scipy.signal.get_window`, etc. The default is
+ :func:`window_hanning`. If a function is passed as the
+ argument, it must take a data segment as an argument and
+ return the windowed version of the segment.
- *pad_to*
- The number of points to which the data segment is padd when
- performing the FFT. This can be different from *NFFT*, which
- specifies the number of data points used. While not increasing
- the actual resolution of the psd (the minimum distance between
- resolvable peaks), this can give more points in the plot,
- allowing for more detail. This corresponds to the *n* parameter
- in the call to fft(). The default is None, which sets *pad_to*
- equal to *NFFT*
+ *noverlap*: integer
+ The number of points of overlap between blocks. The default value
+ is 0 (no overlap).
- *sides* [ 'default' | 'onesided' | 'twosided' ]
- Specifies which sides of the PSD to return. Default gives the
- default behavior, which returns one-sided for real data and both
- for complex data. 'one' forces the return of a one-sided PSD, while
+ *pad_to*: integer
+ The number of points to which the data segment is padd when
+ performing the FFT. This can be different from *NFFT*, which
+ specifies the number of data points used. While not increasing
+ the actual resolution of the psd (the minimum distance between
+ resolvable peaks), this can give more points in the plot,
+ allowing for more detail. This corresponds to the *n* parameter
+ in the call to fft(). The default is None, which sets *pad_to*
+ equal to *NFFT*
+
+ *sides*: [ 'default' | 'onesided' | 'twosided' ]
+ Specifies which sides of the PSD to return. Default gives the
+ default behavior, which returns one-sided for real data and both
+ for complex data. 'one' forces the return of a one-sided PSD, while
'both' forces two-sided.
"""
psd.__doc__ = psd.__doc__ % kwdocd
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ry...@us...> - 2008-11-11 18:42:16
|
Revision: 6392
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6392&view=rev
Author: ryanmay
Date: 2008-11-11 18:42:11 +0000 (Tue, 11 Nov 2008)
Log Message:
-----------
Update the mlab.csd() to match the new options added to mlab.psd(). Factor out the keyword argument docs so that they can be shared between the two functions.
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/mlab.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-11-11 18:39:46 UTC (rev 6391)
+++ trunk/matplotlib/CHANGELOG 2008-11-11 18:42:11 UTC (rev 6392)
@@ -1,3 +1,7 @@
+2008-11-11 Update the mlab.csd() to match the new options added to
+ mlab.psd(). Factor out the keyword argument docs so that
+ they can be shared between the two functions. - RM
+
2008-11-11 Update the axes.psd() method to reflect the new options
available in mlab.psd. Add an example to show how the
options change things. - RM
Modified: trunk/matplotlib/lib/matplotlib/mlab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mlab.py 2008-11-11 18:39:46 UTC (rev 6391)
+++ trunk/matplotlib/lib/matplotlib/mlab.py 2008-11-11 18:42:11 UTC (rev 6392)
@@ -252,51 +252,7 @@
*x*
Array or sequence containing the data
-
- *NFFT*
- The number of data points used in each block for the FFT.
- Must be even; a power 2 is most efficient. The default value is 256.
-
- *Fs*
- The sampling frequency (samples per time unit). It is used
- to calculate the Fourier frequencies, freqs, in cycles per time
- unit. The default value is 2.
-
- *detrend*
- Any callable function (unlike in matlab where it is a vector).
- For examples, see :func:`detrend`, :func:`detrend_none`, and
- :func:`detrend_mean`. The default is :func:`detrend_none`.
-
- *window*
- A function or a vector of length *NFFT*. To create window
- vectors see :func:`window_hanning`, :func:`window_none`,
- :func:`numpy.blackman`, :func:`numpy.hamming`,
- :func:`numpy.bartlett`, :func:`scipy.signal`,
- :func:`scipy.signal.get_window`, etc. The default is
- :func:`window_hanning`. If a function is passed as the
- argument, it must take a data segment as an argument and
- return the windowed version of the segment.
-
- *noverlap*
- The number of points of overlap between blocks. The default value
- is 0 (no overlap).
-
- *pad_to*
- The number of points to which the data segment is padd when
- performing the FFT. This can be different from *NFFT*, which
- specifies the number of data points used. While not increasing
- the actual resolution of the psd (the minimum distance between
- resolvable peaks), this can give more points in the plot,
- allowing for more detail. This corresponds to the *n* parameter
- in the call to fft(). The default is None, which sets *pad_to*
- equal to *NFFT*
-
- *sides* [ 'default' | 'onesided' | 'twosided' ]
- Specifies which sides of the PSD to return. Default gives the
- default behavior, which returns one-sided for real data and both
- for complex data. 'one' forces the return of a one-sided PSD, while
- 'both' forces two-sided.
-
+ %(PSD)s
Returns the tuple (*Pxx*, *freqs*).
Refs:
@@ -314,14 +270,14 @@
if pad_to is None:
pad_to = NFFT
- # for real x, ignore the negative frequencies
+ # For real x, ignore the negative frequencies unless told otherwise
if (sides == 'default' and np.iscomplexobj(x)) or sides == 'twosided':
numFreqs = pad_to
elif sides in ('default', 'onesided'):
numFreqs = pad_to//2 + 1
else:
raise ValueError("sides must be one of: 'default', 'onesided', or "
- "twosided")
+ "'twosided'")
if cbook.iterable(window):
assert(len(window) == NFFT)
@@ -351,23 +307,9 @@
return Pxx, freqs
-def csd(x, y, NFFT=256, Fs=2, detrend=detrend_none,
- window=window_hanning, noverlap=0):
- """
- The cross power spectral density by Welch's average periodogram
- method. The vectors *x* and *y* are divided into *NFFT* length
- blocks. Each block is detrended by the function *detrend* and
- windowed by the function *window*. *noverlap* gives the length
- of the overlap between blocks. The product of the direct FFTs
- of *x* and *y* are averaged over each segment to compute *Pxy*,
- with a scaling to correct for power loss due to windowing.
-
- If len(*x*) < *NFFT* or len(*y*) < *NFFT*, they will be zero
- padded to *NFFT*.
-
- *x*, *y*
- Array or sequence containing the data
-
+#Split out these keyword docs so that they can be used elsewhere
+kwdocd = dict()
+kwdocd['PSD'] ="""
*NFFT*
The number of data points used in each block for the FFT.
Must be even; a power 2 is most efficient. The default value is 256.
@@ -388,12 +330,49 @@
:func:`numpy.blackman`, :func:`numpy.hamming`,
:func:`numpy.bartlett`, :func:`scipy.signal`,
:func:`scipy.signal.get_window`, etc. The default is
- :func:`window_hanning`.
+ :func:`window_hanning`. If a function is passed as the
+ argument, it must take a data segment as an argument and
+ return the windowed version of the segment.
*noverlap*
The number of points of overlap between blocks. The default value
is 0 (no overlap).
+ *pad_to*
+ The number of points to which the data segment is padd when
+ performing the FFT. This can be different from *NFFT*, which
+ specifies the number of data points used. While not increasing
+ the actual resolution of the psd (the minimum distance between
+ resolvable peaks), this can give more points in the plot,
+ allowing for more detail. This corresponds to the *n* parameter
+ in the call to fft(). The default is None, which sets *pad_to*
+ equal to *NFFT*
+
+ *sides* [ 'default' | 'onesided' | 'twosided' ]
+ Specifies which sides of the PSD to return. Default gives the
+ default behavior, which returns one-sided for real data and both
+ for complex data. 'one' forces the return of a one-sided PSD, while
+ 'both' forces two-sided.
+"""
+psd.__doc__ = psd.__doc__ % kwdocd
+
+def csd(x, y, NFFT=256, Fs=2, detrend=detrend_none,
+ window=window_hanning, noverlap=0, pad_to=None, sides='default'):
+ """
+ The cross power spectral density by Welch's average periodogram
+ method. The vectors *x* and *y* are divided into *NFFT* length
+ blocks. Each block is detrended by the function *detrend* and
+ windowed by the function *window*. *noverlap* gives the length
+ of the overlap between blocks. The product of the direct FFTs
+ of *x* and *y* are averaged over each segment to compute *Pxy*,
+ with a scaling to correct for power loss due to windowing.
+
+ If len(*x*) < *NFFT* or len(*y*) < *NFFT*, they will be zero
+ padded to *NFFT*.
+
+ *x*, *y*
+ Array or sequence containing the data
+ %(PSD)s
Returns the tuple (*Pxy*, *freqs*).
Refs:
@@ -401,9 +380,6 @@
Procedures, John Wiley & Sons (1986)
"""
- if NFFT % 2:
- raise ValueError, 'NFFT must be even'
-
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
@@ -417,40 +393,50 @@
y = np.resize(y, (NFFT,))
y[n:] = 0
- # for real x, ignore the negative frequencies
- if np.iscomplexobj(x): numFreqs = NFFT
- else: numFreqs = NFFT//2+1
+ if pad_to is None:
+ pad_to = NFFT
+ # For real x, ignore the negative frequencies unless told otherwise
+ if (sides == 'default' and np.iscomplexobj(x)) or sides == 'twosided':
+ numFreqs = pad_to
+ elif sides in ('default', 'onesided'):
+ numFreqs = pad_to//2 + 1
+ else:
+ raise ValueError("sides must be one of: 'default', 'onesided', or "
+ "'twosided'")
+
if cbook.iterable(window):
assert(len(window) == NFFT)
windowVals = window
else:
windowVals = window(np.ones((NFFT,), x.dtype))
- step = NFFT-noverlap
- ind = range(0,len(x)-NFFT+1,step)
+
+ step = NFFT - noverlap
+ ind = range(0, len(x) - NFFT + 1, step)
n = len(ind)
Pxy = np.zeros((numFreqs,n), np.complex_)
# do the ffts of the slices
for i in range(n):
thisX = x[ind[i]:ind[i]+NFFT]
- thisX = windowVals*detrend(thisX)
+ thisX = windowVals * detrend(thisX)
thisY = y[ind[i]:ind[i]+NFFT]
- thisY = windowVals*detrend(thisY)
- fx = np.fft.fft(thisX)
- fy = np.fft.fft(thisY)
- Pxy[:,i] = np.conjugate(fx[:numFreqs])*fy[:numFreqs]
+ thisY = windowVals * detrend(thisY)
+ fx = np.fft.fft(thisX, n=pad_to)
+ fy = np.fft.fft(thisY, n=pad_to)
+ Pxy[:,i] = np.conjugate(fx[:numFreqs]) * fy[:numFreqs]
-
-
# Scale the spectrum by the norm of the window to compensate for
# windowing loss; see Bendat & Piersol Sec 11.5.2
if n>1:
Pxy = Pxy.mean(axis=1)
+
Pxy /= (np.abs(windowVals)**2).sum()
- freqs = Fs/NFFT*np.arange(numFreqs)
+ freqs = float(Fs) / pad_to * np.arange(numFreqs)
return Pxy, freqs
+csd.__doc__ = csd.__doc__ % kwdocd
+
def specgram(x, NFFT=256, Fs=2, detrend=detrend_none,
window=window_hanning, noverlap=128):
"""
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ry...@us...> - 2008-11-11 18:39:52
|
Revision: 6391
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6391&view=rev
Author: ryanmay
Date: 2008-11-11 18:39:46 +0000 (Tue, 11 Nov 2008)
Log Message:
-----------
Slight whitespace cleanup.
Modified Paths:
--------------
trunk/matplotlib/examples/pylab_examples/psd_demo2.py
Modified: trunk/matplotlib/examples/pylab_examples/psd_demo2.py
===================================================================
--- trunk/matplotlib/examples/pylab_examples/psd_demo2.py 2008-11-11 17:56:07 UTC (rev 6390)
+++ trunk/matplotlib/examples/pylab_examples/psd_demo2.py 2008-11-11 18:39:46 UTC (rev 6391)
@@ -31,9 +31,9 @@
#Plot the PSD with different amounts of overlap between blocks
ax4 = fig.add_subplot(2, 3, 6, sharex=ax2, sharey=ax2)
-ax4.psd(y,NFFT=len(t)//2, pad_to=len(t), noverlap=0, Fs=fs)
-ax4.psd(y,NFFT=len(t)//2, pad_to=len(t), noverlap=int(0.05*len(t)/2.), Fs=fs)
-ax4.psd(y,NFFT=len(t)//2, pad_to=len(t), noverlap=int(0.2*len(t)/2.), Fs=fs)
+ax4.psd(y, NFFT=len(t)//2, pad_to=len(t), noverlap=0, Fs=fs)
+ax4.psd(y, NFFT=len(t)//2, pad_to=len(t), noverlap=int(0.05*len(t)/2.), Fs=fs)
+ax4.psd(y, NFFT=len(t)//2, pad_to=len(t), noverlap=int(0.2*len(t)/2.), Fs=fs)
plt.title('Effect of overlap')
plt.show()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ry...@us...> - 2008-11-11 17:56:13
|
Revision: 6390
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6390&view=rev
Author: ryanmay
Date: 2008-11-11 17:56:07 +0000 (Tue, 11 Nov 2008)
Log Message:
-----------
Update the axes.psd() method to reflect the new options available in mlab.psd. Add an example to show how the options change things.
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/axes.py
Added Paths:
-----------
trunk/matplotlib/examples/pylab_examples/psd_demo2.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-11-11 16:30:03 UTC (rev 6389)
+++ trunk/matplotlib/CHANGELOG 2008-11-11 17:56:07 UTC (rev 6390)
@@ -1,3 +1,7 @@
+2008-11-11 Update the axes.psd() method to reflect the new options
+ available in mlab.psd. Add an example to show how the
+ options change things. - RM
+
2008-11-11 Add 'pad_to' and 'sides' parameters to mlab.psd() to
allow controlling of zero padding and returning of
negative frequency components, respecitively. These are
Added: trunk/matplotlib/examples/pylab_examples/psd_demo2.py
===================================================================
--- trunk/matplotlib/examples/pylab_examples/psd_demo2.py (rev 0)
+++ trunk/matplotlib/examples/pylab_examples/psd_demo2.py 2008-11-11 17:56:07 UTC (rev 6390)
@@ -0,0 +1,39 @@
+#This example shows the effects of some of the different PSD parameters
+import numpy as np
+import matplotlib.pyplot as plt
+
+dt = np.pi / 100.
+fs = 1. / dt
+t = np.arange(0, 8, dt)
+y = 10. * np.sin(2 * np.pi * 4 * t) + 5. * np.sin(2 * np.pi * 4.25 * t)
+y = y + np.random.randn(*t.shape)
+
+#Plot the raw time series
+fig = plt.figure()
+ax = fig.add_subplot(2, 1, 1)
+ax.plot(t, y)
+
+#Plot the PSD with different amounts of zero padding. This uses the entire
+#time series at once
+ax2 = fig.add_subplot(2, 3, 4)
+ax2.psd(y, NFFT=len(t), pad_to=len(t), Fs=fs)
+ax2.psd(y, NFFT=len(t), pad_to=len(t)*2, Fs=fs)
+ax2.psd(y, NFFT=len(t), pad_to=len(t)*4, Fs=fs)
+plt.title('Effect of zero padding')
+
+#Plot the PSD with different block sizes, Zero pad to the length of the orignal
+#data sequence.
+ax3 = fig.add_subplot(2, 3, 5, sharex=ax2, sharey=ax2)
+ax3.psd(y, NFFT=len(t), pad_to=len(t), Fs=fs)
+ax3.psd(y, NFFT=len(t)//2, pad_to=len(t), Fs=fs)
+ax3.psd(y, NFFT=len(t)//4, pad_to=len(t), Fs=fs)
+plt.title('Effect of block size')
+
+#Plot the PSD with different amounts of overlap between blocks
+ax4 = fig.add_subplot(2, 3, 6, sharex=ax2, sharey=ax2)
+ax4.psd(y,NFFT=len(t)//2, pad_to=len(t), noverlap=0, Fs=fs)
+ax4.psd(y,NFFT=len(t)//2, pad_to=len(t), noverlap=int(0.05*len(t)/2.), Fs=fs)
+ax4.psd(y,NFFT=len(t)//2, pad_to=len(t), noverlap=int(0.2*len(t)/2.), Fs=fs)
+plt.title('Effect of overlap')
+
+plt.show()
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2008-11-11 16:30:03 UTC (rev 6389)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2008-11-11 17:56:07 UTC (rev 6390)
@@ -6525,7 +6525,8 @@
hist.__doc__ = cbook.dedent(hist.__doc__) % martist.kwdocd
def psd(self, x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
- window=mlab.window_hanning, noverlap=0, **kwargs):
+ window=mlab.window_hanning, noverlap=0, pad_to=None,
+ sides='default', **kwargs):
"""
call signature::
@@ -6595,7 +6596,8 @@
.. plot:: mpl_examples/pylab_examples/psd_demo.py
"""
if not self._hold: self.cla()
- pxx, freqs = mlab.psd(x, NFFT, Fs, detrend, window, noverlap)
+ pxx, freqs = mlab.psd(x, NFFT, Fs, detrend, window, noverlap, pad_to,
+ sides)
pxx.shape = len(freqs),
freqs += Fc
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ry...@us...> - 2008-11-11 16:30:08
|
Revision: 6389
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6389&view=rev
Author: ryanmay
Date: 2008-11-11 16:30:03 +0000 (Tue, 11 Nov 2008)
Log Message:
-----------
Add 'pad_to' and 'sides' parameters to mlab.psd() to allow controlling of zero padding and returning of negative frequency components, respecitively. These are added in a way that does not change the API.
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/mlab.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-11-11 08:04:24 UTC (rev 6388)
+++ trunk/matplotlib/CHANGELOG 2008-11-11 16:30:03 UTC (rev 6389)
@@ -1,3 +1,8 @@
+2008-11-11 Add 'pad_to' and 'sides' parameters to mlab.psd() to
+ allow controlling of zero padding and returning of
+ negative frequency components, respecitively. These are
+ added in a way that does not change the API. - RM
+
2008-11-10 Fix handling of c kwarg by scatter; generalize
is_string_like to accept numpy and numpy.ma string
array scalars. - RM and EF
Modified: trunk/matplotlib/lib/matplotlib/mlab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mlab.py 2008-11-11 08:04:24 UTC (rev 6388)
+++ trunk/matplotlib/lib/matplotlib/mlab.py 2008-11-11 16:30:03 UTC (rev 6389)
@@ -239,7 +239,7 @@
return y - (b*x + a)
def psd(x, NFFT=256, Fs=2, detrend=detrend_none,
- window=window_hanning, noverlap=0):
+ window=window_hanning, noverlap=0, pad_to=None, sides='default'):
"""
The power spectral density by Welch's average periodogram method.
The vector *x* is divided into *NFFT* length blocks. Each block
@@ -273,22 +273,36 @@
:func:`numpy.blackman`, :func:`numpy.hamming`,
:func:`numpy.bartlett`, :func:`scipy.signal`,
:func:`scipy.signal.get_window`, etc. The default is
- :func:`window_hanning`.
+ :func:`window_hanning`. If a function is passed as the
+ argument, it must take a data segment as an argument and
+ return the windowed version of the segment.
*noverlap*
The number of points of overlap between blocks. The default value
is 0 (no overlap).
+ *pad_to*
+ The number of points to which the data segment is padd when
+ performing the FFT. This can be different from *NFFT*, which
+ specifies the number of data points used. While not increasing
+ the actual resolution of the psd (the minimum distance between
+ resolvable peaks), this can give more points in the plot,
+ allowing for more detail. This corresponds to the *n* parameter
+ in the call to fft(). The default is None, which sets *pad_to*
+ equal to *NFFT*
+
+ *sides* [ 'default' | 'onesided' | 'twosided' ]
+ Specifies which sides of the PSD to return. Default gives the
+ default behavior, which returns one-sided for real data and both
+ for complex data. 'one' forces the return of a one-sided PSD, while
+ 'both' forces two-sided.
+
Returns the tuple (*Pxx*, *freqs*).
Refs:
Bendat & Piersol -- Random Data: Analysis and Measurement
Procedures, John Wiley & Sons (1986)
"""
- # I think we could remove this condition without hurting anything.
- if NFFT % 2:
- raise ValueError('NFFT must be even')
-
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
@@ -297,24 +311,34 @@
x = np.resize(x, (NFFT,)) # Can't use resize method.
x[n:] = 0
+ if pad_to is None:
+ pad_to = NFFT
+
# for real x, ignore the negative frequencies
- if np.iscomplexobj(x): numFreqs = NFFT
- else: numFreqs = NFFT//2+1
+ if (sides == 'default' and np.iscomplexobj(x)) or sides == 'twosided':
+ numFreqs = pad_to
+ elif sides in ('default', 'onesided'):
+ numFreqs = pad_to//2 + 1
+ else:
+ raise ValueError("sides must be one of: 'default', 'onesided', or "
+ "twosided")
if cbook.iterable(window):
assert(len(window) == NFFT)
windowVals = window
else:
- windowVals = window(np.ones((NFFT,),x.dtype))
- step = NFFT-noverlap
- ind = range(0,len(x)-NFFT+1,step)
+ windowVals = window(np.ones((NFFT,), x.dtype))
+
+ step = NFFT - noverlap
+ ind = range(0, len(x) - NFFT + 1, step)
n = len(ind)
Pxx = np.zeros((numFreqs,n), np.float_)
- # do the ffts of the slices
+
+ # do the FFTs of the slices
for i in range(n):
thisX = x[ind[i]:ind[i]+NFFT]
thisX = windowVals * detrend(thisX)
- fx = np.absolute(np.fft.fft(thisX))**2
+ fx = np.absolute(np.fft.fft(thisX, n=pad_to))**2
Pxx[:,i] = fx[:numFreqs]
if n>1:
@@ -323,7 +347,7 @@
# windowing loss; see Bendat & Piersol Sec 11.5.2
Pxx /= (np.abs(windowVals)**2).sum()
- freqs = Fs/NFFT * np.arange(numFreqs)
+ freqs = float(Fs) / pad_to * np.arange(numFreqs)
return Pxx, freqs
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2008-11-11 08:04:30
|
Revision: 6388
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6388&view=rev
Author: efiring
Date: 2008-11-11 08:04:24 +0000 (Tue, 11 Nov 2008)
Log Message:
-----------
Fix autoscaling problem caused by axhline and axvline
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/axes.py
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2008-11-11 06:52:52 UTC (rev 6387)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2008-11-11 08:04:24 UTC (rev 6388)
@@ -1312,7 +1312,8 @@
self._set_artist_props(line)
line.set_clip_path(self.patch)
- self._update_line_limits(line)
+ if line.get_transform() == self.transData:
+ self._update_line_limits(line)
if not line.get_label():
line.set_label('_line%d'%len(self.lines))
self.lines.append(line)
@@ -2774,7 +2775,11 @@
trans = mtransforms.blended_transform_factory(
self.transAxes, self.transData)
- l, = self.plot([xmin,xmax], [y,y], transform=trans, scalex=False, scaley=scaley, **kwargs)
+ l = mlines.Line2D([xmin,xmax], [y,y], transform=trans, **kwargs)
+ self.add_line(l)
+ self.dataLim.y0 = min(self.dataLim.y0, yy)
+ self.dataLim.y1 = max(self.dataLim.y1, yy)
+ self.autoscale_view(scalex=False, scaley=scaley)
return l
@@ -2830,7 +2835,11 @@
trans = mtransforms.blended_transform_factory(
self.transData, self.transAxes)
- l, = self.plot([x,x], [ymin,ymax] , transform=trans, scalex=scalex, scaley=False, **kwargs)
+ l = mlines.Line2D([x,x], [ymin,ymax] , transform=trans, **kwargs)
+ self.add_line(l)
+ self.dataLim.x0 = min(self.dataLim.x0, xx)
+ self.dataLim.x1 = max(self.dataLim.x1, xx)
+ self.autoscale_view(scalex=scalex, scaley=False)
return l
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|