




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、F2PY 用户指南和参考手册作者Author:Pearu PetersonContact:Web site:Date:2005-01-30Revision:1.25译者翻译:cpythonerEmail:Blog:日期:2005-03-10版本1.25-1贡献者目 录1引言22三种封装方法 开始22.1快速方法32.2聪明方法42.3既快且聪明的方法53签名文件63.1Python module block73.2Fortran/C 例程签名73.2.1类型声明(Type declarations)83.2.2语句(Statements)83.2.3A
2、ttributes113.3扩展153.3.1F2PY指令153.3.2C语言表达式163.3.3Multiline blocks174在Python中使用绑定174.1标量参数(或数值参数)184.2字符串参数194.3数组参数204.4回调参数234.5Common blocks264.6Fortran 90 module data284.6.1Allocatable arrays295使用F2PY305.1命令f2py305.2Python module f2py2e346使用scipy_distutils356.1Scipy_distutils 0.2.2及更高版本366.2Scipy
3、_distutils pre 0.2.2367F2PY的扩展用法377.1向F2PY产生的模块中添加自写的函数377.2修改F2PY生成模块的字典381 引言F2PYFortran to Python interface generator项目的目的是要在Python和Fortran语言之间提供一个连接。F2PY是一个Python包(包含一个命令行工具f2py和一个模块f2py2e),用来建立Python C/API扩展模块,从而能够: 调用Fortran 77/90/95外部子程序、Fortran 90/95模块子程序以及C函数; 访问Fortran 77 COMMON blocks和For
4、tran 90/95 module 数据,包括allocatable arrays。2 三种封装方法 开始用F2PY把Fortran 或 C函数封装成Python 包括下列步骤: 创建签名文件,包含:对Fortran或C函数封装器的描述,也称为函数签名。在Fortran routines的情况下,F2PY通过扫描Fortran源码,从而收集创建函数封装器所需要的所有相关信息。 (可选)编辑F2PY所创建的签名文件,以优化函数封装器,使之更“聪明”、更加“Python化”。 F2PY读取签名文件,生成一个Python C/API模块,该模块包含Fortran/C/Python绑定信息。 F2PY
5、编译所有的源文件,建立包含封装器的扩展模块。在建立扩展模块时,F2PY使用了scipy_distutils包,它支持大量的Fortran编译器。上述步骤可以在一条命令中执行,也可以一步一步顺序执行,其中某些步骤可以忽略或者同其它步骤组合使用,视具体情况而定。下面介绍3种使用F2PY的典型方法。以下面的Fortran 77代码为例说明。C FILE: FIB1.F SUBROUTINE FIB(A,N)CC CALCULATE FIRST N FIBONACCI NUMBERSC INTEGER N REAL*8 A(N) DO I=1,N IF (I.EQ.1) THEN A(I) = 0.0
6、D0 ELSEIF (I.EQ.2) THEN A(I) = 1.0D0 ELSE A(I) = A(I-1) + A(I-2) ENDIF ENDDO ENDC END 2.1 快速方法把Fortran 子程序FIB封装为Python函数的最快的方法是运行: F2py c fib1.f m fib1该命令在当前目录下建立一个扩展模块fib1.pyd。现在,在Python中就可以访问Fortran子程序FIB了: import Numeric import fib1 print fib1.fib._doc_fib - Function signature: fib(a,n)Required a
7、rguments: a : input rank-1 array(d) with bounds (n)Optional arguments: n := len(a) input int a=Numeric.zeros(8,d) fib1.fib(a) print a 0. 1. 1. 2. 3. 5. 8. 13.注: F2PY发现第2个参数n是第一个数组参数的维数,因为缺省情况下所有参数都是input-only的,因此F2PY得出结论,n是可选参数,它的缺省值为len(a)。 对于可选参数n,可以使用不同的值。 a1=Numeric.zeros(8,d) fib1.fib(a1,6) pri
8、nt a1 0. 1. 1. 2. 3. 5. 0. 0.但当它和数组参数a不相容时,会抛出一个异常: fib1.fib(a,10)fib:n=10Traceback (most recent call last): File , line 1, in ?fib.error: (len(a)=n) failed for 1st keyword n 这说明F2PY具有一个有用的特征,即,F2PY对相关参数间的相容性进行初步的检查,以避免不可预期的崩溃。 当使用Numeric array 作为输入数组参数时,C指针会被直接传给Fortran。否则,F2PY就复制输入数组,然后将副本的C指针传给Fo
9、rtran子程序。结果,Fortran子程序对输入数组的任何改变都不会影响原先的参数。示例如下: a=Numeric.ones(8,i) fib1.fib(a) print a1 1 1 1 1 1 1 1这显然不是我们所期望的结果。F2PY提供了intent(inplace)属性,它能改变输入数组的属性,使得Fortran 例程所作的任何改变都对输入参数有效。例如,如果你指定 intent(inplace) a,上面的例子就会变为:, a=Numeric.ones(8,i) fib1.fib(a) print a 0. 1. 1. 2. 3. 5. 8. 13.然而,推荐使用intent(o
10、ut)属性,来把fortran例程所作的改变反馈给python,这个方案更有效、更清晰。 在python中使用Fib1.fib与在Fortran中使用FIB非常相似。然而,在python中使用in situ output 参数是不太好的风格,因为python没有安全机制处理错误的参数类型。当使用Fortran和C时,编译器在编译期间就会发现类型不匹配,而python必须在运行期间才进行类型检查。因此,在python中使用in situ output参数会使查找bug变得困难,更不要说在进行必须的类型检查时代码可读性差了。虽然前面演示的封装方法非常简单易懂,但它有几个缺点,这都归因于F2PY无法
11、确定参数的实际目的它是输入参数还是输出参数,还是既为输入又为输出,又或其它?因此,F2PY假定在缺省情况下所有参数都是输入参数。实际上,有办法让F2PY知道函数参数的实际目的,然后产生更加Python化的封装器。2.2 聪明方法让我们按照下面步骤封装Fortran函数。 首先,运行命令f2py fib1.f -m fib2 -h fib1.pyf创建签名文件,保存为fib1.pyf,其内容如下:! -*- f90 -*-python module fib2 ! in interface ! in :fib2 subroutine fib(a,n) ! in :fib2:fib1.f real*
12、8 dimension(n) : a integer optional,check(len(a)=n),depend(a) : n=len(a) end subroutine fib end interface end python module fib2! This auto-generated with f2py (version:2.28.198-1366).! See 接着,告诉F2PY参数n是一个输入参数(使用intent(in)属性),调用Fortran函数FIB所产生的结果应该返回给python(使用intent(out)属性)。此外,数组a应该根据输入参数n动态创建(使用dep
13、end(n)属性以说明依赖关系)。修改后的fib1.pyf(另存为fib2.pyf)内容如下:! -*- f90 -*-python module fib2 interface subroutine fib(a,n) real*8 dimension(n),intent(out),depend(n) : a integer intent(in) : n end subroutine fib end interface end python module fib2 最后,运行f2py -c fib2.pyf fib1.f建立扩展模块In python: import fib2 print fib
14、2.fib._doc_fib - Function signature: a = fib(n)Required arguments: n : input intReturn objects: a : rank-1 array(d) with bounds (n) print fib2.fib(8) 0. 1. 1. 2. 3. 5. 8. 13.注释: 很明显,fib2.fib更符合Fortran子程序FIB的目的,给定n,fib2.fib返回一个前n个菲波拉契数的Numericarray。新的python签名fib2.fib也消除了签名fib1.fib时遇到的那种令人惊讶的现象。 注意,在缺
15、省情况下,单独使用intent(out)也隐含了intent(hide)。Intent(hide)属性指定的参数不出现在封装器函数的参数列表中。2.3 既快且聪明的方法聪明的方法适合封装那些不能修改的Fortran代码(比如,第三方的代码)。然而,Fortran代码如果可以编辑,那么在多数情况下可以跳过生成中间签名文件这一步。也就是说,可以使用F2PY指令将F2PY所特有的属性直接插入到Fortran源代码中。F2PY指令是一条特别的注释行,Fortran编译器忽略它,但F2PY会像普通行那样进行处理。下面是修改后的Fortran源代码,保存为fib3.f:C FILE: FIB3.F SUB
16、ROUTINE FIB(A,N)CC CALCULATE FIRST N FIBONACCI NUMBERSC INTEGER N REAL*8 A(N)Cf2py intent(in) nCf2py intent(out) aCf2py depend(n) a DO I=1,N IF (I.EQ.1) THEN A(I) = 0.0D0 ELSEIF (I.EQ.2) THEN A(I) = 1.0D0 ELSE A(I) = A(I-1) + A(I-2) ENDIF ENDDO ENDC END 现在,可以运行f2py -c -m fib3 fib3.f创建扩展模块。注意封装器函数FIB
17、同前面例子一样“聪明”: import fib3 print fib3.fib._doc_fib - Function signature: a = fib(n)Required arguments: n : input intReturn objects: a : rank-1 array(d) with bounds (n) print fib3.fib(8) 0. 1. 1. 2. 3. 5. 8. 13.3 签名文件签名文件(.pyf文件)的语法借自于Fortran90/95语言规范,它几乎能够理解Fortran90/95所有的标准结构,包括free和fixed format。F2PY
18、还对Fortran 90/95语言规范作了一些扩展,以帮助设计Fortran到Python的接口,使之更Python化(Pythonic)。签名文件可以包含任意Fortran代码(因此,Fortran代码可以看作是签名文件)。对于那些与建立接口无关的Fortran结构,F2PY只是将之忽略掉,这其中也包括语法错误。因此,要注意不要有任何的语法错误(So,be careful not making ones)。签名文件的内容通常是大小写敏感的,在扫描Fortran代码生成签名文件时,F2PY自动将字符转换为小写。在multi-line blocks中的代码或使用-no-lower选项时除外。3.
19、1 Python module block签名文件包含一个(推荐)或多个python module blocks。Python module blocks用来描述F2PY所生成的Python/C扩展模块module.c 的内容。如果包含子字符串_user_,那么相应的python module block描述的是回调函数的签名。Python module block 结构如下:python module . interface end interface . interface module end module end interface .end python module 内为可选部分,
20、表示一个或多个前面部分3.2 Fortran/C 例程签名Fortran例程签名的结构如下: function | subroutine ( ) result ( ) end function | subroutine F2PY根据例程签名产生如下的Python/C扩展函数:def (,): . return Fortran block data的签名结构如下:block data end block data 3.2.1 类型声明(Type declarations)参数/变量的类型声明部分定义如下: : 这里 := byte | character | complex | real | d
21、ouble complex | double precision | integer | logical := * | ( len= , kind= ) | ( kind= , len= ) := * | ( kind= ) := * ( ) | ( ) * | / / | = , 其中 是用逗号分隔的属性列表; 是用逗号分隔的维数边界列表; 是C表达式 对整数类型而言,可以是负整数,这时integer* 表示unsigned C integers. 如果某个参数没有,其类型由参数名的隐含规则决定。3.2.2 语句(Statements) Attribute statements: 是没有的
22、。另外,在 an attribute statement 中不能 use other attributes, 也只能是a list of names. Use statements: 部分的定义是:use , | , ONLY : 这里 := = , 目前,use statement只用于连接回调模块(call-back modules )和外部参数 (回调函数), 参见 Call-back arguments. Common block statements: 部分的定义是:common / / 其中 := ( ) , 一个 python module block不应包含二个或二个以上的同名
23、common blocks,否则,后面的common blocks将会被忽略。 中的变量类型用定义。要注意的是相应的 可能包含array specifications,这样的话就不必在指定了。 Other statements: 部分是指所有前面未提到的其它Fortran语言结构,除了以下情况外,F2PY都予以忽略不作处理。call statements and function calls of external arguments (more details?); n include statementsinclude include 如果文件 不存在,则忽略该include statem
24、ent,否则,文件 is included to a signature file. include statements 能在签名文件的任意部分使用, 在 Fortran/C routine signature blocks的外面也可以使用。n implicit statementsimplicit noneimplicit where := ( )如果未用声明变量类型,那么用隐含规则确定变量类型。缺省隐含规则给定如下:implicit real (a-h,o-z,$_), integer (i-m)n entry statementsentry ()F2PY generates wrapp
25、ers to all entry names using the signature of the routine block.技巧:entry statement can be used to describe the signature of an arbitrary routine allowing F2PY to generate a number of wrappers from only one routine block signature. There are few restrictions while doing this: fortranname cannot be us
26、ed, callstatement and callprotoargument can be used only if they are valid for all entry routines, etc.此外, F2PY 还引入了下列statements:n threadsafe Use Py_BEGIN_ALLOW_THREADS . Py_END_ALLOW_THREADS block around the call to Fortran/C function.n callstatement Replace F2PY generated call statement to Fortran
27、/C function with . The wrapped Fortran/C function is available as (*f2py_func). To raise an exception, set f2py_success = 0 in .n callprotoargument When callstatement statement is used then F2PY may not generate proper prototypes for Fortran/C functions (because may contain any function calls and F2
28、PY has no way to determine what should be the proper prototype). With this statement you can explicitely specify the arguments of the corresponding prototype:extern FUNC_F(,)();n fortranname You can use arbitrary for a given Fortran/C function. Then you have to specify with this statement.If fortran
29、name statement is used without then a dummy wrapper is generated.n usercode When used inside python module block, then given C code will be inserted to generated C/API source just before wrapper function definitions. Here you can define arbitrary C functions to be used in initialization of optional
30、arguments, for example. If usercode is used twise inside python module block then the second multi-line block is inserted after the definition of external routines.When used inside , then given C code will be inserted to the corresponding wrapper function just after declaring variables but before an
31、y C statements. So, usercode follow-up can contain both declarations and C statements.When used inside the first interface block, then given C code will be inserted at the end of the initialization function of the extension module. Here you can modify extension modules dictionary. For example, for d
32、efining additional variables etc.n pymethoddef Multiline block will be inserted to the definition of module methods PyMethodDef-array. It must be a comma-separated list of C arrays (see Extending and Embedding Python documentation for details). pymethoddef statement can be used only inside python mo
33、dule block.3.2.3 AttributesF2PY使用了下列属性: 可选(optional)相应的参数被移到列表的末尾。 可选参数的缺省值由指定,请参见entitydecl 的定义。 缺省值必须是有效的C语言表达式。在使用 时,F2PY自动设为可选属性。可选数组参数的所有维数都必须是有界的。 必须(required) 相应的参数被视为必须的参数,这是缺省属性,只有当使用了,而你又要禁用自动optional设置时,才需要指定required。如果 Python None object被设置为required argument,那么该参数被视为可选的。就是说,in the case o
34、f array argument, the memory is allocated. And if is given, the corresponding initialization is carried out. dimension() 相应的变量视为数组,其维数由指定。 intent() This specifies the intention of the corresponding argument. is a comma separated list of the following keys:n in The argument is considered as an input-
35、only argument. 参数值传给 Fortran/C function ,该函数不能改变参数的值。n inout The argument is considered as an input/output or in situ output argument. intent(inout) arguments can be only contiguous Numeric arrays with proper type and size. Here contiguous can be either in Fortran or C sense. The latter one coincide
36、s with the contiguous concept used in Numeric and is effective only if intent(c) is used. Fortran-contiguousness is assumed by default.通常不推荐使用intent(inout),而代之以 intent(in,out)。 See also intent(inplace) attribute.n inplace The argument is considered as an input/output or in situ output argument. inte
37、nt(inplace) arguments must be Numeric arrays with proper size. If the type of an array is not proper or the array is non-contiguous then the array will be changed in-place to fix the type and make it contiguous.通常也不推荐使用intent(inplace). For example, when slices have been taken from an intent(inplace)
38、 argument then after in-place changes, slices data pointers may point to unallocated memory area.n out The argument is considered as an return variable. It is appended to the list. Using intent(out) sets intent(hide) automatically, unless also intent(in) or intent(inout) were used.缺省情况下,返回的多维数组是Fort
39、ran-contiguous。如果使用了intent(c), 那么返回的多维数组则是C-contiguous。n hide The argument is removed from the list of required or optional arguments. Typically intent(hide) is used with intent(out) or when completely determines the value of the argument like in the following example:integer intent(hide),depend(a)
40、: n = len(a)real intent(in),dimension(n) : a n c The argument is treated as a C scalar or C array argument. In the case of a scalar argument, its value is passed to C function as a C scalar argument (recall that Fortran scalar arguments are actually C pointer arguments). In the case of an array argu
41、ment, the wrapper function is assumed to treat multi-dimensional arrays as C-contiguous arrays.There is no need to use intent(c) for one-dimensional arrays, no matter if the wrapped function is either a Fortran or a C function. This is because the concepts of Fortran- and C-contiguousness overlap in
42、 one-dimensional cases.If intent(c) is used as an statement but without entity declaration list, then F2PY adds intent(c) attibute to all arguments.Also, when wrapping C functions, one must use intent(c) attribute for in order to disable Fortran specific F_FUNC(.,.) macros.n cache The argument is tr
43、eated as a junk of memory. No Fortran nor C contiguousness checks are carried out. Using intent(cache) makes sense only for array arguments, also in connection with intent(hide) or optional attributes.n copy Ensure that the original contents of intent(in) argument is preserved. Typically used in con
44、nection with intent(in,out) attribute. F2PY creates an optional argument overwrite_ with the default value 0.n overwrite The original contents of the intent(in) argument may be altered by the Fortran/C function. F2PY creates an optional argument overwrite_ with the default value 1.n out= Replace the
45、 return name with in the _doc_ string of a wrapper function.n callback Construct an external function suitable for calling Python function from Fortran. intent(callback) must be specified before the corresponding external statement. If argument is not in argument list then it will be added to Python
46、 wrapper but is not used when calling Fortran function.Use intent(callback) in situations where a Fortran/C code assumes that a user implements a function with given prototype and links it to an executable.n aux Define auxiliary C variable in F2PY generated wrapper function. Useful to save parameter
47、 values so that they can be accessed in initialization expression of other variables. Note that intent(aux) silently implies intent(c).The following rules apply: If no intent(in | inout | out | hide) is specified, intent(in) is assumed. intent(in,inout) is intent(in). intent(in,hide) or intent(inout,hide) is intent(hide). intent(out) is intent(out,hide) unless intent(in) or intent(inout) is specified. If intent(copy) or intent(overwrite) is used, then an additional
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 油田开发项目资金申请报告(范文参考)
- 汽车配套产业基地项目投标书(参考模板)
- xx片区城乡供水一体化项目投标书
- 《GB41930-2022低水平放射性废物包特性鉴定水泥固化体》深度解析
- 四川省遂宁市2024-2025学年高一下学期期末考试历史试卷
- 2025年汽车仪表相关计数仪表项目合作计划书
- 2025年医疗物联网技术在患者生命体征监测中的应用前景报告
- 2025健身房租赁合同
- 教育技术的伦理准则与实践探索
- 航空发动机维修技术创新在成本控制中的应用与优化策略报告
- 生产现场变化点管理行动指南
- 中国古典小说巅峰:四大名著鉴赏学习通课后章节答案期末考试题库2023年
- 模拟电子技术基础知到章节答案智慧树2023年兰州石化职业技术大学
- JJF 1915-2021倾角仪校准规范
- GA/T 1310-2016法庭科学笔迹鉴定意见规范
- 2023年本科招生考试
- 新入职护士培训考试试题及答案
- 《消防安全技术实务》课本完整版
- 北师大版七年级数学下册 与信息技术相融合的数学教学案例 教案
- 钝针穿刺法临床应用护理
- 水产养殖行业报告
评论
0/150
提交评论