Thursday, August 11, 2011

Trying Ubuntu Linux (1)

I thought I would play around with Linux a bit, trying to improve my Unix skills. I'm running it in a second partition on my Macbook that has OS X Lion installed (post here) and runs a Virtual Box VM.

I first heard about and tried Oracle's Virtual Box in connection with QIIME (post here).

I grabbed a VirtualBox version 4.1 binary installer for Mac OS X here.

Then I downloaded Ubuntu Linux 11.04 (now why is it called Natty Narwhal?) from here. There is another download page here but I think it has the same choices.

I ended up trying both Desktop "CD"s, because I was a little confused about the version I needed. There appears to be only 32-bit for i386 (ubuntu-11.04-desktop-i386.iso) but 64-bit for AMD (ubuntu-11.04-desktop-amd64.iso). However, the chip running the host OS is not relevant. The QIIME Linux is labeled AMD64 and is 64-bit and can run on my 64-bit machines under a VM. I suppose it would matter if I wanted to run Linux directly in the partition instead of in Virtual Box.

I have to confess, I've installed several different Linux versions (and then removed them) and the one described here a number of times, because I ran into problems with the install that I couldn't figure out how to back out of. But experimentation is relatively cheap, since it's just a VM. I don't have any worries about leftover crap on my disk. If worst comes to worst I can just erase the whole partition. Although it takes patience for the install steps.

Stock 64-bit Ubuntu Linux


So, I ran the Virtual Box installer, set the Name as Ubuntu, Operating System as Linux and the Version as Ubuntu 64. Then I set up the VM with all standard options (except 1 GB for RAM). Just click on through.

To actually install Linux using a .iso file, use the "First Run Wizard" by double-clicking the new machine in the list. For Select Installation Media: I navigated to the saved file. On one try I somehow got past the Wizard without properly installing and had to delete and re-configure the VM.

It takes quite a while to boot the first time, copying all the files over to the VM, I guess. Choose Erase disk and install Ubuntu (the disk size should be only the size of the VM disk). There are a bunch of dialogs to go through. After the install and reboot we get a message that Unity won't run on our hardware and so we're going to get Classic. Oh well.

Reboot..

Now, there are two things that seem really important to have but are not present in this stock install:

• a Shared Folder for file sharing between host and guest OS
• a Clipboard for copy/paste between host and guest OS

To have these features you must install what are called the "Guest Additions," which are additions to the Linux kernel. Some instructions are on this page:

After you have installed the Linux Guest system, there are a few additional packages needed for the Guest Additions. These packages enables you to create kernel modules. For Debian and Debian based distro's like Ubuntu, you need the following packages:
dkms
build-essential
linux-headers-generic


Find the Terminal (why not just drag it to the menu bar) and do:

sudo apt-get install dkms build-essential linux-headers-generic

You'll have to type in the command, since copy/paste doesn't work yet :)
When it's done:

Reboot to make the changes effective..

Next, "mount" the Guest Additions "iso": in the VB menu (in OS X) under Devices, choose Install Guest Additions. It shows up as a CD on the Desktop. Then from the dialog choose the default that automatically runs the shell script. Or hit Open AutoRun Prompt > OK and then in Terminal do:

media/VBOXADDITIONS{version}/VBoxLinuxAdditions.run

After it's done, reboot again..

At this point, copy/paste between host/guest should work. You'll have to click twice, once to switch focus to the VM and once to switch focus again to whatever application is receiving the paste.

There are two different key combos for Linux and neither is CMD. Not sure if this is standard Linux or it is just since the left CMD key is a special key for the VM. To copy and paste within Terminal on Linux use CTL-SHIFT-x and CTL-SHIFT-v rather than CMD (for Text Edit just use CTL-x and CTL-v).

Now we can try to get shared folders. In the Virtual Box window, from the Devices menu choose Shared Folders. Add a folder (navigate the host OS to the desired path). Also, make a folder under Linux that we'll use to share with, say /home/telliott/Desktop/share

In the dialog, choose Automount (and Make Permanent, see below). Even after the specification of a shared folder, you still have to mount it within Linux. The Qiime guys do:

sudo mount -a

Unfortunately, it doesn't seem to work for me. (Not in the Qiime install either). So then I tried this:

sudo mount -t vboxsf -o uid=1000,gid=1000 shared ~/Desktop/share

The first argument after vboxsf above is the name of the folder on the host OS (as defined by us in the Devices menu above). The second argument is the name of the sharepoint --- the path to a folder on the Guest.

It didn't work at first, because it turned out, I had failed to check Automount above. And, if you want to make a change to the Shared Folder setting, it seems that you have to reboot to be able to actually do it, otherwise there's a message about the resource being in use.

Also, I never did figure out how to change Make Permanent. Any change or attempt to delete in the Shared Folders dialog (even after a reboot) gives an error message: VERR_PERMISSION_DENIED. There's a note in the link about putting the mount command in

/etc/rc.local

but I don't see how that's going to work since it needs to run as root? Luckily, the VM allows me to suspend Linux in its current state. And now, thinking that I need to re-run that command every time upon booting, I try it and get:

sudo mount -t vboxsf -o uid=1000,gid=1000 shared ~/Desktop/share
/sbin/mount.vboxsf: mounting failed with the error: Invalid argument


After re-boot, the same mount fails! I am starting to get angry with this thing.

I gave up and set up Dropbox access from within the VM. It works great.

Now, to build some software.

Saturday, August 6, 2011

PyMOL (1)


If you're interested in Python and bioinformatics you've undoubtedly heard of Pymol.

If you're at a place that cares about molecular biology (my institution does not), you may even have a site license. I have a copy that I got for educational use about 3 years ago, and still have some examples that I made for a class I taught. That version has a Cocoa GUI.

There is also an open source version that is up on SourceForge (here). I thought it would be a good challenge to try to build the open source Pymol.

[ Update: I think the Cocoa GUI one is MacPymol here). I just noticed this on the legacy page. ]

The dependencies are listed in the README as:


