Introduction To Fortran 9095 - PowerPoint PPT Presentation

1 / 59
About This Presentation
Title:

Introduction To Fortran 9095

Description:

on the continuation line for continued character strings. Comments. Begin with ! ... with & in column 73 of the continued line and column 6 of the continuation line ... – PowerPoint PPT presentation

Number of Views:196
Avg rating:3.0/5.0
Slides: 60
Provided by: robertab6
Category:

less

Transcript and Presenter's Notes

Title: Introduction To Fortran 9095


1
Introduction To Fortran 90/95
  • Brian T. Smith
  • HPC _at_ UNM
  • University Of New Mexico

2
Introduction Fortran 90/95
  • The Fortran Language
  • A series of standards
  • 1966, 1978, 1990, 1995, 2003 (to be published)
  • Current standard is 1995
  • Compatibility (nearly) throughout the series of
    standards
  • That is, a Fortran 77 program is a Fortran 95
    program and will be a Fortran 2003 program
  • Updated and modernized to reflect current
    programming techniques
  • Continued emphasis on highly optimized executable
    code and code portability
  • Continued emphasis on features that support
    scientific and engineering applications
  • Independent compilation
  • Numeric computation
  • Parallelism
  • Library support
  • Interoperability

3
Outline Of The Fortran Workshop
  • What is the Fortran Language
  • The History of Fortran
  • The Fortran Language
  • Source forms
  • Fortran 77 Communication between program units
  • Fortran 90/95 Communication between program
    units
  • Modules
  • Nesting of Scopes
  • Interfaces
  • Control Statements

4
Outline Continued
  • Supporting Numeric Computation
  • Kinds of the intrinsic types
  • Dynamic Objects
  • Arrays
  • Pointers
  • New procedure features
  • Derived types
  • Programming Hints
  • Fortran 2003

5
The History of The Fortran Language
  • Major events
  • Began as a research project, headed by Backus,
    IBM, 1954
  • First commercial compiler 1957, IBM
  • Later releases called IBM Fortran II and Fortran
    IV in the 60s
  • First language standard completed in 1964,
    published in 1966
  • The 1966 standard is essentially IBMs Fortran IV
  • Rampant dialects occurred in the next 12 years
  • The 1978 standard was a modest change to the 1966
    standard but hardly any of the dialects adopted
  • The 1990 standard is a major enhancement
  • Many modern features, many data parallel
    constructs
  • Many features adopted from other languages
  • Some features invented/tailored for Fortrans
    niche of numerical portability and highly
    efficient executable code

6
History Continued
  • Major events continued
  • The 1995 standard
  • Fixes and clarifications to the standard
  • Several new features to support parallelism
  • The indexed parallel assignment
  • Elemental procedures
  • Scalar procedures can be used for parallel
    element by element operations
  • Pure procedures
  • The 2003 standard (in the future)
  • Interoperability with C
  • Object-oriented support and features (extensible
    types, polymorphism, SELECT TYPE)
  • IEEE Arithmetic and Exceptions support
  • Enhanced derived types (parameterized) OO
  • Derived-type I/O

7
Source Forms
  • Fortran has two source forms
  • Fixed source form old source form related to
    card-oriented systems
  • Free source form a new source form related to
    visual displays with essentially arbitrary wide
  • Recommendation
  • Quickly move to the new source form
  • All Fortran compilers support both by file or
    program unit
  • Two general ways they are selected
  • By the suffix on the file name
  • .f or .f77 implies the file contains Fortran
    code following the fixed source form
  • .f90 or .f95 implies the file contains Fortran
    code following the free source form
  • By a command line option or flag different for
    each compiler
  • The NAGWare f95 command uses fixed or free to
    designate the form
  • The PGI f90 compiler uses Mfixed and -Mfree

8
Comparison of The Two Source Forms
  • Free Source Form
  • Statements
  • Anywhere, up to 132 positions
  • Labels (dont use them)
  • Beginning, separated by from the statement
  • Continuation
  • on the continued line
  • on the continuation line for continued
    character strings
  • Comments
  • Begin with !, and at the end of any line
  • Blanks significant
  • Not allowed within tokens
  • Must be used to separate parts of statements
  • Both cases of letters allowed but are
    indistinguishable
  • Up to 31 character variable names allowed
  • Underscore can be used in identifiers
  • Semicolons used to separate statements on the
    same line
  • Fixed Source Form
  • Statements
  • Columns 7-72
  • Labels
  • Columns 1-5
  • Continuation mark
  • Column 6 of the continued line
  • Comments
  • or C in column 1
  • A line beginning with !
  • Blanks insignificant
  • Not required
  • Blanks may appear anywhere
  • Both cases of letters allowed but are
    indistinguishable
  • Up to 31 character variable names allowed
  • Underscore can be used in identifiers
  • Semicolons used to separate statements on the
    same line

