Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Fortran subroutine with SymPy codegen for a system of equations

Building on a former example that I've found here, I try to find out how to generate a Fortran code that correspond to a specific form that I need to stick to. The required FORTRAN code will look like this (it is based on the FitzHugh–Nagumo model):

  SUBROUTINE FF(NE,U,PAR,F) 
!     ---------- -- 
!     Define the nonlinear term

  IMPLICIT NONE
  INTEGER, INTENT(IN) :: NE
  DOUBLE PRECISION, INTENT(IN) :: U(NE),PAR(*)
  DOUBLE PRECISION, INTENT(OUT) :: F(NE)

  DOUBLE PRECISION u,v,e,a1,a0

    u=U(1)
    v=U(2)
    e=PAR(1)
    a1=PAR(2)
    a0=PAR(3)

    F(1)= u-u**3-v 
    F(2)= e*(u-a1*v-a0)

  END SUBROUTINE FF

I manage to create the right expressions in SymPy, but I haven't figured out how to generate the required code with codegen. Here is my attempt so far:

from sympy import symbols,latex
from sympy.utilities.codegen import codegen
from sympy.tensor import IndexedBase, Idx
from sympy import Matrix
U, PAR = symbols('U PAR', cls=IndexedBase)

u = U[1]
v = U[2]

e = PAR[1]
a1 = PAR[2]
a0 = PAR[3]

dudt = u-u**3-v 
dvdt = e*(u-a1*v-a0)

print latex(dudt)
print latex(dvdt)

F = Matrix([dudt,dvdt])
print F

result = codegen(('my_function', F), 'f95', 'my_project')
print result[0][1]

But it gives me:

IndexException: 
Range is not defined for all indices in: PAR[3]
like image 843
Ohm Avatar asked Aug 19 '16 17:08

Ohm


1 Answers

If you simply need to call the FORTRAN function within your python code, I found that using a FORTRAN wrapper was much simpler than trying to recreate FORTRAN code in python, especially if GOTO's are heavily used.

Have you tried f2py? https://sysbio.ioc.ee/projects/f2py2e/

like image 63
George Zhang Avatar answered Nov 12 '22 06:11

George Zhang