How can I easily convert FORTRAN code to Python code (real code, not wrappers)

Peter Olsen picture Peter Olsen · Aug 14, 2013 · Viewed 22.3k times · Source

I have a numerical library in FORTRAN (I believe FORTRAN IV) and I want to convert it to Python code. I want real source code that I can import on any Python virtual machine --- Windows, MacOS-X, Linux, Android. I started to do this by hand, but there are about 1,000 routines in the library, so that's not a reasonable solution.

Answer

user1220978 picture user1220978 · Aug 14, 2013

edit: added information on numpy

Such a tool exists for Fortran to Lisp, or Fortran to C, or even Fortran to Java. But you will never have a Fortran to Python tool, for a simple reason: unlike Fortran, Lisp or C, Python does not have GOTO [1]. And there are many GOTOs in Fortran (especially Fortran IV) code. Even if there is a theorem by Jacopini stating that you can emulate GOTO with structured programming, it's far too cumbersome to implement a real (and efficient) language conversion tool.

So not only will you need to translate the code of 1000 routines, but you will also need to understand each algorithm, with all its imbricated gotos, and translate the algorithm into a structured program before writing it in Python. Good luck!

Hey, why do you think a wrapper is bad? Windows, OSX and Linux all have Fortran and C [2] compilers and good wrappers!

For C (not your language here, but f2c may be an option), there is SWIG, and Fortran has f2py, now integrated with numpy. SWIG has some support for Android.

By the way, instead of converting to "pure" Python, you can use numpy: numpy capabilities are similar to Fortran 90 (see a comparison here), so you may consider first translating your programs to F90 for a smoother transition. There seems to be also a Numpy on Adnroid. And in case you need numpy on 64-bit Windows, there are binaries here.

If you decide to use wrappers, gfortran runs on Linux (simply install from distribution packages), Windows (MinGW), and Android. If you go along that line, don't forget you compile FIV code, so there is the usual "one-trip loop" problem (usually a compiler option is fine). You will probably have also to manually convert some old, non standard statements, not found in modern compilers.

You have also, obviously, the option to switch your project language to Lisp or Java...

[1] You may ask: but if GOTO is the problem, how come there is a Fortran to Java tool? Well, it uses tricks with the JVM, which has internally the GOTO instruction. There is also a GOTO in Python bytecode (look for JUMP here), so there may be something to investigate here. So my previous statement is wrong: there may be a Fortran to Python tool, using bytecode tricks like in Java. But it remains to develop, and availability of good libraries (like numpy, matplotlib, pandas...) makes it unnecessary, to say the least.