numpy is convenient for handling data, but Python has a slow for loop, so there is no way to do differentiation well. If only the differential part is written in fortran with f2py, the speed can be increased. Differentiation operations are common to many analyses, so once you write them down, you can use them.
Please refer to the official manual of f2py at here.
It seems that writing a function using a subroutine is basic. The basics are as follows
--Be sure to write ʻintent --The return value is managed by ʻintent (out)
For example, a "function that adds 1 to an array and returns" can be written as follows. File name should be f2py_test.f90
etc.
subroutine add(qq,ix,qq_add)
implicit none
integer :: i
integer, intent(in) :: ix
real(8), dimension(ix), intent(in) :: qq
real(8), dimension(ix), intent(out) :: qq_add
do i = 1,ix
qq_add(i) = qq(i) + 1
enddo
return
end subroutine add
f2py --fcompiler=gfortran -m f2py_test -c --f90flags='-O3' f2py_test.f90
And. Be sure to add the option -c
and write the name of the file to be compiled at the end. Each option is below
---- compiler =
: fortran compiler specification
---m
: Module name when used in Python (it does not have to be the same as the file name)
---- f90flags =
: Options used by the fortran compiler
When using f2py from Python, do as follows.
import f2py_test #Import modules compiled with f2py
import numpy as np
ix = 5
qq = np.zeros(ix) #Define a numpy array appropriately
qq_add = f2py_test.add(qq,ix) #Call the function defined in f2py
Since qq_add
defined in the fortran code is set as ʻintent (out), it is judged as a return value and is not included in the function argument. On the other hand, in the above code, the array size ʻix
is also included as a function argument, but in f2py, the array size is automatically determined and used as an optional variable, and then automatically len (qq). It substitutes
. Therefore,
qq_add = f2py_test.add(qq)
The result is the same.
--The method is basically the same for multiple dimensions and multiple arrays. --F2py manages even if the variable shape is different in the call --There is no problem writing multiple subroutines in one file
When parsing an array of numpy, I want to lower the mental barrier of using f2py and speed up the analysis.
Recommended Posts