Movatterモバイル変換


[0]ホーム

URL:


SciPy

Signature file

The syntax specification for signature files (.pyf files) is borrowedfrom the Fortran 90/95 language specification. Almost all Fortran90/95 standard constructs are understood, both in free and fixedformat (recall that Fortran 77 is a subset of Fortran 90/95). F2PYintroduces also some extensions to Fortran 90/95 languagespecification that help designing Fortran to Python interface, make itmore “Pythonic”.

Signature files may contain arbitrary Fortran code (so that Fortrancodes can be considered as signature files). F2PY silently ignoresFortran constructs that are irrelevant for creating the interface.However, this includes also syntax errors. So, be careful not makingones;-).

In general, the contents of signature files is case-sensitive. Whenscanning Fortran codes and writing a signature file, F2PY lowers allcases automatically except in multiline blocks or when--no-loweroption is used.

The syntax of signature files is presented below.

Python module block

A signature file may contain one (recommended) or morepythonmodule blocks.pythonmodule block describes the contents ofa Python/C extension module<modulename>module.c that F2PYgenerates.

Exception: if<modulename> contains a substring__user__, thenthe correspondingpythonmodule block describes the signatures ofso-called call-back functions (seeCall-back arguments).

Apythonmodule block has the following structure:

pythonmodule<modulename>[<usercodestatement>]...[interface<usercodestatement><Fortranblockdatasignatures><Fortran/Croutinesignatures>end[interface]]...[interfacemodule<F90modulename>[<F90moduledatatypedeclarations>][<F90moduleroutinesignatures>]end[module[<F90modulename>]]end[interface]]...end[pythonmodule[<modulename>]]

Here brackets[] indicate an optional part, dots... indicateone or more of a previous part. So,[]... reads zero or more of aprevious part.

Fortran/C routine signatures

The signature of a Fortran routine has the following structure:

[<typespec>]function|subroutine<routinename> \[([<arguments>])][result(<entityname>)][<argument/variabletypedeclarations>][<argument/variableattributestatements>][<usestatements>][<commonblockstatements>][<otherstatements>]end[function|subroutine[<routinename>]]

From a Fortran routine signature F2PY generates a Python/C extensionfunction that has the following signature:

def <routine name>(<required arguments>[,<optional arguments>]):     ...     return <return variables>

The signature of a Fortran block data has the following structure:

blockdata[<blockdataname>][<variabletypedeclarations>][<variableattributestatements>][<usestatements>][<commonblockstatements>][<includestatements>]end[blockdata[<blockdataname>]]

Type declarations

The definition of the<argument/variabletypedeclaration> partis

<typespec>[[<attrspec>]::]<entitydecl>

where

<typespec>:=byte|character[<charselector>]|complex[<kindselector>]|real[<kindselector>]|doublecomplex|doubleprecision|integer[<kindselector>]|logical[<kindselector>]<charselector>:=*<charlen>|([len=]<len>[,[kind=]<kind>])|(kind=<kind>[,len=<len>])<kindselector>:=*<intlen>|([kind=]<kind>)<entitydecl>:=<name>[[*<charlen>][(<arrayspec>)]|[(<arrayspec>)]*<charlen>]|[/<init_expr>/|=<init_expr>] \[,<entitydecl>]

and

  • <attrspec> is a comma separated list ofattributes;
  • <arrayspec> is a comma separated list of dimension bounds;
  • <init_expr> is aC expression.
  • <intlen> may be negative integer forinteger typespecifications. In such casesinteger*<negintlen> representsunsigned C integers.

If an argument has no<argumenttypedeclaration>, its type isdetermined by applyingimplicit rules to its name.

Statements

Attribute statements:
The<argument/variableattributestatement> is<argument/variabletypedeclaration> without<typespec>.In addition, in an attribute statement one cannot use otherattributes, also<entitydecl> can be only a list of names.
Use statements:

The definition of the<usestatement> part is

use<modulename>[,<rename_list>|,ONLY:<only_list>]

where

<rename_list>:=<local_name>=><use_name>[,<rename_list>]

Currently F2PY usesuse statement only for linking call-backmodules andexternal arguments (call-back functions), seeCall-back arguments.

Common block statements:

The definition of the<commonblockstatement> part is

common/<commonname>/<shortentitydecl>

where

<shortentitydecl>:=<name>[(<arrayspec>)][,<shortentitydecl>]

If apythonmodule block contains two or morecommon blockswith the same name, the variables from the additional declarationsare appended. The types of variables in<shortentitydecl> aredefined using<argumenttypedeclarations>. Note that thecorresponding<argumenttypedeclarations> may contain arrayspecifications; then you don’t need to specify these in<shortentitydecl>.

