How do I pass my (7, 3, 3, 3) array to a fortran subroutine?

半城伤御伤魂 提交于 2019-12-13 01:51:29

问题


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

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