PyMOL has the following external dependencies:
1. OpenGL
2. GLUT library for OpenGL (or freeglut)
3. Python (v 2.1 or better) compiled with threads support
4. libpng (can compiled without it, but image saves won't work)
5. Tcl/Tk (for the external GUI)
6. Numerical Python (technically optional - now using numpy instead)
7. Python megawidgets (Pmw -- only required for the "external" GUI)
8. FreeType2 (if you want nice fonts)


Most of these are already present in Lion, so I didn't think it would be too difficult. What I failed to realize is that the Tcl/Tk in Lion is apparently messed up (brief SO discussion here).

I downloaded pymol-v1.4.1.tar.bz2 from the main page at SourceForge, and did the standard distutils thing:

python setup.py build

The first error was:

layer0/ShaderMgr.c:173: error: ‘GLEW_OK’ undeclared (first use in this function)

The top Google hit shows it's related to OpenGL and glut.
If present, there should be a file glew.h (and likely glut.h).

> find /usr -iname *glut*
/usr/X11/include/GL/glut.h
/usr/X11/include/GL/glutf90.h
/usr/X11/lib/libglut.3.7.dylib
/usr/X11/lib/libglut.3.dylib
/usr/X11/lib/libglut.dylib
/usr/X11/lib/pkgconfig/glut.pc
> find /usr -iname *glew*
> find /usr -iname *GLEW*
>

No glew.

brew install glew

works and we have


$ find /usr/local/lib -iname *glew*
/usr/local/lib/libGLEW.1.5.8.dylib
/usr/local/lib/libGLEW.1.5.dylib
/usr/local/lib/libGLEW.a
/usr/local/lib/libGLEW.dylib
/usr/local/lib/pkgconfig/glew.pc

and we find "GLEW_OK defined on line 15273 of glew.h. Unfortunately, the build fails with a link error at the end:


ld: warning: ignoring file /usr/local/lib/libGLEW.dylib, file was built for unsupported file format which is not the architecture being linked (i386)
ld: duplicate symbol __CShaderMgr in build/temp.macosx-10.7-intel-2.7/layer2/RepCylBond.o and build/temp.macosx-10.7-intel-2.7/layer2/RepCartoon.o for architecture i386

> file /usr/local/lib/libGLEW.dylib
/usr/local/lib/libGLEW.dylib: Mach-O 64-bit dynamically linked shared library x86_64


So it seems that Homebrew has built x86_64, which can't work with what pymol is building (i386). What I should do is rebuild libGLEW.dylib with the correct architecture. I haven't accomplished that yet. Instead, I noticed a page that discusses this very same problem. One answer is in a different thread (here):

Kasper, not sure if this will help you, but I think the GLEW stuff was
added recently in V1.4.x and it seems to be still somewhat experimental.
May be to get you started you could switch to v1.3r1 from the repository
and try to embedd that version. V1.3.x should not contain the new GL
stuff.


So let's try 1.3. I grabbed pymol-1.3r2-src.tar.bz2 from here and it got past the previous problem but then dies with:

/usr/X11R6/include/ft2build.h:56:38: error: freetype/config/ftheader.h: No such file or directory

It's looking in /usr/X11R6 and can't find freetype which is in /usr/X11 (my post here).

So.. I modify the setup.py in pymol:

                     
inc_dirs=["ov/src",
"layer0","layer1","layer2",
"layer3","layer4","layer5",
"/usr/X11R6/include",
# my additions
"/usr/X11/include",
"/usr/X11/include/freetype2",
"/usr/local/include/GL",

EXT+"/include",
EXT+"/include/GL",
EXT+"/include/freetype2",
"modules/cealign/src",
"modules/cealign/src/tnt",
]
libs=[]
pyogl_libs = []
lib_dirs=[]
def_macros=[("_PYMOL_MODULE",None),
("_PYMOL_LIBPNG",None),
("_PYMOL_FREETYPE",None),
]
ext_comp_args=[]
ext_link_args=[
"-L/usr/X11R6/lib", "-lGL", "-lXxf86vm",
"-L"+EXT+"/lib", "-lpng", "-lglut", "-lfreetype",
# my additions
"-lGLEW"
]


And now it builds.

But.. after doing ./pymol the GUI hangs. I think it's Python (IDLE?), which I never use.

However, I can get pymol to run from the command line with no GUI:

> pymol -c
PyMOL(TM) Molecular Graphics System, Version 1.3.
..
Command mode. No graphics front end.
Detected 2 CPU cores. Enabled multithreaded rendering.
PyMOL: normal program termination.

I ran a short script and made a figure, it looks fine.

So then, we get wise words from Ned Deily (here), and see (here)

- You should not rely on the Apple-suppled Pythons if you want to use IDLE.


I thought about putting Tcl/Tk 8.4 in a different place, etc.

But finally I said (f*** it) and I reformatted my drive to add a new partition, and then used my USB flash drive with the Lion Installer (post here), and then I installed MacPorts and did

$ sudo port install pymol
---> Computing dependencies for pymol
---> Dependencies to be installed: freetype bzip2 zlib glew libpng mesa makedepend pkgconfig glib2 autoconf help2man gettext expat libiconv gperf ncurses ncursesw p5-locale-gettext perl5 perl5.12 perl5 perl5 m4 automake libtool xorg-xproto py27-libxml2 libxml2 libxml2 python27 db46 gdbm openssl python_select readline sqlite3 python27 xorg-dri2proto xorg-glproto xorg-libXfixes xorg-fixesproto xorg-libX11 xorg-bigreqsproto xorg-inputproto xorg-kbproto xorg-libXau xorg-libXdmcp xorg-libxcb xorg-libpthread-stubs xorg-xcb-proto xorg-util-macros xorg-xcmiscproto xorg-xextproto xorg-xf86bigfontproto xorg-xtrans xorg-libXi xorg-libXext xorg-libXmu xorg-libXt xorg-libsm xorg-libice py26-numeric python26 py26-pmw py26-tkinter tk Xft2 fontconfig xrender xorg-renderproto tcl xorg-libXScrnSaver xorg-scrnsaverproto xdpyinfo xorg-libXinerama xorg-xineramaproto xorg-libXtst xorg-recordproto xorg-libXxf86vm xorg-xf86vidmodeproto xorg-libdmx xorg-dmxproto

Incredible! Everything but the kitchen sink. Perhaps even more incredible, it worked. An hour or two later, we finish with:


---> Attempting to fetch pymol-1.4_2.darwin_11.x86_64.tbz2 from http://packages.macports.org/pymol
---> Fetching pymol
---> Verifying checksum(s) for pymol
---> Extracting pymol
---> Applying patches to pymol
---> Configuring pymol
---> Building pymol
---> Staging pymol into destroot
---> Installing pymol @1.4_2
---> Activating pymol @1.4_2
---> Cleaning pymol
$

I got 1LMB.pdb from the PDB, and I ran this script with pymol script.pml:

load ~/Desktop/1LMB.PDB
hide everything
select D1, chain 1
select D2, chain 2
select R1, chain 3
select R2, chain 4
deselect all
show sticks, D1
show sticks, D2
show cartoon, R1
show cartoon, R2
color red, R1
zoom active, -10
move x, 4
bg_color white
ray 1200,1200
png ~/Desktop/x.png

and I got what's at the top of the post. Pretty cool! More later on this topic.

Friday, August 5, 2011

Exploring ctypes (5)

I was a little snarky about how the ctypes docs start with all Windows examples, but once you get to here they are really excellent. So I won't say too much more about them except to reproduce a fun example:


>>> from ctypes import *
>>> class cell(Structure):
...     pass
... 
>>> cell._fields_ = [('name', c_char_p),
...                  ('next', POINTER(cell))]
>>> 
>>> c1 = cell()
>>> c1.name = 'foo'
>>> c2 = cell()
>>> c2.name = 'bar'
>>> c1.next = pointer(c2)
>>> c2.next = pointer(c1)
>>> p = c1
>>> for i in range(8):
...     print p.name,
...     p = p.next[0]
... 
foo bar foo bar foo bar foo bar

This linked list is a classic example of something that needs a "forward declaration" of the cell type in C.

One other small point, from the docs:
Either the LoadLibrary() method of the dll loaders should be used, or you should load the library by creating an instance of CDLL by calling the constructor:

We used the second method before. To use the first with the example from the other day (here):

>>> import ctypes
>>> libadd = ctypes.cdll.LoadLibrary('add1.so')
>>> libadd.f1(2)
3
>>> libadd.f1(2,3)
3
>>> libadd.f1()
1858614497
>>> libadd.f1.argtypes = [ctypes.c_int]
>>> libadd.f1(2,3)
3
>>> libadd.f1()
Traceback (most recent call last):
File "", line 1, in 
TypeError: this function takes at least 1 argument (0 given)
>>> 

You can get some error checking with the argtypes call, but not everything.

A developer of Cython gave a nice summary of why you might want to start with that in the SO post cited the other day. But for my small purposes, I think ctypes will probably be everything I'll need.

Note to self: .pth

I think I finally got .pth files sorted out. I first ran into this with easy_install (here). The Python library docs are here.

A path configuration file is a file whose name has the form package.pth and exists in one of the four directories mentioned above; its contents are additional items (one per line) to be added to sys.path. Non-existing items are never added to sys.path, but no check is made that the item refers to a directory (rather than a file). No item is added to sys.path more than once. Blank lines and lines beginning with # are skipped. Lines starting with import (followed by space or tab) are executed.

The four directories are:

sys.prefix + lib/site-packages
sys.prefix + lib/site-python
sys.exec_prefix + lib/site-packages
sys.exec_prefix + lib/site-python


So, not all directories on the path are searched for .pth files. I made a nested directory:

/Users/telliott/Desktop/temp/x

and put a .pth file in site-packages:

> cat /Library/Python/2.6/site-packages/x.pth
/Users/telliott/Desktop/temp/x

To test it:

> python -c 'import sys;  L = [p for p in sys.path if "Desk" in p];  print "\n".join(L)'
/Users/telliott/Desktop/temp/x



Of course, I could have just added a path to PYTHONPATH in ~/.bash_profile:

export PYTHONPATH=$PYTHONPATH:$HOME/Desktop/temp



> python -c 'import sys;  L = [p for p in sys.path if "Desk" in p];  print "\n".join(L)'
/Users/telliott/Desktop/temp
/Users/telliott/Desktop/temp/x

You need to restart Terminal to see the effect of changes to PYTHONPATH.


It's worth emphasizing (as pointed out in the quote) that .pth files can contain code. Here is easy_install.pth:

> cat /Library/Python/2.6/site-packages/easy-install.pth
import sys; sys.__plen = len(sys.path)
./Sphinx-0.6.3-py2.6.egg
./docutils-0.6-py2.6.egg
./Jinja2-2.2.1-py2.6.egg
./Pygments-1.1.1-py2.6.egg
./rpy2-2.1.7_20101104-py2.6-macosx-10.6-universal.egg
./numpy-1.5.0-py2.6-macosx-10.6-universal.egg
./Cython-0.14-py2.6-macosx-10.6-universal.egg
./PIL-1.1.7-py2.6-macosx-10.6-universal.egg
import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys,'__egginsert',0); sys.path[p:p]=new; sys.__egginsert = p+len(new)

