You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

f2py整数传递问题:消除NumPy 1.25弃用警告并保留值更新

问题:f2py处理Fortran intent(inout)整数时的警告与值更新问题

关联旧Fortran代码与Python时,使用f2py处理intent(inout)类型整数遇到矛盾:

Fortran代码片段

subroutine maxlags(iext, nump, degree, nsuby, mlag, npt, nnt, nyt, nut, net)
implicit none
integer, intent(in) :: nump, degree, nsuby
integer, intent(in) :: iext(nump, degree, nsuby)
integer, intent(inout) :: mlag, npt(nsuby), nnt(nsuby), nyt, nut, net
...
end subroutine maxlags

两种Python变量定义的问题

  1. 用1维数组定义:
mlag = np.array([0])
nyt = np.array([0])
nut = np.array([0])
net = np.array([0])

调用子程序后变量值能更新,但触发NumPy 1.25弃用警告:

/var/folders/sj/q_5xy_n50ps10lg75p99wbw80000gn/T/ipykernel_87520/378702212.py:18: DeprecationWarning: Conversion of an array with ndim > 0 to a scalar is deprecated, and will error in future. Ensure you extract a single element from your array before performing this operation. (Deprecated NumPy 1.25.)

  1. 用NumPy标量定义:
mlag = np.int32(0)
nyt = np.int32(0)
nut = np.int32(0)
net = np.int32(0)

无警告,但调用后变量值完全不更新。

根据maxlags的文档输出,这些intent(inout)变量被识别为in/output rank-0 array(int,'i'),需找到既消除警告又保证值更新的方法。

解决方案

核心是使用秩为0的NumPy数组(rank-0 array)来传递intent(inout)的标量参数,这完全匹配f2py的要求:

正确的变量定义方式

import numpy as np

mlag = np.array(0, dtype=np.int32)
nyt = np.array(0, dtype=np.int32)
nut = np.array(0, dtype=np.int32)
net = np.array(0, dtype=np.int32)

或者通过reshape将NumPy标量转为秩0数组:

mlag = np.int32(0).reshape(())
nyt = np.int32(0).reshape(())

原理说明

  • 1维数组np.array([0])是ndim=1的数组,f2py会隐式将其转换为标量,这正是NumPy 1.25开始弃用的行为,因此触发警告。
  • np.int32(0)是不可变的NumPy标量(类似Python原生int),Fortran无法修改其内部值,导致更新失效。
  • 秩为0的数组是可变的数组对象,完全符合f2py对intent(inout)标量参数的类型要求,既能被Fortran修改后同步回Python,又不会触发任何弃用警告。

内容的提问来源于stack exchange,提问作者user3749165

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 01:03:31