Best of both worlds - Using python and fortran together

  1. What is f2py and why use it ?
  2. Python is by far one of the easiest languages I have learnt and I love to write python code. It is a very fast language with respect to the time taken to produce a useable/reliable peice of software. One of the lessons I learnt from my advisor and mentor, Dr. Ray Fertig, in graduate school was to first write my code in a language that was easy viz. python or matlab and then compare the results to some kind of hand calculation or trustworthy results produced by someone else. It is only after this initial task has been completed that we must dive into making our computer code efficient (assuming its taking hours to run) by writing it in a language like Fortran/C. But fortran was written for computations and really looses its advantages when it comes to creating user interfaces or reading/writing to files. This is where we should make use of python. Once you have used python for reading/writing to files or creating interfaces, you will never go back to any other language. I say this on a cool April night in 2017. This might have changed if you are reading decades later. This is where f2py comes into picture.

    What is f2py ?



  3. Hello World AGAIN !
  4. Lets write a subroutine for hello world in fortran (fixed form).

    c NAME OF THIS FILE - myCodes.f c ----------------------------- c This subroutine prints hello World c on the screen subroutine hwd() print*, 'Hello World !' end subroutine hwd

    Write this command in the terminal
    f2py -c myCodes.f -m myCodes
    If you do not get any compilation error, you will get a file called
    The module can be then used in python by following the steps
    Python 2.7.12 (default, Nov 19 2016, 06:48:10) 
    [GCC 5.4.0 20160609] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import myCodes # Importing module
    >>> myCodes.hwd()  # Calling the subroutine
    Hello World !      # Hello world gets printed on the screen
  5. Converting polar co-ordinates to rectangular co-ordinates
  6. c This subroutine converts polar co-ordinates to rectangular c coordinates. c Inputs : Polar coordinates R and Theta c Outputs : Rectangular coordinates X and Y subroutine pc2rc(r,theta,x,y) implicit none real r, theta, x, y intent(in) r, theta intent(out) x, y x = r*cos(theta) y = r*sin(theta) end subroutine pc2rc

    >>> import csys
    >>> csys.pc2rc(2,3)
    (-1.979984998703003, 0.282240003347396)