It seems roundabout, but easy_install.pth is first adding these paths to sys.path, and then moving them to the position in the path specified by sys.__egginsert.

Thursday, August 4, 2011

SciPy on Lion (1)

I was looking for new things to do today, and realized I haven't really done much with SciPy. Their page about installing it is here. It seems like the developers are tired of dealing with people who can't get it installed and recommend that you download a binary or at least, install the Python.org version of Python first.

Apple ships its own version of Python with OS X. However, we strongly recommend installing the official Python distribution.


Of course, I wasn't gonna do that. There are other recommendations: that you really ought to get readline (somehow better than what comes with OS X), that you should get and use gcc-4.0 (only gcc-4.2 on Lion that I could find), that you should set LDFLAGS and FFLAGS and so on. I ignored it all.


> svn co http://svn.scipy.org/svn/scipy/trunk scipy
> cd scipy
> python setup.py build


The build fails with


unable to execute swig: No such file or directory



> brew install swig
Error: No available formula for swig


SWIG installation (download here) was a bit of a hiccup:


configure: error: in `/Users/telliott/Desktop/swig-2.0.4':
configure: error:
Cannot find pcre-config script from PCRE (Perl Compatible Regular Expressions)
library package. This dependency is needed for configure to complete,
Either:
- Install the PCRE developer package on your system (preferred approach).
- Download the PCRE source tarball, build and install on your system
as you would for any package built from source distribution.
- Use the Tools/pcre-build.sh script to build PCRE just for SWIG to statically
link against. Run 'Tools/pcre-build.sh --help' for instructions.
(quite easy and does not require privileges to install PCRE on your system)
- Use configure --without-pcre to disable regular expressions support in SWIG
(not recommended).

./configure --without-pcre
make
sudo make install


Back to SciPy and python setup.py build and problems as described here. I'm not too swift with this svn/git stuff so rather than find the patched version I just patched the files:

add #include <complex.h> to each of:


scipy/linalg/src/fblaswrap_veclib_c.c
scipy/lib/blas/fblaswrap_veclib_c.c.src
scipy/sparse/linalg/eigen/arpack/ARPACK/FWRAPPERS/veclib_cabi_c.c


And it seems to have built:


> python
Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from scipy import *
>>>

I'll look into to testing it tomorrow.

Exploring ctypes (4)

Introducing the subject of ctypes, I want to point you to a neat example from Andrew Dalke (second half of post here) that is a little beyond me, in many respects. But I wanted to give a shout out, and also say that I got it to run with a minor tweak.

• in the example file integrators.c, it should read
double integrate_gq(probe_func_t f) {
..
double integrate_rectangle(probe_func_t f) {

• the sym link for the built library should be (on 10.7):
ln -s build/lib.macosx-10.7-intel-2.7/integrators.so

And here is the output I got running his examples by cut and paste. First the build:


> python setup.py build
running build
running build_ext
building 'integrators' extension
llvm-gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch i386 -arch x86_64 -pipe -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c integrators.c -o build/temp.macosx-10.7-intel-2.7/integrators.o
creating build/lib.macosx-10.7-intel-2.7
llvm-gcc-4.2 -Wl,-F. -bundle -undefined dynamic_lookup -Wl,-F. -arch i386 -arch x86_64 build/temp.macosx-10.7-intel-2.7/integrators.o -o build/lib.macosx-10.7-intel-2.7/integrators.so


And the exploration in Python. We load the library:


> python
Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import ctypes
>>> ctypes.CDLL("integrators.so")
<h;CDLL 'integrators.so', handle 7fceb0483980 at 1056d9a90>


We fail to get our C integrator function to accept the Python-defined "probe" function as argument:


>>> integrators = _
>>> integrators.integrate_rectangle
<_FuncPtr object at 0x105759050>
>>> def flat_probe(x):
... return 1.0
...
>>> integrators.integrate_rectangle(flat_probe)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ctypes.ArgumentError: argument 1: <type 'exceptions.TypeError'>: Don't know how to convert parameter 1


[ About _ in Python: here and here ]

A simple cytypes.CFUNCTYPE definition does the trick:


>>> PROBE_FUNC = ctypes.CFUNCTYPE(ctypes.c_double, ctypes.c_double)
>>>
>>> integrators.integrate_rectangle.argtypes = [PROBE_FUNC]
>>> integrators.integrate_rectangle.restype = ctypes.c_double
>>> integrators.integrate_rectangle(PROBE_FUNC(flat_probe))
2.0
>>> integrators.integrate_gq.argtypes=[PROBE_FUNC]
>>> integrators.integrate_gq.restype = ctypes.c_double
>>> integrators.integrate_gq(PROBE_FUNC(flat_probe))
2.0


And the original example


>>> import math
>>> def probe_function(x):
... return math.cos(x)*(x+1)
...
>>> integrators.integrate_gq(PROBE_FUNC(probe_function))
1.6829416883812192
>>> integrators.integrate_rectangle(PROBE_FUNC(probe_function))
1.7006012905844656
>>>


Where I'm going:

• ctypes library documentation
• learn more about distutils

Getting that build from these four lines is simply amazing:

setup.py

from distutils.core import setup, Extension

setup(name="integrators", version="0.0",
ext_modules = [Extension("integrators", ["integrators.c"])])


And for reference, in case the page ever goes away here are his code listings:

integrators.h

#ifndef DALKE_INTEGRATORS_H
#define DALKE_INTEGRATORS_H

/* Two simple numerical integrators */

typedef double (*probe_func_t)(double);

double integrate_gq(probe_func_t f);
double integrate_rectangle(probe_func_t f);

#endif


integrators.c

/* Two numerical integrators */
#include "integrators.h"

/* 4 point Gaussian quadrature integration */
double integrate_gq(probe_func_t f) {
return
0.652145155*(f(+0.339981044) + f(-0.339981044)) +
0.347854845*(f(+0.861136312) + f(-0.861136312));
}

/* 4 point rectangle rule */
double integrate_rectangle(probe_func_t f) {
return (f(-0.75)+f(-0.25)+f(0.25)+f(0.75))/2;
}

Exploring ctypes (3)

Continuing with ctypes---here is an example of scoring a genome for potential sites for a DNA-binding protein according to the methods we talked about here.

We have a single function in a C module that will be compiled into a shared dynamic library. Then we load that library from Python, using ctypes, and call the function. The heavy lifting is done by the function score. The arguments are:

• the DNA sequence as a string (a str on the Python side)
• an array of floats which holds the scoring table
(in order acgt for each position in the site)
• the length of the site (n = 2 in the example)
• an array to hold the result for each position in the sequence

other variables:

• loop counters / index variables i, j, k
• the current character, c, so we can print it
• the current score for this char, d, also so we can print it
• the current score for this position in the sequence, r

The logic is straightforward and elementary. (Although perhaps there are faster approaches that people might suggest?)

mylib.c

#include <stdio.h>
#include <string.h>

void score(const char* dna, double p[], int n, double result[]) {
char c;
int i,j,k,N;
double d,r;

N = strlen(dna)-n+1;
for (i=0; i<N; i++){
r = 0;
for (j=0; j<n; j++){
c = dna[i+j];
switch (c) {
case 'a': { k=0; break; }
case 'c': { k=1; break; }
case 'g': { k=2; break; }
case 't': { k=3; break; }
}
printf("%c ", c);
d = p[j*4 + k];
printf("%3.3f ",d);
r += d;
}
printf("%3.3f\n", r);
result[i] = r;
}
}

We build the shared library using clang (or gcc, a quick test showed no speed difference):

clang -g -Wall -c mylib.c
clang -dynamiclib -current_version 1.0 mylib.o -o mylib.dylib

The Python script is a little more unusual. The array initialization was just adapted from the docs (here), I don't yet understand how it works. (It seems like a pointer would be better).

Here is the second of those:

NFloats = ctypes.c_double * N
result = [0.0] * N
result = NFloats(*result)

And I was surprised that we don't have to worry about the types for arguments to our score function---that's why those lines are commented out at the top.

For this toy example, the DNA sequence is 14 nt, and the scoring table is given in the list L. Here is the script:

script.py

import ctypes
pre = '/Users/telliott/Desktop'
mylib = ctypes.CDLL(pre + '/mylib.dylib', ctypes.RTLD_GLOBAL)
#mylib.score.argtypes = [ctypes.c_char_p]
#ctypes.c_float_p,
#ctypes.c_int]

dna = 'actgtcgactcgag'
L = [ 0.567, -1.603, -0.2245, 0.3605,
-0.1175, -0.4655, -0.5326, 0.6898 ]

EightFloats = ctypes.c_double * len(L)
ff = EightFloats(*L)
n = int(len(L)/4)
N = len(dna) - n + 1

NFloats = ctypes.c_double * N
result = [0.0] * N
result = NFloats(*result)

mylib.score(dna, ff, n, result)
for f in result[:6]: print round(f,3)

Here's the output. Each position is evaluated on a separate line. The last six values printed are the results received back in Python.

> python script.py
a 0.567 c -0.466 0.101
c -1.603 t 0.690 -0.913
t 0.360 g -0.533 -0.172
g -0.225 t 0.690 0.465
t 0.360 c -0.466 -0.105
c -1.603 g -0.533 -2.136
g -0.225 a -0.117 -0.342
a 0.567 c -0.466 0.101
c -1.603 t 0.690 -0.913
t 0.360 c -0.466 -0.105
c -1.603 g -0.533 -2.136
g -0.225 a -0.117 -0.342
a 0.567 g -0.533 0.034
0.101
-0.913
-0.172
0.465
-0.105
-2.136

Not bad for 50 lines of code and a little more than an hour of work! If you want to see it go fast, comment out the printf statements in the C code, and change:

dna = 'actgtcgactcgag'*400000

Now the DNA length is 5.6E6, and it finishes in about 5 seconds. It's impressive.

Wednesday, August 3, 2011

Exploring ctypes (2)

I used an example from before (here) to make a dylib and then called the functions using ctypes. It seems very easy:

add1.c

int f1(int x) { return x + 1; }


add2.c

int f2(int x) { return x + 2; }



> gcc -g -Wall -c add*.c
> gcc -dynamiclib -current_version 1.0 add*.o -o libadd.dylib
> file libadd.dylib
libadd.dylib: Mach-O 64-bit dynamically linked shared library x86_64



> python
Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import ctypes
>>> pre = '/Users/telliott/Desktop'
>>> libadd = ctypes.CDLL(pre + '/libadd.dylib', ctypes.RTLD_GLOBAL)
>>> x = libadd.f1(1)
>>> x
2
>>> y = libadd.f2(x)
>>> y
4
>>>


I guess one question is how to alter / determine the search path for ctypes in loading libraries. libc is in /usr/lib, but libpng is in /usr/X11/lib, as we discussed the other day (here):


>>> libc = ctypes.CDLL('libc.dylib', ctypes.RTLD_GLOBAL)
>>> libpng = ctypes.CDLL('libpng.dylib', ctypes.RTLD_GLOBAL)
Traceback (most recent call last):
File "", line 1, in
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 353, in __init__
self._handle = _dlopen(self._name, mode)
OSError: dlopen(libpng.dylib, 10): image not found
>>> pre = '/usr/X11/lib/'
>>> libpng = ctypes.CDLL(pre + 'libpng.dylib', ctypes.RTLD_GLOBAL)
>>>



>>> import ctypes.util
>>> ctypes.util.find_library('libpng.dylib')
>>> ctypes.util.find_library('png')
>>> ctypes.util.find_library('AGL')
'/System/Library/Frameworks/AGL.framework/AGL'


Obviously, find_library doesn't search /usr/X11/lib. Wonder if there is a way to tell it what we want?

After we look at Andrew's more sophisticated examples, we'll try something relevant to bioinformatics

Exploring ctypes (1)

A perennial question in Python is what to do when Python isn't fast enough, and a related one is how to work with C libraries from Python. As discussed in this SO post, there are several possibilities, here I want to start working with ctypes.

This is now a Python built-in module. I was a bit put off when I looked at the official docs, since all the early examples are windows and there is almost no mention of OS X. (However, I will have to make sure I understand what's there later), I'd start instead with Andrew Dalke's quick tutorial (here). So the first part of this is my code duplicating a few of his examples.

Getting started is literally one line, preceded by the import, and followed by the function call itself. That's wonderful!


>>> import ctypes
>>> libc = ctypes.CDLL("libc.dylib", ctypes.RTLD_GLOBAL)
>>> print libc.strlen("Hello world!")
12
>>>


It's pretty self-explanatory, if you're at all familiar with C, except for the constant RTLD_GLOBAL. Under the hood, the library libc uses the functions dlopen and friends defined in clfcn.h. (We touched on these once before, in the last example of this post).

The prototype for the C call to load a library is:

void *dlopen(const char *file, int mode);

RTLD_GLOBAL is one of several enumerated modes, and the value we provide is passed in as an argument to dlopen. You can read about dlopen here.

Here is printf:


>>> libc.printf("the number %d and string %s\n", 10, 'spam')
the number 10 and string spam
30


I'm not sure why this works, because in the standard C library, printf is in libstdio (ref)

The function printf returns the number of characters printed, or a negative value to indicate an error. The next example introduces the idea that frequently we need to tell ctypes the type of input arguments or return values.


>>> libc.atoi('3')
3
>>> libc.atof('3.14')
3
>>> libc.atof.restype = ctypes.c_double
>>> libc.atof('3.14')
3.14


The assumed return type is int, and in order to get this example to work we have to specify that the returned value is a double. Here's the prototype:

double atof (const char *str);

Argument types are specified like this:


>>> libc.atan2.argtypes = [ctypes.c_double, ctypes.c_double]
>>> libc.atan2.restype = ctypes.c_double
>>> libc.atan2(3.0, 4.0)
0.6435011087932844
>>> import math
>>> math.atan2(3.0, 4.0)
0.6435011087932844


Finally, here's another function, this one from the math library:


>>> libmath = ctypes.CDLL("libm.dylib", ctypes.RTLD_GLOBAL)
>>> libmath.sqrt.restype = ctypes.c_double
>>> libmath.sqrt(2)
nan
>>> libmath.sqrt(2.0)
Traceback (most recent call last):
File "", line 1, in
ctypes.ArgumentError: argument 1: : Don't know how to convert parameter 1
>>>
>>> libmath.sqrt.argtypes = [ctypes.c_double]
>>> libmath.sqrt(2)
1.4142135623730951


And here is a glowing testimonial about controlling a camera via USB with code written in Python.

It'd be interesting to see what we could do on that in OS X.

Still to do:

• finish Andrew's tutorial (lots more there)
• read the official docs
• try to apply it to the problem of finding binding sites (here)

e again

I came across a neat quote from Martin Gardner:

The number e is as ubiquitous as pi, turning up everywhere, and especially in probability theory. If you randomly select real numbers between 0 and 1, and continue until their sum exceeds 1, the expected number of choices is e.


-Martin Gardner
note in Calculus Made Easy, p. 153

Of course, this begs for a Python simulation:

import random

def mean(L):
return float(sum(L))/len(L)

def oneTrial():
counter = 1
f = random.random()
while f <= 1:
counter +=1
f += random.random()
return counter

N = int(1E7)
L = [oneTrial() for i in range(N)]
print mean(L)



> python script.py 
2.7183671

A derivation would be nice, but that'll have to wait. I wonder about the variance.

pkg-config

A reasonably brief post about pkg-config, which we used to help build matplotlib the other day (here).

The web page is here and there is a guide here.

As it says on the first page:

pkg-config is a helper tool used when compiling applications and libraries. It helps you insert the correct compiler options on the command line so an application can use gcc -o test test.c `pkg-config --libs --cflags glib-2.0` for instance, rather than hard-coding values on where to find glib (or other libraries). It is language-agnostic, so it can be used for defining the location of documentation tools, for instance.

And from the man page:


DESCRIPTION
The pkg-config program is used to retrieve
information about installed libraries in the
system. It is typically used to compile and
link against one or more libraries. Here is a
typical usage scenario in a Makefile:

program: program.c
cc program.c $(pkg-config --cflags --libs gnomeui)

pkg-config retrieves information about pack-
ages from special metadata files. These files
are named after the package, and has a .pc
extension. On most systems, pkg-config looks
in and
for these files. It will additionally look
in the colon-separated (on Windows, semicolon-
separated) list of directories specified by
the PKG_CONFIG_PATH environment variable.

The package name specified on the pkg-config
command line is defined to be the name of the
metadata file, minus the .pc extension. If a
library can install multiple versions simulta-
neously, it must give each version its own
name (for example, GTK 1.2 might have the
package name "gtk+" while GTK 2.0 has
"gtk+-2.0").


What's happening is that the matplotlib setup.py script uses pkg-config if it's present. The binary is in /usr/local/bin/pkg-config. It looks for a subdirectory of /usr/X11/lib (and /usr/local/lib) called pkgconfig that constains .pc files for packages that specify metadata about themselves to take advantage of pkgconfig functionality:


> cat /usr/X11/lib/pkgconfig/libpng.pc
prefix=/usr/X11
exec_prefix=${prefix}
libdir=${exec_prefix}/lib
includedir=${prefix}/include/libpng12

Name: libpng
Description: Loads and saves PNG files
Version: 1.2.44
Libs: -L${libdir} -lpng12
Libs.private: -lz
Cflags: -I${includedir}





We used Homebrew only to grab pkg-config. You could get it yourself: 0.26 is the newest, but requires glib-2.0; 0.25 bundles glib with pkg-config. 0.25 builds with no dependencies using the standard ./configure; make; make install. Download page for version 0.25 and 0.26 is here. Or of course, you can use Homebrew like we did.

Not clear why it doesn't ship with OS X. The license is GPLv2. But then, so is BASH.

Some minor issues:

• when I tried using pkg-config on my iMac (Snow Leopard, littered with MacPorts and other stuff), matplotlib seemed to build and install but died with:


> python x.py
Traceback (most recent call last):
File "x.py", line 1, in
import matplotlib.pyplot as plt
File "/Library/Python/2.6/site-packages/matplotlib/pyplot.py", line 95, in
new_figure_manager, draw_if_interactive, _show = pylab_setup()
File "/Library/Python/2.6/site-packages/matplotlib/backends/__init__.py", line 25, in pylab_setup
globals(),locals(),[backend_name])
File "/Library/Python/2.6/site-packages/matplotlib/backends/backend_macosx.py", line 243, in
class TimerMac(_macosx.Timer, TimerBase):
AttributeError: 'module' object has no attribute 'Timer'


For reasons that I don't understand, the version of the file in the build directory


/Users/telliott/Software/matplotlib-1.0.1/build/lib.macosx-10.6-universal-2.6/matplotlib/backends/backend_macosx.py


is not the same as the one in site-packages


/Library/Python/2.6/site-packages/matplotlib/backends/backend_macosx.py


Simply replacing the site-packages version fixed the problem:


> sudo cp /Users/telliott/Software/matplotlib-1.0.1/build/lib.macosx-10.6-universal-2.6/matplotlib/backends/backend_macosx.py /Library/Python/2.6/site-packages/matplotlib/backends/backend_macosx.py
> python -c "import matplotlib.pyplot as plt"
>


• the Homebrew "Formula" in /usr/local/Library/Formula/pkg-config.rb tells the installed pkg-config which paths to search for lib.pc files:


        /usr/local/lib/pkgconfig
/usr/lib/pkgconfig
/usr/X11/lib/pkgconfig


I'm not quite sure how that would work for a manual install.

• the libpng in /usr/local/lib that I installed shadowed the one in /usr/X11/lib so to use the X11 version, I removed the files from /usr/local

• The notation libpng.pcfileLibs.private: -lz indicates that libpng does depend on zlib, but it's already been linked against it (hence private). I'm not sure where it is, though.

Sunday, July 31, 2011

matplotlib on OS X Lion--revised

In the previous post, I repeated an installation of matplotlib (now for OS X Lion) following the same method that I've linked to a number of times on the blog. It worked this time as well, but lead me to consideration of other possible methods. I found one on the web here. So that's what this post is about.

BTW, whatever you do, do not follow the instructions that the matplotlib developers provide. You do not need another Python, including MacPython or the Endthought distribution or anything else..

To recap, matplotlib lists dependencies (in the make.osx file) of: libpng, libfreetype, and zlib. I read somewhere on the matplotlib site today (but can't find the link now) that zlib is not a required dependency. These days, the other two are actually provided by Apple:


> ls -al /usr/X11/lib/libpng*
-rwxr-xr-x 1 root wheel 296864 Jul 29 16:11 /usr/X11/lib/libpng.3.dylib
lrwxr-xr-x 1 root wheel 14 Jul 29 16:11 /usr/X11/lib/libpng.dylib -> libpng15.dylib
-rwxr-xr-x 1 root wheel 294160 Jul 29 16:11 /usr/X11/lib/libpng12.0.dylib
-rwxr-xr-x 1 root wheel 305008 Jul 29 16:11 /usr/X11/lib/libpng15.15.dylib
lrwxr-xr-x 1 root wheel 17 Jul 29 16:11 /usr/X11/lib/libpng15.dylib -> libpng15.15.dylib

> ls -al /usr/X11/lib/libfreetype*
-rwxr-xr-x 1 root wheel 1060416 Jul 29 16:11 /usr/X11/lib/libfreetype.6.dylib
lrwxr-xr-x 1 root wheel 19 Jul 29 16:11 /usr/X11/lib/libfreetype.dylib -> libfreetype.6.dylib


I'm not sure at the moment whether X11 came with Xcode (as it used to) or was present in the original Lion install.

In any case, I spent an hour or two trying to figure out how to use the build commands from the makefile that comes with matplotlib, but point at these libraries. In the process I found what appears to be a bug:


/usr/X11/include/png.h:666: error: forward declaration of ‘struct png_info_def’


(and see Prashant's answer here), but we're going to use a different approach so it doesn't matter. I'm not sure how our method solved this in the end. As mentioned, the approach is to use Homebrew, in particular, something called pkgconfig. I used a Ruby script that downloads and installs Homebrew, as described here. The install gave this warning:


Warning: The following *evil* dylibs exist in /usr/local/lib
They may break builds or worse. You should consider deleting them:
/usr/local/lib/libfreetype.6.dylib
/usr/local/lib/libpng.3.dylib
/usr/local/lib/libpng12.0.dylib
/usr/local/lib/libz.1.2.5.dylib


These are, of course, the libraries we just installed in order to get matplotlib to build.

That's what got me working on the other method more seriously. I don't think the danger is all that great, but clearly it is better to use libraries that are (i) still available from the maintainers and (ii) have been vetted at least to some extent by other folks including Apple. AFAIK there aren't any known security issues with the versions we installed previously. I ripped them out anyway (they seemed to confuse pkgconfig).

If we ask Homebrew for the libraries, it just points us to the ones we saw in /usr/X11:


> brew search libpng
Apple distributes libpng with OS X, you can find it in /usr/X11/lib.
However not all build scripts look here, so you may need to call ENV.x11
in your formula's install function.

> brew search freetype
Apple distributes freetype with OS X, you can find it in /usr/X11/lib.
However not all build scripts look here, so you may need to call ENV.x11
in your formula's install function.


Following the instructions in the blog post I first installed pkgconfig:


> sudo brew install pkgconfig
Cowardly refusing to `sudo brew'
> brew install pkgconfig

