问题
I have written a fortran subroutine to by used in python via the f2py command.
The subroutine takes a numpy ndarray of shape (7, 3, 3, 3). The array is an array of 7 cubes, of size 3x3x3. I also pass the integers 7 and 3 to the subroutine.
Here is the code
subroutine fit(n, m, a)
c ===================================================================
c ArrayTest.f
c ===================================================================
c n - number of cubes being passed
c
c m - edge of cube size
c
c a(n,m,m,m) - array of shape (n,m,m,m)
c
c ===================================================================
implicit none
integer m
integer n
double precision a(n,m,m,m)
end subroutine fit
This is just to see if I can pass the array. When I compile and call it from python, I get the following error.
import ArrayTest as AT
import numpy as np
n = 7
m = 3
a = np.ones((n,m,m,m))
AT.fit(n, m, a)
throws
ArrayTest.error: (shape(a,0)==n) failed for 1st keyword n: fit:n=3
I have no idea what is going on. Defining the array in fortran as a(m,m,m,m) throws up no problems, it is only when I try to define it from two integers that it causes problems, even if I set both m = n = 3. How do I pass my (7, 3, 3, 3) array to a fortran subroutine?
回答1:
Take a look at the docstring of the Python function created by f2py:
fit(a,[n,m])
Wrapper for ``fit``.
Parameters
----------
a : input rank-4 array('d') with bounds (n,m,m,m)
Other Parameters
----------------
n : input int, optional
Default: shape(a,0)
m : input int, optional
Default: shape(a,1)
f2py recognized that n
and m
describe the shape of a
, and so are not required arguments for the Python function, since they can be found by inspecting the shape of the numpy array. So they are optional second and third arguments of the Python function fit
:
In [8]: import ArrayTest as AT
In [9]: n = 7
In [10]: m = 3
In [11]: a = np.zeros((n, m, m, m))
In [12]: AT.fit(a, n, m)
In [13]: AT.fit(a)
来源:https://stackoverflow.com/questions/31700558/how-do-i-pass-my-7-3-3-3-array-to-a-fortran-subroutine