Search code examples
pythonfortranfortran77

Converting Fortran 77 code to Python


I have looked at this Q/A Intent of this Fotran77 code and I have almost converted the below Fortran77 style code into Python 3.x except I had a doubt where the i = i + 1 should be placed in the Python version. As mentioned in the comments of the linked question I have done the conformance tests and the results are off by a margin of 2. Hence the question.

i = 0
500 continue
i = i +1
if (i .le. ni) then
  if (u(i,j-1) .gt. -9999.) then
     r(1,j) = u(i,j-1)
     go to 600
  else
    missing = i
    go to 500
  end if
 end if
600  continue

Here is my Python version

  i = 0
  while (i <= ni):
     i = i+1
     if (u[i,j-1] > -9999.0):
         r[0,j] = u[i,j-1]
         break
     else:
       missing = i

Did I place the increment counter at the right location ?


Solution

  • Directly translating is not advised because you loose a number of nice efficient coding features of python.

    To do this properly in python you should 1) recognize the 0- index convention of python, and 2 ) recognize that that fortran is column major and python is row major so you should reverse the index ordering for all multi-dimensional arrays.

    If you do that the loop can be written:

    try: 
     r[j,0]=[val for val in u[j] if val > -9999 ][0]
     missing=False
    except:
     missing=True
    

    I'm assuming we don't actually need the numeric value of missing. If you need it you will have something like this:

    try: 
     missing,r[j,0]=[(index,val) for (index,val) in enumerate(u[j]) if val > -9999 ][0]
    except:
     missing=-1 
    

    You could also use next which would be faster, but it gets a little trickier handling the missing condition.