!!

That's all the Homebrew we need. This is followed by:


cd ~/Desktop
git clone git://github.com/matplotlib/matplotlib.git
cd matplotlib/
python setup.py build
sudo python setup.py install


And we can see that I really did overwrite the first matplotlib install, and that we're actually using the libraries from /usr/X11, by first doing


export DYLD_PRINT_LIBRARIES=1


Then when we run a script that imports matplotlib.pyplot, the Terminal shows (among much else) this:


dyld: loaded: /usr/X11/lib/libfreetype.6.dylib
..
dyld: loaded: /usr/X11/lib/libpng15.15.dylib


So that's what I'd recommend and it seems to be working fine. This simple script works exactly as you'd expect.


import matplotlib.pyplot as plt
Y = [1,4,9,16]
plt.scatter(range(len(Y)),Y,s=250,color='r')
plt.savefig('example.png')


So the next thing to do is to figure out pkgconfig and Homebrew work their magic!

P.S. You will still need to make and edit ~/.matplotlibas discussed last time.

matplotlib on OS X Lion--old

[ UPDATE: I'm going to leave this post up, for the record, but I found a better way, and that's in the following post. ]

Just a note to say that I got matplotlib installed with only a few issues to solve. As before, I relied on Gavin Huttley's instructions (here). Although the matplotlib instructions say you should install a different Python, I've found that just leads to confusion down the road, and I want to try to use the system version only if I can get away with it. YMMV.