Other statements:

The<otherstatement> part refers to any other Fortran languageconstructs that are not described above. F2PY ignores most of themexcept

  • call statements and function calls ofexternal arguments(more details?);

  • include statements
    include'<filename>'include"<filename>"

    If a file<filename> does not exist, theincludestatement is ignored. Otherwise, the file<filename> isincluded to a signature file.include statements can be usedin any part of a signature file, also outside the Fortran/Croutine signature blocks.

  • implicit statements
    implicitnoneimplicit<listofimplicitmaps>

    where

    <implicitmap>:=<typespec>(<listoflettersorrangeofletters>)

    Implicit rules are used to determine the type specification ofa variable (from the first-letter of its name) if the variableis not defined using<variabletypedeclaration>. Defaultimplicit rule is given by

    implicit real (a-h,o-z,$_), integer (i-m)
  • entry statements
    entry<entryname>[([<arguments>])]

    F2PY generates wrappers to all entry names using the signatureof the routine block.

    Tip:entry statement can be used to describe the signatureof an arbitrary routine allowing F2PY to generate a number ofwrappers from only one routine block signature. There are fewrestrictions while doing this:fortranname cannot be used,callstatement andcallprotoargument can be used only ifthey are valid for all entry routines, etc.

In addition, F2PY introduces the following statements:

  • threadsafe

    UsePy_BEGIN_ALLOW_THREADS..Py_END_ALLOW_THREADS blockaround the call to Fortran/C function.

  • callstatement<C-expr|multi-lineblock>

    Replace F2PY generated call statement to Fortran/C function with<C-expr|multi-lineblock>. The wrapped Fortran/C functionis available as(*f2py_func). To raise an exception, setf2py_success=0 in<C-expr|multi-lineblock>.

  • callprotoargument<C-typespecs>

    Whencallstatement statement is used then F2PY may notgenerate proper prototypes for Fortran/C functions (because<C-expr> may contain any function calls and F2PY has no wayto determine what should be the proper prototype). With thisstatement you can explicitly specify the arguments of thecorresponding prototype:

    extern<returntype>FUNC_F(<routinename>,<ROUTINENAME>)(<callprotoargument>);
  • fortranname[<actualFortran/Croutinename>]

    You can use arbitrary<routinename> for a given Fortran/Cfunction. Then you have to specify<actualFortran/Croutinename> with this statement.

    Iffortranname statement is used without<actualFortran/Croutinename> then a dummy wrapper isgenerated.

  • usercode<multi-lineblock>

    When used insidepythonmodule block, then given C codewill be inserted to generated C/API source just beforewrapper function definitions. Here you can define arbitraryC functions to be used in initialization of optional arguments,for example. Ifusercode is used twice insidepythonmodule block then the second multiline block is insertedafter the definition of external routines.

    When used inside<routinesignature>, then given C code willbe inserted to the corresponding wrapper function just afterdeclaring variables but before any C statements. So,usercodefollow-up can contain both declarations and C statements.

    When used inside the firstinterface block, then given Ccode will be inserted at the end of the initializationfunction of the extension module. Here you can modify extensionmodules dictionary. For example, for defining additionalvariables etc.

  • pymethoddef<multilineblock>

    Multiline block will be inserted to the definition ofmodule methodsPyMethodDef-array. It must be acomma-separated list of C arrays (seeExtending and EmbeddingPython documentation for details).pymethoddef statement can be used only insidepythonmodule block.

Attributes

The following attributes are used by F2PY:

optional

The corresponding argument is moved to the end of<optionalarguments> list. A default value for an optional argument can bespecified<init_expr>, seeentitydecl definition. Note thatthe default value must be given as a valid C expression.

Note that whenever<init_expr> is used,optional attributeis set automatically by F2PY.

For an optional array argument, all its dimensions must be bounded.

required

The corresponding argument is considered as a required one. This isdefault. You need to specifyrequired only if there is a need todisable automaticoptional setting when<init_expr> is used.

If PythonNone object is used as a required argument, theargument is treated as optional. That is, in the case of arrayargument, the memory is allocated. And if<init_expr> is given,the corresponding initialization is carried out.

dimension(<arrayspec>)
The corresponding variable is considered as an array with givendimensions in<arrayspec>.
intent(<intentspec>)