9
A Common Source Form
  • There is a discipline for writing source code
    that, if followed, will be acceptable by both the
    free and fixed form front ends
  • The characters of a statement appear only in
    positions 7 through 72
  • Use ! for comments
  • Continue with in column 73 of the continued
    line and column 6 of the continuation line
  • Place labels in columns 1-5 (or dont ever use
    labels)
  • Write all statements as if blanks are significant

10
Fortran 77 Assumed Known
  • Structure of a (Fortran 77) program
  • A main program
  • A collection of subprograms
  • Functions, subroutines, block data subprograms
  • The source may be
  • All in one file, or
  • In separate files (allowing separate compilation)
  • Programs written in other languages
  • Files used for data
  • Sequential files
  • Direct access files
  • Unformatted (binary) or formatted (ASCII) files
  • Internal versus external files

11
Fortran 77 Continued
  • Data declarations
  • Intrinsic types
  • REAL, LOGICAL, CHARACTER, COMPLEX, INTEGER,
    DOUBLE PRECISION
  • Data attributes
  • DIMENSION to specify array shape
  • DATA to initialize variables with data
  • PARAMETER to defined named constants
  • EXTERNAL to define names as external functions,
    subroutines, block data programs
  • SAVE to ensure variables are static variables
  • COMMON define a global name, specifying storage
    space in memory, with locally named objects in
    the space
  • EQUIVALENCE make objects occupy the same space

12
Fortran 77 Continued
  • Program unit headers
  • FUNCTION name( arguments, )
  • SUBROUTINE name( arguments )
  • BLOCK DATA name
  • Program unit terminators
  • END
  • Executable statements
  • Assignment X ...
  • Read, write, print, rewind, endfile, inquire,
    open, close statements
  • Control constructs
  • DO
  • IF THEN ELSE ELSEIF ENDIF
  • GOTO, STOP, RETURN
  • CALL statements invoking a subroutine
  • func( actual_arguments ) invoking a function
    func

13
A Fortran 77 Program
Function, Subroutine, Block Data Subprogram
Main Program
storage association
Common /Block/
Common /Block/
Function, Subroutine
Call SUBR()
FCN()
subroutine SUBR()
argument association
  • How Fortran 77 Programs Communicate With Each
    Other
  • Essentially by address only
  • May use offsets but the offsets are determined by
    the local scope

14
A Fortran 90/95 Program
Function, Subroutine, Block Data Subprogram
Main Program
storage association
Common /Block/
USE module-name
USE module-name
Common /Block/
argument association
Call SUBR()
FCN()
Function, Subroutine
Module
subroutine SUBR()
CONTAINS
Declarations only
USE module-name
CONTAINS
Internal Procedures
Internal Procedures
USE module-name
  • How Fortran 90/95 Programs Communicate With Each
    Other 2 primary ways
  • Essentially by address only
  • May use offsets but the offsets are determined by
    the local scope
  • Essentially by name association via symbol tables
  • USE association
  • Host association

15
Modules
  • Program units that share objects
  • Data variables
  • Named constants
  • Derived type definitions
  • Interfaces
  • Procedures
  • Consists of two parts separated by the CONTAINS
    statement
  • Declaration part
  • Variables, named constants, derived type
    definitions, interfaces
  • Module procedure part
  • Functions and subroutines

16
A Simple Module Example
  • Module my_constants
  • real, parameter PI 3.14159
  • real, parameter E 2.71
  • End module my_constants
  • Program my_program
  • use my_constants, only PI
  • angle 2.0PIJ/N
  • The USE statement references the module by name
  • The options on the USE statement select only the
    name PI
  • This name could be renamed using the rename
    option as follows
  • USE my_constants, MY_PI gt PI
  • In the scope using this statement, the module
    name PI is known as MY_PI (to avoid name
    conflicts with a prior use of the name PI)