The sticking points for the install always have to do with the basic dependencies, which are listed at the top of the file make.osx in the matplotlib source (from here). The source is the last link at the bottom.


ZLIBVERSION=1.2.3
PNGVERSION=1.2.39
FREETYPEVERSION=2.3.11

As silly as it seems, although OS X provides excellent functionality for dealing with compression, png images and fonts, we need to install these libraries for matplotlib to use. Unfortunately, I'm not expert enough to alter matplotlib to get rid of these dependencies, so we're stuck with it.



libpng

I got libpng-1.2.39 from here. I used this version b/c that's what matplotlib asks for, despite the fact that the current release is 1.5.4 (here). Standard magic incantations:


./configure
make
sudo make install




freetype


curl -O http://ftp.twaren.net/Unix/NonGNU/freetype/freetype-2.3.7.tar.bz2


According to Gavin's notes, we need these compiler flags for the other two (but they interfere with the libpng build):


export MACOSX_DEPLOYMENT_TARGET=10.7
export CFLAGS="-arch i386 -arch x86_64"
export FFLAGS="-arch i386 -arch x86_64"

./configure
make
sudo make install




zlib

zlib is a compression library. The current version is 1.2.5. I tried this:


curl -O http://www.zlib.net/zlib-1.2.3.tar.gz


