<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Bradley Froehle</title>
	<atom:link href="http://bfroehle.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://bfroehle.com</link>
	<description>PhD Candidate, UC Berkeley</description>
	<lastBuildDate>Fri, 27 Jan 2012 03:35:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Instance Methods &amp; Cython Functions</title>
		<link>http://bfroehle.com/2012/01/instance-methods-and-cython-functions/</link>
		<comments>http://bfroehle.com/2012/01/instance-methods-and-cython-functions/#comments</comments>
		<pubDate>Fri, 27 Jan 2012 03:35:19 +0000</pubDate>
		<dc:creator>Bradley Froehle</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Cython]]></category>
		<category><![CDATA[instancemethod]]></category>

		<guid isPermaLink="false">http://bfroehle.com/?p=121</guid>
		<description><![CDATA[One of the great features of Python is the ability to define methods outside of classes. For example, we can define a function which increments the attribute x and add it to a Point class: def incx(self): self.x += 1 &#8230; <a href="http://bfroehle.com/2012/01/instance-methods-and-cython-functions/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>One of the great features of <a href="http://python.org">Python</a> is the ability to define methods outside of classes. For example, we can define a function which increments the attribute <code>x</code> and add it to a <code>Point</code> class:</p>
<pre>def incx(self):
    self.x += 1

class Point(object):
    def __init__(self, x): self.x = x
    incx = incx</pre>
<p>We can then create a point at the origin and increment <code>x</code>:</p>
<pre>In [2]: p = Point(0)

In [3]: p.incx()

In [4]: print p.x
1</pre>
<p>The same code which defines <code>Point</code> continues to work if we move <code>incx</code> to another file, say <code>demo.py</code>, and import it using <code>from demo import incx</code>.</p>
<p>But if we were to put <code>incx</code> in <a href="https://raw.github.com/gist/1686654/demo.pyx"><code>demo.pyx</code></a> and compile it (using <code>python <a href="https://raw.github.com/gist/1686654/setup.py">setup.py</a> build_ext --inplace</code>), we get a strange error when running our <a href="https://raw.github.com/gist/1686654/bad.py">simple test</a>:</p>
<pre>$ python bad.py
Traceback (most recent call last):
  File &quot;bad.py&quot;, line 10, in &lt;module&gt;
    p.incx()
TypeError: incx() takes exactly one argument (0 given)
</pre>
<p>Read on to learn about instance methods and see how I fixed this.<br />
<span id="more-121"></span></p>
<p>My first thought was to write a simple wrapper function, using <a href="http://docs.python.org/library/functools.html#functools.wraps">functools.wraps</a> to preserve the docstring and name. This proved to be a clumsy solution.</p>
<p>A better approach turned out to be to use <a href="http://docs.python.org/library/types.html#types.MethodType"><code>types.MethodType</code></a> to convert our built-in function into an (unbound) instance method.  The docstring for <code>MethodType</code> is pretty short:</p>
<blockquote><p>instancemethod(function, instance, class)</p></blockquote>
<p>The first and third arguments are obvious.  For the second argument we&#8217;ll use <code>None</code> since we have no instance of the class yet, making this an <em>unbound</em> instance method.</p>
<p>So to fix our simple example, we need only replace the <code>incx = incx</code> line in the class definition with a short snippet after the class is defined:</p>
<pre>from types import MethodType
Point.incx = MethodType(incx, None, Point)
</pre>
<p>We can give this <a href="https://raw.github.com/gist/1686654/good.py">new version</a> a try and see that it works:<br />
<code>$ python good.py<br />
1<br />
</code></p>
<p><em>As always, the entire example is <a href="https://gist.github.com/1686654">available as a Gist</a>.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://bfroehle.com/2012/01/instance-methods-and-cython-functions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>True division in IPython</title>
		<link>http://bfroehle.com/2012/01/true-division-in-ipython/</link>
		<comments>http://bfroehle.com/2012/01/true-division-in-ipython/#comments</comments>
		<pubDate>Fri, 06 Jan 2012 16:54:01 +0000</pubDate>
		<dc:creator>Bradley Froehle</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[division]]></category>
		<category><![CDATA[IPython]]></category>

		<guid isPermaLink="false">http://bfroehle.com/?p=104</guid>
		<description><![CDATA[As Python transitions from version 2 to version 3, the meaning of the division operator on integers is changing: Python 2.x Python 3.x $ python2.7 Python 2.7.2+ (...) ... &#62;&#62;&#62; 1/2 0 $ python3.2 Python 3.2.2 (...) ... &#62;&#62;&#62; 1/2 &#8230; <a href="http://bfroehle.com/2012/01/true-division-in-ipython/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>As <a href="http://www.python.org/">Python</a> transitions from version 2 to version 3, the meaning of the <a href="http://www.python.org/dev/peps/pep-0238/">division operator</a> on integers is changing:</p>
<table>
<thead>
<tr>
<td>Python 2.x</td>
<td>Python 3.x</td>
</tr>
</thead>
<tbody>
<tr>
<td>
<pre>$ python2.7
Python 2.7.2+ (...)
...
&gt;&gt;&gt; 1/2
0</pre>
</td>
<td>
<pre>$ python3.2
Python 3.2.2 (...)
...
&gt;&gt;&gt; 1/2
0.5</pre>
</td>
</tr>
</tbody>
</table>
<p>In this post, we&#8217;ll discuss how to configure the behavior of the division operator in Python 2.7 and IPython to behave like the Python 3.x counterpart.</p>
<p><span id="more-104"></span>We&#8217;ll call the division in Python 2.x &#8220;classic&#8221; or &#8220;old.&#8221; It does division in the C sense: an integer divided by an integer yields an integer, rounding down if needed.</p>
<p>The &#8220;new&#8221; division in Python 3.x instead computes the true division result. In this case, an integer divided by an integer yields a float. The floor division can be accessed in a new operator &#8220;//&#8221; as in:<br />
<code></code></p>
<pre>&gt;&gt;&gt; 1 // 2
0</pre>
<p>To allow for a transition period, two compatibility features are provided. First, module developers can add <code></code></p>
<pre>from __future__ import division</pre>
<p>&nbsp;</p>
<p><code></code> to the top of any <code>.py</code> file to indicate that &#8220;/&#8221; should mean true division in that file.</p>
<p>In addition, the Python interpreter can be passed a flag to indicate the desired division behavior:<br />
<code></code></p>
<pre>-Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew</pre>
<p>&nbsp;</p>
<p><code></code><br />
So for example, we can run:<br />
<code></code></p>
<pre>$ python2.7 -Qnew
...
&gt;&gt;&gt; 1/2
0.5</pre>
<p>But what about IPython? There isn&#8217;t a corresponding flag on the <code>ipython</code> script, <a href="https://github.com/ipython/ipython/issues/1239">yet</a>. In discussing adding this feature to IPython, Fernando Perez provided <a href="https://github.com/ipython/ipython/issues/1239#issuecomment-3381024">a useful tip</a> for accomplishing this using the IPython configuration files.</p>
<p>To begin, you&#8217;ll need to create an IPython profile by running<br />
<code></code></p>
<pre>$ ipython profile create</pre>
<p>Then edit the configuration file, which for me was located at <code>~/.config/ipython/profile_default/ipython_config.py</code>, and uncomment and add the following:<br />
<code></code></p>
<pre># lines of code to run at IPython startup.
c.InteractiveShellApp.exec_lines = [
    &#039;from __future__ import division&#039;
]</pre>
<p>We can test it out and see that it does in fact work as desired:<br />
<code></code></p>
<pre>$ ipython
Python 2.7.2+ (default, Oct  4 2011, 20:06:09)
Type &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.

IPython 0.13.dev -- An enhanced Interactive Python.
?         -&gt; Introduction and overview of IPython&#039;s features.
%quickref -&gt; Quick reference.
help      -&gt; Python&#039;s own help system.
object?   -&gt; Details about &#039;object&#039;, use &#039;object??&#039; for extra details.

In [1]: 1/2
Out[1]: 0.5</pre>
]]></content:encoded>
			<wfw:commentRss>http://bfroehle.com/2012/01/true-division-in-ipython/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>IPython Qt Console and printf</title>
		<link>http://bfroehle.com/2011/10/ipython-qtconsole-and-printf/</link>
		<comments>http://bfroehle.com/2011/10/ipython-qtconsole-and-printf/#comments</comments>
		<pubDate>Thu, 13 Oct 2011 17:52:05 +0000</pubDate>
		<dc:creator>Bradley Froehle</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://bfroehle.com/?p=94</guid>
		<description><![CDATA[The recent 0.11 release of IPython includes a Qt-based console which offers an improved experience compared to running IPython in a terminal. In particular, the console feels like a terminal but offers multi-line editing, syntax highlighting, graphical tooltips, and inline &#8230; <a href="http://bfroehle.com/2011/10/ipython-qtconsole-and-printf/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>The recent <a href="http://ipython.org/ipython-doc/stable/whatsnew/version0.11.html">0.11 release</a> of <a href="http://ipython.org/">IPython</a> includes a <a href="http://ipython.org/ipython-doc/stable/interactive/qtconsole.html">Qt-based console</a> which offers an improved experience compared to running IPython in a terminal. In particular, the console feels like a terminal but offers multi-line editing, syntax highlighting, graphical tooltips, and inline plot figures.</p>
<p>But when I tried to run an existing script in the new IPython Qt Console, the usual overly verbose set of diagnostic messages did not appear! The symtoms were:</p>
<ul>
<li>Regular <code>print</code> statements in Python worked fine.</li>
<li><code>printf</code> statements in C-code wrapped with Boost.Python did not appear.</li>
</ul>
<p>Read on to see a solution.<span id="more-94"></span></p>
<p>This seemed quite odd until I read more about the architecture of IPython Qt Console. In particular, IPython Qt Console is a two-process architecture whereby a background IPython process executes code and frontend client handles all user input and output. So our <code>printf</code> statements were being sent to <code>stdout</code> in the background process and therefore never appear in the Qt Console window.</p>
<p>Somebody must have experienced this before, but a few quick Google searched turned up nothing. How would <a href="http://cython.org/">Cython</a> handle this? In particular, we could use Cython to compile a simple Python print statement. So consider the simple <code>printf.pyx</code> file:</p>
<pre class="brush: python; gutter: true">def printf():
    print "Hello"</pre>
<p>which we compile into C using <code>cython printf.pyx</code>. The <a href="https://gist.github.com/1284900">resulting C file</a> is quite lengthy, but the relevant bits are in the <code>__Pyx_PrintOne()</code> function:</p>
<pre class="brush: c; gutter: true">static int __Pyx_PrintOne(PyObject* f, PyObject *o) {
    if (!f) {
        if (!(f = __Pyx_GetStdout()))
            return -1;
    }
    if (PyFile_SoftSpace(f, 0)) {
        if (PyFile_WriteString(" ", f) &lt; 0)
            return -1;
    }
    if (PyFile_WriteObject(o, f, Py_PRINT_RAW) &lt; 0)
        return -1;
    if (PyFile_WriteString("\n", f) &lt; 0)
        return -1;
    return 0;
    /* the line below is just to avoid compiler
     * compiler warnings about unused functions */
    return __Pyx_Print(f, NULL, 0);
}</pre>
<p>The <code>__Pyx_GetStdout()</code> function is nothing more than a thin wrapper to <code>PySys_GetObject((char *)"stdout")</code> with a bit of error checking.</p>
<p>Putting this all together, a simple reporting function (without any error checking) becomes:</p>
<pre class="brush: cpp; gutter: true">void report(std::string msg) {
  PyObject *f = PySys_GetObject((char *)"stdout");
  PyFile_WriteString(msg.c_str(), f);
  PyFile_WriteString("\n", f);
}</pre>
<p>For an example module using this code, see <a href="https://gist.github.com/1284927">gist 1284927</a>.</p>
<p><strong>Update:</strong> After writing this, I learned of <a href="http://docs.python.org/c-api/sys.html#PySys_WriteStdout">PySys_WriteStdout()</a> which is a nearly drop-in replacement of printf.  However the above method is still be useful if you need to print more than 1000 bytes at a time.</p>
]]></content:encoded>
			<wfw:commentRss>http://bfroehle.com/2011/10/ipython-qtconsole-and-printf/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>FILE* and Boost.Python</title>
		<link>http://bfroehle.com/2011/10/file-and-boost-python/</link>
		<comments>http://bfroehle.com/2011/10/file-and-boost-python/#comments</comments>
		<pubDate>Wed, 05 Oct 2011 22:44:09 +0000</pubDate>
		<dc:creator>Bradley Froehle</dc:creator>
				<category><![CDATA[Boost.Python]]></category>
		<category><![CDATA[FILE*]]></category>

		<guid isPermaLink="false">http://bfroehle.com/?p=85</guid>
		<description><![CDATA[One great feature of Boost.Python is the ability to write custom converters from Python types to C++ arguments. Most Boost.Python documentation, including the incredibly helpful post by misspent, show you how to write &#8220;rvalue&#8221; converters (e.g., pass-by-value or pass-by-const-reference). However &#8230; <a href="http://bfroehle.com/2011/10/file-and-boost-python/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>One great feature of <a href="http://www.boost.org/doc/libs/1_47_0/libs/python/doc/">Boost.Python</a> is the ability to write custom converters from Python types to C++ arguments. Most <a href="http://www.boost.org/doc/libs/1_35_0/libs/python/doc/v2/faq.html#question2">Boost.Python documentation</a>, including the incredibly helpful post by <a href="http://misspent.wordpress.com/2009/09/27/how-to-write-boost-python-converters/">misspent</a>, show you how to write &#8220;rvalue&#8221; converters (e.g., pass-by-value or pass-by-const-reference).</p>
<p>However if you need to wrap a function which takes a <code>FILE*</code> argument the previous approach will not prove fruitful. But Boost.Python is clearly capable of handling a similar situation, namely the implicit conversion from a Python string type to a <code>char*</code> type. Since the conversion from the internal <code>PyObject*</code> to <code>char*</code> is likely to be done with the <a href="http://docs.python.org/c-api/string.html">PyString_AsString</a> function, I went off in search of that code.</p>
<p><span id="more-85"></span>There were no references in the installed headers, but it did appear in the source code in <code>converter/builtin_converters.cpp</code> in the <code>convert_to_cstring()</code> function:</p>
<pre class="brush: cpp; gutter: true">// An lvalue conversion function which extracts a char const* from a
// Python String.
void* convert_to_cstring(PyObject* obj)
{
  return PyString_Check(obj) ? PyString_AsString(obj) : 0;
}</pre>
<p>&#8230; which was later called as &#8230;</p>
<pre class="brush: cpp; gutter: true">// Add an lvalue converter for char which gets us char const*
registry::insert
  (convert_to_cstring, type_id(),
   &amp;converter::wrap_pytype&lt;&amp;PyString_Type&gt;::get_pytype);</pre>
<p>Jackpot! We should be able to mimic these lines to create a <a href="http://docs.python.org/library/stdtypes.html#file-objects">Python file</a> to <code>FILE*</code> converter using <a href="http://docs.python.org/c-api/file.html">PyFile_AsFile()</a>:</p>
<pre class="brush: cpp; gutter: true">#include &lt;boost/python.hpp&gt;

namespace {
  void *convert_to_FILEptr(PyObject* obj) {
    return PyFile_Check(obj) ? PyFile_AsFile(obj) : 0;
  }
}

BOOST_PYTHON_MODULE(file_wrapper) {
  boost::python::converter::registry::insert
    (convert_to_FILEptr,
     boost::python::type_id&lt;FILE&gt;(),
     &amp;boost::python::converter::wrap_pytype&lt;&amp;PyFile_Type&gt;::get_pytype);
}</pre>
<p>For a complete example including test code, see <a href="https://gist.github.com/1265889">gist: 1265889</a>.</p>
<p><strong>Edit:</strong> Of course this also works with <code>boost::python::extract&lt;FILE*&gt;</code>. I&#8217;ve updated the gist to demonstrate the relevant usage.</p>
]]></content:encoded>
			<wfw:commentRss>http://bfroehle.com/2011/10/file-and-boost-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Debugging MPI + Python</title>
		<link>http://bfroehle.com/2011/09/debugging-mpi-python/</link>
		<comments>http://bfroehle.com/2011/09/debugging-mpi-python/#comments</comments>
		<pubDate>Wed, 14 Sep 2011 18:44:55 +0000</pubDate>
		<dc:creator>Bradley Froehle</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[gdb]]></category>
		<category><![CDATA[IPython]]></category>
		<category><![CDATA[mpi]]></category>
		<category><![CDATA[mpirun]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[screen]]></category>

		<guid isPermaLink="false">http://bfroehle.com/?p=78</guid>
		<description><![CDATA[Python is increasingly becoming a popular language for controlling large numerical simulations due to its scripting abilities and easy bindings with C, C++, and Fortran as provided by ctypes, Boost.Python, SWIG, etc. In addition, there are some nice convenience wrappers for &#8230; <a href="http://bfroehle.com/2011/09/debugging-mpi-python/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Python is increasingly becoming a popular language for controlling large numerical simulations due to its scripting abilities and easy bindings with C, C++, and Fortran as provided by <a href="http://docs.python.org/library/ctypes.html">ctypes</a>, <a href="www.boost.org/doc/libs/release/libs/python/doc/">Boost.Python</a>, <a href="http://www.swig.org/">SWIG</a>, etc. In addition, there are some nice convenience wrappers for <a href="http://en.wikipedia.org/wiki/Message_Passing_Interface">MPI</a>, including <a href="http://mpi4py.scipy.org/">mpi4py</a>.</p>
<p>However debugging MPI scripts can be challenging. Here are some useful ways to run your programs for debugging.</p>
<ul>
<li>
Open an xterm window for each MPI process, with the script running in <a href="http://ipython.org/">iPython</a>.</p>
<pre class="brush: bash; gutter: true">$ mpirun -np 4 xterm -e "ipython script.py"</pre>
</li>
<li>
Open an xterm window for each MPI process, with <a href="http://www.gnu.org/s/gdb/">gdb</a> attached to each python process. The <code>-x</code> flag tells gdb to run the commands given in the specified file. This is often a good place to add additional breakpoints.</p>
<pre class="brush: bash; gutter: true">$ echo "run script.py" &gt; gdb.in
$ mpirun -np 4 xterm -e "gdb -x gdb.in python"</pre>
</li>
<li>
Open each MPI process within <a href="http://www.gnu.org/s/screen/">screen</a>, then open a <a href="http://en.wikipedia.org/wiki/GNOME_Terminal">gnome-terminal</a> with one tab for each screen.</p>
<pre class="brush: bash; gutter: true">$ mpirun -np 4 screen -L -m -D -S mpi \
    ipython script.py &amp;
$ gnome-terminal --tab -e "screen -RR -p mpi" \
                 --tab -e "screen -RR -p mpi" \
                 --tab -e "screen -RR -p mpi" \
                 --tab -e "screen -RR -p mpi"</pre>
<p>If your program dies unexpectedly, it is probably because LD_LIBRARY_PATH is <a href="http://lists.gnu.org/archive/html/screen-users/2008-01/msg00016.html">stripped by glibc</a> since screen is a setgid/setuid program. You can work around this my modifying the <code>mpirun</code> call as</p>
<pre class="brush: bash; gutter: true">$ mpirun -np 4 screen -L -m -D -S mpi \
    env LD_LIBRARY_PATH=$LD_LIBRARY_PATH ipython script.py</pre>
</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://bfroehle.com/2011/09/debugging-mpi-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Boost.Python and Boost.Function, II</title>
		<link>http://bfroehle.com/2011/07/boost-python-and-boost-function-ii/</link>
		<comments>http://bfroehle.com/2011/07/boost-python-and-boost-function-ii/#comments</comments>
		<pubDate>Mon, 18 Jul 2011 22:58:50 +0000</pubDate>
		<dc:creator>Bradley Froehle</dc:creator>
				<category><![CDATA[Boost.Python]]></category>
		<category><![CDATA[atexit]]></category>
		<category><![CDATA[Boost.Function]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://bfroehle.com/?p=63</guid>
		<description><![CDATA[In two previous posts we showed how to call C functions from other modules and Python methods from within a Boost.Python module.  Here we&#8217;ll show that the techniques are easily combined and demonstrate the atexit module which we&#8217;ll use to prevent &#8230; <a href="http://bfroehle.com/2011/07/boost-python-and-boost-function-ii/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In two previous posts we showed how to call <a title="Python Capsules" href="http://bfroehle.com/2011/07/python-capsules/">C functions from other modules</a> and <a title="Calling Python from C++" href="http://bfroehle.com/2011/07/boost-python-and-boost-function/">Python methods</a> from within a Boost.Python module.  Here we&#8217;ll show that the techniques are easily combined and demonstrate the <a href="http://docs.python.org/library/atexit.html">atexit</a> module which we&#8217;ll use to prevent Python interpreter crashes upon exit.</p>
<p><span id="more-63"></span></p>
<p>For this post we&#8217;ll use the <a title="Python Capsules" href="http://bfroehle.com/2011/07/python-capsules/">CppDuck.cpp</a> and <a title="Calling Python from C++" href="http://bfroehle.com/2011/07/boost-python-and-boost-function/">PyDuck.py</a> from previous posts, changing only the main Bird module.</p>
<p>Most of the code can remain the same, however we&#8217;ll need to now change setQuack() to identify whether the passed object is a callable Python method (using <a href="http://docs.python.org/c-api/object.html">PyCallable_Check</a>) or a capsule.</p>
<pre class="brush: cpp; gutter: true">void setQuack(object obj) {
  if (PyCallable_Check(obj.ptr())) {
    quacker = obj;
  }
  else {
    quacker = reinterpret_cast&lt;quacker_t*&gt;(PyCapsule_GetPointer(obj.ptr(), "quacker"));
  }
  if (PyErr_Occurred())
    throw_error_already_set();
}</pre>
<p>The remainder of Bird.cpp can be as in <a href="http://bfroehle.com/2011/07/boost-python-and-boost-function/">Calling Python from C++</a>. Usage is easy too:</p>
<pre>&gt;&gt;&gt; import Bird
&gt;&gt;&gt; import CppDuck
&gt;&gt;&gt; import PyDuck
&gt;&gt;&gt;
&gt;&gt;&gt; Bird.callQuack()
No noise came out.
&gt;&gt;&gt;
&gt;&gt;&gt; Bird.setQuack(CppDuck.getQuack())
&gt;&gt;&gt; Bird.callQuack()
C++ Quack
&gt;&gt;&gt;
&gt;&gt;&gt; Bird.setQuack(PyDuck.quack)
&gt;&gt;&gt; Bird.callQuack()
Python Quack</pre>
<p>On some versions of Python this may cause the program to crash at exit since Python interpreter may have already shut down before the quacker Boost.Function object is destroyed.  We can fix this by defining a simple finalize function:</p>
<pre class="brush: cpp; gutter: true">void finalize() {
  quacker.clear();
}</pre>
<p>And adding to the module:</p>
<pre class="brush: cpp; gutter: true">BOOST_PYTHON_MODULE(Bird) {
  // ...

  def("_finalize", &amp;finalize);
  // The following code executes:
  // import atexit
  // atexit.register(_finalize)
  object atexit = object(handle&lt;&gt;(PyImport_ImportModule("atexit")));
  object finalize = scope().attr("_finalize");
  atexit.attr("register")(finalize);
}</pre>
<p>This code ensures that the quacker object is cleared before Python is unloaded, preventing any potential crashes.</p>
<p>The full Bird.cpp program then looks like:</p>
<pre class="brush: cpp; gutter: true">#include &lt;boost/python.hpp&gt;
#include &lt;boost/function.hpp&gt;
#include &lt;iostream&gt;

using namespace boost::python;

typedef void (quacker_t)(void);
boost::function&lt;quacker_t&gt; quacker;

void default_quacker() {
  std::cout &lt;&lt; "No noise came out." &lt;&lt; std::endl;
}

void setQuack(object obj) {
  if (PyCallable_Check(obj.ptr())) {
    quacker = obj;
  }
  else {
    quacker = reinterpret_cast&lt;quacker_t*&gt;(PyCapsule_GetPointer(obj.ptr(), "quacker"));
  }
  if (PyErr_Occurred())
    throw_error_already_set();
}

void callQuack() {
  quacker();
}

void finalize() {
  quacker.clear();
}

BOOST_PYTHON_MODULE(Bird) {
  quacker = &amp;default_quacker;

  def("setQuack", &amp;setQuack);
  def("callQuack", &amp;callQuack);

  // Instead we register the function with the atexit module which
  // will be called _before_ the Python C-API is unloaded.
  def("_finalize", &amp;finalize);
  object atexit = object(handle&lt;&gt;(PyImport_ImportModule("atexit")));
  object finalize = scope().attr("_finalize");
  atexit.attr("register")(finalize);
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://bfroehle.com/2011/07/boost-python-and-boost-function-ii/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple Timer using Python&#8217;s With Statement</title>
		<link>http://bfroehle.com/2011/07/simple-timer/</link>
		<comments>http://bfroehle.com/2011/07/simple-timer/#comments</comments>
		<pubDate>Mon, 18 Jul 2011 22:18:52 +0000</pubDate>
		<dc:creator>Bradley Froehle</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[TicToc]]></category>
		<category><![CDATA[with_statement]]></category>

		<guid isPermaLink="false">http://bfroehle.com/?p=46</guid>
		<description><![CDATA[Python&#8217;s with statement, available since Python 2.5, does not seem to be widely used despite being very useful. Here we describe how to use the with statement to create a simple timer with the syntax: &#62;&#62;&#62; with TicToc(): ... some_slow_operations &#8230; <a href="http://bfroehle.com/2011/07/simple-timer/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Python&#8217;s <a href="http://www.python.org/dev/peps/pep-0343/">with statement</a>, available since Python 2.5, does not seem to be widely used despite being very useful.</p>
<p>Here we describe how to use the <code>with</code> statement to create a simple timer with the syntax:</p>
<pre>&gt;&gt;&gt; with TicToc():
...     some_slow_operations
...
Elapsed time is 2.000073 seconds.</pre>
<p>Readers familiar with <a href="http://www.mathworks.com/">MATLAB</a> will recognize the similarity to the familiar <a href="http://www.mathworks.com/help/techdoc/ref/toc.html">timing mechanism</a>:</p>
<pre>&gt; tic ; some_slow_operations; toc
Elapsed time is 10.020349 seconds.</pre>
<p><span id="more-46"></span></p>
<p>Before we describe the TicToc class, let&#8217;s review the <code>with</code> statement. The documentation for <a href="http://docs.python.org/tutorial/inputoutput.html">reading files</a> suggests that it is a good way to ensure files are properly closed, even if the code reading them raises an exception.</p>
<pre>&gt;&gt;&gt; with open('/tmp/workfile', 'r') as f:
...     read_data = f.read()
&gt;&gt;&gt; f.closed
True</pre>
<p>The with statement uses two methods, <code>__enter__</code>, which is run before the block executes, and <code>__exit__</code>, which is run after the block executes even if an exception is raised.  With this in mind, the previous code is <a href="http://effbot.org/zone/python-with-statement.htm">mostly equivalent</a> to:</p>
<pre>&gt;&gt;&gt; f = open('/tmp/workfile', 'r')
&gt;&gt;&gt; f.__enter__()
&lt;open file '/tmp/workfile', mode 'r' at 0x10041d810&gt;
&gt;&gt;&gt; read_data = f.read()
&gt;&gt;&gt; f.__exit__(None, None, None)
&gt;&gt;&gt; f.closed
True</pre>
<p>Here the method <code>file.__exit__</code> has automatically closed the file.</p>
<h2>TicToc</h2>
<p>The timer will be implemented as a class defining two methods:</p>
<ol>
<li><code>__enter__</code> which records the start time.</li>
<li><code>__exit__</code> which prints the difference between the current time and the start time.</li>
</ol>
<div>The actual code to simpletimer.py is quite short:</div>
<div>
<pre class="brush: cpp; gutter: true">import time
class TicToc(object):
    """
    A simple code timer.

    Example
    -------
    &gt;&gt;&gt; with TicToc():
    ...     time.sleep(2)
    Elapsed time is 2.000073 seconds.
    """
    def __init__(self, do_print = True):
        self.do_print = do_print
    def __enter__(self):
        self.start_time = time.time()
        return self
    def __exit__(self, type, value, traceback):
        self.elapsed = time.time() - self.start_time
        if self.do_print:
            print "Elapsed time is %f seconds." % self.elapsed</pre>
</div>
<div>Usage is simple:</div>
<div>
<pre>&gt;&gt;&gt; from simpletimer import TicToc
&gt;&gt;&gt; import time
&gt;&gt;&gt; with TicToc():
...     time.sleep(2)
...
Elapsed time is 2.000115 seconds.
&gt;&gt;&gt; with TicToc(False) as t:
...     time.sleep(1)
...
&gt;&gt;&gt; t.elapsed
1.0001189708709717</pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://bfroehle.com/2011/07/simple-timer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Calling Python from C++</title>
		<link>http://bfroehle.com/2011/07/boost-python-and-boost-function/</link>
		<comments>http://bfroehle.com/2011/07/boost-python-and-boost-function/#comments</comments>
		<pubDate>Mon, 18 Jul 2011 21:30:42 +0000</pubDate>
		<dc:creator>Bradley Froehle</dc:creator>
				<category><![CDATA[Boost.Python]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Boost.Function]]></category>

		<guid isPermaLink="false">http://bfroehle.com/?p=39</guid>
		<description><![CDATA[In a previous post we already covered calling a C function from one Boost.Python module in another module. What if instead we want to call a Python function directly from C? We&#8217;ll stick with the same Bird / Quacker metaphor &#8230; <a href="http://bfroehle.com/2011/07/boost-python-and-boost-function/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In a <a title="Python Capsules" href="http://bfroehle.com/2011/07/python-capsules/">previous post</a> we already covered calling a C function from one Boost.Python module in another module.</p>
<p>What if instead we want to call a Python function directly from C? We&#8217;ll stick with the same Bird / Quacker metaphor as in the previous post, but we&#8217;ll now implement our duck class in PyDuck.py:</p>
<pre class="brush: python; gutter: true">"""
PyDuck.py
"""

def quack():
    print "Python Quack"</pre>
<p>Now how can we call Python from C++? It turns out that Boost.Python defines operator() for the object class, so calling Python is relatively easy.  But things become more difficult if we want to maintain a default implementation in C.</p>
<p><span id="more-39"></span></p>
<p>For example, one could imagine testing whether the Python object is set each time&#8230;</p>
<pre class="brush: cpp; gutter: true">object quacker;

void callQuack() {
  if (quacker) {
    quacker();
  } else {
    default_quacker();
  }
}</pre>
<p>But a cleaner approach is to instead use <a href="http://www.boost.org/doc/libs/1_47_0/doc/html/function.html">Boost.Function</a>. This will allow all calls to use the same syntax as before, both when the quacker is set to a pure C function (i.e., default_quacker) or a callable Python object.</p>
<p>The final Bird.cpp file follows:</p>
<pre class="brush: cpp; gutter: true">#include &lt;boost/python.hpp&gt;
#include &lt;boost/function.hpp&gt;
#include &lt;iostream&gt;

using namespace boost::python;

typedef void (quacker_t)(void);
boost::function&lt;quacker_t&gt; quacker;

void default_quacker() {
  std::cout &lt;&lt; "No noise came out." &lt;&lt; std::endl;
}

void setQuack(object obj) {
  quacker = obj;
}

void callQuack() {
  quacker();
}

BOOST_PYTHON_MODULE(Bird) {
  quacker = &amp;default_quacker;

  def("setQuack", &amp;setQuack);
  def("callQuack", &amp;callQuack);
}</pre>
<p>Testing it out:</p>
<pre>&gt;&gt;&gt; import Bird
&gt;&gt;&gt; import PyDuck
&gt;&gt;&gt;
&gt;&gt;&gt; Bird.callQuack()
No noise came out.
&gt;&gt;&gt;
&gt;&gt;&gt; Bird.setQuack(PyDuck.quack)
&gt;&gt;&gt; Bird.callQuack()
Python Quack</pre>
]]></content:encoded>
			<wfw:commentRss>http://bfroehle.com/2011/07/boost-python-and-boost-function/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Python Capsules</title>
		<link>http://bfroehle.com/2011/07/python-capsules/</link>
		<comments>http://bfroehle.com/2011/07/python-capsules/#comments</comments>
		<pubDate>Mon, 18 Jul 2011 21:02:10 +0000</pubDate>
		<dc:creator>Bradley Froehle</dc:creator>
				<category><![CDATA[Boost.Python]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Capsules]]></category>
		<category><![CDATA[PyCapsule]]></category>

		<guid isPermaLink="false">http://bfroehle.com/?p=27</guid>
		<description><![CDATA[Python Capsules are useful for passing C pointers between different Python modules.  In particular, one can encapsulate a C function pointer in one module and unpack and call it in another module. To begin, suppose we have two Boost.Python modules: Bird, &#8230; <a href="http://bfroehle.com/2011/07/python-capsules/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Python <a href="http://docs.python.org/release/2.7.2/c-api/capsule.html">Capsules</a> are useful for passing C pointers between different Python modules.  In particular, one can encapsulate a C function pointer in one module and unpack and call it in another module.</p>
<p>To begin, suppose we have two Boost.Python modules:</p>
<ol>
<li><strong>Bird</strong>, which has methods setQuack() and callQuack().</li>
<li><strong>CppDuck</strong>, which has a method getQuack().</li>
</ol>
<p>Our goal will be to get a function pointer with CppDuck.getQuack(), set it in another module in Bird.setQuack(), and finally call it with Bird.callQuack().</p>
<p><span id="more-27"></span></p>
<p>First let&#8217;s look at the code for CppDuck.cpp:</p>
<pre class="brush: cpp; gutter: true">#include &lt;boost/python.hpp&gt;
#include &lt;iostream&gt;

using namespace boost::python;

void quack() {
  std::cout &lt;&lt; "C++ Quack" &lt;&lt; std::endl;
}

boost::python::object getQuack() {
  PyObject *result = PyCapsule_New((void*)&amp;quack, "quacker", NULL);
  return object(boost::python::detail::new_reference(result));
}

BOOST_PYTHON_MODULE(CppDuck) {
  def("getQuack", &amp;getQuack);
}</pre>
<p>Note that we define a <code>void (void)</code> function &#8220;quack&#8221; which we will eventually pass to the Bird module. The method &#8220;getQuack&#8221; encapsulates it, and returns it as a Boost.Python object. Since <a href="http://docs.python.org/release/2.7.2/c-api/capsule.html">PyCapsule_New</a>() returns a new reference, we use <code>boost::python::detail::new_reference</code> to get the reference counting correct.</p>
<p>After compiling the module, we can try it out:</p>
<pre>&gt;&gt;&gt; import CppDuck
&gt;&gt;&gt; CppDuck.getQuack()
&lt;capsule object "quacker" at 0x100464930&gt;</pre>
<p>Let&#8217;s move on and see now how we can unpack the function pointer and call it in Bird.cpp:</p>
<pre class="brush: cpp; gutter: true">#include &lt;boost/python.hpp&gt;
#include &lt;iostream&gt;

using namespace boost::python;

typedef void (quacker_t)(void);
quacker_t *quacker;

void default_quacker() {
  std::cout &lt;&lt; "No noise came out." &lt;&lt; std::endl;
}

void setQuack(object obj) {
  quacker = reinterpret_cast&lt;quacker_t*&gt;(PyCapsule_GetPointer(obj.ptr(), "quacker"));
  if (PyErr_Occurred())
    throw_error_already_set();
}

BOOST_PYTHON_MODULE(Bird) {
  quacker = &amp;default_quacker;

  def("setQuack", &amp;setQuack);
  def("callQuack", quacker);
}</pre>
<p>Note the following conveniences in the code:</p>
<ol>
<li>We create a typedef the function type — in this case void (void) — since we use it in multiple places.</li>
<li>We set a default quack function when the Python module is initialized. Without this, the Python interpreter will crash if we call callQuack before setting a valid quack.</li>
<li>PyCapsule_GetPointer gets passed the same string (i.e., &#8220;quacker&#8221;) as we passed to PyCapsule_New in Bird.cpp.</li>
<li>We use <code>boost::python::throw_error_already_set()</code> to display error messages. For example
<pre>&gt;&gt;&gt; Bird.setQuack(map)
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
ValueError: PyCapsule_GetPointer called with invalid PyCapsule object</pre>
</li>
</ol>
<p>With both modules compiled, we can try it:</p>
<pre>&gt;&gt;&gt; import Bird
&gt;&gt;&gt; import CppDuck
&gt;&gt;&gt;
&gt;&gt;&gt; Bird.callQuack()
No noise came out.
&gt;&gt;&gt;
&gt;&gt;&gt; quack = CppDuck.getQuack()
&gt;&gt;&gt; Bird.setQuack(quack)
&gt;&gt;&gt;
&gt;&gt;&gt; Bird.callQuack()
No noise came out.</pre>
]]></content:encoded>
			<wfw:commentRss>http://bfroehle.com/2011/07/python-capsules/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Boost.Python Submodules</title>
		<link>http://bfroehle.com/2011/07/boost-python-submodules/</link>
		<comments>http://bfroehle.com/2011/07/boost-python-submodules/#comments</comments>
		<pubDate>Mon, 18 Jul 2011 18:56:48 +0000</pubDate>
		<dc:creator>Bradley Froehle</dc:creator>
				<category><![CDATA[Boost.Python]]></category>
		<category><![CDATA[submodule]]></category>

		<guid isPermaLink="false">http://bfroehle.com/?p=5</guid>
		<description><![CDATA[I&#8217;ve been using Boost.Python to wrap a C++ library for use in Python for the past few months, and recently needed to have one compiled .so (or .pyd) file behave as a package instead of as a module.  That is, I wanted &#8230; <a href="http://bfroehle.com/2011/07/boost-python-submodules/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been using <a href="http://www.boost.org/doc/libs/1_47_0/libs/python/doc/">Boost.Python</a> to wrap a C++ library for use in Python for the past few months, and recently needed to have one compiled .so (or .pyd) file behave as a package instead of as a module.  That is, I wanted the one file to behave as if it was actually a directory of Python files:</p>
<pre>/application
    __init__.py
    submodule.py</pre>
<p><span id="more-5"></span></p>
<p>I found a <a href="http://isolation-nation.blogspot.com/2008/09/packages-in-python-extension-modules.html">helpful post</a> which uses <a href="http://docs.python.org/c-api/import.html">PyImport_AddModule</a>(&#8220;application.submodule&#8221;) to initialize a new Python module and <code>boost::python::scope</code> to add classes and method definitions to that module.</p>
<p>Unfortunately in my use &#8220;application&#8221; is not known at compile time — instead the C++ code is compiled into a static library which is reused for many different applications.  However, the same method will work if we first use the <code>__name__</code> attribute to get the application name.</p>
<pre class="brush: cpp">#include &lt;boost/python.hpp&gt;
using namespace boost::python;

/**
 * Methods and classes exposed by application.submodule.
 */
void import_application_submodule() {
  def("method1", &amp;method1);
  // ...
}
/**
 * Methods and classes exposed by application.
 */
void import_application() {
  scope current;
  std::string submoduleName(extract&lt;const char*&gt;(current.attr("__name__")));
  submoduleName.append(".submodule");

  // Create the submodule, and attach it to the current scope.
  object submodule(borrowed(PyImport_AddModule(submoduleName.c_str())));
  current.attr("submodule") = submodule;

  {
    // Switch the scope to the submodule, add methods and classes.
    scope submoduleScope = submodule;
    import_application_submodule();
  }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://bfroehle.com/2011/07/boost-python-submodules/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: basic

Served from: bfroehle.com @ 2012-05-18 22:02:55 -->