USE associated
17
A Module With Procedures
  • Module my_values
  • real, public e, pi
  • public set_values
  • CONTAINS
  • subroutine set_values
  • pi 4.0atan(1.0)
  • e exp(1.0)
  • end subroutine set_values
  • End module my_values
  • Program my_program
  • use my_values, only PI, set_values
  • call set_values
  • angle 2.0PIJ/N
  • set_values is a module procedure
  • It is defined in the module
  • It can be referenced by any code that has the
    statement USE my_values

Host associated
USE associated
18
Module Features
  • Public attribute
  • Using the public attribute, you specify that the
    identifier may be used outside the module to mean
    the module entity
  • It is only available, though, when a USE
    statement references the module and named in the
    ONLY clause, if the ONLY clause is provided in
    the USE statement
  • Private attribute
  • Using the private attribute, you specify that the
    identifier is NEVER available outside the module
  • Rename clause on the USE statement
  • Use to avoid name conflicts between the module
    and each reference to it local_name gt
    module_name
  • In each reference, the local_name is used the
    module_name is not available
  • ONLY clause on the USE statement
  • Permits only the identifiers named to be USE
    associated

19
Nesting Of Scopes
  • Examples
  • Module procedures inside modules
  • Internal procedures inside procedures or the main
    program
  • Rules
  • Identifiers declared in the outer scope are
    available (host associated) to the inner scopes
    (if not declared in the inner scope)
  • If an identifier declared in the outer scope is
    declared in the inner scope as well, the two
    identifier identify different objects
  • An identifier declared in the inner scope only is
    available only in the inner scope
  • NOTE an identifier declared in the outer scope
    can be shared in multiple inner scopes
  • Discipline when using nested scopes, use
    IMPLICIT NONE and declare ALL identifiers

20
Interfaces To Procedures
  • An interface to a procedure is
  • The number of arguments
  • The names, types, ranks, and kinds of the
    arguments
  • The order of the arguments
  • The optionality of the arguments
  • In Fortran 77, the interface is implicit
  • The compiler has to guess at the interface from
    the reference
  • Actually, it has specific rules to follow
  • Example call subr(I)
  • It assumes one argument of the type, rank, and
    kind of I, whatever that is eg integer,
    scalar, and default kind
  • In fact, this subroutine may have 2 arguments
  • Eg an array of type double precision real and an
    optional integer scalar argument

21
Interfaces Continued
  • An interface to an internal or module procedure
    is explicit in Fortran 90/95
  • Because the compiler sees the internal procedure
    definition at the same time it sees a reference,
    the compiler knows the interface
  • It knows what diagnostics to deliver, or
  • It knows how to make the arguments match
  • For an external procedure (there is no guarantee
    it sees the definition before the use of the
    procedure)
  • You can supply an interface
  • It consists of an interface block with an
    interface body
  • The block delimiters are the INTERFACE/END
    INTERFACE pair
  • The interface body is one or more procedure
    header/procedure end pairs with full declarations
    of the arguments in between

22
An Interface Example
  • interface
  • subroutine subr( A, I )
  • implicit none
  • real, dimension(,), intent(out) A
  • integer, optional, intent(in) I
  • end subroutine subr
  • end interface
  • Valid references include
  • real, dimension(10,10) b
  • integer i
  • real j
  • call subr( b )
  • call subr( b, i)
  • Invalid references include (which will be
    diagnosed by the compiler)
  • call subr( b, j) wrong type for j
  • call subr( i ) a is not optional and must be
    provided
  • call subr( b b, i ) an expression cannot
    appear as an intent(out) argument

23
Control Statements
  • The Fortran 90 control statements and constructs
    include
  • DO
  • DO WHILE (logical_expression)
  • EXIT and CYCLE
  • CASE (values), SELECT CASE ( expression )
  • DO statement
  • Use of labels is discouraged
  • The END statement for a do-body is ENDDO
  • An EXIT statement transfers to the statement
    beyond the ENDDO statement terminating the
    do-body containing the EXIT
  • A CYCLE statement causes the do-body to be
    reentered with the next value of the do-index
    variable, if there is one
  • Allows for a DO forever no WHILE or iteration
    specification
  • The loop header and ENDDO can be labeled with an
    alphanumeric identifier to identify the loop in
    an EXIT or CYCLE statement