but as I've seen before, although you get a (small) file back that has the right icon, it is really a 404 Page Not Found, which doesn't do me any good. It seems the older versions have been disappeared off the web and I couldn't find them poking around on the site. What I should've done at this point is try the version they do offer, but instead I went to my other machine and grabbed 1.2.3. I guess that since I'd used it before to build zlib, I found I needed to clean it first:


make clean
make
sudo make install




matplotlib

Finally, I got the matplotlib source. I altered the file make.osx:


PREFIX=/usr/local
PYVERSION=2.7
PYTHON=python${PYVERSION}
ZLIBVERSION=1.2.3
PNGVERSION=1.2.39
FREETYPEVERSION=2.3.7
MACOSX_DEPLOYMENT_TARGET=10.7
OSX_SDK_VER=10.7
ARCH_FLAGS="-arch i386-arch x86_64"



make -f make.osx mpl_build
sudo python setup.py install



mkdir ~/.matplotlib
cp matplotlibrc.template ~/.matplotlib/matplotlibrc


Edit the above file to have:


backend      : MacOSX



> python
Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from matplotlib import *
>>>


Yes!

[ UPDATE: I see I used freetype 2.3.7 rather than 2.3.11, by mistake.

And if you don't like my approach, you could use Homebrew and follow this post. I don't have any experience with this yet. ]

