<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>Python on shocksolution.com</title><link>https://shocksolution.com/tags/python/</link><description>Recent content in Python on shocksolution.com</description><generator>Hugo</generator><language>en-us</language><lastBuildDate>Mon, 23 Apr 2018 12:23:29 +0000</lastBuildDate><atom:link href="https://shocksolution.com/tags/python/index.xml" rel="self" type="application/rss+xml"/><item><title>Service account credentials with the Python client for the Google Drive API (v3)</title><link>https://shocksolution.com/posts/service-account-credentials-python-client-google-drive-api-v3/</link><pubDate>Mon, 23 Apr 2018 12:23:29 +0000</pubDate><guid>https://shocksolution.com/posts/service-account-credentials-python-client-google-drive-api-v3/</guid><description>&lt;p&gt;&lt;strong&gt;EDIT:&lt;/strong&gt; &lt;a href="https://github.com/cfinch/Shocksolution_Examples/blob/master/GoogleCloudPlatform/driveAPIexample.py"&gt;Get the full code for this post on Github&lt;/a&gt;. This article only contains important snippets of code that require explanation.&lt;/p&gt;&#10;&lt;p&gt;There are numerous ways to authenticate against the Google Drive API. If you have an application running on Google Compute Engine that needs to access Drive, a Service Account is probably the easiest way to do it. One use case is for an application to write reports or log files to Drive so that users can see them without logging into a server. Before you try this example, go through all of the steps in Google&amp;rsquo;s &lt;a href="https://developers.google.com/identity/protocols/OAuth2ServiceAccount"&gt;Using OAuth 2.0 for Server to Server Applications&lt;/a&gt; guide and save your service account&amp;rsquo;s private key locally in JSON format. Getting credentials from a service account file is easy:&lt;/p&gt;</description></item><item><title>pickle, hickle and HDF5</title><link>https://shocksolution.com/posts/pickle-hickle-and-hdf5/</link><pubDate>Sun, 03 Feb 2013 19:33:57 +0000</pubDate><guid>https://shocksolution.com/posts/pickle-hickle-and-hdf5/</guid><description>&lt;p&gt;&lt;a href="http://%3C%3Cwww.thetelegraphic.com/&amp;amp;gt%3E;" title="Danny%20Price"&gt;Danny Price&lt;/a&gt; recently left a comment to let me know about a new Python package he&amp;rsquo;s developing called &lt;a href="https://github.com/telegraphic/hickle" title="hickle"&gt;hickle&lt;/a&gt;. The goal of &amp;ldquo;hickle&amp;rdquo; is to create a module that works like Python&amp;rsquo;s &lt;a href="http://docs.python.org/2/library/pickle.html" title="Pickle"&gt;pickle&lt;/a&gt; module but stores its data in the &lt;a href="http://%3C%3Cwww.hdfgroup.org/HDF5/&amp;amp;gt%3E;" title="HDF5%20Project"&gt;HDF5&lt;/a&gt; binary file format. This is a promising approach, because I advocate storing binary data in HDF5 files whenever possible instead of creating yet another one-off binary file format that nobody will be able to read in ten years. The immediate advantage of using HDF5 to store picked Python objects is that HDF5 files are portable across many platforms, while &amp;ldquo;pickled&amp;rdquo; objects may not be readable on a different platform. The hickle developers have made a good start, and they have a long way to go before hickle will be useful to a wider audience. Right now, hickle can only store NumPy ndarrays and Python list objects. If you only need to store lists and arrays, you might as well use HDF5 bindings for Python such as &lt;a href="http://%3C%3Cwww.pytables.org/moin&amp;amp;gt%3E;" title="PyTables"&gt;PyTables&lt;/a&gt; or &lt;a href="http://%3C%3Cwww.h5py.org/&amp;amp;gt%3E;" title="HDF5%20for%20Python"&gt;h5py&lt;/a&gt;. The power of the pickle module is that you can immediately serialize almost any Python object of arbitrary complexity, store it on disk, and retrieve it. hickle will only achieve its full potential once it replicates this functionality, and I&amp;rsquo;m not sure how difficult this will be. Ideally, you might be able to derive a class from Pickler that uses Picker&amp;rsquo;s methods to serialize an object, and then add your own method to write the serialized object to an HDF5 file. In a future post, I&amp;rsquo;ll describe some of the practical problems with using pickle files to store data, and try to organize some thoughts about how they might be solved.&lt;/p&gt;</description></item><item><title>Building NumPy and SciPy with Intel Composer 2013 and the MKL</title><link>https://shocksolution.com/posts/building-numpy-and-scipy-with-intel-composer-2013-and-the-mkl/</link><pubDate>Wed, 16 Jan 2013 22:29:19 +0000</pubDate><guid>https://shocksolution.com/posts/building-numpy-and-scipy-with-intel-composer-2013-and-the-mkl/</guid><description>&lt;p&gt;Since Python is widely used as a high-productivity language for scientific computing, &lt;a href="http://software.intel.com/en-us/articles/numpy-scipy-with-mkl" title="Intel:%20building%20NumPy%20with%20Intel%20compilers%20and%20MKL"&gt;Intel has created a page showing how to build NumPy with Intel compilers and the Math Kernel Library (MKL)&lt;/a&gt;. I would like to clarify a few items regarding building NumPy on a 64-bit Red Hat Enterprise Linux 5.4 system. Since this is a production system, I don&amp;rsquo;t want to replace the Python 2.4 binary -2.7.3-intel-composer-2013that ships with RHEL 5.4. Instead, I created a directory called&lt;/p&gt;</description></item><item><title>Tricks for Writing XML with Python 3</title><link>https://shocksolution.com/posts/tricks-for-writing-xml-with-python-3/</link><pubDate>Thu, 27 Sep 2012 16:35:49 +0000</pubDate><guid>https://shocksolution.com/posts/tricks-for-writing-xml-with-python-3/</guid><description>&lt;p&gt;I&amp;rsquo;ve added a &lt;a href="https://github.com/cfinch/Shocksolution_Examples" title="Example:%20generating%20XML%20with%20ElementTree%20in%20Python%203"&gt;Python 3 XML example to my Shocksolution_Examples repo on GitHub&lt;/a&gt;.  The new example shows how to generate an XML file which functions as a template for &lt;a href="http://wxglade.sourceforge.net/" title="wxGlade%20rapid%20GUI%20builder%20tool"&gt;building a GUI with wxGlade&lt;/a&gt;.  However, this example should be helpful for anyone who needs to create XML files with Python.  The full example is on GitHub, so I&amp;rsquo;m just going to highlight a few interesting snippets. Use the SubElement factory function to create a new Element instance and add it to an existing element. Here, I create an element called &lt;em&gt;templatedata&lt;/em&gt; and add it to the root element. I then create another element called &lt;em&gt;author&lt;/em&gt; and add it to templatedata.&lt;/p&gt;</description></item><item><title>Building SciPy with Intel compilers and MKL on 64bit RHEL 5</title><link>https://shocksolution.com/posts/building-scipy-with-intel-compilers-and-mkl-on-64bit-rhel-5/</link><pubDate>Mon, 02 Jul 2012 17:14:54 +0000</pubDate><guid>https://shocksolution.com/posts/building-scipy-with-intel-compilers-and-mkl-on-64bit-rhel-5/</guid><description>&lt;p&gt;This is a follow-up to my earlier &lt;a href="https://shocksolution.com/2012/04/building-numpy-on-a-red-hat-cluster-with-intel-mkl/" title="NumPy%20on%2064%20bit%20RHEL%205%20with%20Intel%20Compilers%20and%20MKL"&gt;post about building NumPy with Intel compilers and the Intel MKL on CentOS 5&lt;/a&gt;. I will now explain how to build SciPy (which requires NumPy). First, download and unpack the SciPy source tarball. The following command can be used to build SciPy:&lt;/p&gt;&#10;&lt;div class="code-block"&gt;&#10; &lt;button class="code-copy" type="button" hidden aria-label="Copy code to clipboard"&gt;&#10; &lt;span class="code-copy-label" aria-hidden="true"&gt;Copy&lt;/span&gt;&#10; &lt;/button&gt;&#10; &lt;div class="highlight"&gt;&lt;pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"&gt;&lt;code class="language-text" data-lang="text"&gt;&lt;span style="display:flex;"&gt;&lt;span&gt;LDFLAGS=&amp;#34;&amp;#34; FFLAGS=&amp;#34;-fPIC -openmp&amp;#34; python2.7 setup.py build --fcompiler=intelem &amp;amp;&amp;gt; build.out&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&#10; &lt;/div&gt;&lt;p&gt;I set the LDFLAGS variable to an empty string to avoid using any LDFLAGS which are defined in my .bashrc. The &lt;strong&gt;-fPIC&lt;/strong&gt;tells the compiler to create position-independent code, although this flag may not be required for newer compilers (ours are quote old: ifort (IFORT) 10.1 20070913 and icc (ICC) 10.1 20070913). I used the**-openmp&lt;strong&gt;flag to be consistent with the flags I used for building NumPy. The option&lt;/strong&gt;--fcompiler=intelem** forces the Intel Fortran compiler to be used instead of g77. I redirected all output to a file called build.out, which is helpful for finding errors and warnings in the build output. Once you have built SciPy successfully, install it with the following command:&lt;/p&gt;</description></item><item><title>Building NumPy on a 64-bit Red Hat Cluster with Intel MKL</title><link>https://shocksolution.com/posts/building-numpy-on-a-red-hat-cluster-with-intel-mkl/</link><pubDate>Tue, 24 Apr 2012 16:40:40 +0000</pubDate><guid>https://shocksolution.com/posts/building-numpy-on-a-red-hat-cluster-with-intel-mkl/</guid><description>&lt;p&gt;In a previous post I described &lt;a href="https://shocksolution.com/2008/12/update-2-building-64-bit-numpy-with-intel-compilers-and-mkl/" title="Build%20NumPy%20with%20Intel%20Compilers%20and%20MKL"&gt;how to build an optimized version of NumPy using the Intel compilers and Math Kernel Library (MKL)&lt;/a&gt;.  This post will update those instructions, since it has been a few years and I am now using NumPy 1.6.1, MKL 10.0.1.014 and Red Hat 4.1.1 (kernel 2.6.18-8.el5). First, copy the file &lt;strong&gt;site.cfg.example&lt;/strong&gt;to&lt;strong&gt;site.cfg&lt;/strong&gt; and open it in an editor like vim. The commented lines in the file give some explanation of how it works. You only need to add the following lines:&lt;/p&gt;</description></item><item><title>Python string format examples</title><link>https://shocksolution.com/posts/python-string-format-examples/</link><pubDate>Thu, 03 Nov 2011 22:38:10 +0000</pubDate><guid>https://shocksolution.com/posts/python-string-format-examples/</guid><description>&lt;p&gt;The &lt;a href="http://docs.python.org/library/string.html#format-string-syntax" title="Python%20strings%20format%20method"&gt;format method for Python strings&lt;/a&gt; (introduced in 2.6) is very flexible and powerful.  It&amp;rsquo;s also easy to use, but the documentation is not very clear.  It all makes sense with a few examples.  I&amp;rsquo;ll add more as I have time: &lt;a href="https://%3C%3Cwww.amazon.com/gp/product/0132269937/ref=as_li_tl?ie=UTF8&amp;amp;camp=1789&amp;amp;creative=9325&amp;amp;creativeASIN=0132269937&amp;amp;linkCode=as2&amp;amp;tag=rootwork0f-20&amp;amp;linkId=44971fe03f445ae25fecb2cc2702d3aa&amp;amp;gt%3E;"&gt;&lt;img src="//ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&amp;amp;MarketPlace=US&amp;amp;ASIN=0132269937&amp;amp;ServiceVersion=20070822&amp;amp;ID=AsinImage&amp;amp;WS=1&amp;amp;Format=_SL160_&amp;amp;tag=rootwork0f-20" alt="image"&gt;&lt;/a&gt;&lt;img src="//ir-na.amazon-adsystem.com/e/ir?t=rootwork0f-20&amp;amp;l=am2&amp;amp;o=1&amp;amp;a=0132269937" alt="image"&gt;&lt;/p&gt;&#10;&lt;h2 id="formatting-numbers-in-python-strings"&gt;Formatting Numbers in Python Strings&lt;/h2&gt;&#10;&lt;h3 id="formatting-a-floating-point-number"&gt;Formatting a floating-point number&lt;/h3&gt;&#10;&lt;p&gt;[code language=&amp;ldquo;python&amp;rdquo;] &amp;ldquo;{0:.4f}&amp;quot;.format(0.1234567890) &amp;ldquo;{0:.4f}&amp;quot;.format(10.1234567890) [/code] The result is the following string:&lt;/p&gt;&#10;&lt;div class="code-block"&gt;&#10; &lt;button class="code-copy" type="button" hidden aria-label="Copy code to clipboard"&gt;&#10; &lt;span class="code-copy-label" aria-hidden="true"&gt;Copy&lt;/span&gt;&#10; &lt;/button&gt;&#10; &lt;div class="highlight"&gt;&lt;pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"&gt;&lt;code class="language-text" data-lang="text"&gt;&lt;span style="display:flex;"&gt;&lt;span&gt;&amp;#39;0.1235&amp;#39;&#10;&lt;/span&gt;&lt;/span&gt;&lt;span style="display:flex;"&gt;&lt;span&gt;&amp;#39;10.1235&amp;#39;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&#10; &lt;/div&gt;&lt;p&gt;Braces { } are used to enclose the &amp;ldquo;replacement field&amp;rdquo; 0 indicates the first argument to method &lt;strong&gt;format&lt;/strong&gt; : indicates the start of the format specifier .4 indicates four decimal places f indicates a floating-point number&lt;/p&gt;</description></item><item><title>How to build ScipPy with Python 2.7.2 on CentOS5</title><link>https://shocksolution.com/posts/how-to-build-scippy-with-python-2-7-2-on-centos5/</link><pubDate>Thu, 25 Aug 2011 00:17:57 +0000</pubDate><guid>https://shocksolution.com/posts/how-to-build-scippy-with-python-2-7-2-on-centos5/</guid><description>&lt;p&gt;EDIT: added &amp;ndash;enable-shared to configure script for building Python, and added /home/yourname/lib to shared library path.  This is necessary for building some packages such as pycairo (which you may need to build pygtk and matplotlib). EDIT 2: you should use the &amp;ndash;prefix=/home/yourusername instead of &amp;ndash;user.  The prefix option places packages in the standard location: /home/yourusername/lib/python2.7/site-packages.  The &amp;ndash;user option places the packages in /home/yourusername/.local/lib/python2.7/site-packages which I think is screwed up!   I use CentoOS5 because I want enterprise-class stability, as well as binary compatibility with a commercial application that is built for RHEL5.  I need to use some &amp;ldquo;bleeding edge&amp;rdquo; packages, such as the latest version of SciPy, but I don&amp;rsquo;t want to affect the base stability of the system.  Here is how I did it.  First, with superuser privileges, use yum to install the following packages.  You may need to set up epel as an alternate repository:&lt;/p&gt;</description></item><item><title>Removing an axis or both axes from a matplotlib plot</title><link>https://shocksolution.com/posts/removing-an-axis-or-both-axes-from-a-matplotlib-plot/</link><pubDate>Wed, 17 Aug 2011 22:40:14 +0000</pubDate><guid>https://shocksolution.com/posts/removing-an-axis-or-both-axes-from-a-matplotlib-plot/</guid><description>&lt;p&gt;Sometimes, the frame around a &lt;a href="http://matplotlib.sourceforge.net/" title="matplotlib"&gt;matplotlib&lt;/a&gt; plot can detract from the information you are trying to convey.  How do you remove the frame, ticks, or axes from a matplotlib plot? &lt;figure class="ma0 w-75"&gt;&lt;img src="https://shocksolution.com/images/plot_without_y_axis.png"&#10;&#9;&#9;&#9;alt="matplotlib plot without a y axis"&gt;&lt;figcaption&gt;&#10;&#9;&#9;&#9;&lt;p&gt;matplotlib plot without a y axis&lt;/p&gt;&#10;&#9;&#9;&lt;/figcaption&gt;&#10;&lt;/figure&gt;&#10;&lt;/p&gt;&#10;&lt;p&gt;Some books you may find useful when working with matplotlib: &lt;a href="https://%3C%3Cwww.amazon.com/gp/product/0132269937/ref=as_li_tl?ie=UTF8&amp;amp;camp=1789&amp;amp;creative=9325&amp;amp;creativeASIN=0132269937&amp;amp;linkCode=as2&amp;amp;tag=rootwork0f-20&amp;amp;linkId=44971fe03f445ae25fecb2cc2702d3aa&amp;amp;gt%3E;"&gt;&lt;img src="//ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&amp;amp;MarketPlace=US&amp;amp;ASIN=0132269937&amp;amp;ServiceVersion=20070822&amp;amp;ID=AsinImage&amp;amp;WS=1&amp;amp;Format=_SL160_&amp;amp;tag=rootwork0f-20" alt="image"&gt;&lt;/a&gt;&lt;img src="//ir-na.amazon-adsystem.com/e/ir?t=rootwork0f-20&amp;amp;l=am2&amp;amp;o=1&amp;amp;a=0132269937" alt="image"&gt;&lt;a href="https://%3C%3Cwww.amazon.com/Python-Data-Analysis-Wrangling-IPython/dp/1491957662/ref=as_li_ss_il?keywords=matplotlib&amp;amp;qid=1537646489&amp;amp;sr=8-12&amp;amp;ref=sr_1_12&amp;amp;linkCode=li2&amp;amp;tag=rootwork0f-20&amp;amp;linkId=545b965f9a5ae1055ae778fca7628568&amp;amp;language=en_US&amp;amp;gt%3E;"&gt;&lt;img src="//ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&amp;amp;ASIN=1491957662&amp;amp;Format=_SL160_&amp;amp;ID=AsinImage&amp;amp;MarketPlace=US&amp;amp;ServiceVersion=20070822&amp;amp;WS=1&amp;amp;tag=rootwork0f-20&amp;amp;language=en_US" alt="image"&gt;&lt;/a&gt;&lt;img src="https://ir-na.amazon-adsystem.com/e/ir?t=rootwork0f-20&amp;amp;language=en_US&amp;amp;l=li2&amp;amp;o=1&amp;amp;a=1491957662" alt="image"&gt;&lt;a href="https://%3C%3Cwww.amazon.com/Mastering-matplotlib-Duncan-M-McGreggor/dp/1783987545/ref=as_li_ss_il?keywords=matplotlib&amp;amp;qid=1537646489&amp;amp;sr=8-1&amp;amp;ref=sr_1_1&amp;amp;linkCode=li2&amp;amp;tag=rootwork0f-20&amp;amp;linkId=ec917748d4c441f93e36024379f32b58&amp;amp;language=en_US&amp;amp;gt%3E;"&gt;&lt;img src="//ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&amp;amp;ASIN=1783987545&amp;amp;Format=_SL160_&amp;amp;ID=AsinImage&amp;amp;MarketPlace=US&amp;amp;ServiceVersion=20070822&amp;amp;WS=1&amp;amp;tag=rootwork0f-20&amp;amp;language=en_US" alt="image"&gt;&lt;/a&gt;&lt;img src="https://ir-na.amazon-adsystem.com/e/ir?t=rootwork0f-20&amp;amp;language=en_US&amp;amp;l=li2&amp;amp;o=1&amp;amp;a=1783987545" alt="image"&gt;&lt;a href="https://%3C%3Cwww.amazon.com/Matplotlib-Plotting-Cookbook-Alexandre-Devert/dp/1849513260/ref=as_li_ss_il?keywords=matplotlib&amp;amp;qid=1537646489&amp;amp;sr=8-2&amp;amp;ref=sr_1_2&amp;amp;linkCode=li2&amp;amp;tag=rootwork0f-20&amp;amp;linkId=6b7d2e5dacde0fa357c7d0316befb29b&amp;amp;language=en_US&amp;amp;gt%3E;"&gt;&lt;img src="//ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&amp;amp;ASIN=1849513260&amp;amp;Format=_SL160_&amp;amp;ID=AsinImage&amp;amp;MarketPlace=US&amp;amp;ServiceVersion=20070822&amp;amp;WS=1&amp;amp;tag=rootwork0f-20&amp;amp;language=en_US" alt="image"&gt;&lt;/a&gt;&lt;img src="https://ir-na.amazon-adsystem.com/e/ir?t=rootwork0f-20&amp;amp;language=en_US&amp;amp;l=li2&amp;amp;o=1&amp;amp;a=1849513260" alt="image"&gt;&lt;/p&gt;&#10;&lt;p&gt;&lt;a href="https://github.com/cfinch/Shocksolution_Examples/tree/master/Plotting/matplotlib" title="Removing%20an%20axis%20from%20a%20Matplotlib%20plot"&gt;The full example is available on github&lt;/a&gt;.&lt;/p&gt;&#10;&lt;p&gt;First, we construct a figure and an axes object:&lt;/p&gt;&#10;&lt;div class="code-block"&gt;&#10; &lt;button class="code-copy" type="button" hidden aria-label="Copy code to clipboard"&gt;&#10; &lt;span class="code-copy-label" aria-hidden="true"&gt;Copy&lt;/span&gt;&#10; &lt;/button&gt;&#10; &lt;div class="highlight"&gt;&lt;pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"&gt;&lt;code class="language-text" data-lang="text"&gt;&lt;span style="display:flex;"&gt;&lt;span&gt;fig1 = plt.figure(facecolor=&amp;#39;white&amp;#39;)&#10;&lt;/span&gt;&lt;/span&gt;&lt;span style="display:flex;"&gt;&lt;span&gt;ax1 = plt.axes(frameon=False)&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&#10; &lt;/div&gt;&lt;p&gt;The Axes object is a container that holds the axes, the ticks, the labels, the plot, the legend, etc.  You will always have an Axes object, even if the axes are not visible! The keyword argument &lt;strong&gt;frameon=False&lt;/strong&gt; turns the frame off. An alternative method is:&lt;/p&gt;</description></item><item><title>Python: lists to tuples and tuples to lists</title><link>https://shocksolution.com/posts/python-lists-to-tuples-and-tuples-to-lists/</link><pubDate>Sat, 02 Jul 2011 17:07:00 +0000</pubDate><guid>https://shocksolution.com/posts/python-lists-to-tuples-and-tuples-to-lists/</guid><description>&lt;p&gt;&lt;a href="https://github.com/cfinch/Shocksolution_Examples/blob/master/Fundamentals/zip.py" title="Example%20code%20for%20Python%20zip"&gt;Get the code for this example&lt;/a&gt; The &lt;a href="http://docs.python.org/library/functions.html#zip" title="zip"&gt;zip&lt;/a&gt; function in Python accepts a number of sequences (such as lists or arrays) and returns a list of tuples.  The first element of each tuple comes from the first sequence, the second from the second sequence, and so on.  For example: [code language=&amp;ldquo;Python&amp;rdquo;]a = range(0, 5) b = range(5, 10) c = range(10, 15) sequence_of_tuples = zip(a, b, c) print(sequence_of_tuples)[/code]&lt;/p&gt;&#10;&lt;div class="code-block"&gt;&#10; &lt;button class="code-copy" type="button" hidden aria-label="Copy code to clipboard"&gt;&#10; &lt;span class="code-copy-label" aria-hidden="true"&gt;Copy&lt;/span&gt;&#10; &lt;/button&gt;&#10; &lt;div class="highlight"&gt;&lt;pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"&gt;&lt;code class="language-text" data-lang="text"&gt;&lt;span style="display:flex;"&gt;&lt;span&gt;[(0, 5, 10), (1, 6, 11), (2, 7, 12), (3, 8, 13), (4, 9, 14)]&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&#10; &lt;/div&gt;&lt;p&gt;&lt;a href="https://%3Cwww.amazon.com/gp/product/0132269937/ref=as_li_tl?ie=UTF8&amp;amp;camp=1789&amp;amp;creative=9325&amp;amp;creativeASIN=0132269937&amp;amp;linkCode=as2&amp;amp;tag=rootwork0f-20&amp;amp;linkId=44971fe03f445ae25fecb2cc2702d3aa%3E"&gt;&lt;img src="//ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&amp;amp;MarketPlace=US&amp;amp;ASIN=0132269937&amp;amp;ServiceVersion=20070822&amp;amp;ID=AsinImage&amp;amp;WS=1&amp;amp;Format=_SL160_&amp;amp;tag=rootwork0f-20" alt="image"&gt;&lt;/a&gt;&lt;img src="//ir-na.amazon-adsystem.com/e/ir?t=rootwork0f-20&amp;amp;l=am2&amp;amp;o=1&amp;amp;a=0132269937" alt="image"&gt;&lt;/p&gt;</description></item><item><title>A self-contained Fortran linear equation solver</title><link>https://shocksolution.com/posts/a-self-contained-fortran-linear-equation-solver/</link><pubDate>Wed, 16 Mar 2011 21:33:27 +0000</pubDate><guid>https://shocksolution.com/posts/a-self-contained-fortran-linear-equation-solver/</guid><description>&lt;p&gt;I&amp;rsquo;ve just released a self-contained Fortran module that solves a system of linear equations using the LU decomposition. &lt;a href="https://github.com/cfinch/Shocksolution_Examples/tree/master/FORTRAN/LinearEquationSolver" title="Fortran%20linear%20system%20solver"&gt;Download the Fortran linear solver from github&lt;/a&gt; This module is based on code that was implemented and released on the Web by &lt;a href="http://jean-pierre.moreau.pagesperso-orange.fr/f_matrices.html"&gt;Jean-Pierre Moreau&lt;/a&gt;.  His implementation was based on one of the &lt;a href="http://%3Cwww.nr.com/%3E"&gt;Numerical Recipes&lt;/a&gt; books.  I updated his code to a more strict Fortran 90 standard and added the necessary comments so that it can be built as a Python module using &lt;a href="http://%3Cwww.scipy.org/F2py%3E" title="f2py"&gt;f2py&lt;/a&gt;.  I replaced Jean-Pierre&amp;rsquo;s Fortran test program with a simpler, self-contained program.  I also included a Python script that implements the same test case. I created this module because sometimes a self-contained routine is more appropriate than a full library.  I am compiling a library that implements a custom boundary condition for a proprietary computational fluid dynamics solver (CFD-ACE+).  The library has to be written in Fortran, and it has to be built using a proprietary set of build scripts.  I could either try to reverse-engineer the build process and to modify it to link to a shared library like &lt;a href="http://%3Cwww.netlib.org/lapack/%3E" title="LAPACK"&gt;LAPACK&lt;/a&gt;, or I could implement a self-contained solver.  Since Pierre had already implemented the solver, I was able to slightly modify his code and get it working relatively quickly.&lt;/p&gt;</description></item><item><title>Sage: open-source mathematical software</title><link>https://shocksolution.com/posts/sage-open-source-mathematical-software/</link><pubDate>Mon, 07 Mar 2011 14:07:19 +0000</pubDate><guid>https://shocksolution.com/posts/sage-open-source-mathematical-software/</guid><description>&lt;p&gt;I&amp;rsquo;ve recently gained a lot of experience with &lt;a href="http://%3Cwww.sagemath.org/%3E" title="Sage"&gt;Sage&lt;/a&gt;, an open-source alternative to MATLAB, Mathematica, Maple, MuPAD, and Magma.  Here are a couple of links to check out:&lt;/p&gt;&#10;&lt;p&gt;&lt;em&gt;&lt;a href="http://%3Cwww.sagenb.org/%3E" title="Sage%20public%20notebook%20servers"&gt;Public notebook servers&lt;/a&gt;--try it online right now!&lt;/em&gt; &lt;a href="http://wiki.sagemath.org/interact" title="Interactive%20Sage%20examples"&gt;Interactive examples with Sage&lt;/a&gt;&lt;/p&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;&lt;a href="http://sagemath.org/library-publications.html" title="Publications%20citing%20Sage"&gt;Mathematical publications citing Sage&lt;/a&gt;&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;h2 id="sage-vs-mathematica"&gt;Sage vs. Mathematica&lt;/h2&gt;&#10;&lt;p&gt;My experience with mathematical software started my freshman year at the University of Illinois when I signed up for a calculus class that was taught almost entirely with Mathematica.  I grew to love Mathematica&amp;rsquo;s symbolic computation and plotting capabilities, although I found its programming language to be cumbersome.  Once I was no longer a student, Mathematica was no longer an option due to the hefty licensing fees.  With the caveat that I haven&amp;rsquo;t used Mathematica in many years,  I will say that Sage compares very favorably to my experience with Mathematica.  Sage has a notebook interface that allows you to integrate code, results, text, typeset equations, and graphics in an interactive document that can be viewed with any standards-compliant web browser.  I don&amp;rsquo;t know how Sage stacks up against Mathematica in areas of advanced mathematics.  I have heard that Sage is far ahead of Mathematica in number theory, because the lead developer of Sage is a number theorist.&lt;/p&gt;</description></item><item><title>Linear system simulation with Python</title><link>https://shocksolution.com/posts/linear-system-simulation-with-python/</link><pubDate>Fri, 17 Dec 2010 21:33:16 +0000</pubDate><guid>https://shocksolution.com/posts/linear-system-simulation-with-python/</guid><description>&lt;p&gt;Linear time-invariant (LTI) systems are widely used in the field of signal processing.  &lt;a href="http://scipy.org/" title="Scipy"&gt;Scipy&lt;/a&gt; contains powerful tools for simulating LTI systems in the &lt;a href="http://docs.scipy.org/doc/scipy/reference/signal.html" title="scipy.signal%20docs"&gt;scipy.signal&lt;/a&gt; package, but they are not well documented.  I will provide a simple example that demonstrates how to use a few of the core classes and functions in scipy.signal for simulating LTI systems with Python.&lt;/p&gt;&#10;&lt;h2 id="define-an-lti-system"&gt;Define an LTI system&lt;/h2&gt;&#10;&lt;p&gt;You will need to have Scipy installed, and you will need to have &lt;a href="http://matplotlib.sourceforge.net/" title="Matplotlib"&gt;Matplotlib&lt;/a&gt; as well to make plots. We will start with an example of a &lt;a href="http://en.wikipedia.org/wiki/Time_constant" title="Time%20constant"&gt;first-order LTI system&lt;/a&gt;, which is characterized by a single parameter known as the time constant.  scipy.signal defines the class &lt;strong&gt;lti&lt;/strong&gt; to represent a linear system in Python.&lt;/p&gt;</description></item><item><title>Constrained least-squares fitting with Python</title><link>https://shocksolution.com/posts/constrained-least-squares-fitting-with-python/</link><pubDate>Fri, 05 Mar 2010 19:27:25 +0000</pubDate><guid>https://shocksolution.com/posts/constrained-least-squares-fitting-with-python/</guid><description>&lt;p&gt;&lt;a href="https://%3C%3Cwww.amazon.com/Elegant-SciPy-Art-Scientific-Python/dp/1491922877/ref=as_li_ss_il?keywords=scipy&amp;amp;qid=1537721480&amp;amp;sr=8-2&amp;amp;ref=sr_1_2&amp;amp;linkCode=li2&amp;amp;tag=rootwork0f-20&amp;amp;linkId=b82af06689ab1a386116469d41f270d6&amp;amp;language=en_US&amp;amp;gt%3E;"&gt;&lt;img src="//ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&amp;amp;ASIN=1491922877&amp;amp;Format=_SL160_&amp;amp;ID=AsinImage&amp;amp;MarketPlace=US&amp;amp;ServiceVersion=20070822&amp;amp;WS=1&amp;amp;tag=rootwork0f-20&amp;amp;language=en_US" alt="image"&gt;&lt;/a&gt;&lt;img src="https://ir-na.amazon-adsystem.com/e/ir?t=rootwork0f-20&amp;amp;language=en_US&amp;amp;l=li2&amp;amp;o=1&amp;amp;a=1491922877" alt="image"&gt;&lt;a href="https://%3C%3Cwww.amazon.com/Learning-Numerical-Scientific-Computing-Second/dp/1783987707/ref=as_li_ss_il?keywords=scipy&amp;amp;qid=1537721480&amp;amp;sr=8-3&amp;amp;ref=sr_1_3&amp;amp;linkCode=li2&amp;amp;tag=rootwork0f-20&amp;amp;linkId=4f28164dbe2c853ec36f6f35b052e71a&amp;amp;language=en_US&amp;amp;gt%3E;"&gt;&lt;img src="//ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&amp;amp;ASIN=1783987707&amp;amp;Format=_SL160_&amp;amp;ID=AsinImage&amp;amp;MarketPlace=US&amp;amp;ServiceVersion=20070822&amp;amp;WS=1&amp;amp;tag=rootwork0f-20&amp;amp;language=en_US" alt="image"&gt;&lt;/a&gt;&lt;img src="https://ir-na.amazon-adsystem.com/e/ir?t=rootwork0f-20&amp;amp;language=en_US&amp;amp;l=li2&amp;amp;o=1&amp;amp;a=1783987707" alt="image"&gt;&lt;a href="https://%3C%3Cwww.amazon.com/SciPy-Recipes-performing-mathematical-computations/dp/1788291468/ref=as_li_ss_il?keywords=scipy&amp;amp;qid=1537721480&amp;amp;sr=8-6&amp;amp;ref=sr_1_6&amp;amp;linkCode=li2&amp;amp;tag=rootwork0f-20&amp;amp;linkId=0f24d2d9680bc94c36ebe6665e04c5e3&amp;amp;language=en_US&amp;amp;gt%3E;"&gt;&lt;img src="//ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&amp;amp;ASIN=1788291468&amp;amp;Format=_SL160_&amp;amp;ID=AsinImage&amp;amp;MarketPlace=US&amp;amp;ServiceVersion=20070822&amp;amp;WS=1&amp;amp;tag=rootwork0f-20&amp;amp;language=en_US" alt="image"&gt;&lt;/a&gt;&lt;img src="https://ir-na.amazon-adsystem.com/e/ir?t=rootwork0f-20&amp;amp;language=en_US&amp;amp;l=li2&amp;amp;o=1&amp;amp;a=1788291468" alt="image"&gt;&lt;/p&gt;&#10;&lt;p&gt;&lt;a href="http://scipy.org" title="SciPy%20home"&gt;Scipy&lt;/a&gt; contains a good least-squares fitting routine, &lt;a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.leastsq.html#scipy-optimize-leastsq"&gt;&lt;strong&gt;leastsq()&lt;/strong&gt;&lt;/a&gt;, which implements a modified Levenberg-Marquardt algorithm.  I just learned that it also has a constrained least-squared routine called &lt;a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fmin_slsqp.html#scipy.optimize.fmin_slsqp" title="scipy.optimize.fmin_slsqp"&gt;&lt;strong&gt;fmin_slsqp()&lt;/strong&gt;&lt;/a&gt;.   I am using simple upper and lower bound constraints, but it&amp;rsquo;s also possible to specify more complex functional constraints. What I did not realize, at first, is that &lt;strong&gt;fmin_slsqp&lt;/strong&gt;requires a different type of objective function than&lt;strong&gt;leastsq&lt;/strong&gt;.   &lt;strong&gt;leastsq&lt;/strong&gt;requires you to write a function that returns a vector of residuals, and&lt;strong&gt;leastsq&lt;/strong&gt;automatically squares and sums the residuals.&lt;strong&gt;fmin_slsqp&lt;/strong&gt; is actually more flexible, in that it can use any objective function that returns a single scalar value.  To implement least-squares curve fitting, your objective function will need to find the residual at each data point, square the values, and sum them up.  Hopefully this tip will save you some time. Check out the &lt;a href="http://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html" title="scipy%20optimization%20tutorial"&gt;scipy optimization tutorial&lt;/a&gt; for more examples.  Here is the original &lt;a href="http://abs-5.me.washington.edu/dynOpt/p262-kraft.pdf" title="SLSQP%20reference"&gt;paper by Dieter Kraft&lt;/a&gt; which introduces the algorithm used by fmin_slsqp.&lt;/p&gt;</description></item><item><title>Storing large Numpy arrays on disk: Python Pickle vs. HDF5</title><link>https://shocksolution.com/posts/storing-large-numpy-arrays-on-disk-python-pickle-vs-hdf5adsf/</link><pubDate>Sun, 10 Jan 2010 23:00:20 +0000</pubDate><guid>https://shocksolution.com/posts/storing-large-numpy-arrays-on-disk-python-pickle-vs-hdf5adsf/</guid><description>&lt;p&gt;&lt;a href="https://shocksolution.com/2008/09/15/python-pickle-painless-binary-storage-for-python-objects/" title="Python%20data%20storage%20with%20Pickle"&gt;In a previous post, I described how Python&amp;rsquo;s Pickle module is fast and convenient&lt;/a&gt; for storing all sorts of data on disk. More recently, I showed &lt;a href="https://shocksolution.com/2009/04/17/profiling-memory-usage-of-python-code/" title="Profiling%20Python%20code"&gt;how to profile the memory usage of Python code&lt;/a&gt;.  In recent weeks, I&amp;rsquo;ve uncovered a serious limitation in the Pickle module when storing large amounts of data: Pickle requires a large amount of memory to save a data structure to disk. Fortunately, there is an open standard called HDF, which defines a binary file format that is designed to efficiently store large scientific data sets. I will demonstrate both approaches, and profile them to see how much memory is required. I am writing the HDF file using the PyTables interface. Here&amp;rsquo;s the little test program I&amp;rsquo;ve been using: [code language=&amp;ldquo;Python&amp;rdquo;]#!/usr/bin/env python from numpy import array&lt;/p&gt;</description></item><item><title>f2py: binding Fortran and Python</title><link>https://shocksolution.com/posts/f2py-binding-fortran-python/</link><pubDate>Wed, 23 Sep 2009 22:56:08 +0000</pubDate><guid>https://shocksolution.com/posts/f2py-binding-fortran-python/</guid><description>&lt;p&gt;I  have recently started using &lt;a href="http://%3C%3Cwww.scipy.org/F2py&amp;amp;gt%3E;" title="F2py"&gt;f2py&lt;/a&gt; to call Fortran from Python.  I have found this useful for two reasons: speeding up Python scripts by calling compiled Fortran code, and using Python as a unit testing framework for Fortran modules.   Unfortunately, the &lt;a href="http://cens.ioc.ee/projects/f2py2e/usersguide/index.html" title="F2py%20docs"&gt;documentation&lt;/a&gt; for f2py is rather sparse, and may not be completely up to date.   In this note, I will hopefully prevent you from wasting a lot of time figuring out how to pass array arguments, and return array results.&lt;/p&gt;</description></item><item><title>Profiling memory usage of Python code</title><link>https://shocksolution.com/posts/profiling-memory-usage-of-python-code/</link><pubDate>Fri, 17 Apr 2009 22:08:52 +0000</pubDate><guid>https://shocksolution.com/posts/profiling-memory-usage-of-python-code/</guid><description>&lt;p&gt;In a previous post, I explained how to use the Python profiler.  The profile is great for finding out which parts of the code run the slowest, or are called most often.  However, the profiler doesn&amp;rsquo;t give any information about how much RAM is being consumed, or where it&amp;rsquo;s being consumed.  If your program needs so much memory that it starts swapping to disk, its speed can be reduced by orders of magnitude.  On the positive side, your code may run much faster if it fits entirely in the processor cache.  In this post, I will introduce two tools that can help you understand the RAM usage of your Python code.&lt;/p&gt;</description></item><item><title>Lookup tables and spline fitting in Python</title><link>https://shocksolution.com/posts/lookup-tables-and-spline-fitting-in-python/</link><pubDate>Wed, 08 Apr 2009 23:36:09 +0000</pubDate><guid>https://shocksolution.com/posts/lookup-tables-and-spline-fitting-in-python/</guid><description>&lt;p&gt;Lookup tables and spline fitting are widely used by scientific programmers.  A particular function may not have an analytic solution&amp;ndash;in other words, it can&amp;rsquo;t be expressed as an equation of elementary functions.  This might happen if the function were empirically determined from experimental data, or if the equation can&amp;rsquo;t be algebraically solved for one variable.  If the analytical function is available, but takes a long time to evaluate, a lookup table or spline approximation can be considerably faster.  In a previous post, I showed how to use the function &lt;a href="https://shocksolution.com/2008/12/11/a-lookup-table-for-fast-python-math/" title="scipy.interpolate.interp1d%20as%20a%20lookup%20table"&gt;interp1d from scipy.interpolate as a lookup table&lt;/a&gt;.  In a later post, I showed that &lt;a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html#scipy.interpolate.interp1d" title="interp1d%20docs"&gt;interp1d&lt;/a&gt; is actually rather slow, and &lt;a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.UnivariateSpline.html#scipy.interpolate.UnivariateSpline" title="Scipy.interpolate.UnivariateSpline"&gt;scipy.interpolate.UnivariateSpline&lt;/a&gt; is much faster.  Now, I will show some benchmark results, and explain a potential pitfall when using UnivariateSpline. The two functions I will use for this demonstration are not very complicated.  Each function is a piecewise approximation of a more complex function.  Here is one of the functions.  For small z, the function uses one approximation, and for large z, it uses a far-field approximation.  For intermediate values, a polynomial is used to smoothly match the two solutions. &lt;a href="https://%3Cwww.amazon.com/Elegant-SciPy-Art-Scientific-Python/dp/1491922877/ref=as_li_ss_il?keywords=scipy&amp;amp;qid=1537721480&amp;amp;sr=8-2&amp;amp;ref=sr_1_2&amp;amp;linkCode=li2&amp;amp;tag=rootwork0f-20&amp;amp;linkId=b82af06689ab1a386116469d41f270d6&amp;amp;language=en_US%3E"&gt;&lt;img src="//ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&amp;amp;ASIN=1491922877&amp;amp;Format=_SL160_&amp;amp;ID=AsinImage&amp;amp;MarketPlace=US&amp;amp;ServiceVersion=20070822&amp;amp;WS=1&amp;amp;tag=rootwork0f-20&amp;amp;language=en_US" alt="image"&gt;&lt;/a&gt;&lt;img src="https://ir-na.amazon-adsystem.com/e/ir?t=rootwork0f-20&amp;amp;language=en_US&amp;amp;l=li2&amp;amp;o=1&amp;amp;a=1491922877" alt="image"&gt;&lt;a href="https://%3Cwww.amazon.com/Learning-Numerical-Scientific-Computing-Second/dp/1783987707/ref=as_li_ss_il?keywords=scipy&amp;amp;qid=1537721480&amp;amp;sr=8-3&amp;amp;ref=sr_1_3&amp;amp;linkCode=li2&amp;amp;tag=rootwork0f-20&amp;amp;linkId=4f28164dbe2c853ec36f6f35b052e71a&amp;amp;language=en_US%3E"&gt;&lt;img src="//ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&amp;amp;ASIN=1783987707&amp;amp;Format=_SL160_&amp;amp;ID=AsinImage&amp;amp;MarketPlace=US&amp;amp;ServiceVersion=20070822&amp;amp;WS=1&amp;amp;tag=rootwork0f-20&amp;amp;language=en_US" alt="image"&gt;&lt;/a&gt;&lt;img src="https://ir-na.amazon-adsystem.com/e/ir?t=rootwork0f-20&amp;amp;language=en_US&amp;amp;l=li2&amp;amp;o=1&amp;amp;a=1783987707" alt="image"&gt;&lt;a href="https://%3Cwww.amazon.com/SciPy-Recipes-performing-mathematical-computations/dp/1788291468/ref=as_li_ss_il?keywords=scipy&amp;amp;qid=1537721480&amp;amp;sr=8-6&amp;amp;ref=sr_1_6&amp;amp;linkCode=li2&amp;amp;tag=rootwork0f-20&amp;amp;linkId=0f24d2d9680bc94c36ebe6665e04c5e3&amp;amp;language=en_US%3E"&gt;&lt;img src="//ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&amp;amp;ASIN=1788291468&amp;amp;Format=_SL160_&amp;amp;ID=AsinImage&amp;amp;MarketPlace=US&amp;amp;ServiceVersion=20070822&amp;amp;WS=1&amp;amp;tag=rootwork0f-20&amp;amp;language=en_US" alt="image"&gt;&lt;/a&gt;&lt;img src="https://ir-na.amazon-adsystem.com/e/ir?t=rootwork0f-20&amp;amp;language=en_US&amp;amp;l=li2&amp;amp;o=1&amp;amp;a=1788291468" alt="image"&gt;&lt;/p&gt;</description></item><item><title>3D Plotting Software for Python::Part 1::PyX</title><link>https://shocksolution.com/posts/3d-plotting-software-for-python-pyx/</link><pubDate>Fri, 20 Mar 2009 23:08:55 +0000</pubDate><guid>https://shocksolution.com/posts/3d-plotting-software-for-python-pyx/</guid><description>&lt;p&gt;There are lots of good open-source tools that you can use to make high-resolution, publication-quality 2D plots.  Personally, I like to use &lt;a href="http://python.org/" title="Python%20homepage"&gt;Python&lt;/a&gt;, &lt;a href="http://numpy.scipy.org/" title="Numpy%20home%20page"&gt;numpy&lt;/a&gt;, and &lt;a href="http://matplotlib.sourceforge.net/" title="Matplotlib%20home%20page"&gt;matplotlib&lt;/a&gt;.  Unfortunately, it is much harder to find a good tools to make 3D plots.  Older versions of matplotlib had rudimentary 3D support, but this was removed in version 0.98.  In this post, I will review a Python 3D plotting library called &lt;a href="http://pyx.sourceforge.net/" title="PyX%20homepage"&gt;PyX&lt;/a&gt;.&lt;/p&gt;&#10;&lt;h2 id="preparing-the-data"&gt;Preparing the data&lt;/h2&gt;&#10;&lt;p&gt;Figuring out how to store the data to be plotted was actually the hardest part of learning to use PyX.  The data format for 3D plots is not well documented.  PyX requires a list of (x,y,z) lists like this:&lt;/p&gt;</description></item><item><title>Updated Python class for writing Paraview (VTK) (.vtu) files</title><link>https://shocksolution.com/posts/updated-python-class-for-writing-paraview-vtk-vtu-files/</link><pubDate>Fri, 23 Jan 2009 23:28:05 +0000</pubDate><guid>https://shocksolution.com/posts/updated-python-class-for-writing-paraview-vtk-vtu-files/</guid><description>&lt;p&gt;I have released a new version of my &lt;a href="https://shocksolution.com/microfluidics-and-biotechnology/python-vtk-paraview/" title="Python%20class%20for%20generating%20VTK%20.vtu%20files"&gt;Python class that generates VTK data files in the .vtu format&lt;/a&gt;, which is compatible with Paraview and other VTK applications.  If you have downloaded the old one, please get the latest version, which incorporates some bug fixes and has been more thoroughly tested.&lt;/p&gt;</description></item><item><title>Deploying Python applications on Windows</title><link>https://shocksolution.com/posts/deploying-python-applications-on-windows/</link><pubDate>Thu, 15 Jan 2009 16:38:56 +0000</pubDate><guid>https://shocksolution.com/posts/deploying-python-applications-on-windows/</guid><description>&lt;p&gt;Writing applications in Python on a Linux system is almost too easy.  Deploying Python apps on other Linux systems is not hard, because most Linux systems already have Python, with its core libraries and tools, installed.  Most Linux systems also have package managers that make it easy to find and install required components.  But, what happens when your co-workers who use Windows need to use your app?  When you tell them to &amp;ldquo;go to the command line and&amp;hellip;&amp;rdquo; you&amp;rsquo;ve pretty much lost them at &amp;ldquo;command line.&amp;rdquo; How do you package Python in a way that&amp;rsquo;s easy for a Windows user to install? Here is a process that worked for me:&lt;/p&gt;</description></item><item><title>Scipy.integrate ODEPACK import error solved!</title><link>https://shocksolution.com/posts/scipyintegrate-odepack-import-error-solved/</link><pubDate>Wed, 14 Jan 2009 16:46:16 +0000</pubDate><guid>https://shocksolution.com/posts/scipyintegrate-odepack-import-error-solved/</guid><description>&lt;p&gt;I recently found a solution to a problem that had been vexing me for about a year. In order to successfully import anything from scipy.integrate, I had edit the file scipy/integrate/__init__.py and comment out the line&lt;/p&gt;&#10;&lt;div class="code-block"&gt;&#10; &lt;button class="code-copy" type="button" hidden aria-label="Copy code to clipboard"&gt;&#10; &lt;span class="code-copy-label" aria-hidden="true"&gt;Copy&lt;/span&gt;&#10; &lt;/button&gt;&#10; &lt;div class="highlight"&gt;&lt;pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"&gt;&lt;code class="language-text" data-lang="text"&gt;&lt;span style="display:flex;"&gt;&lt;span&gt;from odepack import *&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&#10; &lt;/div&gt;&lt;p&gt;If not, I would get various import errors such as&lt;/p&gt;&#10;&lt;div class="code-block"&gt;&#10; &lt;button class="code-copy" type="button" hidden aria-label="Copy code to clipboard"&gt;&#10; &lt;span class="code-copy-label" aria-hidden="true"&gt;Copy&lt;/span&gt;&#10; &lt;/button&gt;&#10; &lt;div class="highlight"&gt;&lt;pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"&gt;&lt;code class="language-text" data-lang="text"&gt;&lt;span style="display:flex;"&gt;&lt;span&gt;Traceback (most recent call last):&#10;&lt;/span&gt;&lt;/span&gt;&lt;span style="display:flex;"&gt;&lt;span&gt; File &amp;#34;&amp;lt;stdin&amp;gt;&amp;#34;, line 1, in &amp;lt;module&amp;gt;&#10;&lt;/span&gt;&lt;/span&gt;&lt;span style="display:flex;"&gt;&lt;span&gt; File &amp;#34;/usr/lib/python2.5/site-packages/scipy/integrate/__init__.py&amp;#34;, line 10,&#10;&lt;/span&gt;&lt;/span&gt;&lt;span style="display:flex;"&gt;&lt;span&gt;in &amp;lt;module&amp;gt;&#10;&lt;/span&gt;&lt;/span&gt;&lt;span style="display:flex;"&gt;&lt;span&gt; from odepack import *&#10;&lt;/span&gt;&lt;/span&gt;&lt;span style="display:flex;"&gt;&lt;span&gt; File &amp;#34;/usr/lib/python2.5/site-packages/scipy/integrate/odepack.py&amp;#34;, line 7,&#10;&lt;/span&gt;&lt;/span&gt;&lt;span style="display:flex;"&gt;&lt;span&gt;in &amp;lt;module&amp;gt;&#10;&lt;/span&gt;&lt;/span&gt;&lt;span style="display:flex;"&gt;&lt;span&gt; import _odepack&#10;&lt;/span&gt;&lt;/span&gt;&lt;span style="display:flex;"&gt;&lt;span&gt;ImportError: /usr/lib/python2.5/site-packages/scipy/integrate/_odepack.so:&#10;&lt;/span&gt;&lt;/span&gt;&lt;span style="display:flex;"&gt;&lt;span&gt;undefined symbol: daxpy_&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&#10; &lt;/div&gt;&lt;p&gt;I found the solution in &lt;a href="http://bugs.gentoo.org/show_bug.cgi?id=251165" title="Gentoo%20bug%20251165"&gt;Gentoo bug 251165&lt;/a&gt;. The problem only occurs when Scipy is built with non-reference versions of BLAS and CBLAS. The solution is to install the reference implementation of BLAS and CBLAS, rebuild Scipy, and then use whichever implementation of BLAS or CBLAS you want. I don&amp;rsquo;t know why this happens, and I don&amp;rsquo;t know if it affects distributions other than Gentoo. By the way, Gentoo has a really useful system tool called &lt;a href="http://%3C%3Cwww.gentoo.org/proj/en/eselect/index.xml&amp;amp;gt%3E;" title="Eselect%20home%20page"&gt;eselect&lt;/a&gt;, which has various modules that are used to choose between different versions or implementations of tools on your system (BLAS, Java virtual machine, kernel sources, OpenGL, etc.)&lt;/p&gt;</description></item><item><title>Optimizing Python code for fast math</title><link>https://shocksolution.com/posts/optimizing-python-code-for-fast-math/</link><pubDate>Fri, 09 Jan 2009 21:14:38 +0000</pubDate><guid>https://shocksolution.com/posts/optimizing-python-code-for-fast-math/</guid><description>&lt;p&gt;I spent some time today profiling a Brownian dynamics simulation written in Python to see how I could make it faster before starting some long runs on a Linux cluster. In the sections below, I have attempted to quantify the speed improvements due to various changes. Keep in mind that the actual speed improvement in your code will vary, depending on where the actual bottlenecks occur. See my post about &lt;a href="https://shocksolution.com/2008/10/24/profiling-python-code/" title="Profiling%20Python%20code"&gt;profiling Python code&lt;/a&gt;. Another caveat: I am running Python 2.4.4 because it&amp;rsquo;s installed on our cluster.&lt;/p&gt;</description></item><item><title>Redirecting standard output from Python: another example</title><link>https://shocksolution.com/posts/redirecting-standard-output-from-python-another-example/</link><pubDate>Wed, 07 Jan 2009 21:54:10 +0000</pubDate><guid>https://shocksolution.com/posts/redirecting-standard-output-from-python-another-example/</guid><description>&lt;p&gt;I wrote a previous post about how to &lt;a href="https://shocksolution.com/2008/08/16/redirecting-text-output-from-python-functions/" title="Redirecting%20Python%20standard%20output"&gt;redirect standard output from a Python script to a GUI window&lt;/a&gt;.  In this post, I will give an even simpler example of to redirect standard output to a log file.  During the early development and debugging of Python programs, I use print statements to keep me informed of what&amp;rsquo;s happening.  However, printing to the terminal is not always practical&amp;ndash;for example, when I run numerical code on a parallel cluster, there is no way to determine which output came from which instance of the program.  Here is a class that you can use to redirect standard output to a log file:&lt;/p&gt;</description></item><item><title>Tools for Python software development</title><link>https://shocksolution.com/posts/tools-for-python-software-development/</link><pubDate>Tue, 06 Jan 2009 18:52:45 +0000</pubDate><guid>https://shocksolution.com/posts/tools-for-python-software-development/</guid><description>&lt;p&gt;I have found a few tools over the years that I find extremely useful for developing software. Python is my language of choice at the moment, but I&amp;rsquo;m sure these tools will be handy for any language.&lt;/p&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;&lt;a href="http://subversion.tigris.org/" title="Subversion%20home%20page"&gt;Subversion&lt;/a&gt; is an open-source version-control system. Version control was designed to allow multiple programmers to work on the same project at the same time without stepping all over one another. However, even though I am a solo developer, I find version control to be extremely helpful.&#10;&lt;ol&gt;&#10;&lt;li&gt;When I commit changes to the repository, I can document what I&amp;rsquo;ve changed and why. This is a great help when I introduce a bug and have to go back and find it.&lt;/li&gt;&#10;&lt;li&gt;The repository is stored on a remote server that is backed up nightly.&lt;/li&gt;&#10;&lt;li&gt;It&amp;rsquo;s easy to make an &amp;ldquo;unstable&amp;rdquo; branch for implementing new features. When I make changes that don&amp;rsquo;t work, it&amp;rsquo;s easy to revert to a previous version that works.&lt;/li&gt;&#10;&lt;li&gt;It is easy to deploy my code to the Linux cluster and make sure that the cluster is running the latest version of my software.&lt;/li&gt;&#10;&lt;/ol&gt;&#10;&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;p&gt;Go read the documentation on the Subversion web site to find out what it can do for you.&lt;em&gt;&lt;a href="http://rapidsvn.tigris.org/" title="RapidSVN%20home%20page"&gt;RapidSVN&lt;/a&gt; is a GUI client for a Subversion server. By default, Subversion comes with a command-line client that does everything you need. However, sometimes it&amp;rsquo;s easier to stay organized when everything is presented visually. Here is a screenshot of RapidSVN: &lt;figure class="ma0 w-75"&gt;&lt;img src="https://shocksolution.com/images/rapidsvn_screenshot-150x150.png"&#10;&#9;&#9;&#9;alt="RapidSVN screenshot"&gt;&lt;figcaption&gt;&#10;&#9;&#9;&#9;&lt;p&gt;RapidSVN screenshot&lt;/p&gt;</description></item><item><title>A lookup table for fast Python math</title><link>https://shocksolution.com/posts/a-lookup-table-for-fast-python-math/</link><pubDate>Thu, 11 Dec 2008 23:17:06 +0000</pubDate><guid>https://shocksolution.com/posts/a-lookup-table-for-fast-python-math/</guid><description>&lt;p&gt;Numerical programming frequently requires the use of look-up tables. A look-up table is a collection of pre-computed values. When given an &amp;ldquo;x&amp;rdquo; value, the table returns a pre-computed &amp;ldquo;y&amp;rdquo; value. Look-up tables can be used to speed up numerical codes, when it is faster to look up a value in the table than it is to compute the value. They are also used when the data in the table cannot be computed&amp;ndash;for example, experimental data or averaged results from an ensemble of Monte Carlo simulations. Another application is to compute a value when a function cannot be solved algebraically. Assume that you have a formula for a function q(h). You need the value of h for a given value of q, but the formula cannot be algebraically solved to get h(q). Instead, choose a range of h values, compute the function q(h), and store each value in a look-up table. Now you can get h(q) for any value stored in the table. The major limitation of a look-up table is that it cannot return valid results for any value of q which is outside the range of those stored in the table. Depending on its implementation, the table may be able to interpolate to return values between known points.&lt;/p&gt;</description></item><item><title>Update 2: building 64-bit Numpy with Intel compilers and MKL</title><link>https://shocksolution.com/posts/update-2-building-64-bit-numpy-with-intel-compilers-and-mkl/</link><pubDate>Tue, 09 Dec 2008 19:33:12 +0000</pubDate><guid>https://shocksolution.com/posts/update-2-building-64-bit-numpy-with-intel-compilers-and-mkl/</guid><description>&lt;p&gt;NOTE: these instructions are obsolete.  Please see &lt;a href="../../2012/04/building-numpy-on-a-red-hat-cluster-with-intel-mkl/" title="Permanent Link: Building NumPy on a 64-bit Red Hat Cluster with Intel MKL"&gt;Building NumPy on a 64-bit Red Hat Cluster with Intel MKL&lt;/a&gt;. In a previous post I described &lt;a href="https://shocksolution.com/2008/10/17/updated-building-64-bit-numpy-with-intel-compilers-icc/" title="Previous%20update"&gt;how I built Numpy with Intel compilers and the Math Kernel Library on a 64-bit cluster&lt;/a&gt;. Today I upgraded to Numpy-1.2.1 and I made a few improvements to my install process. Please read the previous post, since I will not duplicate some important information, and then read on. This time, I made use of a site.cfg file. Copy the file &lt;strong&gt;site.cfg.example&lt;/strong&gt;to&lt;strong&gt;site.cfg&lt;/strong&gt; and edit. At the end of the file, uncomment the [mkl] section and set the path to your library. Mine looks like:&lt;/p&gt;</description></item><item><title>Using Python to generate XML files for visualization in Paraview</title><link>https://shocksolution.com/posts/using-python-to-generate-xml-files-for-visualization-in-paraview/</link><pubDate>Thu, 13 Nov 2008 19:00:23 +0000</pubDate><guid>https://shocksolution.com/posts/using-python-to-generate-xml-files-for-visualization-in-paraview/</guid><description>&lt;p&gt;&lt;a href="http://%3Cwww.vtk.org/%3E" title="VTK%20homepage"&gt;VTK&lt;/a&gt; is an open-source software system for &amp;ldquo;3D computer graphics, image processing, and visualization&amp;rdquo; developed by by Kitware. VTK is the foundation of &lt;a href="http://%3Cwww.paraview.org/%3E" title="Paraview%20homepage"&gt;Paraview,&lt;/a&gt; an industrial-strength CFD visualization tool that I have found to be very useful. I generate &amp;ldquo;second generation&amp;rdquo; XML-based files from my Python code and import them into Paraview for visualization. I am in the process of creating some Python classes to do, and I hope to publish them soon. Until then, I want to share some useful resources. The &lt;a href="http://%3Cwww.vtk.org/pdf/file-formats.pdf%3E" title="VTK%20File%20Formats"&gt;VTK file formats are specified in this document&lt;/a&gt;. It&amp;rsquo;s a pretty good specification, but it lacks some examples. Soon I will post an example of a valid unstructured, serial .vtu file. Each VTK file includes data from only one time step, so you have to keep track of time yourself (the filename is an easy solution). Paraview can read in data from multiple time steps, but you have to specify them in a .pvd file. This is also an XML file, with the following format: (&lt;a href="http://%3Cwww.cmake.org/pipermail/paraview/2008-August/009062.html%3E" title="Cmake%20discussion%20t%20hread"&gt;reference&lt;/a&gt;)&lt;/p&gt;</description></item><item><title>Unexpected integer/float math behavior in Python</title><link>https://shocksolution.com/posts/unexpected-integerfloat-math-behavior-in-python/</link><pubDate>Fri, 07 Nov 2008 00:21:16 +0000</pubDate><guid>https://shocksolution.com/posts/unexpected-integerfloat-math-behavior-in-python/</guid><description>&lt;p&gt;I wasted some time today tracking down a bug in one of my programs.  It turned out to be &amp;ldquo;unexpected behavior&amp;rdquo; rather than a bug.  I was aware of this aspect of the language, but I made an assumption and got bit.  Read on for a valuable lesson. Python handles integer math differently than floating point math.  If you type a number without a decimal point, Python treats it as an integer.  &lt;strong&gt;All math performed only with integers results in integers.&lt;strong&gt;For example, 1/2 evaluates to 0 while 1./2. evaluates to 0.5.  If you mix integers and floats, Python will  produce a floating point result (1/2.=0.5), but you must be very careful.  For example, you might expect the expression 4/3*3.14159 to yield a floating point result.  It does yield a floating point number, but&lt;/strong&gt;not&lt;/strong&gt;the one you were expecting!  4/3*3.14159 yields 3.14159.  What happened?  Python works from left to right.  4/3 evaluates to the integer &amp;ldquo;1&amp;rdquo;.  1*3.14159 evaluates to  3.14159.  For comparison, 4./3.*3.14159 evaluates to 4.1887866.  Here&amp;rsquo;s the problem with this particular aspect of Python: according to the rules of math, 4/3*3.14159 is exactly the same expression as 4*3.14159/3, but in Python they yield different results if you forget the decimal points!  4*3.14159 evaluates to a floating point, so (4*3.14159)/3 yields the &amp;ldquo;correct&amp;rdquo; floating point value. Lesson Learned: be explicit about specifying&lt;strong&gt;all&lt;/strong&gt; floats if you are doing floating-point math!  Sometimes I get lazy and leave a trailing decimal point off of a number when doing a floating point calculation, knowing that the results are &amp;ldquo;upcast&amp;rdquo; into floats. Not any more! Note: this unexpected behavior &lt;a href="http://docs.python.org/dev/3.0/whatsnew/3.0.html#common-stumbling-blocks" title="Python%203.0%20Changes"&gt;goes away in Python 3.0&lt;/a&gt;&lt;/p&gt;</description></item><item><title>Profiling Python code</title><link>https://shocksolution.com/posts/profiling-python-code/</link><pubDate>Fri, 24 Oct 2008 21:37:24 +0000</pubDate><guid>https://shocksolution.com/posts/profiling-python-code/</guid><description>&lt;p&gt;&amp;ldquo;Speed&amp;rdquo; is a complicated term when used in the context of software.  Does it mean raw speed of execution, or reducing the amount of time until a correct result is obtained?  Python is not the first language that comes to mind when people think of &amp;ldquo;fast software.&amp;rdquo;  It is true that pure Python will usually not execute as quickly as the same algorithm directly coded in C or Fortran.  However, when you define speed as &amp;ldquo;least amount of time until you get the right answer,&amp;rdquo; then Python is pretty fast.  It is so easy to develop correct code in Python, when compared to low-level compiled languages, that Python is often the fastet route to a correct answer, even if the execution time is longer.  Having said that, there &lt;strong&gt;are&lt;/strong&gt;times when code has to execute quickly, and that&amp;rsquo;s why I will introduce you to profiling Python code. Like all things Python, profiling is easier than you think.  Python 2.4 has the &lt;a href="http://%3C%3Cwww.python.org/doc/2.4/lib/profile.html&amp;amp;gt%3E;" title="Python%202.4%20profiler"&gt;profile module&lt;/a&gt;, and Python 2.5 has both &lt;a href="http://%3C%3Cwww.python.org/doc/2.5.2/lib/profile.html&amp;amp;gt%3E;" title="Python%202.5%20profilers"&gt;profile and cProfile&lt;/a&gt;.  cProfile is written in C for lower overhead, and it&amp;rsquo;s the recommended version.  I am stuck with profile, because the cluster that I am working with still uses Python 2.4.  You can read the docs for more details, but I will quickly outline what I find to be the most helpful usage.  For example, say I want to profile the file&lt;strong&gt;run_sim.py&lt;/strong&gt;.  I use the following command line:&lt;/p&gt;</description></item><item><title>Updated: building 64-bit Numpy with Intel compilers (icc)</title><link>https://shocksolution.com/posts/updated-building-64-bit-numpy-with-intel-compilers-icc/</link><pubDate>Fri, 17 Oct 2008 19:36:38 +0000</pubDate><guid>https://shocksolution.com/posts/updated-building-64-bit-numpy-with-intel-compilers-icc/</guid><description>&lt;p&gt;I had to re-build Numpy because our cluster was upgraded and the Intel compilers and libraries were moved to a different directory.  This turned out to be a half-day affair of trial-and-error.  I learned a few important things, which I will try to list here:&lt;/p&gt;&#10;&lt;p&gt;*Delete the numpy-1.0.4/build directory after every build attempt.  Doing &amp;ldquo;python setup.py clean&amp;rdquo; is&lt;strong&gt;not&lt;/strong&gt;effective.  I kept getting errors about undefined symbols when I tried to &amp;ldquo;import numpy&amp;rdquo; on the Python command line.  It was looking for symbols in the old locations, even though I had just rebuilt the code using the new library locations.  It turned out that I needed to delete the build directory in order to force a complete bottom-up rebuild.*The use of &amp;ldquo;setup.py&amp;rdquo; from distutils is not well documented online.  The best thing to do is run &amp;ldquo;python setup.py &amp;ndash;help-commands&amp;rdquo; to get a list of available commands.  Then run &amp;ldquo;python setup.py &amp;lt;cmd&amp;gt; &amp;ndash;help&amp;rdquo; to get help for that specific command.  You can string commands together on the command line, as I will show in the example below.&lt;em&gt;When you test the new numpy, make sure you are&lt;strong&gt;not&lt;/strong&gt;in the numpy-1.0.4 directory!  If you are in the numpy source directory, when you import numpy, you will get the message &amp;ldquo;Running from numpy source directory.&amp;rdquo; and you will not be able to load any symbols from numpy.&lt;/em&gt; On 64-bit architectures, you need to compile position-independent library code.  For some reason, distutils does not do this automatically, and the compilation will fail with an error similar to the following:&lt;/p&gt;</description></item><item><title>Even faster collision detection in Python using Numpy</title><link>https://shocksolution.com/posts/even-faster-collision-detection-in-python-using-numpy/</link><pubDate>Thu, 16 Oct 2008 19:44:15 +0000</pubDate><guid>https://shocksolution.com/posts/even-faster-collision-detection-in-python-using-numpy/</guid><description>&lt;p&gt;Last night, in the shower, I realized that my collision detection routine could be even faster. Here is a representative snippet of code from my previous post:&lt;/p&gt;&#10;&lt;div class="code-block"&gt;&#10; &lt;button class="code-copy" type="button" hidden aria-label="Copy code to clipboard"&gt;&#10; &lt;span class="code-copy-label" aria-hidden="true"&gt;Copy&lt;/span&gt;&#10; &lt;/button&gt;&#10; &lt;div class="highlight"&gt;&lt;pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"&gt;&lt;code class="language-text" data-lang="text"&gt;&lt;span style="display:flex;"&gt;&lt;span&gt; d2 = (x-self.x[0:i])*(x-self.x[0:i]) + (y-self.y[0:i])*(y-self.y[0:i]) + (z-self.z[0:i])*(z-self.z[0:i])&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&#10; &lt;/div&gt;&lt;p&gt;For some reason, I used the code (x-self.x)*(x-self.x) instead of (x-self.x)**2. Upon further reflection, I realized that (x-self.x)*(x-self.x) computes the difference between array elements twice, and then multiplies the results. Using a &amp;ldquo;power function&amp;rdquo; should enable the interpreter to compute the difference only once, and then multiply each element times itself. Here is the updated code, using Python&amp;rsquo;s power operator:&lt;/p&gt;</description></item><item><title>Speeding up Python math with Numpy: collision detection example</title><link>https://shocksolution.com/posts/speeding-up-python-math-with-numpy-collision-detection-example/</link><pubDate>Sun, 12 Oct 2008 18:10:20 +0000</pubDate><guid>https://shocksolution.com/posts/speeding-up-python-math-with-numpy-collision-detection-example/</guid><description>&lt;p&gt;Python is a very-high-level language.  That makes it easy to write code quickly, but the program may not be as fast as a program compiled from a lower-level language.  For this reason, many scientific programs are written in Fortran or C++.  However, it has always been my experience that the majority of time on a project is spent in writing, modifiying, and debugging code, rather than executing.  Fortunately, if written correctly, the time-critical parts of Python code can execute almost as fast as compiled software.  Here is an example of a collision-detection algorithm which achieved almost a ten-fold increase in speed when written to use &lt;a href="http://numpy.scipy.org/" title="Numpy%20homepage"&gt;Numpy&lt;/a&gt;.&lt;/p&gt;</description></item><item><title>Installing numpy with the Intel Math Kernel Library (mkl)</title><link>https://shocksolution.com/posts/installing-numpy-with-the-intel-math-kernel-library-mkl/</link><pubDate>Fri, 19 Sep 2008 21:24:58 +0000</pubDate><guid>https://shocksolution.com/posts/installing-numpy-with-the-intel-math-kernel-library-mkl/</guid><description>&lt;p&gt;Today I installed numpy on a cluster. Normally, as a Gentoo admin, I just install things with emerge, and all the details are taken care of automagically. However, this cluster runs Red Hat Enterprise, and I don&amp;rsquo;t have admin privileges, so I had to install numpy in my home directory. I installed 1.0.4, to match the version used on another system. You may not need to do this for more recent versions of numpy, which may have an improved setup script. The overall process is:&lt;/p&gt;</description></item><item><title>Python Pickle: Painless binary storage for Python objects</title><link>https://shocksolution.com/posts/python-pickle-painless-binary-storage-for-python-objects/</link><pubDate>Mon, 15 Sep 2008 22:23:18 +0000</pubDate><guid>https://shocksolution.com/posts/python-pickle-painless-binary-storage-for-python-objects/</guid><description>&lt;p&gt;The &lt;a href="http://docs.python.org/lib/module-pickle.html"&gt;pickle&lt;/a&gt; module provided with Python is so useful that I&amp;rsquo;m surprised I haven&amp;rsquo;t used it before. Pickle allows you to save an entire data structure (such as an object) to disk as a binary file in a effortless (and fairly efficient) manner. For example, in my latest project I have created a Monte Carlo simulation that can take quite a bit of time to run. I also need to make multiple runs to get statistics on the results. At the end of each run, I need to dump the resulting data to disk so that it can be read in later by an analysis program. If I had to write data in a format that could be interchanged with other scientific software, I&amp;rsquo;d use the &lt;a href="http://hdf.ncsa.uiuc.edu/HDF5/"&gt;hdf5&lt;/a&gt; format with the &lt;a href="http://%3C%3Cwww.pytables.org/moin&amp;amp;gt%3E;"&gt;pytables&lt;/a&gt; package. However, right now I just need to get something working, and the pickle module is perfect. Here is how I save an object called box:&lt;/p&gt;</description></item><item><title>Python threads are easy (with example)</title><link>https://shocksolution.com/posts/python-threads-are-easy-with-example/</link><pubDate>Tue, 19 Aug 2008 22:50:07 +0000</pubDate><guid>https://shocksolution.com/posts/python-threads-are-easy-with-example/</guid><description>&lt;p&gt;It&amp;rsquo;s remarkably easy to spawn a Python thread.  However, before doing so, I caution you that a Python thread is not the same thing as an OS thread.  Python threads run within the Python interpreter, but the Python interpreter always executes in a single process.  The reasons why have already been explained elsewhere, so I refer you to the &lt;a href="http://docs.python.org/api/threads.html" title="thread%20module%20docs"&gt;thread module documentation&lt;/a&gt; to learn about the Global Interpreter Lock.  You probably have objections to this state of affairs, and I assure you they have already been &lt;a href="http://blog.snaplogic.org/?p=94" title="Objections%20to%20the%20Global%20Interpreter%20Lock"&gt;voiced&lt;/a&gt; by Juergen Brendel and &lt;a href="http://%3C%3Cwww.artima.com/weblogs/viewpost.jsp?thread=214235&amp;amp;gt%3E;" title="Guido%20van%20Rossum's%20response"&gt;responded to&lt;/a&gt; by Guido van Rossum (creator of Python).  Anyway, the upshot is that Python can only utilize one core of a multi-core CPU.  This isn&amp;rsquo;t such a big deal for me because I&amp;rsquo;m a scientific programmer, and if I really need to write parallel code it&amp;rsquo;s going to have to run on a cluster or a grid.  Threads don&amp;rsquo;t help with that. Having said all that, threads in Python are still useful.  I will detail one example in which I spawn a thread to load a large binary file.  While this doesn&amp;rsquo;t spread the work across multiple CPU cores, it does enable the GUI to remain interactive while the file loads. All you have to do to create a Python thread is create a class that is derived from Thread. In the example below, I derived a class called Loader, which &amp;ldquo;wraps&amp;rdquo; the function that actually reads the binary files. The __init__ method accepts the filename and other options as arguments. The run() method is required. Don&amp;rsquo;t call run() directly&amp;ndash;instead, call the start() method (inherited from the base class) to start the thread.&lt;/p&gt;</description></item><item><title>Redirecting text output from Python functions</title><link>https://shocksolution.com/posts/redirecting-text-output-from-python-functions/</link><pubDate>Sat, 16 Aug 2008 20:47:05 +0000</pubDate><guid>https://shocksolution.com/posts/redirecting-text-output-from-python-functions/</guid><description>&lt;p&gt;Two posts ago, I described how I wrote a function in Python that reads in a binary file from Labview. In my last post, I described using wxPython to write a GUI to process the data from those binary files. Naturally, I called the binary-file-reader function from the GUI. The problem is that the file reader prints a lot of information to the terminal, using Python &lt;strong&gt;print&lt;/strong&gt;statements. None of this goes to the GUI, requiring the user to run the GUI from a terminal and keep an eye on the text output, which is inconvenient. However, I don&amp;rsquo;t want to modify the file reader to include GUI-specific code, because that would be less modular and less re-usable. Instead, I learned that Python has a very easy facility to redirect&lt;strong&gt;stdout&lt;/strong&gt;, the default destination of the &lt;strong&gt;print&lt;/strong&gt; statement. I modified the file reader as follows:&lt;/p&gt;</description></item><item><title>Fun with threads in Python and wxPython</title><link>https://shocksolution.com/posts/fun-with-threads-in-python-and-wxpython/</link><pubDate>Mon, 11 Aug 2008 22:12:07 +0000</pubDate><guid>https://shocksolution.com/posts/fun-with-threads-in-python-and-wxpython/</guid><description>&lt;p&gt;I have finally gotten back to programming in the last couple of days.  Our project has finally started to generate a lot of data, so I&amp;rsquo;ve been refactoring and improving my code that &lt;a href="https://shocksolution.com/blog/2008/06/25/reading-labview-binary-files-with-python/" title="Reading%20Labview%20binaries%20with%20Python"&gt;reads data stored in LabView binaries&lt;/a&gt;.  Today I spent a lot of time creating a GUI for browsing data.  Arguably, this wasn&amp;rsquo;t the best use of my time, but I learned a lot about multi-threaded Python GUI programming with wxPython.  You can find a gold mine of &lt;a href="http://wiki.wxpython.org/LongRunningTasks" title="Multi-threading%20with%20wxpython"&gt;information on the multi-threaded wx programming&lt;/a&gt; at the wxPython wiki.  Because the LabView binary data has to be read sequentially, and the files are rather large, it takes a long time to read in a file.  I spawn a thread to handle the file reading,  while allowing the GUI to remain responsive.  The thread posts messages to the GUI window, which are used to update the user on the status of the file reading operation.  When the file is read, a final message containing the data is posted to the window.  It&amp;rsquo;s really pretty slick now that I&amp;rsquo;ve figured out how to do it. I will soon post a clever scheme to capture text output from the file-reading function, and display it in the GUI, without making substantial changes to the file-reading function.&lt;/p&gt;</description></item><item><title>Reading Labview binary files with Python</title><link>https://shocksolution.com/posts/reading-labview-binary-files-with-python/</link><pubDate>Wed, 25 Jun 2008 16:04:46 +0000</pubDate><guid>https://shocksolution.com/posts/reading-labview-binary-files-with-python/</guid><description>&lt;p&gt;My research group uses Labview 7.1 to write custom data acquisition (DAQ) software. I code everything else in Python, so I need to get data from Labview into Python for processing. Our DAQ program produces Labview binary files, so I had to find a way to read them with Python. Binary files are nice because they are a compact way to store numerical data as compared to ASCI or (heaven forbid) XML, but they are much harder to read. The binary format used by Labview is documented only indirectly, so I had to hack a little. The first thing to realize is that the Labview binary file is a direct dump of the data that was stored in RAM. &lt;a href="http://zone.ni.com/reference/en-XX/help/371361A-01/lvconcepts/how_labview_stores_data_in_memory/" title="How%20Labview%20stores%20data%20in%20RAM"&gt;How Labview stores data in memory is documented here.&lt;/a&gt; Indirectly, this documents how binary files are stored on disk. Our DAQ program writes a rather complex &amp;ldquo;cluster&amp;rdquo; (Labview&amp;rsquo;s version of a C structure) to disk. The elements of the cluster are stored contiguously as a sequence of bytes, and there&amp;rsquo;s no way to know which byte goes with which element, unless you know the size of each element and the order in which they are stored in the cluster. So, the first step is to document the cluster that&amp;rsquo;s being written to disk. You can use the context help in Labview to view the data type of the wire that leads to the VI that writes the file. With this in hand, you are ready to write Python code. First, make sure you open the file in binary mode:&lt;/p&gt;</description></item></channel></rss>