24
DO WHILE
  • DO WHILE (logical_expression)
  • The do-body is executed repeatedly while the
    logical expression is true
  • The expression is tested at the beginning of the
    do-body
  • SELECT CASE (expression)
  • Like the C switch statement
  • Permits the selection of different blocks of code
    depending on the value of an integer, character,
    or logical expression
  • Each block of code is headed by a CASE statement,
    listing the values of the expression that cause
    the following block of code to be executed
  • A CASE DEFAULT block can be specified
  • It is a replacement for ELSE IF ladders

25
Support For Numeric Computation
  • Much of the design of Fortran 90/95/2003 is
    driven by the goal of useful, highly optimized
    code for numeric computation
  • One main principle followed throughout the
    enhancements
  • The Fortran code must be capable of a high level
    of optimization
  • Added features that support numeric computation
  • The kind parameter mechanism to support
    optimizability and numeric code portability
  • Intrinsic functions to support common numeric
    operations
  • Array features to support data parallel
    algorithms
  • Pointers that can be optimized
  • Modules to support safer, more robust computation
  • The IEEE arithmetic and exceptions handling
    module of Fortran 2003
  • The C interoperability requirements of Fortran
    2003

26
Kinds Of Intrinsic Types
  • Most CPUs support multiple kinds of the basic
    types
  • The kinds differ typically by length but may have
    other differences
  • Example
  • Integers
  • 8, 16, 32, and 64 bit integers
  • Reals
  • 32, 64, and 128 bit reals
  • Logicals
  • 1, 8, 16, 32, 64 bit logical values
  • Characters
  • 8, 16 bit character representations
  • Complex numbers
  • 64, 128 bit words with a real and imaginary part

27
Kinds Continued
  • Besides length, a more meaningful difference is
    range and precision for the arithmetic types
  • Fortran uses range and precision to specify the
    different arithmetic types
  • Fortran 90/95 introduces kinds of types to
    distinguish the different representations
  • The different kinds are distinguished by a number
    known as the kind number
  • It is like a serial number with no inherent
    meaning
  • May be (and are) different serial numbers for
    the kinds on different machines
  • A family of intrinsic functions are introduced to
    provide meaningful semantics and meaningful
    specifications of the kind numbers
  • NOTE these functions do NOT provide a dynamic
    precision control for a program

28
Default Kinds
  • Each of the 5 intrinsic types has a default kind
  • If the declaration does not specify the kind
    value, this default kind is substituted
  • Essentially, the default kind for each type is
    the Fortran 77 default datatype and rules
  • Default real, integer, logical must be the same
    size
  • Default complex and double precision are the same
    size and twice default real
  • Character sizes are not related to integer sizes
  • Real X ! Default real, no kind specified
  • Integer I ! Default integer
  • Logical L ! Default logical
  • Character CH
  • Complex C ! Default complex
  • Double precision D ! Default double precision

Size of 1 word
Size of 1 character storage unit
Size of 2 words
29
Non-default Kinds
  • After the type name, in parenthesis, is the kind
    value
  • The kind value is an integer
  • Positive to specify a legal kind value
  • Minus 1 indicates an illegal value
  • Real(1) r ! Might be the default kind
  • Real(2) d ! Might be double precision
  • Certain intrinsic functions specify kind values
  • Eg kind(0.0) is the kind value for default real
  • kind(0.0d0) is the kind value for double
    precision
  • selected_real_kind(10) is the kind value that
    supports at least 10 decimal digits of precision
  • selected_int_kind(8) is the kind value that
    supports a range of integers from -108 to 108

30
Constants Of Non-default Kinds
  • In Fortran, the form of the literal determines
    its kind value (range and precision)
  • 1.0, 2.0e-5, are default real kind constants
  • 1.0d0, 2.0d-5, are double precision kind
    constants
  • Recall that 0.1 and 0.1d0 are different numbers
    in the machine
  • Fortran 90/95 provides a second (and preferred
    way) to specify the kind of any literal constant
  • Append an underscore followed by a kind value as
    an integer literal constant or as a named
    constant
  • Examples
  • For reals, 1.0_1, 1.0_SP, 2.5e10_1, 25e-10_DP
  • Where SP and DP are named integer constants
  • For integers, 1_2, 1234_SR
  • Where SR is a named integer constants
  • For logicals, .false._onebit, .true._word
  • Where onebit and word are named integer constants