Saturday, July 30, 2011

OS X Lion

OS X Lion has been released for a week now, so I thought I'd try it out on one of my machines. A definitive review is here. I'll be too busy to really play with it for a while, or to do much programming, but I thought I should at least try. An additional motivation is that my laptop (an aluminum MacBook from about December 08), had developed an issue. It completely drains the battery (starting from full charge) in sleep mode, even when no apps are running. The battery hasn't been particularly stressed:

Health Information:
Cycle Count: 568
Condition: Normal
Battery Installed: Yes
Amperage (mA): 0
Voltage (mV): 12546

And, it doesn't drain when powered off. This problem appeared recently, and I am interested to see if installing Lion might fix it, but that hasn't been tested yet. I'll update when I have those results.

This post is just to document that I got Lion onto a USB flash drive and used it to do the install and it worked fine. Instructions from here. I did this because it's the only way to do a clean install. One odd thing: if the machine on which you are attempting to do the download can't run Lion, you won't be allowed to do the download at all! I had to bring my laptop to work (and get the IT guys to reauthorize it for our network).

Also, I have two Apple IDs---an old one and one that goes with my MobileMe account. When I set up Mail, the ID for the computer was automatically set to be the latter, but I originally did the Lion download with the former. We'll see if and when that causes a problem.

It seems clear that the Mac OS will (in time) become more iOS-like (locked down, user not allowed to risk hurting himself, even if he wants to) and less easy to hack around with. But for now, it's still a win over Linux, for me.

Python is 2.7:



> python
Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.


The default scrolling is like that on the iPhone---as if you're moving the content, rather than a scrollbar. After 2 or 3 hours, I changed the setting back to the old method. Maybe I will try to retrain my brain at a later date.

I also downloaded Xcode 4. It quit in the middle for no reason, but completed on the second try. Weirdly, in the middle of the install I got this alert panel:



I say "weirdly" because iTunes is not running. Starting and quitting iTunes had no effect, either. Finally I went in Terminal and looked for an iTunes-related process:


  163 ??         0:00.03 /Applications/iTunes.app/Contents/MacOS/iTunesHelper.app/Contents/MacOS/iTunesHelper -psn_0_57358


after I killed it, the install finished fine. There is a mention in the big Ars Technica review that apps don't actually quit (or perhaps not always), and may not show the little dot for an active app, but there was no process for iTunes so I don't think so. It's weird that a bug like that should still be present at this stage of the game.

And I like the new looks in Terminal:



