Me, blogging!

thoughts, science, code, jobs, and thoughts

f2py in action

Recently, I heavily made use of <code>f2py</code>—a tool that converts your FORTRAN code into a Python module. Here is how to use it:

$ f2py -c -m module_name fortran_code.f90

In the current directory there is now a shared object of your module To use it in Python, just do the usual import. A docstring is generated for you as well, so you know how to call the methods, i.e., FORTRAN subroutines or functions

import module_name as mymodule
print mymodule.__doc__

Let's suppose you've written a subroutine that does some calculations that are faster in FORTRAN than in Python

! fortran_code.f90
subroutine some_calulations(a,b,c)
  implicit none
  real, intent(in) :: a, b
  real, intent(out) :: c
  real :: some_result

  ! start some calculations
  c = some_result
end subroutine

To call that subroutine, our Python script has to look like this

import module_name as mymodule
print mymodule.__doc__

x1 = <some value>
x2 = <also some value>

result = mymodule.some_calculations(x1,x2)

That's it. Pretty easy, huh? Now you can use your fast code and let Python do the rest, like making a proper data analysis using numpy or scipy, or doing the graphics using matplotlib.

Tags: f2py, fortran, python, tools 2013/08/02

Ever longed for a simple way to type a mathematical expression in HTML just to realize there is no proper way for doing that? There is: MathJax (Thanks to JavaScript). All you have to do is to insert the following sniplet into the head of your html file.

<script type="text/javascript"

Here's an example of the Lorenz attractor (taken from the MathJax Demo page): \begin{align} \dot{x} &= \sigma(y-x) \\ \dot{y} &= \rho x - y - xz \\ \dot{z} &= -\beta z + xy \end{align}

The source:

\dot{x} &= \sigma(y-x) \\
\dot{y} &= \rho x - y - xz \\
\dot{z} &= -\beta z + xy

You probably have to escape the two backslash characters \\ (the newline command). Works also for inline expressions like this \(e^{\imath \pi} + 1 = 0\).

Tags: tools, latex 2012/10/18
About Mario Krapp
I'm a physicist by training and graduated in Earth System Science.

And I like coding. I've been working with complex computer models ever since my undergrad and I enjoy data exploration and data analysis to gain insights into the underlying principles.

Feel free to contact me.