Comment utiliser un code fortran en passant par python ?

Active 18 février 2014    /    Viewed 3331    /    Comments 0    /    Edit


Méthode utilisant le module Subprocess

Script Python:

import numpy as np
import math
import subprocess

def function(x):
    y1 = x**4 + 2*x**3 + 4*x**2 + 1
    y2 = x**2
    return y1,y2

x = 1.0
print function(x)

#---------- Now using Fortran Code ----------#

i=0
command = ['CodeFortran', str(x)]
process = subprocess.Popen(command, stdout=subprocess.PIPE)
while True:
    text = process.stdout.readline()
    if text != '':
        y1, y2 = text.split()
        print float(y1), float(y2)  
        i=i+1
    else:
        break

print 'Number of line:', i

Code Fortran:

program BasicFortranCode
implicit none 
integer none
integer, parameter :: pr = selected_real_kind(15,3)
real(pr) :: x
character :: arg

call getarg(1,arg)
read(arg,*) x ! Convert String to Real

write(6,*) x**4 + 2*x**3 + 4*x**2 + 1, x**2

end program

Méthode utilisant le module f2py

f2py -c -m FortranModule CodeFortran02.f90

FortranModule.so

python ExamplePythonScriptUsingFortran02.py

Script Python:

import numpy as np
import math
import subprocess

import FortranModule

def function(x):
    y1 = x**4 + 2*x**3 + 4*x**2 + 1
    y2 = x**2
    return y1,y2

x = 1.0
print 'From python: ', function(x)[0], function(x)[1]

#---------- Now using Fortran Code ----------#

FortranModule.test.x = 1.0
FortranModule.test.foo()

Code Fortran:

module test

integer, parameter :: pr = selected_real_kind(15,3)
real(pr) :: x

contains

subroutine foo

implicit none

write(6,*) 'From Fortran', x**4 + 2*x**3 + 4*x**2 + 1, x**2

end subroutine foo

end module test

Références

Liens |
------------- | -------------
f2py page |
subprocess page |
python: reading subprocess output in threads |
read subprocess stdout line by line |
How to get output from subprocess.Popen() |
fortran f2py page |


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount