numpy 1.7中 f2py示例和说明文档,主要是介绍如何将fortran转为python模块,如下:

f2py

F2py allows you to automatically construct an extension module that interfaces to routines in Fortran 77/90/95 code. It has the ability to parse Fortran 77/90/95 code and automatically generate Python signatures for the subroutines it encounters, or you can guide how the subroutine interfaces with Python by constructing an interface-definition-file (or modifying the f2py-produced one).

Creating source for a basic extension module

Probably the easiest way to introduce f2py is to offer a simple example. Here is one of the subroutines contained in a file named add.f:

CSUBROUTINE ZADD(A,B,C,N)
CDOUBLE COMPLEX A(*)DOUBLE COMPLEX B(*)DOUBLE COMPLEX C(*)INTEGER NDO 20 J = 1, NC(J) = A(J)+B(J)20   CONTINUEEND

This routine simply adds the elements in two contiguous arrays and places the result in a third. The memory for all three arrays must be provided by the calling routine. A very basic interface to this routine can be automatically generated by f2py:

f2py -m add add.f

You should be able to run this command assuming your search-path is set-up properly. This command will produce an extension module named add module.c in the current directory. This extension module can now be compiled and used from Python just like any other extension module.

Creating a compiled extension module

You can also get f2py to compile add.f and also compile its produced extension module leaving only a shared-library extension file that canbe imported from Python:

f2py -c -m add add.f

This command leaves a file named add.{ext} in the current directory(where {ext} is the appropriate extension for a python extension module on your platform — so, pyd,etc. ). This module may then be imported from Python. It will contain a method for each subroutine inadd (zadd, cadd, dadd, sadd). The docstring of each method contains nformation about how the module method may be called:

>>> import add
>>> print add.zadd.__doc__
zadd - Function signature:zadd(a,b,c,n)
Required arguments:a : input rank-1 array('D') with bounds (*)b : input rank-1 array('D') with bounds (*)c : input rank-1 array('D') with bounds (*)n : input int

Improving the basic interface

The default interface is a very literal translation of the fortran code into Python. The Fortran array arguments must now be NumPy arrays and the integer argument should be an integer. The interface will attempt to convert all arguments to their required types (and shapes)and issue an error if unsuccessful. However, because it knows nothing about the semantics of the arguments (such that C is an output and n should really match the array sizes), it is possible to abuse this function in ways that can cause Python to crash. For example:

>>> add.zadd([1,2,3],[1,2],[3,4],1000)

will cause a program crash on most systems. Under the covers, thelists are being converted to proper arrays but then the underlying add loop is told to cycle way beyond the borders of the allocated memory.

In order to improve the interface, directives should be provided. This is accomplished by constructing an interface definition file. It is usually best to start from the interface file that f2py can produce(where it gets its default be havior from). To get f2py to generate the interface file use the -h option:

f2py -h add.pyf -m add add.f

This command leaves the file add.pyf in the current directory. The section of this file corresponding to zadd is:

subroutine zadd(a,b,c,n) ! in :add:add.fdouble complex dimension(*) :: adouble complex dimension(*) :: bdouble complex dimension(*) :: cinteger :: n
end subroutine zadd

By placing intent directives and checking code, the interface can becleaned up quite a bit until the Python module method is both easierto use and more robust.

subroutine zadd(a,b,c,n) ! in :add:add.fdouble complex dimension(n) :: adouble complex dimension(n) :: bdouble complex intent(out),dimension(n) :: cinteger intent(hide),depend(a) :: n=len(a)
end subroutine zadd

The intent directive, intent(out) is used to tell f2py that c is an output variable and should be created by the interface before being passed to the underlying code. The intent(hide) directive tells f2pyto not allow the user to specify the variable,n, but instead toget it from the size ofa. The depend(a ) directive is necessary to tell f2py that the value of n depends on the input a (so that it won’t try to create the variable n until the variable a is created).

The new interface has docstring:

>>> print add.zadd.__doc__
zadd - Function signature:c = zadd(a,b)
Required arguments:a : input rank-1 array('D') with bounds (n)b : input rank-1 array('D') with bounds (n)
Return objects:c : rank-1 array('D') with bounds (n)

Now, the function can be called in a much more robust way:

>>> add.zadd([1,2,3],[4,5,6])
array([ 5.+0.j,  7.+0.j,  9.+0.j])

Notice the automatic conversion to the correct format that occurred.

Inserting directives in Fortran source

The nice interface can also be generated automatically by placing the variable directives as special comments in the original fortran code.Thus, if I modify the source code to contain:

CSUBROUTINE ZADD(A,B,C,N)
C
CF2PY INTENT(OUT) :: C
CF2PY INTENT(HIDE) :: N
CF2PY DOUBLE COMPLEX :: A(N)
CF2PY DOUBLE COMPLEX :: B(N)
CF2PY DOUBLE COMPLEX :: C(N)DOUBLE COMPLEX A(*)DOUBLE COMPLEX B(*)DOUBLE COMPLEX C(*)INTEGER NDO 20 J = 1, NC(J) = A(J) + B(J)20   CONTINUEEND

Then, I can compile the extension module using:

f2py -c -m add add.f

The resulting signature for the function add.zadd is exactly the same one that was created previously. If the original source code had contained A(N) instead of A(*) and so forth with B and C, then Icould obtain (nearly) the same interface simply by placing the INTENT(OUT) :: C comment line in the source code. The only differenceis that N would be an optional input that would default to the length of A.

A filtering example

For comparison with the other methods to be discussed. Here is another example of a function that filters a two-dimensional array of double precision floating-point numbers using a fixed averaging filter. The advantage of using Fortran to index into multi-dimensional arrays should be clear from this example.

      SUBROUTINE DFILTER2D(A,B,M,N)
CDOUBLE PRECISION A(M,N)DOUBLE PRECISION B(M,N)INTEGER N, M
CF2PY INTENT(OUT) :: B
CF2PY INTENT(HIDE) :: N
CF2PY INTENT(HIDE) :: MDO 20 I = 2,M-1DO 40 J=2,N-1B(I,J) = A(I,J) +$           (A(I-1,J)+A(I+1,J) +$            A(I,J-1)+A(I,J+1) )*0.5D0 +$           (A(I-1,J-1) + A(I-1,J+1) +$            A(I+1,J-1) + A(I+1,J+1))*0.25D040      CONTINUE20   CONTINUEEND

This code can be compiled and linked into an extension module named filter using:

f2py -c -m filter filter.f

This will produce an extension module named filter.so in the current directory with a method named dfilter2d that returns a filteredversion of the input.

Calling f2py from Python¶

The f2py program is written in Python and can be run from inside your module. This provides a facility that is somewhat similar to the use of weave.ext_tools described below. An example of the final interface executed using Python code is:

import numpy.f2py as f2py
fid = open('add.f')
source = fid.read()
fid.close()
f2py.compile(source, modulename='add')
import add

The source string can be any valid Fortran code. If you want to save the extension-module source code then a suitable file-name can be provided by the source_fn keyword to the compile function.

Automatic extension module generation

If you want to distribute your f2py extension module, then you only need to include the .pyf file and the Fortran code. The distutils extensions in NumPy allow you to define an extension module entirely in terms of this interface file. A valid setup.py file allowing distribution of the add.f module (as part of the package f2py_examples so that it would be loaded as f2py_examples.add) is:

def configuration(parent_package='', top_path=None):from numpy.distutils.misc_util import Configurationconfig = Configuration('f2py_examples',parent_package, top_path)config.add_extension('add', sources=['add.pyf','add.f'])return configif __name__ == '__main__':from numpy.distutils.core import setupsetup(**configuration(top_path='').todict())

Installation of the new package is easy using:

python setup.py install

assuming you have the proper permissions to write to the main site-packages directory for the version of Python you are using. For theresulting package to work, you need to create a file named __init__.py(in the same directory as add.pyf). Notice the extension module is defined entirely in terms of the “add.pyf” and “add.f” files. The conversion of the .pyf file to a .c file is handled by numpy.disutils.

Conclusion

The interface definition file (.pyf) is how you can fine-tune theinterface between Python and Fortran. There is decent documentationfor f2py found in the numpy/f2py/docs directory where-ever NumPy isinstalled on your system (usually under site-packages). There is alsomore information on using f2py (including how to use it to wrap Ccodes) athttp://www.scipy.org/Cookbook under the “Using NumPy withOther Languages” heading.

The f2py method of linking compiled code is currently the mostsophisticated and integrated approach. It allows clean separation ofPython with compiled code while still allowing for separatedistribution of the extension module. The only draw-back is that itrequires the existence of a Fortran compiler in order for a user toinstall the code. However, with the existence of the free-compilersg77, gfortran, and g95, as well as high-quality commerical compilers,this restriction is not particularly onerous. In my opinion, Fortranis still the easiest way to write fast and clear code for scientificcomputing. It handles complex numbers, and multi-dimensional indexingin the most straightforward way. Be aware, however, that some Fortrancompilers will not be able to optimize code as well as good hand-written C-code.

