Generate Fortran subroutine with SymPy codegen for a system of equations

こ雲淡風輕ζ 提交于 2019-12-22 04:13:08

问题


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]

回答1:


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/



来源:https://stackoverflow.com/questions/39045066/generate-fortran-subroutine-with-sympy-codegen-for-a-system-of-equations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!