31
An Example Of Kinds
  • Module precision
  • integer, parameter WP kind(0.0d0)
  • End module precision
  • Module my_values
  • use precision, only WP
  • real(WP), public e, pi
  • public set_values
  • CONTAINS
  • subroutine set_values
  • pi 4.0_WPatan(1.0_WP)
  • e exp(1.0_WP)
  • end subroutine set_values
  • End module my_values
  • Program my_program
  • use my_values, only WP, PI, set_values
  • call set_values
  • angle 2.0_WPPIJ/N

Defines WP as a named constant with the kind
value for double precision
Declares real variables of the double precision
kind
Specifies real constants of the double precision
kind
Change the value of WP in the module precision,
recompile, and all real specifications change
type eg WP selected_real_kind(P 25)
32
Dynamic Objects
  • Fortran 90/95 has the following dynamic objects
  • Arrays
  • Allocated arrays and pointers to allocated arrays
  • Scalars
  • Pointers to scalars
  • Arrays
  • Can be created and destroyed at runtime
  • ALLOCATE and DEALLOCATE
  • Can be used in array expressions
  • Operations are element-by-element and all
    intrinsic operations are defined
  • Most of the intrinsic functions support array
    arguments
  • Pointers an attribute on any object, including
    arrays
  • The target is explicitly attached to the pointer

33
Arrays
  • Arrays have a rank, extents in each dimension,
    shape, size, and are conformable
  • The rank is the number of dimensions
  • The extent in a dimension is the number of
    elements in that dimension
  • The shape is the vector representing the extents
    in each dimension
  • The size is the product of the extents in each
    dimension
  • Eg for the declarations
  • Integer, dimension(3,4,7) array1, array2 !
    Shape (3,4,7)
  • Logical, dimension(-33,05) mask ! Shape
    (7,6)
  • Arrays of the same shape are said to conform
  • Arrays of the same shape can be operands of any
    binary operation
  • The following expressions produce an array of
    shape (3,4,7)
  • array1 array2
  • array1array2 array2
  • array1array2
  • The results are the operation applied elementwise
    to corresponding elements
  • This applies to all of the intrinsic operators
    , -, , /, , .AND., .LT.,
  • These are operations that can be performed in
    parallel because no order is specified

34
Array Operations
  • Array operations are element-by-element
  • Suppose A and B are two arrays of declared shape
    (2,3)
  • Then, C A B is the same as
  • do i 1, 2 ! But no order is specified
  • do j 1, 3 ! But no order is specified
  • C(i,j) A(i,j) B(i,j)
  • enddo
  • enddo

c11 a11b11
b11
a11


c23 a231b23
a23
b23
C
A
B
35
Array Sections
  • A section (a rectangular piece) can be formed
    using what is called the triplet notation
  • For an array A of shape (10,12)
  • A(12,12) is the upper left 2 x 2 submatrix
  • A(1102,1122) is a rectangle section made up
    of every second element in each dimension
  • A section is specified by a triplet
    lower_boundupper_boundstride
  • The stride may be negative
  • The most frequent section uses a default value of
    1 for the stride when the stride is missing

36
Array Section An Example
  • Suppose you want to perform the inner product of
    the i-th row of a matrix A by the j-th column of
    matrix B
  • Eg Declarations of A and B
  • Real, dimension(M,P) A
  • Real, dimension(P,N) B
  • A vector A(I,)B(,J) is the pairwise products
    of corresponding elements
  • There are intrinsic functions that perform lots
    of array manipulations
  • For example, sum forms the sum of the elements of
    an array
  • Thus, sum(A(I,)B(,J)) is the desired inner
    product
  • Notice also it is the (I,J) element of the matrix
    product AB
  • It is also the same result as the following loop
  • C(i,j) 0.0
  • do k 1, P
  • C(i,j) C(i,j) A(i,k)B(k,j)
  • enddo