This specifies the “intention” of the correspondingargument.<intentspec> is a comma separated list of thefollowing keys:

  • in

    The argument is considered as an input-only argument. It meansthat the value of the argument is passed to Fortran/C function andthat function is expected not to change the value of an argument.

  • inout

    The argument is considered as an input/output orin situoutput argument.intent(inout) arguments can be only“contiguous” NumPy arrays with proper type and size. Here“contiguous” can be either in Fortran or C sense. The latter onecoincides with the contiguous concept used in NumPy and iseffective only ifintent(c) is used. Fortran contiguityis assumed by default.

    Usingintent(inout) is generally not recommended, useintent(in,out) instead. See alsointent(inplace) attribute.

  • inplace

    The argument is considered as an input/output orin situoutput argument.intent(inplace) arguments must beNumPy arrays with proper size. If the type of an array isnot “proper” or the array is non-contiguous then the arraywill be changed in-place to fix the type and make it contiguous.

    Usingintent(inplace) is generally not recommended either.For example, when slices have been taken from anintent(inplace) argument then after in-place changes,slices data pointers may point to unallocated memory area.

  • out

    The argument is considered as a return variable. It is appendedto the<returnedvariables> list. Usingintent(out)setsintent(hide) automatically, unless alsointent(in) orintent(inout) were used.

    By default, returned multidimensional arrays areFortran-contiguous. Ifintent(c) is used, then returnedmultidimensional arrays are C-contiguous.

  • hide

    The argument is removed from the list of required or optionalarguments. Typicallyintent(hide) is used withintent(out)or when<init_expr> completely determines the value of theargument like in the following example:

    integerintent(hide),depend(a)::n=len(a)realintent(in),dimension(n)::a
  • c

    The argument is treated as a C scalar or C array argument. Inthe case of a scalar argument, its value is passed to C functionas a C scalar argument (recall that Fortran scalar arguments areactually C pointer arguments). In the case of an arrayargument, the wrapper function is assumed to treatmultidimensional arrays as C-contiguous arrays.

    There is no need to useintent(c) for one-dimensionalarrays, no matter if the wrapped function is either a Fortran ora C function. This is because the concepts of Fortran- andC contiguity overlap in one-dimensional cases.

    Ifintent(c) is used as a statement but without an entitydeclaration list, then F2PY adds theintent(c) attribute to allarguments.

    Also, when wrapping C functions, one must useintent(c)attribute for<routinename> in order to disable FortranspecificF_FUNC(..,..) macros.

  • cache

    The argument is treated as a junk of memory. No Fortran nor Ccontiguity checks are carried out. Usingintent(cache)makes sense only for array arguments, also in connection withintent(hide) oroptional attributes.

  • copy

    Ensure that the original contents ofintent(in) argument ispreserved. Typically used in connection withintent(in,out)attribute. F2PY creates an optional argumentoverwrite_<argumentname> with the default value0.

  • overwrite

    The original contents of theintent(in) argument may bealtered by the Fortran/C function. F2PY creates an optionalargumentoverwrite_<argumentname> with the default value1.

  • out=<newname>

    Replace the return name with<newname> in the__doc__string of a wrapper function.

  • callback

    Construct an external function suitable for calling Python functionfrom Fortran.intent(callback) must be specified before thecorrespondingexternal statement. If ‘argument’ is not inargument list then it will be added to Python wrapper but onlyinitializing external function.

    Useintent(callback) in situations where a Fortran/C codeassumes that a user implements a function with given prototypeand links it to an executable. Don’t useintent(callback)if function appears in the argument list of a Fortran routine.

    Withintent(hide) oroptional attributes specified andusing a wrapper function without specifying the callback argumentin argument list then call-back function is looked in thenamespace of F2PY generated extension module where it can beset as a module attribute by a user.

  • aux

    Define auxiliary C variable in F2PY generated wrapper function.Useful to save parameter values so that they can be accessedin initialization expression of other variables. Note thatintent(aux) silently impliesintent(c).

The following rules apply:

  • If nointent(in|inout|out|hide) is specified,intent(in) is assumed.
  • intent(in,inout) isintent(in).
  • intent(in,hide) orintent(inout,hide) isintent(hide).
  • intent(out) isintent(out,hide) unlessintent(in) orintent(inout) is specified.
  • Ifintent(copy) orintent(overwrite) is used, then anadditional optional argument is introduced with a nameoverwrite_<argumentname> and a default value 0 or 1, respectively.
  • intent(inout,inplace) isintent(inplace).
  • intent(in,inplace) isintent(inplace).
  • intent(hide) disablesoptional andrequired.
check([<C-booleanexpr>])

Perform consistency check of arguments by evaluating<C-booleanexpr>; if<C-booleanexpr> returns 0, an exceptionis raised.

Ifcheck(..) is not used then F2PY generates few standard checks(e.g. in a case of an array argument, check for the proper shapeand size) automatically. Usecheck() to disable checks generatedby F2PY.

depend([<names>])

