本文介绍了使用SymPy码本为方程组生成Fortran子例程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在,我尝试找出如何生成与我需要坚持的特定形式相对应的Fortran代码。所需的FORTRAN代码如下所示():

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

我设法在SymPy中创建正确的表达式,但是我还没有弄清楚如何使用 codegen 。到目前为止,这是我的尝试:

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]

但这给了我

IndexException:
Range is not defined for all indices in: PAR[3]


推荐答案

如果只需要在python代码中调用FORTRAN函数,我发现使用FORTRAN包装器是比尝试在python中重新创建FORTRAN代码简单得多,尤其是在GOTO的情况下

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.

您尝试过f2py吗?

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

这篇关于使用SymPy码本为方程组生成Fortran子例程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 11:42
查看更多