Vector Form Of This Loop C(i,j)
sum(a(i,)b(,j))
37
Array Constructors
  • Create an arbitrary-shaped array from a 1-d array
  • One_d_array (/ list_of_values /)
  • One_d_array (/ ((IJ, I 1, 10), J 1, 10)/)
    ! Implied-DO
  • The pair (/ and /) constructs a 1-d array
  • The intrinsic function RESHAPE converts a
    1d-array into an array of any shape
  • Two_d_array reshape( one_d_array, (/10,20/) )
  • Here the shape is specified by the shape vector
    (10,20)
  • The one_d_array must have at least 200 elements
    in it
  • It may have fewer if the optional argument PAD is
    used
  • PAD represents the values used to pad out the
    array

38
And Special Array Assignments
  • Masked array assignment (WHERE)
  • A parallel array assignment selecting certain
    elements
  • A mask specifies what values are selected for
    assignment in an array assignment
  • Indexed array assignment (FORALL)
  • A parallel array assignment using specified
    indices

39
Specifying Arrays
  • Arrays are specified with declarations containing
    a DIMENSION attribute
  • Explicit-shape array (Fortran 77)
  • Real, dimension(10,20) c
  • The rank, extents, and shape are completely
    specified
  • The rank, extents, and shape of c are 2, 10, 20,
    (10,20)
  • The size is 200
  • Assumed-shape array (Fortran 90/95/2003)
  • Real, dimension(,) d
  • d must be a dummy argument
  • The rank is specified, 2 in this case
  • The extents and shape are assumed they are
    determined (the same as) by the corresponding
    actual argument
  • Deferred-shape array (Fortran 90/95/2003)
  • Real, dimension(,), allocatable e
  • The extents and shape are deferred they are
    determined by an ALLOCATE statement for e when it
    is executed
  • ALLOCATE (e(N,N4))
  • The shape is (N,N4)

40
Miscellaneous Array Features
  • An array in a procedure can be automatic
  • That is, it can be declared with a shape using
    variables that are not known until run time
  • The array is allocated on entry to the procedure
  • The array is deallocated on return and cannot be
    SAVEd
  • A function can return a whole array
  • For example, a function can be written to return
    C where C is the matrix product of A and B and
    the shape of A and B are not known until run time
  • A very large collection of array intrinsic
    functions
  • Dot_product, matmul, shape, reshape, sum, prod,
    lbound, ubound, size, any, all, maxloc, minloc,
    maxval, minval, transpose, merge, pack, unpack,
    spread, cshift, eoshift, count,

41
Pointers
  • Why have them?
  • Supports arbitrary dynamic structures
  • More and more scientific computation needs this
    capability as simulations become bigger and
    bigger
  • Recognition that high level programming
    capabilities simplify programs
  • Code becomes very complex when simulating high
    level algorithms with low level features
  • The concern that this produces potential
    execution inefficiencies that the programmer may
    be unaware of
  • Ameliorated by careful design of the language
    features so that the compiler can detect and
    avoid these inefficiencies

42
Pointers Continued
  • The principle behind Fortrans pointers
  • Distinguishes between the pointer (an address
    pointing to a target) and a target with special
    syntax for pointer operations
  • A reference without special syntax is a reference
    to the target
  • Eg Suppose PTR is a pointer to a real array
  • PTR A B
  • In the above statement, PTR is the target, not
    the pointer
  • A reference to the pointer is designated with
    special syntax
  • gt in a pointer assignment statement
  • PTR gt A
  • PTR is now pointing to the target A
  • Intrinsic function pointer arguments such as
    ASSOCIATED, ALLOCATED
  • Pointer arguments of procedures whose
    corresponding dummy argument has the pointer
    attribute

43
Other General Characteristics of Pointers
  • Strongly typed
  • No pointer arithmetic allowed
  • Automatic de-referencing in non-pointer contexts
  • The target is the object of interest in numeric
    codes, not the pointer
  • It is designed to be mostly a restricted name
    aliasing facility
  • Pointer is not a type but an attribute attached
    to an object with a type, rank, kind, and shape
  • A variable with the POINTER attribute is either
  • An address of a target called associated
  • A null value called disassociated
  • An undefined (unpredictable, not testable) value
    called undefined

44
Disassociated State
  • A pointer becomes disassociated as follows
  • It is nullified by a NULLIFY statement
  • It is assigned the result of the intrinsic
    function NULL()
  • PTR gt NULL()
  • It is deallocated explicitly or implicitly
  • Explicitly as in
  • DEALLOCATE (PTR)
  • Implicitly when leaving a procedure where it is a
    local variable
  • It is pointer-assigned to a disassociated pointer
  • PTR gt PTR_A
  • where PTR_A is disassociated

