0

how can I write this fortran code in python? I need to use this subroutine inside of my homework but I am writing my code in python.Any way to use it or change it?

# This subroutine calculates Energy and forces for Lennard-Jones clusters
#  input:   nat = no. of atoms, xyz = atomic Cartesian coordinates
#  output:  epot = energy, fxyz = forces on each atom  
#======================================================================== 

subroutine LJ EandF(nat,xyz,epot,fxyz)
implicit none
integer nat
real*8 xyz(3,nat),epot,fxyz(3,nat)
real*8 dx,dy,dz,r2
real*8 t2,t6,ff
real*8, parameter :: eps=1.d0
real*8, parameter :: sigma=1.d0 
real*8, parameter :: sigma2=sigma**2
integer iat, jat
do iat=1,nat-1
do jat=iat+1,nat
    dx=xyz(1,iat)-xyz(1,jat)
    dy=xyz(2,iat)-xyz(2,jat)
    dz=xyz(3,iat)-xyz(3,jat)
    r2=dx*dx+dy*dy+dz*dz
    t2=sigma2/r2
    t6=t2*t2*t2
    epot =epot + 4.d0*eps*(t6-1.d0)*t6
    ff= 48.d0*eps*(t6-0.5d0)*t6/r2
    fxyz(1,iat)=fxyz(1,iat) +ff*dx
    fxyz(1,jat)=fxyz(1,jat) -ff*dx
    fxyz(2,iat)=fxyz(2,iat) +ff*dy
    fxyz(2,jat)=fxyz(2,jat) -ff*dy
    fxyz(3,iat)=fxyz(3,iat) +ff*dz
    fxyz(3,jat)=fxyz(3,jat) -ff*dz
enddo
enddo
endsubroutine    
3
  • You might want to show us what you have tried so far. Do you understand the Fortran syntax? Commented Jun 7, 2019 at 6:42
  • 1
    You can try F2PY. Commented Jun 7, 2019 at 6:48
  • You could use Fortran :-) Joke aside, this type of "loop intensive" code will perform poorly in Python. Commented Jun 7, 2019 at 11:22

1 Answer 1

1

You are able to use fortran subroutines and functions in python. I recommend you use f2py from numpy. In the next link you will find the documentation: https://docs.scipy.org/doc/numpy/f2py/

If you want to use a fortran subroutine in python, you should be careful because the subroutine will be transformed to a python function. You must write the intent of the variables in your program. For example, you have the a module test in the file file.f90:

module test
  implicit none
  contains
  subroutine sub(a,b)
    real, intent(in):: a
    real, intent(out):: b
    b=2.0*a
  end subroutine sub
end module test

Now you can create the python module using f2py (command line):

f2py -c -m python_mod file.f90

f2py will have created a file called python_mod.so in the working folder. Now you can use it in a python program as a function :

from python_mod import test

c = test.sub(3.0)
print(c)

The output will be 6.0.

I hope you find it useful. Good luck!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.