[ UPDATE: Yep, the battery does not drain on sleep anymore. (Well, 2% in 2 hr). That's the good news. The bad news is that the extension I had to help autofill passwords when forms contain autocomplete="off" doesn't work with Safari any more (post here, extension here). I sure hope Apple didn't do that on purpose. ]

UPDATE 2: I just needed to check to the right box in the Prefs.


Friday, July 15, 2011

Verification

I posted two derivations for Euler's famous equation (here and here):

eix = cos x + i sin x

This can be verified in a particularly simple way.
The series representation of the exponential function:

ex =  1 +  x + x2/2! +  x3/3! + x4/4! + ..

is especially neat because each term in the series is the derivative of the term following, and the result of that is:

d/dx ex = ex

Which is, indeed, one definition of this function.
Substitution of ix leads to a simple shift in the pattern:

eix = 1 + ix - x2/2! - ix3/3! + x4/4! + ..

repeating with a period of 4. Powers of x like:

4n + 1 are multiplied by  i
4n + 2 -1
4n + 3 -i
4n 1

But remembering the series for sine and cosine, and multiplying the former by i:

  sin x =  x -  x3/3! + x5/5! - x7/7! + ..
i sin x = ix - ix3/3! + ..
cos x = 1 - x2/2! + x4/4! - x6/6! + ..

Adding:

cos x + i sin x = 1 + ix - x2/2! - ix3/3!+ x4/4! + ..
= eix

Thursday, July 14, 2011

Note on trig substitution

A fact we needed in a recent post deriving Euler's formula is the value of a particular integral:

∫ dx / √(x2 + 1) = ln (x + √(x2 + 1))

This gave me a lot more trouble than expected, so I thought I'd work through it here for reference. The easiest way is to differentiate the answer. Let:

u = x + √(x2 + 1)
du = [1 + 2x / 2 √(x2 + 1)] dx
= [1 + x / √(x2 + 1)] dx

y = ln(u)
dy = 1/u du = [1 / (x + √(x2 + 1)) ] [ 1 + x / (√(x2 + 1)] dx


The trick is to notice that when we find the common denominator for the part at the far right and then add the terms, we generate the denominator of the part to the left.

dy = [1 / (x + √(x2 + 1) ] [ (√(x2 + 1) + x) / (√(x2 + 1)] dx
= 1 / (√(x2 + 1)

The integrand is normally written more generally as:

∫ 1 / √(x2 + a2)

and that doesn't change anything.

The forward version starts with a trigonometric substitution.


x = a tan y
y = tan-1 (x/a)

Remembering that

(u/v)' = (vu' - uv')/v2
tan' = (cos2 + sin2)/cos2 = 1/cos2 = sec2

So

dx = a sec2 y dy

The other part of the integral is:

1 / √(x2 + a2)

x = a tan y
x2 = a2 tan2 y
x2 + a2 = a2 tan2 y + a2
= a2 ( 1 + tan2 y)

If we start with the standard identity:

sin2 y + cos2 y = 1

and divide by cos2 y:

tan2 y + 1 = sec2 y
x2 = a2 ( 1 + tan2 y) = a2 sec2 y

Thus the integral reduces to:

∫ (a sec2 y) / (a sec y)  dy = ∫ sec y dy

This small integral is itself a bit tricky. The answer, which I found on a really nice site (here), is to multiply top and bottom by:

       sec y + tan y
sec y -------------
sec y + tan y

Let u = sec y + tan y

If you work through it you'll see that

du = (sec y tan y + sec2 y) dy

Thus, this is

∫ du/u = ln(u) = ln (sec y + tan y) 
= ln [ ((√(x2 + a2) + x ) / a ]

As I said, not so easy as other trig substitutions.

Euler's Gem 2

Here is a sketch of a second derivation of Euler's famous formula:

eiθ = cosθ + i sinθ

as presented by William Dunham in his book Euler, The Master of Us All. First post here.

The first step is to recall a standard trigonometric substitution in calculus:


y = sin x
x = sin-1 y

√(1 - y2) = cos x

We're interested in the integral:

∫ dy / √(1 - y2)

Substituting with x we see that:

dy = cos x dx

And the integral is

∫ (1/cos x) cos x dx = ∫ dx = x
x = ∫ dy / √(1 - y2)

Now Euler makes a complex change of variable:

y = iz
x = ∫ dy / √(1 - y2)
= ∫ i dz / √(1-(iz)2)
= i ∫ dz / √(1 + z2)
= i ln [√(1 + z2) + z]

The last step is another standard result from calculus which I will assume for the time being (more here).

Undo the substitution:

z = y/i = sin x / i
z2 = -sin2 x
√(1 + z2) = √(1 - sin2 x)
= cos x

x = i ln (cos x + sin x / i)

We will use two identities involving i:

u / i = - i u
1 / (cos u - i sin u) = (cos u + i sin u)

(For the second one, see the previous post). Now:

x = i ln (cos x + sin x / i)
x = i ln (cos x - i sin x)
ix = - ln (cos x - i sin x)
= ln [ 1 / (cos x - i sin x) ]
= ln (cos x + i sin x)

Just eponentiate:

eix = cos x + i sin x

Wow, again!

Wednesday, July 13, 2011

Euler's gem

Here is a sketch of the derivation of Euler's famous formula:

eiθ = cosθ + i sinθ

as presented by William Dunham in his book Euler, The Master of Us All.

The first part of the proof is similar to when we used Euler's formula to derive other formulas for trig functions of sums and differences of angles (post), only backward. Start from the definition of i:

i = √-1

To begin with, having i allows us to factor new expressions:

1 = cos2 s + sin2 s
= (cos s + i sin s)(cos s - i sin s)

(I'm going to use s and t, as before, rather than θ and φ).

This shows where the original idea of cos + i sin comes from. (Of course, we could just as well do sin + i cos, that would result in a different convention for the orientation of the complex plane).

Suppose we have two angles s and t, we can multiply and then use the formulas from before (obtained by the geometric proof):

(cos s + i sin s)(cos t + i sin t) =
= (cos s cos t - sin s sin t) + i(sin s cos t + cos s sin t)
= cos(s + t) + i sin(s + t)

Set s = t:

(cos s + i sin s)2 = cos(2s) + i sin(2s)

In fact Euler showed it works for fractional n but I'll assume that part:

[1] (cos s + i sin s)n = cos(ns) + i sin(ns)
n >= 1

If we multiply the difference rather than the sum:

(cos s - i sin s)(cos t - i sin t) =
= (cos s cos t - sin s sin t) - i (sin s cos t + cos s sin t)
= cos(s + t) - i sin(s + t)

Again, with s = t we have:

(cos s - i sin s)2 = cos(2s) - i sin(2s)
[2] (cos s - i sin s)n = cos(ns) - i sin(ns)

Adding [1] and [2] we have:

2 cos(ns) = (cos s + i sin s)n + (cos s - i sin s)n



The middle part of the proof is where the magic happens. Let:

s = x/n

As

n -> ∞
s -> 0
cos s -> 1
sin s -> s

So..

cos x = cos ns = 1/2 [(cos s + i sin s)n + (cos s - i sin s)n]
cos x = 1/2 [(1 + is)n + (1 - is)n]
cos x = 1/2 [(1 + ix/n)n + (1 - ix/n)n]

But..

eix = (1 + ix/n)n 
as n -> ∞

So

cos x = 1/2 [eix + e-ix]



By very similar manipulation to what's in the first part we can also handle the sine:

2i sin(ns) = (cos s + i sin s)n - (cos s - i sin s)n

We will obtain:

sin x = 1/(2i) [eix - e-ix]

Now it's just a matter of addition:

cos x + i sin x = 1/2 [eix + e-ix + eix - e-ix]
= 1/2 [eix + eix]
= eix

Wow!