45
Associated State
  • A pointer becomes associated by
  • A pointer assignment to a target explicitly or to
    another pointer that is associated with a target
  • PTR gt A ! Here A is not a pointer but a
    target
  • PTR gt A_PTR ! Here A is a pointer pointing to
    some
  • ! target
  • An ALLOCATE statement, assigning an unnamed
    target to the pointer, by allocating space for it
  • ALLOCATE (PTR)

46
Major Uses In Scientific Computation
  • Avoiding the copy operation for large data
    structures
  • Eg large arrays
  • OLD_GRID NEW_GRID ! A large movement of data
  • NEW_GRID OLD_GRID
  • Versus
  • TEMP_PTR gt OLD_GRID
  • OLD_GRID gt NEW_GRID
  • NEW_GRID gt TEMP_PTR
  • Dynamically sized data structures
  • Arrays, particularly sparse arrays
  • Linked lists of grids for mesh refinement
  • Lists, stacks, queues, graphs, trees

47
Declaring A Linked List
  • To create a linked list, a pointer is used to
    link the elements together
  • Thus, a linked list is made up of an unknown and
    arbitrary set of elements declared as follows
  • type list_node_type
  • private
  • integer element_value
  • type( list_node_type ), pointer next
  • end type list_node_type
  • The component next is a pointer to the next node
    in the list
  • The components of the type list_node_type are
    private so that the implementation can be changed
    without effecting the programs used this derived
    type
  • The head of such a list is specified by
  • type( list_node_type ) head
  • To create an element for the list
  • type( list_node_type), pointer node
  • allocate (node)
  • headnext gt node

48
Procedure Features
  • Intents of the dummy arguments
  • IN, INOUT, OUT
  • Eg real, intent(in) x
  • If specified in the interface, it allows the
    compiler to detect illegal references to
    procedures
  • Arguments can be optional
  • If so, add optional as an attribute to the
    declaration of the argument
  • Eg integer, optional algorithm
  • An optional dummy argument must never be
    referenced at runtime unless it is present
  • Use the PRESENT(dummy_argument_name) function to
    determine if the argument is present

49
Procedure Features Continued
  • Functions and subroutines can be recursive
  • If a procedure references itself directly or
    indirectly, it must have the recursive attribute
  • EG recursive subroutine print_list( list_ptr )
  • For functions, the result clause permits one to
    disambiguate between a recursive reference and an
    assignment of the result
  • EG real function nfactorial( n ) result( res )
  • Functions and subroutines can be specified as
    pure
  • They have NO side effects
  • The compiler can optimize code around them
  • A pure procedure is limited in what features of
    the language it can use and in what it must use.
    Eg
  • No I/O
  • Intents must be specified for all arguments
  • If it is a function, all arguments must have
    intent(IN)
  • No SAVE attribute
  • See page 466, Fortran 90/95 Handbook

50
Procedure Features Continued
  • Functions and subroutines can be elemental
  • That is, a scalar procedure (a procedure with
    scalar arguments) can be called with array
    arguments that conform in shape and the procedure
    operates elementwise on each argument
  • Eg the intrinsic functions sqrt, sin, max, abs,
    are elemental
  • Sqrt(array_2d) is the same as
  • do i 1, size(array_2d,1)
  • do j 1, size(array_2d,2)
  • result(i,j) sqrt(array_2d(i,j))
  • enddo
  • enddo
  • A user-supplied function or subroutine can be
    supplied by
  • Defining a pure function or subroutine with
    scalar arguments
  • Add the elemental attribute to the header as in
  • Real elemental function erf( x )

51
Derived Types
  • A mechanism is provided to define new types
  • The new types are aggregates of components of
    other types or the same type
  • Example of complex type
  • type polar
  • real r, theta
  • end type
  • Made up from components existing intrinsic types,
    previously defined derived types, or the same
    derived type
  • An object of a derived type may be a scalar or an
    array
  • Type(polar) x
  • Type(polar), dimension(10,10) a
  • Objects of a derived type can be passed as
    arguments, appear in common blocks, appear in
    modules,