This declares that the corresponding argument depends on the valuesof variables in the list<names>. For example,<init_expr>may use the values of other arguments. Using information given bydepend(..) attributes, F2PY ensures that arguments areinitialized in a proper order. Ifdepend(..) attribute is notused then F2PY determines dependence relations automatically. Usedepend() to disable dependence relations generated by F2PY.

When you edit dependence relations that were initially generated byF2PY, be careful not to break the dependence relations of otherrelevant variables. Another thing to watch out is cyclicdependencies. F2PY is able to detect cyclic dependencieswhen constructing wrappers and it complains if any are found.

allocatable
The corresponding variable is Fortran 90 allocatable array definedas Fortran 90 module data.
external

The corresponding argument is a function provided by user. Thesignature of this so-called call-back function can be defined

  • in__user__ module block,
  • or by demonstrative (or real, if the signature file is a real Fortrancode) call in the<otherstatements> block.

For example, F2PY generates from

externalcb_sub,cb_funintegernreala(n),rcallcb_sub(a,n)r=cb_fun(4)

the following call-back signatures:

subroutinecb_sub(a,n)realdimension(n)::aintegeroptional,check(len(a)>=n),depend(a)::n=len(a)endsubroutinecb_subfunctioncb_fun(e_4_e)result(r)integer::e_4_ereal::rendfunctioncb_fun

The corresponding user-provided Python function are then:

defcb_sub(a,[n]):...returndefcb_fun(e_4_e):...returnr

See alsointent(callback) attribute.

parameter
The corresponding variable is a parameter and it must have a fixedvalue. F2PY replaces all parameter occurrences by theircorresponding values.

Extensions

F2PY directives

The so-called F2PY directives allow using F2PY signature fileconstructs also in Fortran 77/90 source codes. With this feature youcan skip (almost) completely intermediate signature file generationsand apply F2PY directly to Fortran source codes.

F2PY directive has the following form:

<commentchar>f2py...

where allowed comment characters for fixed and free format Fortrancodes arecC*!# and!, respectively. Everything that follows<commentchar>f2py is ignored by a compiler but read by F2PY as anormal Fortran, non-comment line:

When F2PY finds a line with F2PY directive, the directive is firstreplaced by 5 spaces and then the line is reread.

For fixed format Fortran codes,<commentchar> must be at thefirst column of a file, of course. For free format Fortran codes,F2PY directives can appear anywhere in a file.

C expressions

C expressions are used in the following parts of signature files:

  • <init_expr> of variable initialization;
  • <C-booleanexpr> of thecheck attribute;
  • <arrayspec>ofthe``dimension attribute;
  • callstatement statement, here also a C multiline block can be used.

A C expression may contain:

  • standard C constructs;

  • functions frommath.h andPython.h;

  • variables from the argument list, presumably initialized beforeaccording to given dependence relations;

  • the following CPP macros:

    rank(<name>)

    Returns the rank of an array<name>.

    shape(<name>,<n>)

    Returns the<n>-th dimension of an array<name>.

    len(<name>)

    Returns the length of an array<name>.

    size(<name>)

    Returns the size of an array<name>.

    slen(<name>)

    Returns the length of a string<name>.

For initializing an array<arrayname>, F2PY generates a loop overall indices and dimensions that executes the followingpseudo-statement:

<arrayname>(_i[0],_i[1],...)=<init_expr>;

where_i[<i>] refers to the<i>-th index value and that runsfrom0 toshape(<arrayname>,<i>)-1.

For example, a functionmyrange(n) generated from the followingsignature

subroutine myrange(a,n)  fortranname        ! myrange is a dummy wrapper  integer intent(in) :: n  real*8 intent(c,out),dimension(n),depend(n) :: a = _i[0]end subroutine myrange

is equivalent tonumpy.arange(n,dtype=float).

Warning

F2PY may lower cases also in C expressions when scanning Fortran codes(see--[no]-lower option).

Multiline blocks

A multiline block starts with''' (triple single-quotes) and endswith''' in somestrictly subsequent line. Multiline blocks canbe used only within .pyf files. The contents of a multiline block canbe arbitrary (except that it cannot contain''') and notransformations (e.g. lowering cases) are applied to it.

Currently, multiline blocks can be used in the following constructs:

  • as a C expression of thecallstatement statement;
  • as a C type specification of thecallprotoargument statement;
  • as a C code block of theusercode statement;
  • as a list of C arrays of thepymethoddef statement;
  • as documentation string.

Table Of Contents

Previous topic

Three ways to wrap - getting started

Next topic

Using F2PY bindings in Python

Quick search

  • © Copyright 2008-2018, The SciPy community.
  • Last updated on Jul 24, 2018.
  • Created usingSphinx 1.6.6.

[8]ページ先頭

©2009-2025 Movatter.jp