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: <md...@us...> - 2010-06-24 18:25:23
|
Revision: 8465
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8465&view=rev
Author: mdboom
Date: 2010-06-24 18:25:16 +0000 (Thu, 24 Jun 2010)
Log Message:
-----------
[3018198] Fixing the build with clang
Typo in agg causes a template instantiation bug on compilers that actually instantiate everything.
Modified Paths:
--------------
trunk/matplotlib/agg24/include/agg_scanline_u.h
Modified: trunk/matplotlib/agg24/include/agg_scanline_u.h
===================================================================
--- trunk/matplotlib/agg24/include/agg_scanline_u.h 2010-06-24 17:59:48 UTC (rev 8464)
+++ trunk/matplotlib/agg24/include/agg_scanline_u.h 2010-06-24 18:25:16 UTC (rev 8465)
@@ -2,8 +2,8 @@
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
-// Permission to copy, use, modify, sell and distribute this software
-// is granted provided this copyright notice appears in all copies.
+// Permission to copy, use, modify, sell and distribute this software
+// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
@@ -13,12 +13,12 @@
// http://www.antigrain.com
//----------------------------------------------------------------------------
//
-// Adaptation for 32-bit screen coordinates (scanline32_u) has been sponsored by
+// Adaptation for 32-bit screen coordinates (scanline32_u) has been sponsored by
// Liberty Technology Systems, Inc., visit http://lib-sys.com
//
// Liberty Technology Systems, Inc. is the provider of
// PostScript and PDF technology for software developers.
-//
+//
//----------------------------------------------------------------------------
#ifndef AGG_SCANLINE_U_INCLUDED
@@ -32,22 +32,22 @@
//
// Unpacked scanline container class
//
- // This class is used to transfer data from a scanline rasterizer
- // to the rendering buffer. It's organized very simple. The class stores
- // information of horizontal spans to render it into a pixel-map buffer.
- // Each span has staring X, length, and an array of bytes that determine the
- // cover-values for each pixel.
- // Before using this class you should know the minimal and maximal pixel
+ // This class is used to transfer data from a scanline rasterizer
+ // to the rendering buffer. It's organized very simple. The class stores
+ // information of horizontal spans to render it into a pixel-map buffer.
+ // Each span has staring X, length, and an array of bytes that determine the
+ // cover-values for each pixel.
+ // Before using this class you should know the minimal and maximal pixel
// coordinates of your scanline. The protocol of using is:
// 1. reset(min_x, max_x)
- // 2. add_cell() / add_span() - accumulate scanline.
+ // 2. add_cell() / add_span() - accumulate scanline.
// When forming one scanline the next X coordinate must be always greater
// than the last stored one, i.e. it works only with ordered coordinates.
// 3. Call finalize(y) and render the scanline.
// 3. Call reset_spans() to prepare for the new scanline.
- //
+ //
// 4. Rendering:
- //
+ //
// Scanline provides an iterator class that allows you to extract
// the spans and the cover values for each pixel. Be aware that clipping
// has not been done yet, so you should perform it yourself.
@@ -61,10 +61,10 @@
// ************************************
//
// scanline_u8::const_iterator span = sl.begin();
- //
- // unsigned char* row = m_rbuf->row(y); // The the address of the beginning
+ //
+ // unsigned char* row = m_rbuf->row(y); // The the address of the beginning
// // of the current row
- //
+ //
// unsigned num_spans = sl.num_spans(); // Number of spans. It's guaranteed that
// // num_spans is always greater than 0.
//
@@ -75,7 +75,7 @@
//
// int num_pix = span->len; // Number of pixels of the span.
// // Always greater than 0, still it's
- // // better to use "int" instead of
+ // // better to use "int" instead of
// // "unsigned" because it's more
// // convenient for clipping
// int x = span->x;
@@ -86,24 +86,24 @@
// **************************************
//
// unsigned char* dst = row + x; // Calculate the start address of the row.
- // // In this case we assume a simple
+ // // In this case we assume a simple
// // grayscale image 1-byte per pixel.
// do
// {
- // *dst++ = *covers++; // Hypotetical rendering.
+ // *dst++ = *covers++; // Hypotetical rendering.
// }
// while(--num_pix);
//
// ++span;
- // }
+ // }
// while(--num_spans); // num_spans cannot be 0, so this loop is quite safe
//------------------------------------------------------------------------
//
// The question is: why should we accumulate the whole scanline when we
// could render just separate spans when they're ready?
- // That's because using the scanline is generally faster. When is consists
+ // That's because using the scanline is generally faster. When is consists
// of more than one span the conditions for the processor cash system
- // are better, because switching between two different areas of memory
+ // are better, because switching between two different areas of memory
// (that can be very large) occurs less frequently.
//------------------------------------------------------------------------
class scanline_u8
@@ -203,9 +203,9 @@
}
//--------------------------------------------------------------------
- void finalize(int y)
- {
- m_y = y;
+ void finalize(int y)
+ {
+ m_y = y;
}
//--------------------------------------------------------------------
@@ -238,11 +238,11 @@
//==========================================================scanline_u8_am
- //
+ //
// The scanline container with alpha-masking
- //
+ //
//------------------------------------------------------------------------
- template<class AlphaMask>
+ template<class AlphaMask>
class scanline_u8_am : public scanline_u8
{
public:
@@ -264,9 +264,9 @@
unsigned count = base_type::num_spans();
do
{
- m_alpha_mask->combine_hspan(span->x,
- base_type::y(),
- span->covers,
+ m_alpha_mask->combine_hspan(span->x,
+ base_type::y(),
+ span->covers,
span->len);
++span;
}
@@ -390,8 +390,8 @@
}
else
{
- m_spans.add(span(coord_type(x + m_min_x),
- coord_type(len),
+ m_spans.add(span(coord_type(x + m_min_x),
+ coord_type(len),
&m_covers[x]));
}
m_last_x = x + len - 1;
@@ -408,17 +408,17 @@
}
else
{
- m_spans.add(span(coord_type(x + m_min_x),
- coord_type(len),
+ m_spans.add(span(coord_type(x + m_min_x),
+ coord_type(len),
&m_covers[x]));
}
m_last_x = x + len - 1;
}
//--------------------------------------------------------------------
- void finalize(int y)
- {
- m_y = y;
+ void finalize(int y)
+ {
+ m_y = y;
}
//--------------------------------------------------------------------
@@ -450,15 +450,15 @@
//========================================================scanline32_u8_am
- //
+ //
// The scanline container with alpha-masking
- //
+ //
//------------------------------------------------------------------------
- template<class AlphaMask>
+ template<class AlphaMask>
class scanline32_u8_am : public scanline32_u8
{
public:
- typedef scanline_u8 base_type;
+ typedef scanline32_u8 base_type;
typedef AlphaMask alpha_mask_type;
typedef base_type::cover_type cover_type;
typedef base_type::coord_type coord_type;
@@ -477,9 +477,9 @@
unsigned count = base_type::num_spans();
do
{
- m_alpha_mask->combine_hspan(span->x,
- base_type::y(),
- span->covers,
+ m_alpha_mask->combine_hspan(span->x,
+ base_type::y(),
+ span->covers,
span->len);
++span;
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2010-06-24 17:59:55
|
Revision: 8464
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8464&view=rev
Author: mdboom
Date: 2010-06-24 17:59:48 +0000 (Thu, 24 Jun 2010)
Log Message:
-----------
Speed up Gouraud shading in Agg backend.
Modified Paths:
--------------
trunk/matplotlib/src/_backend_agg.cpp
trunk/matplotlib/src/_backend_agg.h
Modified: trunk/matplotlib/src/_backend_agg.cpp
===================================================================
--- trunk/matplotlib/src/_backend_agg.cpp 2010-06-24 17:12:26 UTC (rev 8463)
+++ trunk/matplotlib/src/_backend_agg.cpp 2010-06-24 17:59:48 UTC (rev 8464)
@@ -1824,19 +1824,15 @@
}
void
-RendererAgg::_draw_gouraud_triangle(const GCAgg& gc, const double* points,
+RendererAgg::_draw_gouraud_triangle(const double* points,
const double* colors,
- agg::trans_affine trans)
+ agg::trans_affine trans,
+ bool has_clippath)
{
typedef agg::rgba8 color_t;
typedef agg::span_gouraud_rgba<color_t> span_gen_t;
typedef agg::span_allocator<color_t> span_alloc_t;
- theRasterizer.reset_clipping();
- rendererBase.reset_clipping(true);
- set_clipbox(gc.cliprect, theRasterizer);
- bool has_clippath = render_clippath(gc.clippath, gc.clippath_trans);
-
trans *= agg::trans_affine_scaling(1.0, -1.0);
trans *= agg::trans_affine_translation(0.0, (double)height);
@@ -1897,6 +1893,11 @@
PyArrayObject* points = NULL;
PyArrayObject* colors = NULL;
+ theRasterizer.reset_clipping();
+ rendererBase.reset_clipping(true);
+ set_clipbox(gc.cliprect, theRasterizer);
+ bool has_clippath = render_clippath(gc.clippath, gc.clippath_trans);
+
try
{
points = (PyArrayObject*)PyArray_ContiguousFromAny
@@ -1916,7 +1917,8 @@
}
_draw_gouraud_triangle(
- gc, (double*)PyArray_DATA(points), (double*)PyArray_DATA(colors), trans);
+ (double*)PyArray_DATA(points), (double*)PyArray_DATA(colors),
+ trans, has_clippath);
}
catch (...)
{
@@ -1951,6 +1953,11 @@
PyArrayObject* points = NULL;
PyArrayObject* colors = NULL;
+ theRasterizer.reset_clipping();
+ rendererBase.reset_clipping(true);
+ set_clipbox(gc.cliprect, theRasterizer);
+ bool has_clippath = render_clippath(gc.clippath, gc.clippath_trans);
+
try
{
points = (PyArrayObject*)PyArray_ContiguousFromAny
@@ -1976,7 +1983,9 @@
for (int i = 0; i < PyArray_DIM(points, 0); ++i)
{
- _draw_gouraud_triangle(gc, (double*)PyArray_GETPTR1(points, i), (double*)PyArray_GETPTR1(colors, i), trans);
+ _draw_gouraud_triangle(
+ (double*)PyArray_GETPTR1(points, i),
+ (double*)PyArray_GETPTR1(colors, i), trans, has_clippath);
}
}
catch (...)
Modified: trunk/matplotlib/src/_backend_agg.h
===================================================================
--- trunk/matplotlib/src/_backend_agg.h 2010-06-24 17:12:26 UTC (rev 8463)
+++ trunk/matplotlib/src/_backend_agg.h 2010-06-24 17:59:48 UTC (rev 8464)
@@ -263,8 +263,8 @@
void
_draw_gouraud_triangle(
- const GCAgg& gc,
- const double* points, const double* colors, agg::trans_affine trans);
+ const double* points, const double* colors,
+ agg::trans_affine trans, bool has_clippath);
private:
void create_alpha_buffers();
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2010-06-24 17:12:32
|
Revision: 8463
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8463&view=rev
Author: mdboom
Date: 2010-06-24 17:12:26 +0000 (Thu, 24 Jun 2010)
Log Message:
-----------
Clipping to the figure rectangle doesn't work on curves, so turn it off in that case.
Modified Paths:
--------------
trunk/matplotlib/src/_backend_agg.cpp
Modified: trunk/matplotlib/src/_backend_agg.cpp
===================================================================
--- trunk/matplotlib/src/_backend_agg.cpp 2010-06-24 17:05:49 UTC (rev 8462)
+++ trunk/matplotlib/src/_backend_agg.cpp 2010-06-24 17:12:26 UTC (rev 8463)
@@ -1304,7 +1304,7 @@
trans *= agg::trans_affine_scaling(1.0, -1.0);
trans *= agg::trans_affine_translation(0.0, (double)height);
- bool clip = !face.first && gc.hatchpath.isNone();
+ bool clip = !face.first && gc.hatchpath.isNone() && !path.has_curves();
bool simplify = path.should_simplify() && clip;
transformed_path_t tpath(path, trans);
@@ -1498,7 +1498,7 @@
}
}
- bool do_clip = !face.first && gc.hatchpath.isNone();
+ bool do_clip = !face.first && gc.hatchpath.isNone() && !has_curves;
if (check_snap)
{
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2010-06-24 17:05:55
|
Revision: 8462
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8462&view=rev
Author: mdboom
Date: 2010-06-24 17:05:49 +0000 (Thu, 24 Jun 2010)
Log Message:
-----------
Use the more standard term "pop" rather than "flush" for removing the next item from the queue.
Modified Paths:
--------------
trunk/matplotlib/src/path_converters.h
Modified: trunk/matplotlib/src/path_converters.h
===================================================================
--- trunk/matplotlib/src/path_converters.h 2010-06-24 14:48:00 UTC (rev 8461)
+++ trunk/matplotlib/src/path_converters.h 2010-06-24 17:05:49 UTC (rev 8462)
@@ -88,7 +88,7 @@
}
inline bool
- queue_flush(unsigned *cmd, double *x, double *y)
+ queue_pop(unsigned *cmd, double *x, double *y)
{
if (queue_nonempty())
{
@@ -159,7 +159,7 @@
if (m_has_curves)
{
/* This is the slow method for when there might be curves. */
- if (queue_flush(&code, x, y))
+ if (queue_pop(&code, x, y))
{
return code;
}
@@ -216,7 +216,7 @@
}
}
- if (queue_flush(&code, x, y))
+ if (queue_pop(&code, x, y))
{
return code;
}
@@ -567,7 +567,7 @@
the queue before proceeding to the main loop below.
-- Michael Droettboom */
- if (queue_flush(&cmd, x, y))
+ if (queue_pop(&cmd, x, y))
{
return cmd;
}
@@ -740,7 +740,7 @@
/* Return the first item in the queue, if any, otherwise
indicate that we're done. */
- if (queue_flush(&cmd, x, y))
+ if (queue_pop(&cmd, x, y))
{
return cmd;
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2010-06-24 14:48:06
|
Revision: 8461
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8461&view=rev
Author: mdboom
Date: 2010-06-24 14:48:00 +0000 (Thu, 24 Jun 2010)
Log Message:
-----------
[3020704] set_xlim() problem
Bug in PathClipper when vertices fall precisely on the clipping edge.
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/tests/test_simplification.py
trunk/matplotlib/src/path_converters.h
Added Paths:
-----------
trunk/matplotlib/lib/matplotlib/tests/baseline_images/test_simplification/clipper_edge.pdf
trunk/matplotlib/lib/matplotlib/tests/baseline_images/test_simplification/clipper_edge.png
trunk/matplotlib/lib/matplotlib/tests/baseline_images/test_simplification/clipper_edge.svg
Added: trunk/matplotlib/lib/matplotlib/tests/baseline_images/test_simplification/clipper_edge.pdf
===================================================================
(Binary files differ)
Property changes on: trunk/matplotlib/lib/matplotlib/tests/baseline_images/test_simplification/clipper_edge.pdf
___________________________________________________________________
Added: svn:mime-type
+ application/octet-stream
Added: trunk/matplotlib/lib/matplotlib/tests/baseline_images/test_simplification/clipper_edge.png
===================================================================
(Binary files differ)
Property changes on: trunk/matplotlib/lib/matplotlib/tests/baseline_images/test_simplification/clipper_edge.png
___________________________________________________________________
Added: svn:mime-type
+ application/octet-stream
Added: trunk/matplotlib/lib/matplotlib/tests/baseline_images/test_simplification/clipper_edge.svg
===================================================================
--- trunk/matplotlib/lib/matplotlib/tests/baseline_images/test_simplification/clipper_edge.svg (rev 0)
+++ trunk/matplotlib/lib/matplotlib/tests/baseline_images/test_simplification/clipper_edge.svg 2010-06-24 14:48:00 UTC (rev 8461)
@@ -0,0 +1,104 @@
+<?xml version="1.0" standalone="no"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
+ "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<!-- Created with matplotlib (http://matplotlib.sourceforge.net/) -->
+<svg width="144pt" height="72pt" viewBox="0 0 144 72"
+ xmlns="http://www.w3.org/2000/svg"
+ xmlns:xlink="http://www.w3.org/1999/xlink"
+ version="1.1"
+ id="svg1">
+<filter id="colorAdd"><feComposite in="SourceGraphic" in2="BackgroundImage" operator="arithmetic" k2="1" k3="1"/></filter>
+<g id="figure1">
+<g id="patch1">
+<path style="fill: #ffffff; stroke: #ffffff; stroke-width: 1.000000; stroke-linejoin: round; stroke-linecap: square; opacity: 1.000000" d="M0.000000 72.000000L144.000000 72.000000L144.000000 0.000000
+L0.000000 0.000000L0.000000 72.000000"/>
+</g>
+<g id="axes1">
+<g id="patch2">
+<path style="fill: #ffffff; opacity: 1.000000" d="M0.000000 72.000000L144.000000 72.000000L144.000000 0.000000
+L0.000000 0.000000L0.000000 72.000000"/>
+</g>
+<g id="line2d1">
+<defs>
+ <clipPath id="p7a7a30041bcd0eda414889f4295b8ec2">
+<rect x="0.000000" y="0.000000" width="144.000000" height="72.000000"/>
+ </clipPath>
+</defs><path style="fill: none; stroke: #0000ff; stroke-width: 1.000000; stroke-linejoin: round; stroke-linecap: square; opacity: 1.000000" clip-path="url(#p7a7a30041bcd0eda414889f4295b8ec2)" d="M-180.000000 72.000000L36.000000 72.000000L72.000000 14.400000
+L108.000000 72.000000L144.000000 0.000000"/>
+</g>
+<g id="matplotlib.axis1">
+<g id="xtick1">
+<g id="line2d2">
+<defs><path id="m30e32995789d870ad79a2e54c91cf9c6" d="M0.000000 0.000000L0.000000 -4.000000"/></defs>
+<g ><use style="fill: none; stroke: #000000; stroke-width: 0.500000; stroke-linejoin: round; stroke-linecap: butt; opacity: 1.000000" xlink:href="#m30e32995789d870ad79a2e54c91cf9c6" x="0.000000" y="72.000000"/>
+</g></g>
+</g>
+<g id="xtick2">
+<g id="line2d3">
+<g ><use style="fill: none; stroke: #000000; stroke-width: 0.500000; stroke-linejoin: round; stroke-linecap: butt; opacity: 1.000000" xlink:href="#m30e32995789d870ad79a2e54c91cf9c6" x="36.000000" y="72.000000"/>
+</g></g>
+</g>
+<g id="xtick3">
+<g id="line2d4">
+<g ><use style="fill: none; stroke: #000000; stroke-width: 0.500000; stroke-linejoin: round; stroke-linecap: butt; opacity: 1.000000" xlink:href="#m30e32995789d870ad79a2e54c91cf9c6" x="72.000000" y="72.000000"/>
+</g></g>
+</g>
+<g id="xtick4">
+<g id="line2d5">
+<g ><use style="fill: none; stroke: #000000; stroke-width: 0.500000; stroke-linejoin: round; stroke-linecap: butt; opacity: 1.000000" xlink:href="#m30e32995789d870ad79a2e54c91cf9c6" x="108.000000" y="72.000000"/>
+</g></g>
+</g>
+<g id="xtick5">
+<g id="line2d6">
+<g ><use style="fill: none; stroke: #000000; stroke-width: 0.500000; stroke-linejoin: round; stroke-linecap: butt; opacity: 1.000000" xlink:href="#m30e32995789d870ad79a2e54c91cf9c6" x="144.000000" y="72.000000"/>
+</g></g>
+</g>
+</g>
+<g id="matplotlib.axis2">
+<g id="ytick1">
+<g id="line2d7">
+<defs><path id="m3400efa6b1638b3fea9e19e898273957" d="M0.000000 0.000000L4.000000 0.000000"/></defs>
+<g ><use style="fill: none; stroke: #000000; stroke-width: 0.500000; stroke-linejoin: round; stroke-linecap: butt; opacity: 1.000000" xlink:href="#m3400efa6b1638b3fea9e19e898273957" x="0.000000" y="72.000000"/>
+</g></g>
+</g>
+<g id="ytick2">
+<g id="line2d8">
+<g ><use style="fill: none; stroke: #000000; stroke-width: 0.500000; stroke-linejoin: round; stroke-linecap: butt; opacity: 1.000000" xlink:href="#m3400efa6b1638b3fea9e19e898273957" x="0.000000" y="57.600000"/>
+</g></g>
+</g>
+<g id="ytick3">
+<g id="line2d9">
+<g ><use style="fill: none; stroke: #000000; stroke-width: 0.500000; stroke-linejoin: round; stroke-linecap: butt; opacity: 1.000000" xlink:href="#m3400efa6b1638b3fea9e19e898273957" x="0.000000" y="43.200000"/>
+</g></g>
+</g>
+<g id="ytick4">
+<g id="line2d10">
+<g ><use style="fill: none; stroke: #000000; stroke-width: 0.500000; stroke-linejoin: round; stroke-linecap: butt; opacity: 1.000000" xlink:href="#m3400efa6b1638b3fea9e19e898273957" x="0.000000" y="28.800000"/>
+</g></g>
+</g>
+<g id="ytick5">
+<g id="line2d11">
+<g ><use style="fill: none; stroke: #000000; stroke-width: 0.500000; stroke-linejoin: round; stroke-linecap: butt; opacity: 1.000000" xlink:href="#m3400efa6b1638b3fea9e19e898273957" x="0.000000" y="14.400000"/>
+</g></g>
+</g>
+<g id="ytick6">
+<g id="line2d12">
+<g ><use style="fill: none; stroke: #000000; stroke-width: 0.500000; stroke-linejoin: round; stroke-linecap: butt; opacity: 1.000000" xlink:href="#m3400efa6b1638b3fea9e19e898273957" x="0.000000" y="0.000000"/>
+</g></g>
+</g>
+</g>
+<g id="patch3">
+<path style="fill: none; stroke: #000000; stroke-width: 1.000000; stroke-linejoin: round; stroke-linecap: square; opacity: 1.000000" d="M0.000000 0.000000L144.000000 0.000000"/>
+</g>
+<g id="patch4">
+<path style="fill: none; stroke: #000000; stroke-width: 1.000000; stroke-linejoin: round; stroke-linecap: square; opacity: 1.000000" d="M144.000000 72.000000L144.000000 0.000000"/>
+</g>
+<g id="patch5">
+<path style="fill: none; stroke: #000000; stroke-width: 1.000000; stroke-linejoin: round; stroke-linecap: square; opacity: 1.000000" d="M0.000000 72.000000L144.000000 72.000000"/>
+</g>
+<g id="patch6">
+<path style="fill: none; stroke: #000000; stroke-width: 1.000000; stroke-linejoin: round; stroke-linecap: square; opacity: 1.000000" d="M0.000000 72.000000L0.000000 0.000000"/>
+</g>
+</g>
+</g>
+</svg>
Modified: trunk/matplotlib/lib/matplotlib/tests/test_simplification.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/tests/test_simplification.py 2010-06-24 13:06:03 UTC (rev 8460)
+++ trunk/matplotlib/lib/matplotlib/tests/test_simplification.py 2010-06-24 14:48:00 UTC (rev 8461)
@@ -186,7 +186,24 @@
else:
rcParams['path.simplify'] = True
+@image_comparison(baseline_images=['clipper_edge'])
+def test_clipper():
+ dat = (0, 1, 0, 2, 0, 3, 0, 4, 0, 5)
+ fig = plt.figure(figsize=(2, 1))
+ fig.subplots_adjust(left = 0, bottom = 0, wspace = 0, hspace = 0)
+ ax = fig.add_axes((0, 0, 1.0, 1.0), ylim = (0, 5), autoscale_on = False)
+ ax.plot(dat)
+ ax.xaxis.set_major_locator(plt.MultipleLocator(1))
+ ax.xaxis.set_major_formatter(plt.NullFormatter())
+ ax.yaxis.set_major_locator(plt.MultipleLocator(1))
+ ax.yaxis.set_major_formatter(plt.NullFormatter())
+ ax.xaxis.set_ticks_position('bottom')
+ ax.yaxis.set_ticks_position('left')
+
+ ax.set_xlim(5, 9)
+ fig.savefig('clipper_edge')
+
if __name__=='__main__':
import nose
nose.runmodule(argv=['-s','--with-doctest'], exit=False)
Modified: trunk/matplotlib/src/path_converters.h
===================================================================
--- trunk/matplotlib/src/path_converters.h 2010-06-24 13:06:03 UTC (rev 8460)
+++ trunk/matplotlib/src/path_converters.h 2010-06-24 14:48:00 UTC (rev 8461)
@@ -288,7 +288,7 @@
PathClipper(VertexSource& source, bool do_clipping,
double width, double height) :
m_source(&source), m_do_clipping(do_clipping),
- m_cliprect(0.0, 0.0, width, height), m_moveto(true),
+ m_cliprect(-1.0, -1.0, width + 1.0, height + 1.0), m_moveto(true),
m_has_next(false)
{
// empty
@@ -296,10 +296,13 @@
PathClipper(VertexSource& source, bool do_clipping,
const agg::rect_base<double>& rect) :
- m_source(&source), m_do_clipping(do_clipping),
- m_cliprect(rect), m_moveto(true), m_has_next(false)
+ m_source(&source), m_do_clipping(do_clipping),
+ m_cliprect(rect), m_moveto(true), m_has_next(false)
{
- // empty
+ m_cliprect.x1 -= 1.0;
+ m_cliprect.y1 -= 1.0;
+ m_cliprect.x2 += 1.0;
+ m_cliprect.y2 += 1.0;
}
inline void
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2010-06-24 13:06:10
|
Revision: 8460
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8460&view=rev
Author: mdboom
Date: 2010-06-24 13:06:03 +0000 (Thu, 24 Jun 2010)
Log Message:
-----------
Standardizing formatting of C/C++ code.
Modified Paths:
--------------
trunk/matplotlib/src/_backend_agg.cpp
trunk/matplotlib/src/_backend_agg.h
trunk/matplotlib/src/_gtkagg.cpp
trunk/matplotlib/src/_image.cpp
trunk/matplotlib/src/_image.h
trunk/matplotlib/src/_path.cpp
trunk/matplotlib/src/_png.cpp
trunk/matplotlib/src/_tkagg.cpp
trunk/matplotlib/src/_ttconv.cpp
trunk/matplotlib/src/_windowing.cpp
trunk/matplotlib/src/_wxagg.cpp
trunk/matplotlib/src/agg_py_path_iterator.h
trunk/matplotlib/src/ft2font.cpp
trunk/matplotlib/src/ft2font.h
trunk/matplotlib/src/mplutils.cpp
trunk/matplotlib/src/mplutils.h
trunk/matplotlib/src/path_cleanup.cpp
trunk/matplotlib/src/path_converters.h
Modified: trunk/matplotlib/src/_backend_agg.cpp
===================================================================
--- trunk/matplotlib/src/_backend_agg.cpp 2010-06-23 14:44:32 UTC (rev 8459)
+++ trunk/matplotlib/src/_backend_agg.cpp 2010-06-24 13:06:03 UTC (rev 8460)
@@ -54,57 +54,82 @@
/*
Convert dashes from the Python representation as nested sequences to
the C++ representation as a std::vector<std::pair<double, double> >
- (GCAgg::dash_t)
-*/
-void convert_dashes(const Py::Tuple& dashes, double dpi, GCAgg::dash_t& dashes_out,
- double& dashOffset_out) {
- if (dashes.length()!=2)
- throw Py::ValueError(Printf("Dash descriptor must be a length 2 tuple; found %d", dashes.length()).str());
+ (GCAgg::dash_t) */
+void
+convert_dashes(const Py::Tuple& dashes, double dpi,
+ GCAgg::dash_t& dashes_out, double& dashOffset_out)
+{
+ if (dashes.length() != 2)
+ {
+ throw Py::ValueError(
+ Printf("Dash descriptor must be a length 2 tuple; found %d",
+ dashes.length()).str()
+ );
+ }
- dashes_out.clear();
- dashOffset_out = 0.0;
- if (dashes[0].ptr() == Py_None)
- return;
+ dashes_out.clear();
+ dashOffset_out = 0.0;
+ if (dashes[0].ptr() == Py_None)
+ {
+ return;
+ }
- dashOffset_out = double(Py::Float(dashes[0])) * dpi/72.0;
+ dashOffset_out = double(Py::Float(dashes[0])) * dpi / 72.0;
- Py::SeqBase<Py::Object> dashSeq = dashes[1];
+ Py::SeqBase<Py::Object> dashSeq = dashes[1];
- size_t Ndash = dashSeq.length();
- if (Ndash % 2 != 0)
- throw Py::ValueError(Printf("Dash sequence must be an even length sequence; found %d", Ndash).str());
+ size_t Ndash = dashSeq.length();
+ if (Ndash % 2 != 0)
+ {
+ throw Py::ValueError(
+ Printf("Dash sequence must be an even length sequence; found %d", Ndash).str()
+ );
+ }
- dashes_out.clear();
- dashes_out.reserve(Ndash / 2);
+ dashes_out.clear();
+ dashes_out.reserve(Ndash / 2);
- double val0, val1;
- for (size_t i = 0; i < Ndash; i += 2) {
- val0 = double(Py::Float(dashSeq[i])) * dpi/72.0;
- val1 = double(Py::Float(dashSeq[i+1])) * dpi/72.0;
- dashes_out.push_back(std::make_pair(val0, val1));
- }
+ double val0, val1;
+ for (size_t i = 0; i < Ndash; i += 2)
+ {
+ val0 = double(Py::Float(dashSeq[i])) * dpi / 72.0;
+ val1 = double(Py::Float(dashSeq[i+1])) * dpi / 72.0;
+ dashes_out.push_back(std::make_pair(val0, val1));
+ }
}
-Py::Object BufferRegion::to_string(const Py::Tuple &args) {
- // owned=true to prevent memory leak
- return Py::String(PyString_FromStringAndSize((const char*)data, height*stride), true);
+
+Py::Object
+BufferRegion::to_string(const Py::Tuple &args)
+{
+ // owned=true to prevent memory leak
+ return Py::String(PyString_FromStringAndSize((const char*)data, height*stride), true);
}
-Py::Object BufferRegion::set_x(const Py::Tuple &args) {
+
+Py::Object
+BufferRegion::set_x(const Py::Tuple &args)
+{
args.verify_length(1);
- size_t x = Py::Int( args[0] );
+ size_t x = Py::Int(args[0]);
rect.x1 = x;
return Py::Object();
}
-Py::Object BufferRegion::set_y(const Py::Tuple &args) {
+
+Py::Object
+BufferRegion::set_y(const Py::Tuple &args)
+{
args.verify_length(1);
- size_t y = Py::Int( args[0] );
+ size_t y = Py::Int(args[0]);
rect.y1 = y;
return Py::Object();
}
-Py::Object BufferRegion::get_extents(const Py::Tuple &args) {
+
+Py::Object
+BufferRegion::get_extents(const Py::Tuple &args)
+{
args.verify_length(0);
Py::Tuple extents(4);
@@ -116,562 +141,673 @@
return extents;
}
-Py::Object BufferRegion::to_string_argb(const Py::Tuple &args) {
- // owned=true to prevent memory leak
- Py_ssize_t length;
- unsigned char* pix;
- unsigned char* begin;
- unsigned char* end;
- unsigned char tmp;
- size_t i, j;
- PyObject* str = PyString_FromStringAndSize((const char*)data, height*stride);
- if (PyString_AsStringAndSize(str, (char**)&begin, &length)) {
- throw Py::TypeError("Could not create memory for blit");
- }
+Py::Object
+BufferRegion::to_string_argb(const Py::Tuple &args)
+{
+ // owned=true to prevent memory leak
+ Py_ssize_t length;
+ unsigned char* pix;
+ unsigned char* begin;
+ unsigned char* end;
+ unsigned char tmp;
+ size_t i, j;
- pix = begin;
- end = begin + (height * stride);
- for (i = 0; i < (size_t)height; ++i) {
- pix = begin + i * stride;
- for (j = 0; j < (size_t)width; ++j) {
- // Convert rgba to argb
- tmp = pix[2];
- pix[2] = pix[0];
- pix[0] = tmp;
- pix += 4;
+ PyObject* str = PyString_FromStringAndSize(
+ (const char*)data, height * stride);
+ if (PyString_AsStringAndSize(str, (char**)&begin, &length))
+ {
+ throw Py::TypeError("Could not create memory for blit");
}
- }
- return Py::String(str, true);
+ pix = begin;
+ end = begin + (height * stride);
+ for (i = 0; i < (size_t)height; ++i)
+ {
+ pix = begin + i * stride;
+ for (j = 0; j < (size_t)width; ++j)
+ {
+ // Convert rgba to argb
+ tmp = pix[2];
+ pix[2] = pix[0];
+ pix[0] = tmp;
+ pix += 4;
+ }
+ }
+
+ return Py::String(str, true);
}
+
GCAgg::GCAgg(const Py::Object &gc, double dpi) :
- dpi(dpi), isaa(true), dashOffset(0.0)
+ dpi(dpi), isaa(true), dashOffset(0.0)
{
- _VERBOSE("GCAgg::GCAgg");
- linewidth = points_to_pixels ( gc.getAttr("_linewidth") ) ;
- alpha = Py::Float( gc.getAttr("_alpha") );
- color = get_color(gc);
- _set_antialiased(gc);
- _set_linecap(gc);
- _set_joinstyle(gc);
- _set_dashes(gc);
- _set_clip_rectangle(gc);
- _set_clip_path(gc);
- _set_snap(gc);
- _set_hatch_path(gc);
+ _VERBOSE("GCAgg::GCAgg");
+ linewidth = points_to_pixels(gc.getAttr("_linewidth")) ;
+ alpha = Py::Float(gc.getAttr("_alpha"));
+ color = get_color(gc);
+ _set_antialiased(gc);
+ _set_linecap(gc);
+ _set_joinstyle(gc);
+ _set_dashes(gc);
+ _set_clip_rectangle(gc);
+ _set_clip_path(gc);
+ _set_snap(gc);
+ _set_hatch_path(gc);
}
+
void
-GCAgg::_set_antialiased(const Py::Object& gc) {
- _VERBOSE("GCAgg::antialiased");
- isaa = Py::Int( gc.getAttr( "_antialiased") );
+GCAgg::_set_antialiased(const Py::Object& gc)
+{
+ _VERBOSE("GCAgg::antialiased");
+ isaa = Py::Int(gc.getAttr("_antialiased"));
}
+
agg::rgba
-GCAgg::get_color(const Py::Object& gc) {
- _VERBOSE("GCAgg::get_color");
- Py::Tuple rgb = Py::Tuple( gc.getAttr("_rgb") );
+GCAgg::get_color(const Py::Object& gc)
+{
+ _VERBOSE("GCAgg::get_color");
+ Py::Tuple rgb = Py::Tuple(gc.getAttr("_rgb"));
- double alpha = Py::Float( gc.getAttr("_alpha") );
+ double alpha = Py::Float(gc.getAttr("_alpha"));
- double r = Py::Float(rgb[0]);
- double g = Py::Float(rgb[1]);
- double b = Py::Float(rgb[2]);
- return agg::rgba(r, g, b, alpha);
+ double r = Py::Float(rgb[0]);
+ double g = Py::Float(rgb[1]);
+ double b = Py::Float(rgb[2]);
+ return agg::rgba(r, g, b, alpha);
}
+
double
-GCAgg::points_to_pixels( const Py::Object& points) {
- _VERBOSE("GCAgg::points_to_pixels");
- double p = Py::Float( points ) ;
- return p * dpi/72.0;
+GCAgg::points_to_pixels(const Py::Object& points)
+{
+ _VERBOSE("GCAgg::points_to_pixels");
+ double p = Py::Float(points) ;
+ return p * dpi / 72.0;
}
+
void
-GCAgg::_set_linecap(const Py::Object& gc) {
- _VERBOSE("GCAgg::_set_linecap");
+GCAgg::_set_linecap(const Py::Object& gc)
+{
+ _VERBOSE("GCAgg::_set_linecap");
- std::string capstyle = Py::String( gc.getAttr( "_capstyle" ) );
+ std::string capstyle = Py::String(gc.getAttr("_capstyle"));
- if (capstyle=="butt")
- cap = agg::butt_cap;
- else if (capstyle=="round")
- cap = agg::round_cap;
- else if(capstyle=="projecting")
- cap = agg::square_cap;
- else
- throw Py::ValueError(Printf("GC _capstyle attribute must be one of butt, round, projecting; found %s", capstyle.c_str()).str());
+ if (capstyle == "butt")
+ {
+ cap = agg::butt_cap;
+ }
+ else if (capstyle == "round")
+ {
+ cap = agg::round_cap;
+ }
+ else if (capstyle == "projecting")
+ {
+ cap = agg::square_cap;
+ }
+ else
+ {
+ throw Py::ValueError(Printf("GC _capstyle attribute must be one of butt, round, projecting; found %s", capstyle.c_str()).str());
+ }
}
+
void
-GCAgg::_set_joinstyle(const Py::Object& gc) {
- _VERBOSE("GCAgg::_set_joinstyle");
+GCAgg::_set_joinstyle(const Py::Object& gc)
+{
+ _VERBOSE("GCAgg::_set_joinstyle");
- std::string joinstyle = Py::String( gc.getAttr("_joinstyle") );
+ std::string joinstyle = Py::String(gc.getAttr("_joinstyle"));
- if (joinstyle == "miter")
- join = agg::miter_join_revert;
- else if (joinstyle == "round")
- join = agg::round_join;
- else if (joinstyle == "bevel")
- join = agg::bevel_join;
- else
- throw Py::ValueError(Printf("GC _joinstyle attribute must be one of butt, round, projecting; found %s", joinstyle.c_str()).str());
+ if (joinstyle == "miter")
+ {
+ join = agg::miter_join_revert;
+ }
+ else if (joinstyle == "round")
+ {
+ join = agg::round_join;
+ }
+ else if (joinstyle == "bevel")
+ {
+ join = agg::bevel_join;
+ }
+ else
+ {
+ throw Py::ValueError(Printf("GC _joinstyle attribute must be one of butt, round, projecting; found %s", joinstyle.c_str()).str());
+ }
}
+
void
-GCAgg::_set_dashes(const Py::Object& gc) {
- //return the dashOffset, dashes sequence tuple.
- _VERBOSE("GCAgg::_set_dashes");
+GCAgg::_set_dashes(const Py::Object& gc)
+{
+ //return the dashOffset, dashes sequence tuple.
+ _VERBOSE("GCAgg::_set_dashes");
- Py::Object dash_obj( gc.getAttr( "_dashes" ) );
- if (dash_obj.ptr() == Py_None) {
- dashes.clear();
- return;
- }
+ Py::Object dash_obj(gc.getAttr("_dashes"));
+ if (dash_obj.ptr() == Py_None)
+ {
+ dashes.clear();
+ return;
+ }
- convert_dashes(dash_obj, dpi, dashes, dashOffset);
+ convert_dashes(dash_obj, dpi, dashes, dashOffset);
}
+
void
-GCAgg::_set_clip_rectangle( const Py::Object& gc) {
- //set the clip rectangle from the gc
+GCAgg::_set_clip_rectangle(const Py::Object& gc)
+{
+ //set the clip rectangle from the gc
- _VERBOSE("GCAgg::_set_clip_rectangle");
+ _VERBOSE("GCAgg::_set_clip_rectangle");
- Py::Object o ( gc.getAttr( "_cliprect" ) );
- cliprect = o;
+ Py::Object o(gc.getAttr("_cliprect"));
+ cliprect = o;
}
+
void
-GCAgg::_set_clip_path( const Py::Object& gc) {
- //set the clip path from the gc
+GCAgg::_set_clip_path(const Py::Object& gc)
+{
+ //set the clip path from the gc
- _VERBOSE("GCAgg::_set_clip_path");
+ _VERBOSE("GCAgg::_set_clip_path");
- Py::Object method_obj = gc.getAttr("get_clip_path");
- Py::Callable method(method_obj);
- Py::Tuple path_and_transform = method.apply(Py::Tuple());
- if (path_and_transform[0].ptr() != Py_None) {
- clippath = path_and_transform[0];
- clippath_trans = py_to_agg_transformation_matrix(path_and_transform[1].ptr());
- }
+ Py::Object method_obj = gc.getAttr("get_clip_path");
+ Py::Callable method(method_obj);
+ Py::Tuple path_and_transform = method.apply(Py::Tuple());
+ if (path_and_transform[0].ptr() != Py_None)
+ {
+ clippath = path_and_transform[0];
+ clippath_trans = py_to_agg_transformation_matrix(path_and_transform[1].ptr());
+ }
}
+
void
-GCAgg::_set_snap( const Py::Object& gc) {
- //set the snap setting
+GCAgg::_set_snap(const Py::Object& gc)
+{
+ //set the snap setting
- _VERBOSE("GCAgg::_set_snap");
+ _VERBOSE("GCAgg::_set_snap");
- Py::Object method_obj = gc.getAttr("get_snap");
- Py::Callable method(method_obj);
- Py::Object py_snap = method.apply(Py::Tuple());
- if (py_snap.isNone()) {
- snap_mode = SNAP_AUTO;
- } else if (py_snap.isTrue()) {
- snap_mode = SNAP_TRUE;
- } else {
- snap_mode = SNAP_FALSE;
- }
+ Py::Object method_obj = gc.getAttr("get_snap");
+ Py::Callable method(method_obj);
+ Py::Object py_snap = method.apply(Py::Tuple());
+ if (py_snap.isNone())
+ {
+ snap_mode = SNAP_AUTO;
+ }
+ else if (py_snap.isTrue())
+ {
+ snap_mode = SNAP_TRUE;
+ }
+ else
+ {
+ snap_mode = SNAP_FALSE;
+ }
}
+
void
-GCAgg::_set_hatch_path( const Py::Object& gc) {
- _VERBOSE("GCAgg::_set_hatch_path");
+GCAgg::_set_hatch_path(const Py::Object& gc)
+{
+ _VERBOSE("GCAgg::_set_hatch_path");
- Py::Object method_obj = gc.getAttr("get_hatch_path");
- Py::Callable method(method_obj);
- hatchpath = method.apply(Py::Tuple());
+ Py::Object method_obj = gc.getAttr("get_hatch_path");
+ Py::Callable method(method_obj);
+ hatchpath = method.apply(Py::Tuple());
}
+
const size_t
RendererAgg::PIXELS_PER_INCH(96);
+
RendererAgg::RendererAgg(unsigned int width, unsigned int height, double dpi,
int debug) :
- width(width),
- height(height),
- dpi(dpi),
- NUMBYTES(width*height*4),
- pixBuffer(NULL),
- renderingBuffer(),
- alphaBuffer(NULL),
- alphaMaskRenderingBuffer(),
- alphaMask(alphaMaskRenderingBuffer),
- pixfmtAlphaMask(alphaMaskRenderingBuffer),
- rendererBaseAlphaMask(),
- rendererAlphaMask(),
- scanlineAlphaMask(),
- slineP8(),
- slineBin(),
- pixFmt(),
- rendererBase(),
- rendererAA(),
- rendererBin(),
- theRasterizer(),
- debug(debug)
+ width(width),
+ height(height),
+ dpi(dpi),
+ NUMBYTES(width*height*4),
+ pixBuffer(NULL),
+ renderingBuffer(),
+ alphaBuffer(NULL),
+ alphaMaskRenderingBuffer(),
+ alphaMask(alphaMaskRenderingBuffer),
+ pixfmtAlphaMask(alphaMaskRenderingBuffer),
+ rendererBaseAlphaMask(),
+ rendererAlphaMask(),
+ scanlineAlphaMask(),
+ slineP8(),
+ slineBin(),
+ pixFmt(),
+ rendererBase(),
+ rendererAA(),
+ rendererBin(),
+ theRasterizer(),
+ debug(debug)
{
- _VERBOSE("RendererAgg::RendererAgg");
- unsigned stride(width*4);
+ _VERBOSE("RendererAgg::RendererAgg");
+ unsigned stride(width*4);
- pixBuffer = new agg::int8u[NUMBYTES];
- renderingBuffer.attach(pixBuffer, width, height, stride);
- pixFmt.attach(renderingBuffer);
- rendererBase.attach(pixFmt);
- rendererBase.clear(agg::rgba(1, 1, 1, 0));
- rendererAA.attach(rendererBase);
- rendererBin.attach(rendererBase);
- hatchRenderingBuffer.attach(hatchBuffer, HATCH_SIZE, HATCH_SIZE, HATCH_SIZE*4);
+ pixBuffer = new agg::int8u[NUMBYTES];
+ renderingBuffer.attach(pixBuffer, width, height, stride);
+ pixFmt.attach(renderingBuffer);
+ rendererBase.attach(pixFmt);
+ rendererBase.clear(agg::rgba(1, 1, 1, 0));
+ rendererAA.attach(rendererBase);
+ rendererBin.attach(rendererBase);
+ hatchRenderingBuffer.attach(hatchBuffer, HATCH_SIZE, HATCH_SIZE,
+ HATCH_SIZE*4);
}
-void RendererAgg::create_alpha_buffers() {
- if (!alphaBuffer) {
- unsigned stride(width*4);
- alphaBuffer = new agg::int8u[NUMBYTES];
- alphaMaskRenderingBuffer.attach(alphaBuffer, width, height, stride);
- rendererBaseAlphaMask.attach(pixfmtAlphaMask);
- rendererAlphaMask.attach(rendererBaseAlphaMask);
- }
+
+void
+RendererAgg::create_alpha_buffers()
+{
+ if (!alphaBuffer)
+ {
+ unsigned stride(width*4);
+ alphaBuffer = new agg::int8u[NUMBYTES];
+ alphaMaskRenderingBuffer.attach(alphaBuffer, width, height, stride);
+ rendererBaseAlphaMask.attach(pixfmtAlphaMask);
+ rendererAlphaMask.attach(rendererBaseAlphaMask);
+ }
}
+
template<class R>
void
-RendererAgg::set_clipbox(const Py::Object& cliprect, R& rasterizer) {
- //set the clip rectangle from the gc
+RendererAgg::set_clipbox(const Py::Object& cliprect, R& rasterizer)
+{
+ //set the clip rectangle from the gc
- _VERBOSE("RendererAgg::set_clipbox");
+ _VERBOSE("RendererAgg::set_clipbox");
- double l, b, r, t;
- if (py_convert_bbox(cliprect.ptr(), l, b, r, t)) {
- rasterizer.clip_box(int(mpl_round(l)), height - int(mpl_round(b)),
- int(mpl_round(r)), height - int(mpl_round(t)));
- }
+ double l, b, r, t;
+ if (py_convert_bbox(cliprect.ptr(), l, b, r, t))
+ {
+ rasterizer.clip_box(int(mpl_round(l)), height - int(mpl_round(b)),
+ int(mpl_round(r)), height - int(mpl_round(t)));
+ }
- _VERBOSE("RendererAgg::set_clipbox done");
+ _VERBOSE("RendererAgg::set_clipbox done");
}
+
std::pair<bool, agg::rgba>
-RendererAgg::_get_rgba_face(const Py::Object& rgbFace, double alpha) {
- _VERBOSE("RendererAgg::_get_rgba_face");
- std::pair<bool, agg::rgba> face;
+RendererAgg::_get_rgba_face(const Py::Object& rgbFace, double alpha)
+{
+ _VERBOSE("RendererAgg::_get_rgba_face");
+ std::pair<bool, agg::rgba> face;
- if (rgbFace.ptr() == Py_None) {
- face.first = false;
- }
- else {
- face.first = true;
- Py::Tuple rgb = Py::Tuple(rgbFace);
- face.second = rgb_to_color(rgb, alpha);
- }
- return face;
+ if (rgbFace.ptr() == Py_None)
+ {
+ face.first = false;
+ }
+ else
+ {
+ face.first = true;
+ Py::Tuple rgb = Py::Tuple(rgbFace);
+ face.second = rgb_to_color(rgb, alpha);
+ }
+ return face;
}
+
Py::Object
-RendererAgg::copy_from_bbox(const Py::Tuple& args) {
- //copy region in bbox to buffer and return swig/agg buffer object
- args.verify_length(1);
+RendererAgg::copy_from_bbox(const Py::Tuple& args)
+{
+ //copy region in bbox to buffer and return swig/agg buffer object
+ args.verify_length(1);
- Py::Object box_obj = args[0];
- double l, b, r, t;
- if (!py_convert_bbox(box_obj.ptr(), l, b, r, t))
- throw Py::TypeError("Invalid bbox provided to copy_from_bbox");
+ Py::Object box_obj = args[0];
+ double l, b, r, t;
+ if (!py_convert_bbox(box_obj.ptr(), l, b, r, t))
+ {
+ throw Py::TypeError("Invalid bbox provided to copy_from_bbox");
+ }
- // std::cout << l << " " << b << " " << r << " " << t << " " << (height - (int)b) << " " << height - (int)t << std::endl;
- agg::rect_i rect((int)l, height - (int)t, (int)r, height - (int)b);
+ agg::rect_i rect((int)l, height - (int)t, (int)r, height - (int)b);
- BufferRegion* reg = NULL;
- try {
- reg = new BufferRegion(rect, true);
- } catch (...) {
- throw Py::MemoryError("RendererAgg::copy_from_bbox could not allocate memory for buffer");
- }
+ BufferRegion* reg = NULL;
+ try
+ {
+ reg = new BufferRegion(rect, true);
+ }
+ catch (...)
+ {
+ throw Py::MemoryError(
+ "RendererAgg::copy_from_bbox could not allocate memory for buffer");
+ }
- if (!reg) {
- throw Py::MemoryError("RendererAgg::copy_from_bbox could not allocate memory for buffer");
- }
+ if (!reg)
+ {
+ throw Py::MemoryError(
+ "RendererAgg::copy_from_bbox could not allocate memory for buffer");
+ }
- try {
- agg::rendering_buffer rbuf;
- rbuf.attach(reg->data, reg->width, reg->height, reg->stride);
+ try
+ {
+ agg::rendering_buffer rbuf;
+ rbuf.attach(reg->data, reg->width, reg->height, reg->stride);
- pixfmt pf(rbuf);
- renderer_base rb(pf);
- rb.copy_from(renderingBuffer, &rect, -rect.x1, -rect.y1);
- } catch (...) {
- delete reg;
- throw Py::RuntimeError("An unknown error occurred in copy_from_bbox");
- }
- return Py::asObject(reg);
+ pixfmt pf(rbuf);
+ renderer_base rb(pf);
+ rb.copy_from(renderingBuffer, &rect, -rect.x1, -rect.y1);
+ }
+ catch (...)
+ {
+ delete reg;
+ throw Py::RuntimeError("An unknown error occurred in copy_from_bbox");
+ }
+ return Py::asObject(reg);
}
+
Py::Object
-RendererAgg::restore_region(const Py::Tuple& args) {
- //copy BufferRegion to buffer
- args.verify_length(1);
- BufferRegion* region = static_cast<BufferRegion*>(args[0].ptr());
+RendererAgg::restore_region(const Py::Tuple& args)
+{
+ //copy BufferRegion to buffer
+ args.verify_length(1);
+ BufferRegion* region = static_cast<BufferRegion*>(args[0].ptr());
- if (region->data==NULL)
- throw Py::ValueError("Cannot restore_region from NULL data");
- //return Py::Object();
+ if (region->data == NULL)
+ {
+ throw Py::ValueError("Cannot restore_region from NULL data");
+ }
- //std::cout << "restoring " << region->width << " " << region->height << " " << region->stride << " " << region->rect.x1 << " " << region->rect.y1 << std::endl;
+ agg::rendering_buffer rbuf;
+ rbuf.attach(region->data,
+ region->width,
+ region->height,
+ region->stride);
- agg::rendering_buffer rbuf;
- rbuf.attach(region->data,
- region->width,
- region->height,
- region->stride);
+ rendererBase.copy_from(rbuf, 0, region->rect.x1, region->rect.y1);
- rendererBase.copy_from(rbuf, 0, region->rect.x1, region->rect.y1);
-
- return Py::Object();
+ return Py::Object();
}
+
// Restore the part of the saved region with offsets
Py::Object
-RendererAgg::restore_region2(const Py::Tuple& args) {
- //copy BufferRegion to buffer
- args.verify_length(7);
+RendererAgg::restore_region2(const Py::Tuple& args)
+{
+ //copy BufferRegion to buffer
+ args.verify_length(7);
+ int x(0), y(0), xx1(0), yy1(0), xx2(0), yy2(0);
+ try
+ {
+ xx1 = Py::Int(args[1]);
+ yy1 = Py::Int(args[2]);
+ xx2 = Py::Int(args[3]);
+ yy2 = Py::Int(args[4]);
+ x = Py::Int(args[5]);
+ y = Py::Int(args[6]);
+ }
+ catch (Py::TypeError)
+ {
+ throw Py::TypeError("Invalid input arguments to draw_text_image");
+ }
- int x(0),y(0), xx1(0),yy1(0), xx2(0), yy2(0);
- try {
- xx1 = Py::Int( args[1] );
- yy1 = Py::Int( args[2] );
- xx2 = Py::Int( args[3] );
- yy2 = Py::Int( args[4] );
- x = Py::Int( args[5] );
- y = Py::Int( args[6] );
- }
- catch (Py::TypeError) {
- throw Py::TypeError("Invalid input arguments to draw_text_image");
- }
+ BufferRegion* region = static_cast<BufferRegion*>(args[0].ptr());
+ if (region->data == NULL)
+ {
+ throw Py::ValueError("Cannot restore_region from NULL data");
+ }
- BufferRegion* region = static_cast<BufferRegion*>(args[0].ptr());
+ agg::rect_i rect(xx1 - region->rect.x1, (yy1 - region->rect.y1),
+ xx2 - region->rect.x1, (yy2 - region->rect.y1));
- if (region->data==NULL)
- throw Py::ValueError("Cannot restore_region from NULL data");
+ agg::rendering_buffer rbuf;
+ rbuf.attach(region->data,
+ region->width,
+ region->height,
+ region->stride);
- agg::rect_i rect(xx1-region->rect.x1, (yy1-region->rect.y1),
- xx2-region->rect.x1, (yy2-region->rect.y1));
+ rendererBase.copy_from(rbuf, &rect, x, y);
-
- agg::rendering_buffer rbuf;
- rbuf.attach(region->data,
- region->width,
- region->height,
- region->stride);
-
- rendererBase.copy_from(rbuf, &rect, x, y);
-
- return Py::Object();
+ return Py::Object();
}
-bool RendererAgg::render_clippath(const Py::Object& clippath, const agg::trans_affine& clippath_trans) {
- typedef agg::conv_transform<PathIterator> transformed_path_t;
- typedef agg::conv_curve<transformed_path_t> curve_t;
+bool
+RendererAgg::render_clippath(const Py::Object& clippath,
+ const agg::trans_affine& clippath_trans)
+{
+ typedef agg::conv_transform<PathIterator> transformed_path_t;
+ typedef agg::conv_curve<transformed_path_t> curve_t;
- bool has_clippath = (clippath.ptr() != Py_None);
+ bool has_clippath = (clippath.ptr() != Py_None);
- if (has_clippath &&
- (clippath.ptr() != lastclippath.ptr() ||
- clippath_trans != lastclippath_transform)) {
- create_alpha_buffers();
- agg::trans_affine trans(clippath_trans);
- trans *= agg::trans_affine_scaling(1.0, -1.0);
- trans *= agg::trans_affine_translation(0.0, (double)height);
+ if (has_clippath &&
+ (clippath.ptr() != lastclippath.ptr() ||
+ clippath_trans != lastclippath_transform))
+ {
+ create_alpha_buffers();
+ agg::trans_affine trans(clippath_trans);
+ trans *= agg::trans_affine_scaling(1.0, -1.0);
+ trans *= agg::trans_affine_translation(0.0, (double)height);
- PathIterator clippath_iter(clippath);
- rendererBaseAlphaMask.clear(agg::gray8(0, 0));
- transformed_path_t transformed_clippath(clippath_iter, trans);
- agg::conv_curve<transformed_path_t> curved_clippath(transformed_clippath);
- theRasterizer.add_path(curved_clippath);
- rendererAlphaMask.color(agg::gray8(255, 255));
- agg::render_scanlines(theRasterizer, scanlineAlphaMask, rendererAlphaMask);
- lastclippath = clippath;
- lastclippath_transform = clippath_trans;
- }
+ PathIterator clippath_iter(clippath);
+ rendererBaseAlphaMask.clear(agg::gray8(0, 0));
+ transformed_path_t transformed_clippath(clippath_iter, trans);
+ agg::conv_curve<transformed_path_t> curved_clippath(transformed_clippath);
+ theRasterizer.add_path(curved_clippath);
+ rendererAlphaMask.color(agg::gray8(255, 255));
+ agg::render_scanlines(theRasterizer, scanlineAlphaMask, rendererAlphaMask);
+ lastclippath = clippath;
+ lastclippath_transform = clippath_trans;
+ }
- return has_clippath;
+ return has_clippath;
}
#define MARKER_CACHE_SIZE 512
+
Py::Object
-RendererAgg::draw_markers(const Py::Tuple& args) {
- typedef agg::conv_transform<PathIterator> transformed_path_t;
- typedef PathSnapper<transformed_path_t> snap_t;
- typedef agg::conv_curve<snap_t> curve_t;
- typedef agg::conv_stroke<curve_t> stroke_t;
- typedef agg::pixfmt_amask_adaptor<pixfmt, alpha_mask_type> pixfmt_amask_type;
- typedef agg::renderer_base<pixfmt_amask_type> amask_ren_type;
- typedef agg::renderer_scanline_aa_solid<amask_ren_type> amask_aa_renderer_type;
- typedef agg::renderer_scanline_bin_solid<amask_ren_type> amask_bin_renderer_type;
- args.verify_length(5, 6);
+RendererAgg::draw_markers(const Py::Tuple& args)
+{
+ typedef agg::conv_transform<PathIterator> transformed_path_t;
+ typedef PathSnapper<transformed_path_t> snap_t;
+ typedef agg::conv_curve<snap_t> curve_t;
+ typedef agg::conv_stroke<curve_t> stroke_t;
+ typedef agg::pixfmt_amask_adaptor<pixfmt, alpha_mask_type> pixfmt_amask_type;
+ typedef agg::renderer_base<pixfmt_amask_type> amask_ren_type;
+ typedef agg::renderer_scanline_aa_solid<amask_ren_type> amask_aa_renderer_type;
+ typedef agg::renderer_scanline_bin_solid<amask_ren_type> amask_bin_renderer_type;
+ args.verify_length(5, 6);
- Py::Object gc_obj = args[0];
- Py::Object marker_path_obj = args[1];
- agg::trans_affine marker_trans = py_to_agg_transformation_matrix(args[2].ptr());
- Py::Object path_obj = args[3];
- agg::trans_affine trans = py_to_agg_transformation_matrix(args[4].ptr());
- Py::Object face_obj;
- if (args.size() == 6)
- face_obj = args[5];
+ Py::Object gc_obj = args[0];
+ Py::Object marker_path_obj = args[1];
+ agg::trans_affine marker_trans = py_to_agg_transformation_matrix(args[2].ptr());
+ Py::Object path_obj = args[3];
+ agg::trans_affine trans = py_to_agg_transformation_matrix(args[4].ptr());
+ Py::Object face_obj;
+ if (args.size() == 6)
+ {
+ face_obj = args[5];
+ }
- GCAgg gc(gc_obj, dpi);
+ GCAgg gc(gc_obj, dpi);
- // Deal with the difference in y-axis direction
- marker_trans *= agg::trans_affine_scaling(1.0, -1.0);
- trans *= agg::trans_affine_scaling(1.0, -1.0);
- trans *= agg::trans_affine_translation(0.0, (double)height);
+ // Deal with the difference in y-axis direction
+ marker_trans *= agg::trans_affine_scaling(1.0, -1.0);
+ trans *= agg::trans_affine_scaling(1.0, -1.0);
+ trans *= agg::trans_affine_translation(0.0, (double)height);
- PathIterator marker_path(marker_path_obj);
- transformed_path_t marker_path_transformed(marker_path, marker_trans);
- snap_t marker_path_snapped(marker_path_transformed,
- gc.snap_mode,
- marker_path.total_vertices(),
- gc.linewidth);
- curve_t marker_path_curve(marker_path_snapped);
+ PathIterator marker_path(marker_path_obj);
+ transformed_path_t marker_path_transformed(marker_path, marker_trans);
+ snap_t marker_path_snapped(marker_path_transformed,
+ gc.snap_mode,
+ marker_path.total_vertices(),
+ gc.linewidth);
+ curve_t marker_path_curve(marker_path_snapped);
- PathIterator path(path_obj);
- transformed_path_t path_transformed(path, trans);
- snap_t path_snapped(path_transformed,
- gc.snap_mode,
- path.total_vertices(),
- 1.0);
- curve_t path_curve(path_snapped);
- path_curve.rewind(0);
+ PathIterator path(path_obj);
+ transformed_path_t path_transformed(path, trans);
+ snap_t path_snapped(path_transformed,
+ gc.snap_mode,
+ path.total_vertices(),
+ 1.0);
+ curve_t path_curve(path_snapped);
+ path_curve.rewind(0);
- facepair_t face = _get_rgba_face(face_obj, gc.alpha);
+ facepair_t face = _get_rgba_face(face_obj, gc.alpha);
- //maxim's suggestions for cached scanlines
- agg::scanline_storage_aa8 scanlines;
- theRasterizer.reset();
- theRasterizer.reset_clipping();
- rendererBase.reset_clipping(true);
+ //maxim's suggestions for cached scanlines
+ agg::scanline_storage_aa8 scanlines;
+ theRasterizer.reset();
+ theRasterizer.reset_clipping();
+ rendererBase.reset_clipping(true);
- agg::int8u staticFillCache[MARKER_CACHE_SIZE];
- agg::int8u staticStrokeCache[MARKER_CACHE_SIZE];
- agg::int8u* fillCache = staticFillCache;
- agg::int8u* strokeCache = staticStrokeCache;
+ agg::int8u staticFillCache[MARKER_CACHE_SIZE];
+ agg::int8u staticStrokeCache[MARKER_CACHE_SIZE];
+ agg::int8u* fillCache = staticFillCache;
+ agg::int8u* strokeCache = staticStrokeCache;
- try {
- unsigned fillSize = 0;
- if (face.first) {
- theRasterizer.add_path(marker_path_curve);
- agg::render_scanlines(theRasterizer, slineP8, scanlines);
- fillSize = scanlines.byte_size();
- if (fillSize >= MARKER_CACHE_SIZE)
- fillCache = new agg::int8u[fillSize];
- scanlines.serialize(fillCache);
- }
+ try
+ {
+ unsigned fillSize = 0;
+ if (face.first)
+ {
+ theRasterizer.add_path(marker_path_curve);
+ agg::render_scanlines(theRasterizer, slineP8, scanlines);
+ fillSize = scanlines.byte_size();
+ if (fillSize >= MARKER_CACHE_SIZE)
+ {
+ fillCache = new agg::int8u[fillSize];
+ }
+ scanlines.serialize(fillCache);
+ }
- stroke_t stroke(marker_path_curve);
- stroke.width(gc.linewidth);
- stroke.line_cap(gc.cap);
- stroke.line_join(gc.join);
- theRasterizer.reset();
- theRasterizer.add_path(stroke);
- agg::render_scanlines(theRasterizer, slineP8, scanlines);
- unsigned strokeSize = scanlines.byte_size();
- if (strokeSize >= MARKER_CACHE_SIZE)
- strokeCache = new agg::int8u[strokeSize];
- scanlines.serialize(strokeCache);
+ stroke_t stroke(marker_path_curve);
+ stroke.width(gc.linewidth);
+ stroke.line_cap(gc.cap);
+ stroke.line_join(gc.join);
+ theRasterizer.reset();
+ theRasterizer.add_path(stroke);
+ agg::render_scanlines(theRasterizer, slineP8, scanlines);
+ unsigned strokeSize = scanlines.byte_size();
+ if (strokeSize >= MARKER_CACHE_SIZE)
+ {
+ strokeCache = new agg::int8u[strokeSize];
+ }
+ scanlines.serialize(strokeCache);
- theRasterizer.reset_clipping();
- rendererBase.reset_clipping(true);
- set_clipbox(gc.cliprect, rendererBase);
- bool has_clippath = render_clippath(gc.clippath, gc.clippath_trans);
+ theRasterizer.reset_clipping();
+ rendererBase.reset_clipping(true);
+ set_clipbox(gc.cliprect, rendererBase);
+ bool has_clippath = render_clippath(gc.clippath, gc.clippath_trans);
- double x, y;
+ double x, y;
- agg::serialized_scanlines_adaptor_aa8 sa;
- agg::serialized_scanlines_adaptor_aa8::embedded_scanline sl;
+ agg::serialized_scanlines_adaptor_aa8 sa;
+ agg::serialized_scanlines_adaptor_aa8::embedded_scanline sl;
- agg::rect_d clipping_rect(
- -(scanlines.min_x() + 1.0),
- -(scanlines.min_y() + 1.0),
- width + scanlines.max_x() + 1.0,
- height + scanlines.max_y() + 1.0);
+ agg::rect_d clipping_rect(
+ -(scanlines.min_x() + 1.0),
+ -(scanlines.min_y() + 1.0),
+ width + scanlines.max_x() + 1.0,
+ height + scanlines.max_y() + 1.0);
- if (has_clippath) {
- while (path_curve.vertex(&x, &y) != agg::path_cmd_stop) {
- if (MPL_notisfinite64(x) || MPL_notisfinite64(y)) {
- continue;
- }
+ if (has_clippath)
+ {
+ while (path_curve.vertex(&x, &y) != agg::path_cmd_stop)
+ {
+ if (MPL_notisfinite64(x) || MPL_notisfinite64(y))
+ {
+ continue;
+ }
- x = (double)(int)x; y = (double)(int)y;
+ x = (double)(int)x;
+ y = (double)(int)y;
- // Cull points outside the boundary of the image. Values
- // that are too large may overflow and create segfaults.
- // because they can create segfaults of they overflow; eg
- // http://sourceforge.net/tracker/?func=detail&aid=2865490&group_id=80706&atid=560720
- if (!clipping_rect.hit_test(x, y)) {
- continue;
- }
+ // Cull points outside the boundary of the image.
+ // Values that are too large may overflow and create
+ // segfaults.
+ // http://sourceforge.net/tracker/?func=detail&aid=2865490&group_id=80706&atid=560720
+ if (!clipping_rect.hit_test(x, y))
+ {
+ continue;
+ }
- pixfmt_amask_type pfa(pixFmt, alphaMask);
- amask_ren_type r(pfa);
- amask_aa_renderer_type ren(r);
+ pixfmt_amask_type pfa(pixFmt, alphaMask);
+ amask_ren_type r(pfa);
+ amask_aa_renderer_type ren(r);
- if (face.first) {
- ren.color(face.second);
- sa.init(fillCache, fillSize, x, y);
- agg::render_scanlines(sa, sl, ren);
+ if (face.first)
+ {
+ ren.color(face.second);
+ sa.init(fillCache, fillSize, x, y);
+ agg::render_scanlines(sa, sl, ren);
+ }
+ ren.color(gc.color);
+ sa.init(strokeCache, strokeSize, x, y);
+ agg::render_scanlines(sa, sl, ren);
+ }
}
- ren.color(gc.color);
- sa.init(strokeCache, strokeSize, x, y);
- agg::render_scanlines(sa, sl, ren);
- }
- } else {
- while (path_curve.vertex(&x, &y) != agg::path_cmd_stop) {
- if (MPL_notisfinite64(x) || MPL_notisfinite64(y)) {
- continue;
- }
+ else
+ {
+ while (path_curve.vertex(&x, &y) != agg::path_cmd_stop)
+ {
+ if (MPL_notisfinite64(x) || MPL_notisfinite64(y))
+ {
+ continue;
+ }
- x = (double)(int)x; y = (double)(int)y;
+ x = (double)(int)x;
+ y = (double)(int)y;
- // Cull points outside the boundary of the image. Values
- // that are too large may overflow and create segfaults.
- // because they can create segfaults of they overflow; eg
- // http://sourceforge.net/tracker/?func=detail&aid=2865490&group_id=80706&atid=560720
- if (!clipping_rect.hit_test(x, y)) {
- continue;
- }
+ // Cull points outside the boundary of the image.
+ // Values that are too large may overflow and create
+ // segfaults.
+ // http://sourceforge.net/tracker/?func=detail&aid=2865490&group_id=80706&atid=560720
+ if (!clipping_rect.hit_test(x, y))
+ {
+ continue;
+ }
- if (face.first) {
- rendererAA.color(face.second);
- sa.init(fillCache, fillSize, x, y);
- agg::render_scanlines(sa, sl, rendererAA);
+ if (face.first)
+ {
+ rendererAA.color(face.second);
+ sa.init(fillCache, fillSize, x, y);
+ agg::render_scanlines(sa, sl, rendererAA);
+ }
+
+ rendererAA.color(gc.color);
+ sa.init(strokeCache, strokeSize, x, y);
+ agg::render_scanlines(sa, sl, rendererAA);
+ }
}
+ }
+ catch (...)
+ {
+ if (fillCache != staticFillCache)
+ delete[] fillCache;
+ if (strokeCache != staticStrokeCache)
+ delete[] strokeCache;
+ throw;
+ }
- rendererAA.color(gc.color);
- sa.init(strokeCache, strokeSize, x, y);
- agg::render_scanlines(sa, sl, rendererAA);
- }
- }
- } catch(...) {
if (fillCache != staticFillCache)
- delete[] fillCache;
+ delete[] fillCache;
if (strokeCache != staticStrokeCache)
- delete[] strokeCache;
- throw;
- }
+ delete[] strokeCache;
- if (fillCache != staticFillCache)
- delete[] fillCache;
- if (strokeCache != staticStrokeCache)
- delete[] strokeCache;
-
- return Py::Object();
+ return Py::Object();
}
+
/**
* This is a custom span generator that converts spans in the
* 8-bit inverted greyscale font buffer to rgba that agg can use.
@@ -680,1380 +816,1626 @@
class font_to_rgba
{
public:
- typedef ChildGenerator child_type;
- typedef agg::rgba8 color_type;
- typedef typename child_type::color_type child_color_type;
- typedef agg::span_allocator<child_color_type> span_alloc_type;
+ typedef ChildGenerator child_type;
+ typedef agg::rgba8 color_type;
+ typedef typename child_type::color_type child_color_type;
+ typedef agg::span_allocator<child_color_type> span_alloc_type;
private:
- child_type* _gen;
- color_type _color;
- span_alloc_type _allocator;
+ child_type* _gen;
+ color_type _color;
+ span_alloc_type _allocator;
public:
- font_to_rgba(child_type* gen, color_type color) :
- _gen(gen),
- _color(color) {
- }
+ font_to_rgba(child_type* gen, color_type color) :
+ _gen(gen),
+ _color(color)
+ {
- inline void generate(color_type* output_span, int x, int y, unsigned len)
- {
- _allocator.allocate(len);
- child_color_type* input_span = _allocator.span();
- _gen->generate(input_span, x, y, len);
+ }
- do {
- *output_span = _color;
- output_span->a = ((unsigned int)_color.a * (unsigned int)input_span->v) >> 8;
- ++output_span;
- ++input_span;
- } while (--len);
- }
+ inline void
+ generate(color_type* output_span, int x, int y, unsigned len)
+ {
+ _allocator.allocate(len);
+ child_color_type* input_span = _allocator.span();
+ _gen->generate(input_span, x, y, len);
- void prepare()
- {
- _gen->prepare();
- }
+ do
+ {
+ *output_span = _color;
+ output_span->a = ((unsigned int)_color.a *
+ (unsigned int)input_span->v) >> 8;
+ ++output_span;
+ ++input_span;
+ }
+ while (--len);
+ }
+ void
+ prepare()
+ {
+ _gen->prepare();
+ }
};
+
// MGDTODO: Support clip paths
Py::Object
-RendererAgg::draw_text_image(const Py::Tuple& args) {
- _VERBOSE("RendererAgg::draw_text");
+RendererAgg::draw_text_image(const Py::Tuple& args)
+{
+ _VERBOSE("RendererAgg::draw_text");
- typedef agg::span_allocator<agg::gray8> gray_span_alloc_type;
- typedef agg::span_allocator<agg::rgba8> color_span_alloc_type;
- typedef agg::span_interpolator_linear<> interpolator_type;
- typedef agg::image_accessor_clip<agg::pixfmt_gray8> image_accessor_type;
- //typedef agg::span_image_filter_gray_2x2<image_accessor_type, interpolator_type>
- // image_span_gen_type;
- typedef agg::span_image_filter_gray<image_accessor_type, interpolator_type>
- image_span_gen_type;
+ typedef agg::span_allocator<agg::gray8> gray_span_alloc_type;
+ typedef agg::span_allocator<agg::rgba8> color_span_alloc_type;
+ typedef agg::span_interpolator_linear<> interpolator_type;
+ typedef agg::image_accessor_clip<agg::pixfmt_gray8> image_accessor_type;
+ typedef agg::span_image_filter_gray<image_accessor_type,
+ interpolator_type> image_span_gen_type;
+ typedef font_to_rgba<image_span_gen_type> span_gen_type;
+ typedef agg::renderer_scanline_aa<renderer_base, color_span_alloc_type,
+ span_gen_type> renderer_type;
- typedef font_to_rgba<image_span_gen_type> span_gen_type;
- typedef agg::renderer_scanline_aa<renderer_base, color_span_alloc_type, span_gen_type>
- renderer_type;
+ args.verify_length(5);
- args.verify_length(5);
+ const unsigned char* buffer = NULL;
+ int width, height;
+ Py::Object image_obj = args[0];
+ PyArrayObject* image_array = NULL;
- const unsigned char* buffer = NULL;
- int width, height;
- Py::Object image_obj = args[0];
- PyArrayObject* image_array = NULL;
- if (PyArray_Check(image_obj.ptr())) {
- image_array = (PyArrayObject*)PyArray_FromObject(image_obj.ptr(), PyArray_UBYTE, 2, 2);
- if (!image_array)
- throw Py::ValueError("First argument to draw_text_image must be a FT2Font.Image object or a Nx2 uint8 numpy array.");
- buffer = (unsigned char *)PyArray_DATA(image_array);
- width = PyArray_DIM(image_array, 1);
- height = PyArray_DIM(image_array, 0);
- } else {
- FT2Image *image = static_cast<FT2Image*>(args[0].ptr());
- if (!image->get_buffer())
- throw Py::ValueError("First argument to draw_text_image must be a FT2Font.Image object or a Nx2 uint8 numpy array.");
- buffer = image->get_buffer();
- width = image->get_width();
- height = image->get_height();
- }
+ if (PyArray_Check(image_obj.ptr()))
+ {
+ image_array = (PyArrayObject*)PyArray_FromObject(image_obj.ptr(), PyArray_UBYTE, 2, 2);
+ if (!image_array)
+ {
+ throw Py::ValueError(
+ "First argument to draw_text_image must be a FT2Font.Image object or a Nx2 uint8 numpy array.");
+ }
+ buffer = (unsigned char *)PyArray_DATA(image_array);
+ width = PyArray_DIM(image_array, 1);
+ height = PyArray_DIM(image_array, 0);
+ }
+ else
+ {
+ FT2Image *image = static_cast<FT2Image*>(args[0].ptr());
+ if (!image->get_buffer())
+ {
+ throw Py::ValueError(
+ "First argument to draw_text_image must be a FT2Font.Image object or a Nx2 uint8 numpy array.");
+ }
+ buffer = image->get_buffer();
+ width = image->get_width();
+ height = image->get_height();
+ }
- int x(0),y(0);
- try {
- x = Py::Int( args[1] );
- y = Py::Int( args[2] );
- }
- catch (Py::TypeError) {
- Py_XDECREF(image_array);
- throw Py::TypeError("Invalid input arguments to draw_text_image");
- }
+ int x(0), y(0);
+ try
+ {
+ x = Py::Int(args[1]);
+ y = Py::Int(args[2]);
+ }
+ catch (Py::TypeError)
+ {
+ Py_XDECREF(image_array);
+ throw Py::TypeError("Invalid input arguments to draw_text_image");
+ }
- double angle = Py::Float( args[3] );
+ double angle = Py::Float(args[3]);
- GCAgg gc(args[4], dpi);
+ GCAgg gc(args[4], dpi);
- theRasterizer.reset_clipping();
- rendererBase.reset_clipping(true);
- set_clipbox(gc.cliprect, theRasterizer);
+ theRasterizer.reset_clipping();
+ rendererBase.reset_clipping(true);
+ set_clipbox(gc.cliprect, theRasterizer);
- agg::rendering_buffer srcbuf((agg::int8u*)buffer, width, height, width);
- agg::pixfmt_gray8 pixf_img(srcbuf);
+ agg::rendering_buffer srcbuf((agg::int8u*)buffer, width, height, width);
+ agg::pixfmt_gray8 pixf_img(srcbuf);
- agg::trans_affine mtx;
- mtx *= agg::trans_affine_translation(0, -height);
- mtx *= agg::trans_affine_rotation(-angle * agg::pi / 180.0);
- mtx *= agg::trans_affine_translation(x, y);
+ agg::trans_affine mtx;
+ mtx *= agg::trans_affine_translation(0, -height);
+ mtx *= agg::trans_affine_rotation(-angle * agg::pi / 180.0);
+ mtx *= agg::trans_affine_translation(x, y);
- agg::path_storage rect;
- rect.move_to(0, 0);
- rect.line_to(width, 0);
- rect.line_to(width, height);
- rect.line_to(0, height);
- rect.line_to(0, 0);
- agg::conv_transform<agg::path_storage> rect2(rect, mtx);
+ agg::path_storage rect;
+ rect.move_to(0, 0);
+ rect.line_to(width, 0);
+ rect.line_to(width, height);
+ rect.line_to(0, height);
+ rect.line_to(0, 0);
+ agg::conv_transform<agg::path_storage> rect2(rect, mtx);
- agg::trans_affine inv_mtx(mtx);
- inv_mtx.invert();
+ agg::trans_affine inv_mtx(mtx);
+ inv_mtx.invert();
- agg::image_filter_lut filter;
- filter.calculate(agg::image_filter_spline36());
- interpolator_type interpolator(inv_mtx);
- color_span_alloc_type sa;
- image_accessor_type ia(pixf_img, 0);
- image_span_gen_type image_span_generator(ia, interpolator, filter);
- span_gen_type output_span_generator(&image_span_generator, gc.color);
- renderer_type ri(rendererBase, sa, output_span_generator);
+ agg::image_filter_lut filter;
+ filter.calculate(agg::image_filter_spline36());
+ interpolator_type interpolator(inv_mtx);
+ color_span_alloc_type sa;
+ image_accessor_type ia(pixf_img, 0);
+ image_span_gen_type image_span_generator(ia, interpolator, filter);
+ span_gen_type output_span_generator(&image_span_generator, gc.color);
+ renderer_type ri(rendererBase, sa, output_span_generator);
- theRasterizer.add_path(rect2);
- agg::render_scanlines(theRasterizer, slineP8, ri);
+ theRasterizer.add_path(rect2);
+ agg::render_scanlines(theRasterizer, slineP8, ri);
- Py_XDECREF(image_array);
+ Py_XDECREF(image_array);
- return Py::Object();
+ return Py::Object();
}
Py::Object
-RendererAgg::draw_image(const Py::Tuple& args) {
- _VERBOSE("RendererAgg::draw_image");
+RendererAgg::draw_image(const Py::Tuple& args)
+{
+ _VERBOSE("RendererAgg::draw_image");
- args.verify_length(4, 7); // 7 if affine matrix if given
+ args.verify_length(4, 7); // 7 if affine matrix if given
- GCAgg gc(args[0], dpi);
- Image *image = static_cast<Image*>(args[3].ptr());
- bool has_clippath = false;
- agg::trans_affine affine_trans;
- bool has_affine = false;
- double x, y, w, h;
+ GCAgg gc(args[0], dpi);
+ Image *image = static_cast<Image*>(args[3].ptr());
+ bool has_clippath = false;
+ agg::trans_affine affine_trans;
+ bool has_affine = false;
+ double x, y, w, h;
-
- if (args.size() == 7) {
- has_affine = true;
- x = Py::Float(args[1]);
- y = Py::Float(args[2]);
- w = Py::Float(args[4]);
- h = Py::Float(args[5]);
- affine_trans = py_to_agg_transformation_matrix(args[6].ptr());
- } else {
- x = mpl_round(Py::Float(args[1]));
- y = mpl_round(Py::Float(args[2]));
- w = h = 0; /* w and h not used in this case, but assign to prevent
+ if (args.size() == 7)
+ {
+ has_affine = true;
+ x = Py::Float(args[1]);
+ y = Py::Float(args[2]);
+ w = Py::Float(args[4]);
+ h = Py::Float(args[5]);
+ affine_trans = py_to_agg_transformation_matrix(args[6].ptr());
+ }
+ else
+ {
+ x = mpl_round(Py::Float(args[1]));
+ y = mpl_round(Py::Float(args[2]));
+ w = h = 0; /* w and h not used in this case, but assign to prevent
warnings from the compiler */
- }
+ }
+ theRasterizer.reset_clipping();
+ rendererBase.reset_clipping(true);
+ set_clipbox(gc.cliprect, theRasterizer);
+ has_clippath = render_clippath(gc.clippath, gc.clippath_trans);
- theRasterizer.reset_clipping();
- rendererBase.reset_clipping(true);
- set_clipbox(gc.cliprect, theRasterizer);
- has_clippath = render_clippath(gc.clippath, gc.clippath_trans);
+ Py::Tuple empty;
+ image->flipud_out(empty);
+ pixfmt pixf(*(image->rbufOut));
- Py::Tuple empty;
- image->flipud_out(empty);
- pixfmt pixf(*(image->rbufOut));
+ if (has_affine | has_clippath)
+ {
+ agg::trans_affine mtx;
+ agg::path_storage rect;
- if (has_affine | has_clippath) {
- agg::trans_affine mtx;
- agg::path_storage rect;
+ if (has_affine)
+ {
+ mtx *= agg::trans_affine_scaling(1, -1);
+ mtx *= agg::trans_affine_translation(0, image->rowsOut);
+ mtx *= agg::trans_affine_scaling(w / (image->colsOut),
+ h / (image->rowsOut));
+ mtx *= agg::trans_affine_translation(x, y);
+ mtx *= affine_trans;
+ mtx *= agg::trans_affine_scaling(1.0, -1.0);
+ mtx *= agg::trans_affine_translation(0.0, (double) height);
+ }
+ else
+ {
+ mtx *= agg::trans_affine_translation(
+ (int)x,
+ (int)(height - (y + image->rowsOut)));
+ }
- if (has_affine) {
- mtx *= agg::trans_affine_scaling(1, -1);
- mtx *= agg::trans_affine_translation(0, image->rowsOut);
- mtx *= agg::trans_affine_scaling(w/(image->colsOut), h/(image->rowsOut));
- mtx *= agg::trans_affine_translation(x, y);
- mtx *= affine_trans;
- mtx *= agg::trans_affine_scaling(1.0, -1.0);
- mtx *= agg::trans_affine_translation(0.0, (double) height);
- } else {
- mtx *= agg::trans_affine_translation((int)x, (int)(height-(y+image->rowsOut)));
- }
+ rect.move_to(0, 0);
+ rect.line_to(image->colsOut, 0);
+ rect.line_to(image->colsOut, image->rowsOut);
+ rect.line_to(0, image->rowsOut);
+ rect.line_to(0, 0);
- rect.move_to(0, 0);
- rect.line_to(image->colsOut, 0);
- rect.line_to(image->colsOut, image->rowsOut);
- rect.line_to(0, image->rowsOut);
- rect.line_to(0, 0);
+ agg::conv_transform<agg::path_storage> rect2(rect, mtx);
- agg::conv_transform<agg::path_storage> rect2(rect, mtx);
+ agg::trans_affine inv_mtx(mtx);
+ inv_mtx.invert();
- agg::trans_affine inv_mtx(mtx);
- inv_mtx.invert();
+ typedef agg::span_allocator<agg::rgba8> color_span_alloc_type;
+ typedef agg::image_accessor_clip<agg::pixfmt_rgba32>
+ image_accessor_type;
+ typedef agg::span_interpolator_linear<> interpolator_type;
+ typedef agg::span_image_filter_rgba_nn<image_accessor_type,
+ interpolator_type> image_span_gen_type;
+ color_span_alloc_type sa;
+ image_accessor_type ia(pixf, agg::rgba8(0, 0, 0, 0));
+ interpolator_type interpolator(inv_mtx);
+ image_span_gen_type image_span_generator(ia, interpolator);
- typedef agg::span_allocator<agg::rgba8> color_span_alloc_type;
- typedef agg::image_accessor_clip<agg::pixfmt_rgba32> image_accessor_type;
- typedef agg::span_interpolator_linear<> interpolator_type;
- typedef agg::span_image_filter_rgba_nn<image_accessor_type, interpolator_type> image_span_gen_type;
+ if (has_clippath)
+ {
+ typedef agg::pixfmt_amask_adaptor<pixfmt, alpha_mask_type>
+ pixfmt_amask_type;
+ typedef agg::renderer_base<pixfmt_amask_type> amask_ren_type;
+ typedef agg::renderer_scanline_aa<amask_ren_type,
+ color_span_alloc_type,
+ image_span_gen_type>
+ renderer_type_alpha;
+ pixfmt_amask_type pfa(pixFmt, alphaMask);
+ amask_ren_type r(pfa);
+ renderer_type_alpha ri(r, sa, image_span_generator);
- color_span_alloc_type sa;
- image_accessor_type ia(pixf, agg::rgba8(0, 0, 0, 0));
- interpolator_type interpolator(inv_mtx);
- image_span_gen_type image_span_generator(ia, interpolator);
+ theRasterizer.add_path(rect2);
+ agg::render_scanlines(theRasterizer, slineP8, ri);
+ }
+ else
+ {
+ typedef agg::renderer_base<pixfmt> ren_type;
+ typedef agg::renderer_scanline_aa<ren_type,
+ color_span_alloc_type,
+ image_span_gen_type>
+ renderer_type;
+ ren_type r(pixFmt);
+ renderer_type ri(r, sa, image_span_generator);
- if (has_clippath) {
- typedef agg::pixfmt_amask_adaptor<pixfmt, alpha_mask_type> pixfmt_amask_type;
- typedef agg::renderer_base<pixfmt_amask_type> amask_ren_type;
- typedef agg::renderer_scanline_aa<amask_ren_type, color_span_alloc_type, image_span_gen_type> renderer_type_alpha;
+ theRasterizer.add_path(rect2);
+ agg::render_scanlines(theRasterizer, slineP8, ri);
+ }
- pixfmt_amask_type pfa(pixFmt, alphaMask);
- amask_ren_type r(pfa);
- renderer_type_alpha ri(r, sa, image_span_generator);
-
- theRasterizer.add_path(rect2);
- agg::render_scanlines(theRasterizer, slineP8, ri);
- } else {
- typedef agg::renderer_base<pixfmt> ren_type;
- typedef agg::renderer_scanline_aa<ren_type, color_span_alloc_type, image_span_gen_type> renderer_type;
- ren_type r(pixFmt);
- renderer_type ri(r, sa, image_span_generator);
-
- theRasterizer.add_path(rect2);
- agg::render_scanlines(theRasterizer, slineP8, ri);
}
+ else
+ {
+ set_clipbox(gc.cliprect, rendererBase);
+ rendererBase.blend_from(pixf, 0, (int)x, (int)(height - (y + image->rowsOut)));
+ }
- } else {
- set_clipbox(gc.cliprect, rendererBase);
- rendererBase.blend_from(pixf, 0, (int)x, (int)(height-(y+image->rowsOut)));
- }
+ image->flipud_out(empty);
- image->flipud_out(empty);
-
- return Py::Object();
+ return Py::Object();
}
-
-
template<class path_t>
void RendererAgg::_draw_path(path_t& path, bool has_clippath,
- const facepair_t& face, const GCAgg& gc) {
- typedef agg::conv_stroke<path_t> stroke_t;
- typedef agg::conv_dash<path_t> dash_t;
- typedef agg::conv_stroke<dash_t> stroke_dash_t;
- typedef agg::pixfmt_amask_adaptor<pixfmt, alpha_mask_type> pixfmt_amask_type;
- typedef agg::renderer_base<pixfmt_amask_type> amask_ren_type;
- typedef agg::renderer_scanline_aa_solid<amask_ren_type> amask_aa_renderer_type;
- typedef agg::renderer_scanline_bin_solid<amask_ren_type> amask_bin_renderer_type;
+ const facepair_t& face, const GCAgg& gc)
+{
+ typedef agg::conv_stroke<path_t> stroke_t;
+ typedef agg::conv_dash<path_t> dash_t;
+ typedef agg::conv_stroke<dash_t> stroke_dash_t;
+ typedef agg::pixfmt_amask_adaptor<pixfmt, alpha_mask_type> pixfmt_amask_type;
+ typedef agg::renderer_base<pixfmt_amask_type> amask_ren_type;
+ typedef agg::renderer_scanline_aa_solid<amask_ren_type> amask_aa_renderer_type;
+ typedef agg::renderer_scanline_bin_solid<amask_ren_type> amask_bin_renderer_type;
- // Render face
- if (face.first) {
- theRasterizer.add_path(path);
+ // Render face
+ if (face.first)
+ {
+ theRasterizer.add_path(path);
- if (gc.isaa) {
- if (has_clippath) {
- pixfmt_amask_type pfa(pixFmt, alphaMask);
- amask_ren_type r(pfa);
- amask_aa_renderer_type ren(r);
- ren.color(face.second);
- agg::render_scanlines(theRasterizer, slineP8, ren);
- } else {
- rendererAA.color(face.second);
- agg::render_scanlines(theRasterizer, slineP8, rendererAA);
- }
- } else {
- if (has_clippath) {
- pixfmt_amask_type pfa(pixFmt, alphaMask);
- amask_ren_type r(pfa);
- amask_bin_renderer_type ren(r);
- ren.color(face.second);
- agg::render_scanlines(theRasterizer, slineP8, ren);
- } else {
- rendererBin.color(face.second);
- agg::render_scanlines(theRasterizer, slineP8, rendererBin);
- }
+ if (gc.isaa)
+ {
+ if (has_clippath)
+ {
+ pixfmt_amask_type pfa(pixFmt, alphaMask);
+ amask_ren_type r(pfa);
+ amask_aa_renderer_type ren(r);
+ ren.color(face.second);
+ agg::render_scanlines(theRasterizer, slineP8, ren);
+ }
+ else
+ {
+ rendererAA.color(face.second);
+ agg::render_scanlines(theRasterizer, slineP8, rendererAA);
+ }
+ }
+ else
+ {
+ if (has_clippath)
+ {
+ pixfmt_amask_type pfa(pixFmt, alphaMask);
+ amask_ren_type r(pfa);
+ amask_bin_renderer_type ren(r);
+ ren.color(face.second);
+ agg::render_scanlines(theRasterizer, slineP8, ren);
+ }
+ else
+ {
+ rendererBin.color(face.second);
+ agg::render_scanlines(theRasterizer, slineP8, rendererBin);
+ }
+ }
}
- }
- // Render hatch
- if (!gc.hatchpath.isNone()) {
- // Reset any clipping that may be in effect, since we'll be
- // drawing the hatch in a scratch buffer at origin (0, 0)
- theRasterizer.reset_clipping();
- rendererBase.reset_clipping(true);
+ // Render hatch
+ if (!gc.hatchpath.isNone())
+ {
+ // Reset any clipping that may be in effect, since we'll be
+ // drawing the hatch in a scratch buffer at origin (0, 0)
+ theRasterizer.reset_clipping();
+ rendererBase.reset_clipping(true);
- // Create and transform the path
- typedef agg::conv_transform<PathIterator> hatch_p...
[truncated message content] |
|
From: <md...@us...> - 2010-06-23 14:44:38
|
Revision: 8459
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8459&view=rev
Author: mdboom
Date: 2010-06-23 14:44:32 +0000 (Wed, 23 Jun 2010)
Log Message:
-----------
Add unit test to ensure that rendering complexity exceeded exception is properly propagated to Python.
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/tests/test_simplification.py
Modified: trunk/matplotlib/lib/matplotlib/tests/test_simplification.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/tests/test_simplification.py 2010-06-23 14:43:52 UTC (rev 8458)
+++ trunk/matplotlib/lib/matplotlib/tests/test_simplification.py 2010-06-23 14:44:32 UTC (rev 8459)
@@ -6,6 +6,10 @@
from pylab import *
import numpy as np
from matplotlib import patches, path, transforms
+
+from nose.tools import raises
+import cStringIO
+
nan = np.nan
Path = path.Path
@@ -165,6 +169,24 @@
assert len(segs) == 1
assert segs[0][1] == Path.MOVETO
+@raises(OverflowError)
+def test_throw_rendering_complexity_exceeded():
+ rcParams['path.simplify'] = False
+
+ xx = np.arange(200000)
+ yy = np.random.rand(200000)
+ yy[1000] = np.nan
+ fig = plt.figure()
+ ax = fig.add_subplot(111)
+ ax.plot(xx, yy)
+ try:
+ fig.savefig(cStringIO.StringIO())
+ except e:
+ raise e
+ else:
+ rcParams['path.simplify'] = True
+
+
if __name__=='__main__':
import nose
nose.runmodule(argv=['-s','--with-doctest'], exit=False)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2010-06-23 14:44:01
|
Revision: 8458
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8458&view=rev
Author: mdboom
Date: 2010-06-23 14:43:52 +0000 (Wed, 23 Jun 2010)
Log Message:
-----------
Uses doubles for rectangle clipping everywhere in the Agg backend.
Modified Paths:
--------------
trunk/matplotlib/src/_backend_agg.h
trunk/matplotlib/src/_image.cpp
Modified: trunk/matplotlib/src/_backend_agg.h
===================================================================
--- trunk/matplotlib/src/_backend_agg.h 2010-06-23 14:18:05 UTC (rev 8457)
+++ trunk/matplotlib/src/_backend_agg.h 2010-06-23 14:43:52 UTC (rev 8458)
@@ -55,7 +55,7 @@
typedef agg::renderer_base<pixfmt> renderer_base;
typedef agg::renderer_scanline_aa_solid<renderer_base> renderer_aa;
typedef agg::renderer_scanline_bin_solid<renderer_base> renderer_bin;
-typedef agg::rasterizer_scanline_aa<> rasterizer;
+typedef agg::rasterizer_scanline_aa<agg::rasterizer_sl_clip_dbl> rasterizer;
typedef agg::scanline_p8 scanline_p8;
typedef agg::scanline_bin scanline_bin;
Modified: trunk/matplotlib/src/_image.cpp
===================================================================
--- trunk/matplotlib/src/_image.cpp 2010-06-23 14:18:05 UTC (rev 8457)
+++ trunk/matplotlib/src/_image.cpp 2010-06-23 14:43:52 UTC (rev 8458)
@@ -39,7 +39,7 @@
typedef agg::pixfmt_rgba32 pixfmt;
typedef agg::renderer_base<pixfmt> renderer_base;
typedef agg::span_interpolator_linear<> interpolator_type;
-typedef agg::rasterizer_scanline_aa<> rasterizer;
+typedef agg::rasterizer_scanline_aa<agg::rasterizer_sl_clip_dbl> rasterizer;
Image::Image() :
@@ -351,7 +351,7 @@
pixfmt pixf(*rbufOut);
renderer_base rb(pixf);
rb.clear(bg);
- agg::rasterizer_scanline_aa<agg::rasterizer_sl_clip_dbl> ras;
+ rasterizer ras;
agg::scanline_u8 sl;
ras.clip_box(0, 0, numcols, numrows);
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2010-06-23 14:18:16
|
Revision: 8457
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8457&view=rev
Author: mdboom
Date: 2010-06-23 14:18:05 +0000 (Wed, 23 Jun 2010)
Log Message:
-----------
Do image clipping of images in doubles rather than ints -- prevents the "disappearing image when zooming in too far" problem.
Modified Paths:
--------------
trunk/matplotlib/src/_image.cpp
Modified: trunk/matplotlib/src/_image.cpp
===================================================================
--- trunk/matplotlib/src/_image.cpp 2010-06-22 19:30:57 UTC (rev 8456)
+++ trunk/matplotlib/src/_image.cpp 2010-06-23 14:18:05 UTC (rev 8457)
@@ -29,6 +29,7 @@
#include "agg_span_image_filter_rgb.h"
#include "agg_span_image_filter_rgba.h"
#include "agg_span_interpolator_linear.h"
+#include "agg_rasterizer_sl_clip.h"
#include "util/agg_color_conv_rgb8.h"
#include "_image.h"
#include "mplutils.h"
@@ -350,7 +351,7 @@
pixfmt pixf(*rbufOut);
renderer_base rb(pixf);
rb.clear(bg);
- agg::rasterizer_scanline_aa<> ras;
+ agg::rasterizer_scanline_aa<agg::rasterizer_sl_clip_dbl> ras;
agg::scanline_u8 sl;
ras.clip_box(0, 0, numcols, numrows);
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2010-06-22 19:31:03
|
Revision: 8456
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8456&view=rev
Author: mdboom
Date: 2010-06-22 19:30:57 +0000 (Tue, 22 Jun 2010)
Log Message:
-----------
Fix severe slowness with very high image magnification.
Modified Paths:
--------------
trunk/matplotlib/src/_image.cpp
Modified: trunk/matplotlib/src/_image.cpp
===================================================================
--- trunk/matplotlib/src/_image.cpp 2010-06-22 16:30:24 UTC (rev 8455)
+++ trunk/matplotlib/src/_image.cpp 2010-06-22 19:30:57 UTC (rev 8456)
@@ -353,6 +353,7 @@
agg::rasterizer_scanline_aa<> ras;
agg::scanline_u8 sl;
+ ras.clip_box(0, 0, numcols, numrows);
//srcMatrix *= resizingMatrix;
//imageMatrix *= resizingMatrix;
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2010-06-22 16:30:31
|
Revision: 8455
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8455&view=rev
Author: mdboom
Date: 2010-06-22 16:30:24 +0000 (Tue, 22 Jun 2010)
Log Message:
-----------
Debian Bug#585442: python-matplotlib: crashes when calling axis() after imshow()
This allows the C++ exception raised when Agg rendering complexity is exceeded to percolate up correctly to a Python exception, rather than crashing the interpreter.
Fixes problem in last commit.
Modified Paths:
--------------
trunk/matplotlib/agg24/include/agg_rasterizer_cells_aa.h
Modified: trunk/matplotlib/agg24/include/agg_rasterizer_cells_aa.h
===================================================================
--- trunk/matplotlib/agg24/include/agg_rasterizer_cells_aa.h 2010-06-22 16:00:55 UTC (rev 8454)
+++ trunk/matplotlib/agg24/include/agg_rasterizer_cells_aa.h 2010-06-22 16:30:24 UTC (rev 8455)
@@ -179,16 +179,15 @@
template<class Cell>
AGG_INLINE void rasterizer_cells_aa<Cell>::add_curr_cell()
{
- static Py::Exception e(
- Py::OverflowError(
- "Agg rendering complexity exceeded. Consider downsampling or decimating your data."));
-
-
if(m_curr_cell.area | m_curr_cell.cover)
{
if((m_num_cells & cell_block_mask) == 0)
{
if(m_num_blocks >= cell_block_limit) {
+ static Py::Exception e(
+ Py::OverflowError(
+ "Agg rendering complexity exceeded. Consider downsampling or decimating your data."));
+
/* If this exception is thrown too often, one can
increase cell_block_limit */
throw e;
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2010-06-22 16:01:01
|
Revision: 8454
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8454&view=rev
Author: mdboom
Date: 2010-06-22 16:00:55 +0000 (Tue, 22 Jun 2010)
Log Message:
-----------
Debian Bug#585442: python-matplotlib: crashes when calling axis() after imshow()
This allows the C++ exception raised when Agg rendering complexity is exceeded to percolate up correctly to a Python exception, rather than crashing the interpreter.
Modified Paths:
--------------
trunk/matplotlib/agg24/include/agg_rasterizer_cells_aa.h
Modified: trunk/matplotlib/agg24/include/agg_rasterizer_cells_aa.h
===================================================================
--- trunk/matplotlib/agg24/include/agg_rasterizer_cells_aa.h 2010-06-21 21:41:19 UTC (rev 8453)
+++ trunk/matplotlib/agg24/include/agg_rasterizer_cells_aa.h 2010-06-22 16:00:55 UTC (rev 8454)
@@ -29,16 +29,15 @@
#ifndef AGG_RASTERIZER_CELLS_AA_INCLUDED
#define AGG_RASTERIZER_CELLS_AA_INCLUDED
+#include "CXX/Exception.hxx"
#include <exception>
#include <string.h>
#include <math.h>
#include "agg_math.h"
#include "agg_array.h"
-
namespace agg
{
-
//-----------------------------------------------------rasterizer_cells_aa
// An internal class that implements the main rasterization algorithm.
// Used in the rasterizer. Should not be used direcly.
@@ -180,6 +179,11 @@
template<class Cell>
AGG_INLINE void rasterizer_cells_aa<Cell>::add_curr_cell()
{
+ static Py::Exception e(
+ Py::OverflowError(
+ "Agg rendering complexity exceeded. Consider downsampling or decimating your data."));
+
+
if(m_curr_cell.area | m_curr_cell.cover)
{
if((m_num_cells & cell_block_mask) == 0)
@@ -187,8 +191,7 @@
if(m_num_blocks >= cell_block_limit) {
/* If this exception is thrown too often, one can
increase cell_block_limit */
- throw "Agg rendering complexity exceeded. "
- "Consider downsampling or decimating your data.";
+ throw e;
}
allocate_block();
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2010-06-21 21:41:25
|
Revision: 8453
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8453&view=rev
Author: efiring
Date: 2010-06-21 21:41:19 +0000 (Mon, 21 Jun 2010)
Log Message:
-----------
tick_params: fixed errors in handling top, bottom, etc. kwargs.
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/axes.py
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2010-06-21 20:53:22 UTC (rev 8452)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2010-06-21 21:41:19 UTC (rev 8453)
@@ -2168,13 +2168,17 @@
"""
if axis in ['x', 'both']:
xkw = dict(kwargs)
- xkw.pop('top', None)
- xkw.pop('bottom', None)
+ xkw.pop('left', None)
+ xkw.pop('right', None)
+ xkw.pop('labelleft', None)
+ xkw.pop('labelright', None)
self.xaxis.set_tick_params(**xkw)
if axis in ['y', 'both']:
ykw = dict(kwargs)
- ykw.pop('left', None)
- ykw.pop('right', None)
+ ykw.pop('top', None)
+ ykw.pop('bottom', None)
+ ykw.pop('labeltop', None)
+ ykw.pop('labelbottom', None)
self.yaxis.set_tick_params(**ykw)
def set_axis_off(self):
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2010-06-21 20:53:29
|
Revision: 8452
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8452&view=rev
Author: efiring
Date: 2010-06-21 20:53:22 +0000 (Mon, 21 Jun 2010)
Log Message:
-----------
Let pcolor antialiasing default be controlled by patch.antialiasing.
See ticket 3017725. In most cases antialiasing is better than, or
nearly as good as, non-antialiasing. A note about artifacts is now
in the docstring.
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/axes.py
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2010-06-21 20:37:27 UTC (rev 8451)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2010-06-21 20:53:22 UTC (rev 8452)
@@ -6740,16 +6740,16 @@
*shading*: [ 'flat' | 'faceted' ]
If 'faceted', a black grid is drawn around each rectangle; if
'flat', edges are not drawn. Default is 'flat', contrary to
- Matlab(TM).
+ Matlab.
This kwarg is deprecated; please use 'edgecolors' instead:
- * shading='flat' -- edgecolors='None'
+ * shading='flat' -- edgecolors='none'
* shading='faceted -- edgecolors='k'
- *edgecolors*: [ None | 'None' | color | color sequence]
+ *edgecolors*: [ None | 'none' | color | color sequence]
If *None*, the rc setting is used by default.
- If 'None', edges will not be visible.
+ If 'none', edges will not be visible.
An mpl color or sequence of colors will set the edge color
@@ -6805,6 +6805,16 @@
:class:`~matplotlib.collection.PolyCollection` properties:
%(PolyCollection)s
+
+ Note: the default *antialiaseds* is taken from
+ rcParams['patch.antialiased'], which defaults to *True*.
+ In some cases, particularly if *alpha* is 1,
+ you may be able to reduce rendering artifacts (light or
+ dark patch boundaries) by setting it to *False*. An
+ alternative it to set *edgecolors* to 'face'. Unfortunately,
+ there seems to be no single combination of parameters that
+ eliminates artifacts under all conditions.
+
"""
if not self._hold: self.cla()
@@ -6850,19 +6860,22 @@
axis=1)
verts = xy.reshape((npoly, 5, 2))
- #verts = zip(zip(X1,Y1),zip(X2,Y2),zip(X3,Y3),zip(X4,Y4))
-
C = compress(ravelmask, ma.filled(C[0:Ny-1,0:Nx-1]).ravel())
-
if shading == 'faceted':
- edgecolors = (0,0,0,1),
- linewidths = (0.25,)
+ edgecolors = 'k',
else:
- edgecolors = 'face'
- linewidths = (1.0,)
+ edgecolors = 'none'
+ linewidths = (0.25,)
+ # Not sure if we want to have the following, or just trap
+ # invalid kwargs and raise an exception.
+ if 'edgecolor' in kwargs:
+ kwargs['edgecolors'] = kwargs.pop('edgecolor')
+ if 'linewidth' in kwargs:
+ kwargs['linewidths'] = kwargs.pop('linewidth')
+ if 'antialiased' in kwargs:
+ kwargs['antialiaseds'] = kwargs.pop('antialiased')
kwargs.setdefault('edgecolors', edgecolors)
- kwargs.setdefault('antialiaseds', (0,))
kwargs.setdefault('linewidths', linewidths)
collection = mcoll.PolyCollection(verts, **kwargs)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <js...@us...> - 2010-06-21 20:37:34
|
Revision: 8451
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8451&view=rev
Author: jswhit
Date: 2010-06-21 20:37:27 +0000 (Mon, 21 Jun 2010)
Log Message:
-----------
add antialiased=True to pcolor call (SF bugs item #3019150)
Modified Paths:
--------------
trunk/toolkits/basemap/examples/ccsm_popgrid.py
Modified: trunk/toolkits/basemap/examples/ccsm_popgrid.py
===================================================================
--- trunk/toolkits/basemap/examples/ccsm_popgrid.py 2010-06-21 14:33:58 UTC (rev 8450)
+++ trunk/toolkits/basemap/examples/ccsm_popgrid.py 2010-06-21 20:37:27 UTC (rev 8451)
@@ -55,8 +55,9 @@
map.fillcontinents(color='white')
x, y = map(tlon,tlat)
-im = map.pcolor(x,y,ma.masked_array(np.zeros(temp.shape,'f'), temp.mask),\
- shading='faceted',cmap=plt.cm.cool,vmin=0,vmax=0)
+im = map.pcolor(x,y,ma.masked_array(np.zeros(temp.shape,'f'), temp.mask),
+ shading='faceted', antialiased=True, cmap=plt.cm.cool,
+ vmin=0, vmax=0)
# disclaimer: these are not really the grid cells because of the
# way pcolor interprets the x and y args.
plt.title('(A) CCSM POP Grid Cells')
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2010-06-21 14:34:04
|
Revision: 8450
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8450&view=rev
Author: mdboom
Date: 2010-06-21 14:33:58 +0000 (Mon, 21 Jun 2010)
Log Message:
-----------
[3018374] Link to examples is hardcoded
Modified Paths:
--------------
trunk/matplotlib/doc/_templates/layout.html
Modified: trunk/matplotlib/doc/_templates/layout.html
===================================================================
--- trunk/matplotlib/doc/_templates/layout.html 2010-06-21 13:19:11 UTC (rev 8449)
+++ trunk/matplotlib/doc/_templates/layout.html 2010-06-21 14:33:58 UTC (rev 8450)
@@ -4,7 +4,7 @@
{% block rootrellink %}
<li><a href="{{ pathto('index') }}">home</a>| </li>
<li><a href="{{ pathto('search') }}">search</a>| </li>
- <li><a href="http://matplotlib.sf.net/examples/index.html">examples</a>| </li>
+ <li><a href="{{ pathto('examples/index') }}">examples</a>| </li>
<li><a href="{{ pathto('gallery') }}">gallery</a>| </li>
<li><a href="{{ pathto('contents') }}">docs</a> »</li>
{% endblock %}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2010-06-21 13:19:18
|
Revision: 8449
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8449&view=rev
Author: mdboom
Date: 2010-06-21 13:19:11 +0000 (Mon, 21 Jun 2010)
Log Message:
-----------
[3015217] Don't add piwik code to html docs by default
This prevents the web browser from making remote http requests when browsing the docs locally.
Modified Paths:
--------------
trunk/matplotlib/doc/_templates/layout.html
Modified: trunk/matplotlib/doc/_templates/layout.html
===================================================================
--- trunk/matplotlib/doc/_templates/layout.html 2010-06-21 08:51:30 UTC (rev 8448)
+++ trunk/matplotlib/doc/_templates/layout.html 2010-06-21 13:19:11 UTC (rev 8449)
@@ -13,17 +13,24 @@
{% block relbar1 %}
<!-- Piwik -->
<script type="text/javascript">
-var pkBaseURL = (("https:" == document.location.protocol) ? "https://apps.sourceforge.net/piwik/matplotlib/" : "http://apps.sourceforge.net/piwik/matplotlib/");
-document.write(unescape("%3Cscript src='" + pkBaseURL + "piwik.js' type='text/javascript'%3E%3C/script%3E"));
-</script><script type="text/javascript">
-piwik_action_name = '';
-piwik_idsite = 1;
-piwik_url = pkBaseURL + "piwik.php";
-piwik_log(piwik_action_name, piwik_idsite, piwik_url);
+if ("matplotlib.sourceforge.net" == document.location.hostname ||
+ "matplotlib.sf.net" == document.location.hostname) {
+ var pkBaseURL = (("https:" == document.location.protocol) ? "https://apps.sourceforge.net/piwik/matplotlib/" : "http://apps.sourceforge.net/piwik/matplotlib/");
+ document.write(unescape("%3Cscript src='" + pkBaseURL + "piwik.js' type='text/javascript'%3E%3C/script%3E"));
+}
</script>
-<object><noscript><p><img src="http://apps.sourceforge.net/piwik/matplotlib/piwik.php?idsite=1" alt="piwik"/></p></noscript></object>
+<script type="text/javascript">
+if ("matplotlib.sourceforge.net" == document.location.hostname ||
+ "matplotlib.sf.net" == document.location.hostname) {
+ piwik_action_name = '';
+ piwik_idsite = 1;
+ piwik_url = pkBaseURL + "piwik.php";
+ piwik_log(piwik_action_name, piwik_idsite, piwik_url);
+ document.write(unescape('%3Cobject%3E%3Cnoscript%3E%3Cp%3E%3Cimg src="http://apps.sourceforge.net/piwik/matplotlib/piwik.php?idsite=1" alt="piwik"/%3E%3C/p%3E%3C/noscript%3E%3C/object%3E'));
+}
+</script>
<!-- End Piwik Tag -->
-<link rel="shortcut icon" href="_static/favicon.ico">
+<link rel="shortcut icon" href="_static/favicon.ico">
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<a href="{{ pathto('index') }}"><img src="{{
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2010-06-21 08:51:37
|
Revision: 8448
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8448&view=rev
Author: efiring
Date: 2010-06-21 08:51:30 +0000 (Mon, 21 Jun 2010)
Log Message:
-----------
Add Axes.tick_params and pyplot.tick_params to control tick and tick label appearance.
This allows interactive modification of tick and tick label color, size, etc.
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/boilerplate.py
trunk/matplotlib/lib/matplotlib/axes.py
trunk/matplotlib/lib/matplotlib/axis.py
trunk/matplotlib/lib/matplotlib/pyplot.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2010-06-20 23:31:49 UTC (rev 8447)
+++ trunk/matplotlib/CHANGELOG 2010-06-21 08:51:30 UTC (rev 8448)
@@ -1,3 +1,7 @@
+2010-06-20 Added Axes.tick_params and corresponding pyplot function
+ to control tick and tick label appearance after an Axes
+ has been created. - EF
+
2010-06-09 Allow Axes.grid to control minor gridlines; allow
Axes.grid and Axis.grid to control major and minor
gridlines in the same method call. - EF
Modified: trunk/matplotlib/boilerplate.py
===================================================================
--- trunk/matplotlib/boilerplate.py 2010-06-20 23:31:49 UTC (rev 8447)
+++ trunk/matplotlib/boilerplate.py 2010-06-21 08:51:30 UTC (rev 8448)
@@ -107,6 +107,7 @@
'annotate',
'ticklabel_format',
'locator_params',
+ 'tick_params',
'margins',
)
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2010-06-20 23:31:49 UTC (rev 8447)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2010-06-21 08:51:30 UTC (rev 8448)
@@ -2101,7 +2101,82 @@
self.yaxis.get_major_locator().set_params(**kwargs)
self.autoscale_view(tight=tight, scalex=_x, scaley=_y)
+ def tick_params(self, axis='both', **kwargs):
+ """
+ Convenience method for changing the appearance of ticks and
+ tick labels.
+ Keyword arguments:
+
+ *axis*
+ ['x' | 'y' | 'both'] Axis on which to operate;
+ default is 'both'.
+
+ *reset*
+ [True | False] If *True*, set all parameters to defaults
+ before processing other keyword arguments. Default is
+ *False*.
+
+ *which*
+ ['major' | 'minor' | 'both'] Default is 'major': apply
+ arguments to major ticks only.
+
+ *direction*
+ ['in' | 'out'] Puts ticks inside or outside the axes.
+
+ *length*
+ Tick length in points.
+
+ *width*
+ Tick width in points.
+
+ *color*
+ Tick color; accepts any mpl color spec.
+
+ *pad*
+ Distance in points between tick and label.
+
+ *labelsize*
+ Tick label font size in points or as a string (e.g. 'large').
+
+ *labelcolor*
+ Tick label color; mpl color spec.
+
+ *colors*
+ Changes the tick color and the label color to the same value:
+ mpl color spec.
+
+ *zorder*
+ Tick and label zorder.
+
+ *bottom*, *top*, *left*, *right*
+ Boolean or ['on' | 'off'], controls whether to draw the
+ respective ticks.
+
+ *labelbottom*, *labeltop*, *labelleft*, *labelright*
+ Boolean or ['on' | 'off'], controls whether to draw the
+ respective tick labels.
+
+ Example::
+
+ ax.tick_params(direction='out', length=6, width=2, colors='r')
+
+ This will make all major ticks be red, pointing out of the box,
+ and with dimensions 6 points by 2 points. Tick labels will
+ also be red.
+
+ """
+ if axis in ['x', 'both']:
+ xkw = dict(kwargs)
+ xkw.pop('top', None)
+ xkw.pop('bottom', None)
+ self.xaxis.set_tick_params(**xkw)
+ if axis in ['y', 'both']:
+ ykw = dict(kwargs)
+ ykw.pop('left', None)
+ ykw.pop('right', None)
+ self.yaxis.set_tick_params(**ykw)
+
def set_axis_off(self):
"""turn off the axis"""
self.axison = False
Modified: trunk/matplotlib/lib/matplotlib/axis.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axis.py 2010-06-20 23:31:49 UTC (rev 8447)
+++ trunk/matplotlib/lib/matplotlib/axis.py 2010-06-21 08:51:30 UTC (rev 8448)
@@ -60,7 +60,16 @@
"""
def __init__(self, axes, loc, label,
- size = None, # points
+
+ size = None, # points
+ width = None,
+ color = None,
+ tickdir = None,
+ pad = None,
+ labelsize = None,
+ labelcolor = None,
+ zorder = None,
+
gridOn = None, # defaults to axes.grid
tick1On = True,
tick2On = True,
@@ -71,7 +80,7 @@
"""
bbox is the Bound2D bounding box in display coords of the Axes
loc is the tick location in data coords
- size is the tick size in relative, axes coords
+ size is the tick size in points
"""
artist.Artist.__init__(self)
@@ -81,27 +90,47 @@
self.axes = axes
name = self.__name__.lower()
+ self._name = name
+
+ self._loc = loc
+
if size is None:
if major:
size = rcParams['%s.major.size'%name]
+ else:
+ size = rcParams['%s.minor.size'%name]
+ self._size = size
+
+ self._width = width # can be None for marker default
+
+ if color is None:
+ color = rcParams['%s.color' % name]
+ self._color = color
+
+ if pad is None:
+ if major:
pad = rcParams['%s.major.pad'%name]
else:
- size = rcParams['%s.minor.size'%name]
pad = rcParams['%s.minor.pad'%name]
+ self._base_pad = pad
- self._tickdir = rcParams['%s.direction'%name]
- if self._tickdir == 'in':
- self._xtickmarkers = (mlines.TICKUP, mlines.TICKDOWN)
- self._ytickmarkers = (mlines.TICKRIGHT, mlines.TICKLEFT)
- self._pad = pad
- else:
- self._xtickmarkers = (mlines.TICKDOWN, mlines.TICKUP)
- self._ytickmarkers = (mlines.TICKLEFT, mlines.TICKRIGHT)
- self._pad = pad + size
+ if labelcolor is None:
+ labelcolor = rcParams['%s.color' % name]
+ self._labelcolor = labelcolor
- self._loc = loc
- self._size = size
+ if labelsize is None:
+ labelsize = rcParams['%s.labelsize' % name]
+ self._labelsize = labelsize
+ if zorder is None:
+ if major:
+ zorder = mlines.Line2D.zorder + 0.01
+ else:
+ zorder = mlines.Line2D.zorder
+ self._zorder = zorder
+
+ self.apply_tickdir(tickdir)
+
self.tick1line = self._get_tick1line()
self.tick2line = self._get_tick2line()
self.gridline = self._get_gridline()
@@ -118,6 +147,20 @@
self.update_position(loc)
+ def apply_tickdir(self, tickdir):
+ if tickdir is None:
+ tickdir = rcParams['%s.direction' % self._name]
+ self._tickdir = tickdir
+
+ if self._tickdir == 'in':
+ self._xtickmarkers = (mlines.TICKUP, mlines.TICKDOWN)
+ self._ytickmarkers = (mlines.TICKRIGHT, mlines.TICKLEFT)
+ self._pad = self._base_pad
+ else:
+ self._xtickmarkers = (mlines.TICKDOWN, mlines.TICKUP)
+ self._ytickmarkers = (mlines.TICKLEFT, mlines.TICKRIGHT)
+ self._pad = self._base_pad + self._size
+
def get_children(self):
children = [self.tick1line, self.tick2line, self.gridline, self.label1, self.label2]
return children
@@ -242,15 +285,13 @@
# x in data coords, y in axes coords
#t = mtext.Text(
trans, vert, horiz = self.axes.get_xaxis_text1_transform(self._pad)
- size = rcParams['xtick.labelsize']
t = mtext.Text(
x=0, y=0,
- fontproperties=font_manager.FontProperties(size=size),
- color=rcParams['xtick.color'],
+ fontproperties=font_manager.FontProperties(size=self._labelsize),
+ color=self._labelcolor,
verticalalignment=vert,
horizontalalignment=horiz,
)
-
t.set_transform(trans)
self._set_artist_props(t)
return t
@@ -262,11 +303,10 @@
# x in data coords, y in axes coords
#t = mtext.Text(
trans, vert, horiz = self.axes.get_xaxis_text2_transform(self._pad)
-
t = mtext.Text(
x=0, y=1,
- fontproperties=font_manager.FontProperties(size=rcParams['xtick.labelsize']),
- color=rcParams['xtick.color'],
+ fontproperties=font_manager.FontProperties(size=self._labelsize),
+ color=self._labelcolor,
verticalalignment=vert,
horizontalalignment=horiz,
)
@@ -278,10 +318,12 @@
'Get the default line2D instance'
# x in data coords, y in axes coords
l = mlines.Line2D(xdata=(0,), ydata=(0,),
- color='k',
+ color=self._color,
linestyle = 'None',
marker = self._xtickmarkers[0],
markersize=self._size,
+ markeredgewidth=self._width,
+ zorder=self._zorder,
)
l.set_transform(self.axes.get_xaxis_transform(which='tick1'))
self._set_artist_props(l)
@@ -291,10 +333,12 @@
'Get the default line2D instance'
# x in data coords, y in axes coords
l = mlines.Line2D( xdata=(0,), ydata=(1,),
- color='k',
+ color=self._color,
linestyle = 'None',
marker = self._xtickmarkers[1],
markersize=self._size,
+ markeredgewidth=self._width,
+ zorder=self._zorder,
)
l.set_transform(self.axes.get_xaxis_transform(which='tick2'))
@@ -372,13 +416,11 @@
def _get_text1(self):
'Get the default Text instance'
# x in axes coords, y in data coords
- #t = mtext.Text(
trans, vert, horiz = self.axes.get_yaxis_text1_transform(self._pad)
-
t = mtext.Text(
x=0, y=0,
- fontproperties=font_manager.FontProperties(size=rcParams['ytick.labelsize']),
- color=rcParams['ytick.color'],
+ fontproperties=font_manager.FontProperties(size=self._labelsize),
+ color=self._labelcolor,
verticalalignment=vert,
horizontalalignment=horiz,
)
@@ -390,13 +432,11 @@
def _get_text2(self):
'Get the default Text instance'
# x in axes coords, y in data coords
- #t = mtext.Text(
trans, vert, horiz = self.axes.get_yaxis_text2_transform(self._pad)
-
t = mtext.Text(
x=1, y=0,
- fontproperties=font_manager.FontProperties(size=rcParams['ytick.labelsize']),
- color=rcParams['ytick.color'],
+ fontproperties=font_manager.FontProperties(size=self._labelsize),
+ color=self._labelcolor,
verticalalignment=vert,
horizontalalignment=horiz,
)
@@ -408,11 +448,14 @@
'Get the default line2D instance'
# x in axes coords, y in data coords
- l = mlines.Line2D( (0,), (0,), color='k',
+ l = mlines.Line2D( (0,), (0,),
+ color=self._color,
marker = self._ytickmarkers[0],
linestyle = 'None',
markersize=self._size,
- )
+ markeredgewidth=self._width,
+ zorder=self._zorder,
+ )
l.set_transform(self.axes.get_yaxis_transform(which='tick1'))
self._set_artist_props(l)
return l
@@ -420,12 +463,14 @@
def _get_tick2line(self):
'Get the default line2D instance'
# x in axes coords, y in data coords
- l = mlines.Line2D( (1,), (0,), color='k',
+ l = mlines.Line2D( (1,), (0,),
+ color=self._color,
marker = self._ytickmarkers[1],
linestyle = 'None',
markersize=self._size,
+ markeredgewidth=self._width,
+ zorder=self._zorder,
)
-
l.set_transform(self.axes.get_yaxis_transform(which='tick2'))
self._set_artist_props(l)
return l
@@ -549,6 +594,10 @@
self.minorTicks = []
self.pickradius = pickradius
+ # Initialize here for testing; later add API
+ self._major_tick_kw = dict()
+ self._minor_tick_kw = dict()
+
self.cla()
self.set_scale('linear')
@@ -631,10 +680,16 @@
self.label.set_text('')
self._set_artist_props(self.label)
+ self.reset_ticks()
+
+ self.converter = None
+ self.units = None
+ self.set_units(None)
+
+ def reset_ticks(self):
# build a few default ticks; grow as necessary later; only
# define 1 so properties set on ticks will be copied as they
# grow
-
cbook.popall(self.majorTicks)
cbook.popall(self.minorTicks)
@@ -643,10 +698,84 @@
self._lastNumMajorTicks = 1
self._lastNumMinorTicks = 1
- self.converter = None
- self.units = None
- self.set_units(None)
+ def set_tick_params(self, which='major', reset=False, **kw):
+ """
+ Set appearance parameters for ticks and ticklabels.
+ For documentation of keyword arguments, see
+ :meth:`matplotlib.axes.Axes.tick_params`.
+ """
+ dicts = []
+ if which == 'major' or which == 'both':
+ dicts.append(self._major_tick_kw)
+ if which == 'minor' or which == 'both':
+ dicts.append(self._minor_tick_kw)
+ kwtrans = self._translate_tick_kw(kw, to_init_kw=True)
+ for d in dicts:
+ if reset:
+ d.clear()
+ d.update(kwtrans)
+ self.reset_ticks()
+
+ @staticmethod
+ def _translate_tick_kw(kw, to_init_kw=True):
+ # We may want to move the following function to
+ # a more visible location; or maybe there already
+ # is something like this.
+ def _bool(arg):
+ if cbook.is_string_like(arg):
+ if arg.lower() == 'on':
+ return True
+ if arg.lower() == 'off':
+ return False
+ raise ValueError('String "%s" should be "on" or "off"' % arg)
+ return bool(arg)
+ # The following lists may be moved to a more
+ # accessible location.
+ kwkeys0 = ['size', 'width', 'color', 'tickdir', 'pad',
+ 'labelsize', 'labelcolor', 'zorder',
+ 'tick1On', 'tick2On', 'label1On', 'label2On']
+ kwkeys1 = ['length', 'direction', 'left', 'bottom', 'right', 'top',
+ 'labelleft', 'labelbottom', 'labelright', 'labeltop']
+ kwkeys = kwkeys0 + kwkeys1
+ kwtrans = dict()
+ if to_init_kw:
+ if 'length' in kw:
+ kwtrans['size'] = kw.pop('length')
+ if 'direction' in kw:
+ kwtrans['tickdir'] = kw.pop('direction')
+ if 'left' in kw:
+ kwtrans['tick1On'] = _bool(kw.pop('left'))
+ if 'bottom' in kw:
+ kwtrans['tick1On'] = _bool(kw.pop('bottom'))
+ if 'right' in kw:
+ kwtrans['tick2On'] = _bool(kw.pop('right'))
+ if 'top' in kw:
+ kwtrans['tick2On'] = _bool(kw.pop('top'))
+
+ if 'labelleft' in kw:
+ kwtrans['label1On'] = _bool(kw.pop('labelleft'))
+ if 'labelbottom' in kw:
+ kwtrans['label1On'] = _bool(kw.pop('labelbottom'))
+ if 'labelright' in kw:
+ kwtrans['label2On'] = _bool(kw.pop('labelright'))
+ if 'labeltop' in kw:
+ kwtrans['label2On'] = _bool(kw.pop('labeltop'))
+ if 'colors' in kw:
+ c = kw.pop('colors')
+ kwtrans['color'] = c
+ kwtrans['labelcolor'] = c
+ # Maybe move the checking up to the caller of this method.
+ for key in kw:
+ if key not in kwkeys:
+ raise ValueError(
+ "keyword %s is not recognized; valid keywords are %s"
+ % (key, kwkeys))
+ kwtrans.update(kw)
+ else:
+ raise NotImplementedError("Inverse translation is deferred")
+ return kwtrans
+
def set_clip_path(self, clippath, transform=None):
artist.Artist.set_clip_path(self, clippath, transform)
majorticks = self.get_major_ticks()
@@ -1303,13 +1432,18 @@
return inaxis, {}
def _get_tick(self, major):
- return XTick(self.axes, 0, '', major=major)
+ if major:
+ tick_kw = self._major_tick_kw
+ else:
+ tick_kw = self._minor_tick_kw
+ return XTick(self.axes, 0, '', major=major, **tick_kw)
def _get_label(self):
# x in axes coords, y in display coords (to be updated at draw
# time by _update_label_positions)
label = mtext.Text(x=0.5, y=0,
- fontproperties = font_manager.FontProperties(size=rcParams['axes.labelsize']),
+ fontproperties = font_manager.FontProperties(
+ size=rcParams['axes.labelsize']),
color = rcParams['axes.labelcolor'],
verticalalignment='top',
horizontalalignment='center',
@@ -1325,7 +1459,8 @@
def _get_offset_text(self):
# x in axes coords, y in display coords (to be updated at draw time)
offsetText = mtext.Text(x=1, y=0,
- fontproperties = font_manager.FontProperties(size=rcParams['xtick.labelsize']),
+ fontproperties = font_manager.FontProperties(
+ size=rcParams['xtick.labelsize']),
color = rcParams['xtick.color'],
verticalalignment='top',
horizontalalignment='right',
@@ -1562,7 +1697,11 @@
return inaxis, {}
def _get_tick(self, major):
- return YTick(self.axes, 0, '', major=major)
+ if major:
+ tick_kw = self._major_tick_kw
+ else:
+ tick_kw = self._minor_tick_kw
+ return YTick(self.axes, 0, '', major=major, **tick_kw)
def _get_label(self):
@@ -1570,7 +1709,8 @@
# y in axes coords
label = mtext.Text(x=0, y=0.5,
# todo: get the label position
- fontproperties=font_manager.FontProperties(size=rcParams['axes.labelsize']),
+ fontproperties=font_manager.FontProperties(
+ size=rcParams['axes.labelsize']),
color = rcParams['axes.labelcolor'],
verticalalignment='center',
horizontalalignment='right',
@@ -1586,7 +1726,8 @@
def _get_offset_text(self):
# x in display coords, y in axes coords (to be updated at draw time)
offsetText = mtext.Text(x=0, y=0.5,
- fontproperties = font_manager.FontProperties(size=rcParams['ytick.labelsize']),
+ fontproperties = font_manager.FontProperties(
+ size=rcParams['ytick.labelsize']),
color = rcParams['ytick.color'],
verticalalignment = 'baseline',
horizontalalignment = 'left',
Modified: trunk/matplotlib/lib/matplotlib/pyplot.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/pyplot.py 2010-06-20 23:31:49 UTC (rev 8447)
+++ trunk/matplotlib/lib/matplotlib/pyplot.py 2010-06-21 08:51:30 UTC (rev 8448)
@@ -1936,8 +1936,7 @@
# This function was autogenerated by boilerplate.py. Do not edit as
# changes will be lost
@autogen_docstring(Axes.boxplot)
-def boxplot(x, notch=0, sym='b+', vert=1, whis=1.5, positions=None, widths=None,
- hold=None, patch_artist=False):
+def boxplot(x, notch=0, sym='b+', vert=1, whis=1.5, positions=None, widths=None, patch_artist=False, bootstrap=None, hold=None):
ax = gca()
# allow callers to override the hold state by passing hold=True|False
washold = ax.ishold()
@@ -1945,8 +1944,7 @@
if hold is not None:
ax.hold(hold)
try:
- ret = ax.boxplot(x, notch, sym, vert, whis, positions, widths,
- patch_artist=patch_artist)
+ ret = ax.boxplot(x, notch, sym, vert, whis, positions, widths, patch_artist, bootstrap)
draw_if_interactive()
finally:
ax.hold(washold)
@@ -2136,7 +2134,7 @@
# This function was autogenerated by boilerplate.py. Do not edit as
# changes will be lost
@autogen_docstring(Axes.hist)
-def hist(x, bins=10, range=None, normed=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, hold=None, **kwargs):
+def hist(x, bins=10, range=None, normed=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, hold=None, **kwargs):
ax = gca()
# allow callers to override the hold state by passing hold=True|False
washold = ax.ishold()
@@ -2144,7 +2142,7 @@
if hold is not None:
ax.hold(hold)
try:
- ret = ax.hist(x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, **kwargs)
+ ret = ax.hist(x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, **kwargs)
draw_if_interactive()
finally:
ax.hold(washold)
@@ -2421,7 +2419,6 @@
sci(ret[-1])
return ret
-
# This function was autogenerated by boilerplate.py. Do not edit as
# changes will be lost
@autogen_docstring(Axes.stem)
@@ -2643,13 +2640,21 @@
# This function was autogenerated by boilerplate.py. Do not edit as
# changes will be lost
@docstring.copy_dedent(Axes.locator_params)
-def locator_params(axis='both', tight=False, **kwargs):
+def locator_params(axis='both', tight=None, **kwargs):
ret = gca().locator_params(axis, tight, **kwargs)
draw_if_interactive()
return ret
# This function was autogenerated by boilerplate.py. Do not edit as
# changes will be lost
+@docstring.copy_dedent(Axes.tick_params)
+def tick_params(axis='both', **kwargs):
+ ret = gca().tick_params(axis, **kwargs)
+ draw_if_interactive()
+ return ret
+
+# This function was autogenerated by boilerplate.py. Do not edit as
+# changes will be lost
@docstring.copy_dedent(Axes.margins)
def margins(*args, **kw):
ret = gca().margins(*args, **kw)
@@ -2879,3 +2884,6 @@
if im is not None:
im.set_cmap(cm.spectral)
draw_if_interactive()
+
+
+
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <lee...@us...> - 2010-06-20 23:31:55
|
Revision: 8447
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8447&view=rev
Author: leejjoon
Date: 2010-06-20 23:31:49 +0000 (Sun, 20 Jun 2010)
Log Message:
-----------
revert r8445,8446 and fix plot_directive.py to support sphinx 1.0
Modified Paths:
--------------
trunk/matplotlib/doc/faq/howto_faq.rst
trunk/matplotlib/lib/matplotlib/sphinxext/plot_directive.py
Modified: trunk/matplotlib/doc/faq/howto_faq.rst
===================================================================
--- trunk/matplotlib/doc/faq/howto_faq.rst 2010-06-20 20:55:42 UTC (rev 8446)
+++ trunk/matplotlib/doc/faq/howto_faq.rst 2010-06-20 23:31:49 UTC (rev 8447)
@@ -178,6 +178,9 @@
of each of the labels and uses it to move the left of the subplots
over so that the tick labels fit in the figure
+.. plot:: pyplots/auto_subplots_adjust.py
+ :include-source:
+
.. _howto-ticks:
Configure the tick linewidths
@@ -218,6 +221,9 @@
below shows the default behavior in the left subplots, and the manual
setting in the right subplots.
+.. plot:: pyplots/align_ylabels.py
+ :include-source:
+
.. _date-index-plots:
Skip dates where there is no data
Modified: trunk/matplotlib/lib/matplotlib/sphinxext/plot_directive.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/sphinxext/plot_directive.py 2010-06-20 20:55:42 UTC (rev 8446)
+++ trunk/matplotlib/lib/matplotlib/sphinxext/plot_directive.py 2010-06-20 23:31:49 UTC (rev 8447)
@@ -366,8 +366,13 @@
if options.has_key('include-source'):
if plot_code is None:
+ if sphinx_version > (1,):
+ include_prefix = '/'
+ else:
+ include_prefix = setup.app.builder.srcdir
+
lines.extend(
- ['.. include:: %s' % os.path.join(setup.app.builder.srcdir, plot_path),
+ ['.. include:: %s' % os.path.join(include_prefix, plot_path),
' :literal:'])
if options.has_key('encoding'):
lines.append(' :encoding: %s' % options['encoding'])
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <lee...@us...> - 2010-06-20 20:55:49
|
Revision: 8446
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8446&view=rev
Author: leejjoon
Date: 2010-06-20 20:55:42 +0000 (Sun, 20 Jun 2010)
Log Message:
-----------
remove align_ylabels.py entry from howto_faq.rst to test doc-build
Modified Paths:
--------------
trunk/matplotlib/doc/faq/howto_faq.rst
Modified: trunk/matplotlib/doc/faq/howto_faq.rst
===================================================================
--- trunk/matplotlib/doc/faq/howto_faq.rst 2010-06-20 20:05:57 UTC (rev 8445)
+++ trunk/matplotlib/doc/faq/howto_faq.rst 2010-06-20 20:55:42 UTC (rev 8446)
@@ -218,9 +218,6 @@
below shows the default behavior in the left subplots, and the manual
setting in the right subplots.
-.. plot:: pyplots/align_ylabels.py
- :include-source:
-
.. _date-index-plots:
Skip dates where there is no data
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <lee...@us...> - 2010-06-20 20:06:03
|
Revision: 8445
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8445&view=rev
Author: leejjoon
Date: 2010-06-20 20:05:57 +0000 (Sun, 20 Jun 2010)
Log Message:
-----------
remove auto_subplots_adjust.py entry from howto_faq.rst to test doc-build
Modified Paths:
--------------
trunk/matplotlib/doc/faq/howto_faq.rst
Modified: trunk/matplotlib/doc/faq/howto_faq.rst
===================================================================
--- trunk/matplotlib/doc/faq/howto_faq.rst 2010-06-20 20:05:49 UTC (rev 8444)
+++ trunk/matplotlib/doc/faq/howto_faq.rst 2010-06-20 20:05:57 UTC (rev 8445)
@@ -178,9 +178,6 @@
of each of the labels and uses it to move the left of the subplots
over so that the tick labels fit in the figure
-.. plot:: pyplots/auto_subplots_adjust.py
- :include-source:
-
.. _howto-ticks:
Configure the tick linewidths
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <lee...@us...> - 2010-06-20 20:05:55
|
Revision: 8444
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8444&view=rev
Author: leejjoon
Date: 2010-06-20 20:05:49 +0000 (Sun, 20 Jun 2010)
Log Message:
-----------
mpl_toolkits.axisartist.grid_finder.MaxNLocator supports factor
Modified Paths:
--------------
trunk/matplotlib/lib/mpl_toolkits/axisartist/grid_finder.py
Modified: trunk/matplotlib/lib/mpl_toolkits/axisartist/grid_finder.py
===================================================================
--- trunk/matplotlib/lib/mpl_toolkits/axisartist/grid_finder.py 2010-06-20 16:46:34 UTC (rev 8443)
+++ trunk/matplotlib/lib/mpl_toolkits/axisartist/grid_finder.py 2010-06-20 20:05:49 UTC (rev 8444)
@@ -260,14 +260,22 @@
trim=trim, integer=integer,
symmetric=symmetric, prune=prune)
self.create_dummy_axis()
+ self._factor = None
-
def __call__(self, v1, v2):
- self.set_bounds(v1, v2)
- locs = mticker.MaxNLocator.__call__(self)
- return np.array(locs), len(locs), None
+ if self._factor is not None:
+ self.set_bounds(v1*self._factor, v2*self._factor)
+ locs = mticker.MaxNLocator.__call__(self)
+ return np.array(locs), len(locs), self._factor
+ else:
+ self.set_bounds(v1, v2)
+ locs = mticker.MaxNLocator.__call__(self)
+ return np.array(locs), len(locs), None
+ def set_factor(self, f):
+ self._factor = f
+
class FixedLocator(object):
def __init__(self, locs):
self._locs = locs
@@ -287,11 +295,14 @@
def __init__(self):
self._fmt = mticker.ScalarFormatter()
self._fmt.create_dummy_axis()
+ self._ignore_factor = True
def __call__(self, direction, factor, values):
- if factor is None:
- factor = 1.
- values = [v/factor for v in values]
+ if not self._ignore_factor:
+ if factor is None:
+ factor = 1.
+ values = [v/factor for v in values]
+ #values = [v for v in values]
self._fmt.set_locs(values)
return [self._fmt(v) for v in values]
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2010-06-20 16:46:40
|
Revision: 8443
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8443&view=rev
Author: efiring
Date: 2010-06-20 16:46:34 +0000 (Sun, 20 Jun 2010)
Log Message:
-----------
finance: restore original adjustment algorithm, but use ndarray.
A numpy recarray replaces the Bunch when asobject is True.
Additional fields are provided.
Modified Paths:
--------------
trunk/matplotlib/examples/pylab_examples/date_demo1.py
trunk/matplotlib/examples/pylab_examples/date_demo2.py
trunk/matplotlib/examples/pylab_examples/finance_demo.py
trunk/matplotlib/lib/matplotlib/finance.py
Modified: trunk/matplotlib/examples/pylab_examples/date_demo1.py
===================================================================
--- trunk/matplotlib/examples/pylab_examples/date_demo1.py 2010-06-20 01:34:30 UTC (rev 8442)
+++ trunk/matplotlib/examples/pylab_examples/date_demo1.py 2010-06-20 16:46:34 UTC (rev 8443)
@@ -27,7 +27,7 @@
quotes = quotes_historical_yahoo(
'INTC', date1, date2)
-if not quotes:
+if len(quotes) == 0:
raise SystemExit
dates = [q[0] for q in quotes]
Modified: trunk/matplotlib/examples/pylab_examples/date_demo2.py
===================================================================
--- trunk/matplotlib/examples/pylab_examples/date_demo2.py 2010-06-20 01:34:30 UTC (rev 8442)
+++ trunk/matplotlib/examples/pylab_examples/date_demo2.py 2010-06-20 16:46:34 UTC (rev 8443)
@@ -23,7 +23,7 @@
quotes = quotes_historical_yahoo('INTC', date1, date2)
-if not quotes:
+if len(quotes) == 0:
print 'Found no quotes'
raise SystemExit
Modified: trunk/matplotlib/examples/pylab_examples/finance_demo.py
===================================================================
--- trunk/matplotlib/examples/pylab_examples/finance_demo.py 2010-06-20 01:34:30 UTC (rev 8442)
+++ trunk/matplotlib/examples/pylab_examples/finance_demo.py 2010-06-20 16:46:34 UTC (rev 8443)
@@ -5,20 +5,18 @@
from matplotlib.finance import quotes_historical_yahoo, candlestick,\
plot_day_summary, candlestick2
-import datetime
+# (Year, month, day) tuples suffice as args for quotes_historical_yahoo
+date1 = ( 2004, 2, 1)
+date2 = ( 2004, 4, 12 )
-date1 = datetime.date( 2004, 2, 1)
-date2 = datetime.date( 2004, 4, 12 )
-
mondays = WeekdayLocator(MONDAY) # major ticks on the mondays
alldays = DayLocator() # minor ticks on the days
weekFormatter = DateFormatter('%b %d') # Eg, Jan 12
dayFormatter = DateFormatter('%d') # Eg, 12
-quotes = quotes_historical_yahoo(
- 'INTC', date1, date2)
-if not quotes:
+quotes = quotes_historical_yahoo('INTC', date1, date2)
+if len(quotes) == 0:
raise SystemExit
fig = figure()
Modified: trunk/matplotlib/lib/matplotlib/finance.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/finance.py 2010-06-20 01:34:30 UTC (rev 8442)
+++ trunk/matplotlib/lib/matplotlib/finance.py 2010-06-20 16:46:34 UTC (rev 8443)
@@ -11,90 +11,130 @@
from hashlib import md5
except ImportError:
from md5 import md5 #Deprecated in 2.5
+import datetime
-try: import datetime
-except ImportError:
- raise ImportError('The finance module requires datetime support (python2.3)')
-
import numpy as np
from matplotlib import verbose, get_configdir
-from dates import date2num
-from matplotlib.cbook import Bunch
+from matplotlib.dates import date2num
+from matplotlib.cbook import iterable, is_string_like
from matplotlib.collections import LineCollection, PolyCollection
from matplotlib.colors import colorConverter
-from lines import Line2D, TICKLEFT, TICKRIGHT
-from patches import Rectangle
+from matplotlib.lines import Line2D, TICKLEFT, TICKRIGHT
+from matplotlib.patches import Rectangle
from matplotlib.transforms import Affine2D
-
configdir = get_configdir()
cachedir = os.path.join(configdir, 'finance.cache')
-def parse_yahoo_historical(fh, asobject=False, adjusted=True):
+stock_dt = np.dtype([('date', object),
+ ('year', np.int16),
+ ('month', np.int8),
+ ('day', np.int8),
+ ('d', np.float), # mpl datenum
+ ('open', np.float),
+ ('close', np.float),
+ ('high', np.float),
+ ('low', np.float),
+ ('volume', np.int),
+ ('aclose', np.float)])
+
+
+def parse_yahoo_historical(fh, adjusted=True, asobject=False):
"""
- Parse the historical data in file handle fh from yahoo finance and return
- results as a list of
+ Parse the historical data in file handle fh from yahoo finance.
- d, open, close, high, low, volume
+ *adjusted*
+ If True (default) replace open, close, high, low, and volume with
+ their adjusted values.
+ The adjustment is by a scale factor, S = adjusted_close/close.
+ Adjusted volume is actual volume divided by S;
+ Adjusted prices are actual prices multiplied by S. Hence,
+ the product of price and volume is unchanged by the adjustment.
- where d is a floating poing representation of date, as returned by date2num
+ *asobject*
+ If False (default for compatibility with earlier versions)
+ return a list of tuples containing
- if adjusted=True, use adjusted prices. Note that volume is not
- adjusted and we are not able to handle volume adjustments properly
- because the Yahoo CSV does not distinguish between split and
- dividend adjustments.
+ d, open, close, high, low, volume
+
+ If None (preferred alternative to False), return
+ a 2-D ndarray corresponding to the list of tuples.
+
+ Otherwise return a numpy recarray with
+
+ date, year, month, day, d, open, close, high, low,
+ volume, adjusted_close
+
+ where d is a floating poing representation of date,
+ as returned by date2num, and date is a python standard
+ library datetime.date instance.
+
+ The name of this kwarg is a historical artifact. Formerly,
+ True returned a cbook Bunch
+ holding 1-D ndarrays. The behavior of a numpy recarray is
+ very similar to the Bunch.
+
"""
- results = []
lines = fh.readlines()
- datefmt = None
+ results = []
+ datefmt = '%Y-%m-%d'
+
for line in lines[1:]:
vals = line.split(',')
-
- if len(vals)!=7: continue
+ if len(vals)!=7:
+ continue # add warning?
datestr = vals[0]
- if datefmt is None:
- try:
- datefmt = '%Y-%m-%d'
- dt = datetime.date(*time.strptime(datestr, datefmt)[:3])
- except ValueError:
- datefmt = '%d-%b-%y' # Old Yahoo--cached file?
- dt = datetime.date(*time.strptime(datestr, datefmt)[:3])
- d = date2num(dt)
+ #dt = datetime.date(*time.strptime(datestr, datefmt)[:3])
+ # Using strptime doubles the runtime. With the present
+ # format, we don't need it.
+ dt = datetime.date(*[int(val) for val in datestr.split('-')])
+ dnum = date2num(dt)
open, high, low, close = [float(val) for val in vals[1:5]]
volume = int(vals[5])
- if adjusted:
- aclose = float(vals[6])
- delta = aclose-close
- open += delta
- high += delta
- low += delta
- close = aclose
+ aclose = float(vals[6])
- results.append((d, open, close, high, low, volume))
+ results.append((dt, dt.year, dt.month, dt.day,
+ dnum, open, close, high, low, volume, aclose))
results.reverse()
- if asobject:
- if len(results)==0: return None
- else:
- date, open, close, high, low, volume = map(np.asarray, zip(*results))
- return Bunch(date=date, open=open, close=close, high=high, low=low, volume=volume)
- else:
+ d = np.array(results, dtype=stock_dt)
+ if adjusted:
+ scale = d['aclose'] / d['close']
+ scale[np.isinf(scale)] = np.nan
+ d['open'] *= scale
+ d['close'] *= scale
+ d['high'] *= scale
+ d['low'] *= scale
- return results
+ if not asobject:
+ # 2-D sequence; formerly list of tuples, now ndarray
+ ret = np.zeros((len(d), 6), dtype=np.float)
+ ret[:,0] = d['d']
+ ret[:,1] = d['open']
+ ret[:,2] = d['close']
+ ret[:,3] = d['high']
+ ret[:,4] = d['low']
+ ret[:,5] = d['volume']
+ if asobject is None:
+ return ret
+ return [tuple(row) for row in ret]
+ return d.view(np.recarray) # Close enough to former Bunch return
+
+
def fetch_historical_yahoo(ticker, date1, date2, cachename=None):
"""
Fetch historical data for ticker between date1 and date2. date1 and
- date2 are datetime instances
+ date2 are date or datetime instances, or (year, month, day) sequences.
Ex:
- fh = fetch_historical_yahoo('^GSPC', d1, d2)
+ fh = fetch_historical_yahoo('^GSPC', (2000, 1, 1), (2001, 12, 31))
cachename is the name of the local file cache. If None, will
default to the md5 hash or the url (which incorporates the ticker
@@ -106,8 +146,14 @@
ticker = ticker.upper()
- d1 = (date1.month-1, date1.day, date1.year)
- d2 = (date2.month-1, date2.day, date2.year)
+ if iterable(date1):
+ d1 = (date1[1]-1, date1[2], date1[0])
+ else:
+ d1 = (date1.month-1, date1.day, date1.year)
+ if iterable(date2):
+ d2 = (date2[1]-1, date2[2], date2[0])
+ else:
+ d2 = (date2.month-1, date2.day, date2.year)
urlFmt = 'http://table.finance.yahoo.com/table.csv?a=%d&b=%d&c=%d&d=%d&e=%d&f=%d&s=%s&y=0&g=d&ignore=.csv'
@@ -123,7 +169,8 @@
fh = file(cachename)
verbose.report('Using cachefile %s for %s'%(cachename, ticker))
else:
- if not os.path.isdir(cachedir): os.mkdir(cachedir)
+ if not os.path.isdir(cachedir):
+ os.mkdir(cachedir)
urlfh = urlopen(url)
fh = file(cachename, 'w')
@@ -135,27 +182,18 @@
return fh
-def quotes_historical_yahoo(ticker, date1, date2, asobject=False, adjusted=True, cachename=None):
+def quotes_historical_yahoo(ticker, date1, date2, asobject=False,
+ adjusted=True, cachename=None):
"""
Get historical data for ticker between date1 and date2. date1 and
- date2 are datetime instances
+ date2 are datetime instances or (year, month, day) sequences.
- results are a list of tuples
+ See :func:`parse_yahoo_historical` for explanation of output formats
+ and the *asobject* and *adjusted* kwargs.
- (d, open, close, high, low, volume)
-
- where d is a floating poing representation of date, as returned by date2num
-
- if asobject is True, the return val is an object with attrs date,
- open, close, high, low, volume, which are equal length arrays
-
- if adjusted=True, use adjusted prices. Note that volume is not
- adjusted and we are not able to handle volume adjustments properly
- because the Yahoo CSV does not distinguish between split and
- dividend adjustments.
-
Ex:
- sp = f.quotes_historical_yahoo('^GSPC', d1, d2, asobject=True, adjusted=True)
+ sp = f.quotes_historical_yahoo('^GSPC', d1, d2,
+ asobject=True, adjusted=True)
returns = (sp.open[1:] - sp.open[:-1])/sp.open[1:]
[n,bins,patches] = hist(returns, 100)
mu = mean(returns)
@@ -167,10 +205,18 @@
default to the md5 hash or the url (which incorporates the ticker
and date range)
"""
+ # Maybe enable a warning later as part of a slow transition
+ # to using None instead of False.
+ #if asobject is False:
+ # warnings.warn("Recommend changing to asobject=None")
fh = fetch_historical_yahoo(ticker, date1, date2, cachename)
- try: ret = parse_yahoo_historical(fh, asobject, adjusted)
+ try:
+ ret = parse_yahoo_historical(fh, asobject=asobject,
+ adjusted=adjusted)
+ if len(ret) == 0:
+ return None
except IOError, exc:
warnings.warn('urlopen() failure\n' + url + '\n' + exc.strerror[1])
return None
@@ -181,7 +227,7 @@
colorup='k', colordown='r',
):
"""
- quotes is a list of (time, open, close, high, low, ...) tuples
+ quotes is a sequence of (time, open, close, high, low, ...) sequences
Represent the time, open, close, high, low as a vertical line
ranging from low to high. The left tick is the open and the right
@@ -196,9 +242,6 @@
return value is a list of lines added
"""
-
-
-
lines = []
for q in quotes:
@@ -244,9 +287,9 @@
"""
- quotes is a list of (time, open, close, high, low, ...) tuples.
- As long as the first 5 elements of the tuples are these values,
- the tuple can be as long as you want (eg it may store volume).
+ quotes is a sequence of (time, open, close, high, low, ...) sequences.
+ As long as the first 5 elements are these values,
+ the record can be as long as you want (eg it may store volume).
time must be in float days format - see date2num
@@ -263,12 +306,11 @@
return value is lines, patches where lines is a list of lines
added and patches is a list of the rectangle patches added
+
"""
-
OFFSET = width/2.0
-
lines = []
patches = []
for q in quotes:
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2010-06-20 01:34:39
|
Revision: 8442
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8442&view=rev
Author: efiring
Date: 2010-06-20 01:34:30 +0000 (Sun, 20 Jun 2010)
Log Message:
-----------
[2564093] backend_wx: don't initialize printer by default; deprecate Printer*
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/backends/backend_wx.py
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_wx.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_wx.py 2010-06-19 23:46:47 UTC (rev 8441)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_wx.py 2010-06-20 01:34:30 UTC (rev 8442)
@@ -754,7 +754,11 @@
self.macros = {} # dict from wx id to seq of macros
- self.Printer_Init()
+ # printer attributes and methods deprecated, 2010/06/19
+ self._printerData = None
+ self._printerPageData = None
+ self.printer_width = 5.5
+ self.printer_margin = 0.5
def Destroy(self, *args, **kwargs):
wx.Panel.Destroy(self, *args, **kwargs)
@@ -769,7 +773,12 @@
wx.TheClipboard.Close()
def Printer_Init(self):
- """initialize printer settings using wx methods"""
+ """
+ initialize printer settings using wx methods
+
+ Deprecated.
+ """
+ warnings.warn("Printer* methods will be removed", DeprecationWarning)
self.printerData = wx.PrintData()
self.printerData.SetPaperId(wx.PAPER_LETTER)
self.printerData.SetPrintMode(wx.PRINT_MODE_PRINTER)
@@ -781,14 +790,37 @@
self.printer_width = 5.5
self.printer_margin= 0.5
+ def _get_printerData(self):
+ if self._printerData is None:
+ warnings.warn("Printer* methods will be removed", DeprecationWarning)
+ self._printerData = wx.PrintData()
+ self._printerData.SetPaperId(wx.PAPER_LETTER)
+ self._printerData.SetPrintMode(wx.PRINT_MODE_PRINTER)
+ return self._printerData
+ printerData = property(_get_printerData)
+
+ def _get_printerPageData(self):
+ if self._printerPageData is None:
+ warnings.warn("Printer* methods will be removed", DeprecationWarning)
+ self._printerPageData= wx.PageSetupDialogData()
+ self._printerPageData.SetMarginBottomRight((25,25))
+ self._printerPageData.SetMarginTopLeft((25,25))
+ self._printerPageData.SetPrintData(self.printerData)
+ return self._printerPageData
+ printerPageData = property(_get_printerPageData)
+
def Printer_Setup(self, event=None):
- """set up figure for printing. The standard wx Printer
+ """
+ set up figure for printing. The standard wx Printer
Setup Dialog seems to die easily. Therefore, this setup
- simply asks for image width and margin for printing. """
+ simply asks for image width and margin for printing.
+ Deprecated.
+ """
dmsg = """Width of output figure in inches.
The current aspect ratio will be kept."""
+ warnings.warn("Printer* methods will be removed", DeprecationWarning)
dlg = wx.Dialog(self, -1, 'Page Setup for Printing' , (-1,-1))
df = dlg.GetFont()
df.SetWeight(wx.NORMAL)
@@ -844,9 +876,14 @@
return
def Printer_Setup2(self, event=None):
- """set up figure for printing. Using the standard wx Printer
- Setup Dialog. """
+ """
+ set up figure for printing. Using the standard wx Printer
+ Setup Dialog.
+ Deprecated.
+ """
+
+ warnings.warn("Printer* methods will be removed", DeprecationWarning)
if hasattr(self, 'printerData'):
data = wx.PageSetupDialogData()
data.SetPrintData(self.printerData)
@@ -865,7 +902,12 @@
dlg.Destroy()
def Printer_Preview(self, event=None):
- """ generate Print Preview with wx Print mechanism"""
+ """
+ generate Print Preview with wx Print mechanism
+
+ Deprecated.
+ """
+ warnings.warn("Printer* methods will be removed", DeprecationWarning)
po1 = PrintoutWx(self, width=self.printer_width,
margin=self.printer_margin)
po2 = PrintoutWx(self, width=self.printer_width,
@@ -886,7 +928,12 @@
self.gui_repaint()
def Printer_Print(self, event=None):
- """ Print figure using wx Print mechanism"""
+ """
+ Print figure using wx Print mechanism
+
+ Deprecated.
+ """
+ warnings.warn("Printer* methods will be removed", DeprecationWarning)
pdd = wx.PrintDialogData()
# SetPrintData for 2.4 combatibility
pdd.SetPrintData(self.printerData)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2010-06-19 23:46:53
|
Revision: 8441
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8441&view=rev
Author: efiring
Date: 2010-06-19 23:46:47 +0000 (Sat, 19 Jun 2010)
Log Message:
-----------
[1530104, 3017380] slider grabs mouse; patch by C. Gohlke and baxissimo
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/backend_bases.py
trunk/matplotlib/lib/matplotlib/widgets.py
Modified: trunk/matplotlib/lib/matplotlib/backend_bases.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backend_bases.py 2010-06-17 17:45:38 UTC (rev 8440)
+++ trunk/matplotlib/lib/matplotlib/backend_bases.py 2010-06-19 23:46:47 UTC (rev 8441)
@@ -1122,7 +1122,10 @@
return
# Find all axes containing the mouse
- axes_list = [a for a in self.canvas.figure.get_axes() if a.in_axes(self)]
+ if self.canvas.mouse_grabber is None:
+ axes_list = [a for a in self.canvas.figure.get_axes() if a.in_axes(self)]
+ else:
+ axes_list = [self.canvas.mouse_grabber]
if len(axes_list) == 0: # None found
self.inaxes = None
@@ -1332,6 +1335,7 @@
self._lastx, self._lasty = None, None
self.button_pick_id = self.mpl_connect('button_press_event',self.pick)
self.scroll_pick_id = self.mpl_connect('scroll_event',self.pick)
+ self.mouse_grabber = None # the axes currently grabbing mouse
if False:
## highlight the artists that are hit
@@ -1610,6 +1614,26 @@
event = IdleEvent(s, self, guiEvent=guiEvent)
self.callbacks.process(s, event)
+ def grab_mouse(self, ax):
+ """
+ Set the child axes which are currently grabbing the mouse events.
+ Usually called by the widgets themselves.
+ It is an error to call this if the mouse is already grabbed by
+ another axes.
+ """
+ if self.mouse_grabber not in (None, ax):
+ raise RuntimeError('two different attempted to grab mouse input')
+ self.mouse_grabber = ax
+
+ def release_mouse(self, ax):
+ """
+ Release the mouse grab held by the axes, ax.
+ Usually called by the widgets.
+ It is ok to call this even if you ax doesn't have the mouse grab currently.
+ """
+ if self.mouse_grabber is ax:
+ self.mouse_grabber = None
+
def draw(self, *args, **kwargs):
"""
Render the :class:`~matplotlib.figure.Figure`
Modified: trunk/matplotlib/lib/matplotlib/widgets.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/widgets.py 2010-06-17 17:45:38 UTC (rev 8440)
+++ trunk/matplotlib/lib/matplotlib/widgets.py 2010-06-19 23:46:47 UTC (rev 8441)
@@ -106,6 +106,7 @@
ax.figure.canvas.mpl_connect('button_press_event', self._click)
+ ax.figure.canvas.mpl_connect('button_release_event', self._release)
ax.figure.canvas.mpl_connect('motion_notify_event', self._motion)
ax.set_navigate(False)
ax.set_axis_bgcolor(color)
@@ -117,8 +118,21 @@
self._lastcolor = color
def _click(self, event):
- if event.inaxes != self.ax: return
- if not self.eventson: return
+ if event.inaxes != self.ax:
+ return
+ if not self.eventson:
+ return
+ if event.canvas.mouse_grabber != self.ax:
+ event.canvas.grab_mouse(self.ax)
+
+ def _release(self, event):
+ if event.canvas.mouse_grabber != self.ax:
+ return
+ event.canvas.release_mouse(self.ax)
+ if not self.eventson:
+ return
+ if event.inaxes != self.ax:
+ return
for cid, func in self.observers.items():
func(event)
@@ -209,6 +223,7 @@
ax.set_navigate(False)
ax.figure.canvas.mpl_connect('button_press_event', self._update)
+ ax.figure.canvas.mpl_connect('button_release_event', self._update)
if dragging:
ax.figure.canvas.mpl_connect('motion_notify_event', self._update)
self.label = ax.text(-0.02, 0.5, label, transform=ax.transAxes,
@@ -227,14 +242,35 @@
self.closedmax = closedmax
self.slidermin = slidermin
self.slidermax = slidermax
+ self.drag_active = False
def _update(self, event):
'update the slider position'
- if event.button !=1: return
- if event.inaxes != self.ax: return
+ if event.button != 1:
+ return
+
+ if event.name == 'button_press_event' and event.inaxes == self.ax:
+ self.drag_active = True
+ event.canvas.grab_mouse(self.ax)
+
+ if not self.drag_active:
+ return
+
+ elif ((event.name == 'button_release_event')
+ or (event.name == 'button_press_event' and event.inaxes != self.ax)):
+ self.drag_active = False
+ event.canvas.release_mouse(self.ax)
+ return
+
val = event.xdata
- if not self.closedmin and val<=self.valmin: return
- if not self.closedmax and val>=self.valmax: return
+ if val <= self.valmin:
+ if not self.closedmin:
+ return
+ val = self.valmin
+ elif val >= self.valmax:
+ if not self.closedmax:
+ return
+ val = self.valmax
if self.slidermin is not None:
if val<=self.slidermin.val: return
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|