52
Derived Types Continued
  • Objects of derived type can be assigned
  • Component by component assignment
  • Operations (with infix operators) can be defined
    for objects of derived type
  • For polar, can define addition, subtraction,
    multiplication, division, exponentation, or any
    user-defined operator as a dot operation (eg.
    .ADD.) and even assignment
  • Such definitions of operations are via functions
    with explicit operator interfaces or for
    assignment, subroutines with explicit assignment
    interfaces
  • Values of derived type can be constructed with
    derived-type constructors
  • The components of a derived-type object can be
    selected with the selector

53
Derived Type Examples
  • With the polar type
  • Construct a value and assign it
  • type(polar) up, down, left, right
  • up polar(1.0,90.0)
  • down polar(1.0,270.0)
  • Selecting a component with
  • Upradius has the value 1.0
  • Downtheta has the value 270.0

Type name
List of component values
Intrinsic assignment component by component
54
Defining A Derived-Type Operation
  • To define a derived-type binary operation
  • Define a function with two intent(in) arguments
    and returns the result of the operation
  • Define an operator interface for the function
  • See the example code on the next slide
  • Notice the following
  • The definition of the polar type
  • The definition of various constants, some
    private, some public
  • The definition of the function
  • The operator interface

55
The Polar Coordinate Module
  • module polar_module
  • ! This module defines the polar type, some
    polar
  • ! constants, and some operations with operands
  • ! represented in polar coordinates.
  • ! Define the polar type.
  • type polar
  • real radius, theta
  • end type polar
  • ! Define some polar constants.
  • type(polar), parameter up polar( 1.0, 90.0
    )
  • real, parameter, private circle 360.0
  • ! Everything is public by default except the
  • ! objects declared specifically as private.

! Define operators for polar objects interface
operator( ) module procedure
polar_multiply end interface ! Define
procedures to operate on polar coordinates.
contains type(polar) function polar_multiply(
x, y ) implicit none type(polar),
intent(in) x, y intrinsic mod
polar_multiply polar( xradius yradius,
mod( xtheta ytheta, circle
) ) end function polar_multiply end module
polar_module
56
Referencing The Polar Operation
  • program test_polar
  • ! This program uses the polar module to perform
    a polar multiply on objects of type polar.
  • use polar_module
  • implicit none
  • type(polar) x, y, z
  • ! Initialize some values in polar coordinates.
  • x up y polar( 0.5, 45.0 )
  • ! Multiply two values, represented in polar
    coordinates.
  • z x y
  • print , 'x in polar coordinates is ', x
  • print , 'y in polar coordinates is ', y

57
Programming Hints
  • Use the IMPLICIT NONE statement in every program
    unit (actually scoping unit)
  • Specifies no default typing of identifiers
  • Allows the compiler to diagnose program errors
  • Particularly important when using nested scopes
    such as in modules and internal procedures in
    host procedures
  • The flush subroutine (non-standard now but )
  • Clears all I/O buffers for the specified unit
  • Helpful for an aborting program that does not
    flush its output
  • Helpful for debugging parallel MPI codes
  • Not in the Fortran 90/95 standard
  • Now in the Fortran 2003 standard as a statement
    like CLOSE

58
Programming Hints Continued
  • Prepare interface specifications for all external
    procedure references
  • The interface body is the header and end
    statement of the external procedure plus all
    declarations related to the dummy arguments
  • Use the checking options on the compiler when
    developing your code
  • For the NAGware compiler, it is C and P
  • For the PGI compiler, it is Mbounds and Mchkptr
  • For the NAGWare compiler, to ensure maximum
    checking at compile time, make sure the external
    procedures are defined lexically before they are
    first referenced

59
Additions to Fortran in Fortran 2003
  • The Fortran 2003 is compatible almost completely
    with previous Fortrans
  • That is, a Fortran 77/90/95 compiler will compile
    with the same results on a Fortran 2003 compiler
  • There are a few exceptions with the intrinsic
    functions
  • Added to Fortran in Fortran 2003
  • Interoperability requirements and support for a
    companion C compiler
  • Parameterized derived-types
  • Support of the IEEE 754 Floating-Point Arithmetic
    standard via intrinsic modules
  • Asynchronous data transfer and derived-type
    input/output
  • Command line argument processing
  • Extensive object-oriented support (inheritance,
    extensibility of types, polymorphorisms,
    procedure pointers, and type-bound procedures)
Write a Comment
User Comments (0)
About PowerShow.com