numpy 1.7中 f2py示例和说明文档相关推荐

  1. 【GIT】GitHub中的readme.md说明文档中如何将表格居中显示?

    问题描述 实际上无法将它进行视觉上的居中. 正如您在下图中看到的,GitHub 会自动呈现表格,以便它们已经占据了整个宽度.正因为如此,你不能将 GitHub 的 Markdown 渲染器生成的文本居 ...

  2. srvctl 在oracle下运行,Oracle RAC中Srvctl命令详细说明文档

    SRVCTL是ORACLE9i RAC集群配置管理的工具.本文是对SRVCTL的所有命令进行详细说明的一篇参考文档. 读者对象:ORACLE9i RAC数据库集群管理员. 注: RAC:Real Ap ...

  3. Caysn打印机IOS平台打印开发包、接口说明文档及示例程序_20170717

    打印机开发包,接口说明文档,打印示例程序下载地址:Caysn打印机IOS开发包.接口说明文档.打印示例程序_20170717 Framework版本要求:IOS8  Framework架构:armv7 ...

  4. Caysn打印机IOS平台打印示例及接口说明文档 - 20161008

    打印示例下载地址: Caysn打印机IOS打印示例程序 - sample_20161008 接口说明文档下载地址: Caysn打印机IOS开发包接口说明文档 - PrinterLibs For IOS ...

  5. python numpy allclose用法及代码示例

    python numpy allclose用法及代码示例 用法: numpy.allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False) 如果两个数 ...

  6. 【无为则无心Python基础】— 39、Python中函数的说明文档

    文章目录 1.函数的说明文档的作用 2.语法 3.查看函数的说明文档 4.快速体验 5.拓展:完美的函数说明文档 1.函数的说明文档的作用 思考:定义一个函数后,程序员如何书写程序能够快速提示这个函数 ...

  7. python找出值为nan_Python Numpy:找到list中的np.nan值方法

    这个问题源于在训练机器学习的一个模型时,使用训练数据时提示prepare的数据中存在np.nan 报错信息如下: ValueError: np.nan is an invalid document, ...

  8. numpy找到数组中符合条件的数

    numpy找到数组中符合条件的数 import numpy as nparr = np.array([1, 1, 1, 134, 45, 3, 46, 45, 65, 3, 23424, 234, 1 ...

  9. python保存运行结果下次使用_将python运行结果保存至本地文件中的示例讲解

    一.建立文件,保存数据 1.使用python中内置的open函数 打开txt文件 #mode 模式 #w 只能操作写入 r 只能读取 a 向文件追加 #w+ 可读可写 r+可读可写 a+可读可追加 # ...

  10. (36)System Verilog类中方法示例

    (36)System Verilog类中方法示例 1.1 目录 1)目录 2)FPGA简介 3)System Verilog简介 4)System Verilog类中方法示例 5)结语 1.2 FPG ...

最新文章

  1. Screenlets:桌面小玩意
  2. 【MaxCompute】学习笔记基础说明
  3. 朝着理想坚实迈进_坚实原则:开放/封闭原则
  4. 【DP】UVA 103 Stacking Boxes 输出路径
  5. 中移4G模块-ML302-OpenCpu开发-2-MQTT连接阿里云
  6. 牛X网整理的JAVA面试题
  7. java主函数_《左手 Java 右手 Python 》之 Java 的安装与初识(1)
  8. canvas beginPath()的初步理解
  9. java基础考试_Java基础试题及其答案
  10. 史上最详细Excel制作生命游戏,体验生命演化。
  11. onenote同步速度慢
  12. Python oct()函数
  13. 漫谈广告竞价模式(二)
  14. 提高代码质量的那些建议
  15. latex中文小标题_科学网—一个较为完整的中文图书Latex模板 - 张金龙的博文
  16. 系统培训流程及注意事项,实操总节
  17. This is an MDK version 4 project ,require Device support for Cortex-M based devices.
  18. 基于JavaWeb的教务管理系统(SSM)
  19. C Primer Plus (第五版)中文版——第 10 章 数组和指针
  20. tp5insertAll和saveAll

热门文章

  1. 鄂州市网站建设多少钱,鄂州市建设企业网站要多少钱
  2. VSCode中使用GitHub
  3. Javaweb大作业文档部分预览
  4. w ndows7旗舰版怎么重装系统,windows7旗舰版64位怎么重装32位系统
  5. Windows命令:tracert
  6. blender python编程入门
  7. 使用jQuery Easyui 制作的后台界面
  8. ThinkPHP3.2.3实现后台登录界面
  9. [转帖]任正非管理思想
  10. 即时通讯软件到底有哪些呢?