Sie sind auf Seite 1von 58

Modern Fortran (90/95/2003)

Ravi Chella

Chemical Engineering

May 10, 2016

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 1 / 58


INTRODUCTION Program Structure

Outline I

1 INTRODUCTION
Program Structure
Compiling, linking, and running a Fortran code
2 VARIABLES
Data Types
Declaration
Mathematical operators
Intrinsic functions
Relational Logical Operators
Combinational logic operators
3 CONTROL STRUCTURES
Block IF/ELSE
Example 1
DO loops
Iterative DO loops
Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 2 / 58
INTRODUCTION Program Structure

Outline II
Exercise 1
FORALL block

4 ARRAYS
Array types and Specifications
Static and Dynamic Arrays
Array operations
Multiplication and Division
Arrays and Intrinsics
Mask Operations

5 PROCEDURES
Internal Procedures
Interface Blocks
Automatic Arrays
INTENT attribute
Keyword Arguments
Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 3 / 58
INTRODUCTION Program Structure

Outline III
Optional Arguments
6 MODULES
Usage
Selective Inclusion
Implicit and Explicit Interfaces
SAVE attribute
PUBLIC and PRIVATE attributes
Modules Cascade
7 DERIVED TYPES AND OPERATORS
More Complex Derived Types
Exercise 4
Operators
Overloading
8 Input Output
OPEN Statement
Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 4 / 58
INTRODUCTION Program Structure

A simple Fortran program will typically consist of the following sections:


1 declaration: statements declaring the program name as well as

constant and variable types, names (and optionally) values.


2 execution: Statements defining actions to be performed.

3 termination: Stop

Assignment statements evaluate RHS assign to variable on LHS.


1 [PROGRAM program name ]
[ s p e c i f i c a t i o n s t a t e m e n t s ]
3 [ e x e c u t a b l e s t a t e m e n t s ]
[ CONTAINS
5 i n t e r n a l procedures ]
END [PROGRAM [ program name ] ]
7
PROGRAM t s t
9 a = 5.0
b = 3.0
11 c = a + b
END PROGRAM t s t
More generally, programs will include other components such as
procedures (subroutines & functions) and modules to be discussed later.
Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 5 / 58
INTRODUCTION Program Structure

Statement may start in any column including the first column (0-132
characters)
Statement continuation with an ampersand (&) as last character
Multiple statements can be on one line separated by semicolons (;)
Exclamation point (!) starts a comment (except in literal strings);
Everything following ! on the line is considered a comment
Blanks are not allowed in keywords or variables
Fortran is not case-sensitive: dens and DEns refer to the same
variable
exponentiation is ** not as in MATLAB
By default, array indices start at 1, not 0 as in C-type languages

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 6 / 58


INTRODUCTION Program Structure

Recommended Practices
Properly indent code.
Comment code sections and individual statements.
Use reasonably descriptive variable names.
Always initialize variables before using.
1 Follow the style guide for your research group.

The convention used below is:


1 two spaces (not tabs) for indentations
2 keywords and constants capitalized;
3 lower-case for program variables.
4 < > for user supplied
5 [ ] for optional

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 7 / 58


INTRODUCTION Compiling, linking, and running a Fortran code

A Fortran file cannot be run directly like a MATLAB or Python script.


Instead it must be converted into object code (a version of the code
that is in a machine language specific to the type of computer) by the
compiler.
Then a linker must be used to convert the object code into an
executable that can actually be executed.
This is usually split into two steps because large programs are often split
into many different .f90 files.
Each one can be compiled into a separate object file, which by default has
the same name but with a .o extension (for example, from tst1.f90 the
compiler would produce tst1.o).
One may also want to call on library routines that have already been
compiled and reside in some library. The linker combines all of these into a
single executable.
These steps can be automated using Makefiles or preferably cmake.

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 8 / 58


VARIABLES Data Types

There are five intrinsic data types:


INTEGER : : i =1 , k=20
2 REAL : : a =2.1 , b =4.633E3
LOGICAL : : s t a t =.TRUE . ! o r . FALSE
4 CHARACTER(LEN=16) : : s r= T h i s i s a s t r i n g
COMPLEX : : c =(4 ,3)

Variable names can be a combination of letters, digits, and the underscore


character; however, the first character must be a letter.

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 9 / 58


VARIABLES Declaration

Implicit: By default, Fortran takes all variables to be real except those


whose names start with the letters i through n which are taken to be
integers. However even in this case, character, logical variables and arrays
have to explicitly declared.
Explicit: Much better programming practice to explicitly declare all
variables by: IMPLICIT NONE
Declarations
REAL, <attribute> :: varname
Some important values for <attribute> are:
PARAMETER :: A variable whose value has to be set at declaration
and cannot be changed :
REAL, PARAMETER :: PI=3.1415
DIMENSION :: DIMENSION(2,3) :: AMAT explicitly sets rank/shape
(number of dimensions) and size
ALLOCATABLE ::
DIMENSION(:,:), ALLOCATABLE :: AMAT
INTENT ::INTENT(IN) or INTENT(OUT) or INTENT(IN OUT)
Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 10 / 58
VARIABLES Mathematical operators

Mathematical operators: Addition +, Subtraction -, Multiplication *,


Division /, and exponentiation **.

Hierarchy of operations:
1 Contents of expressions in parantheses, starting from innermost, to
outermost.
2 exponentials evaluated from right to left,
3 * and / evaluated from left to right,
4 + and - evaluated from left to right.

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 11 / 58


VARIABLES Intrinsic functions

Several mathematical functions are built into the Fortran language.


Function Returns
SIN(x) sine of x
ASIN(x)| ACOS(x)|ATAN(x) arcsine|arcosine|arctangent of x (radians)
ATAN2(x,y) arctangent of a complex number x+iy
SINH(x)|COSH(x)|TANH(x) hyperbolic sine|cosine|tangent of x
EXP(x) e raised to the power of x
LOG(x) natural logarithm of x
LOG10(x) logarithm to the base 10 of x
SQRT(x) square root of x
ABS(x) absolute of x
INT(x) integer part of x by truncation
REAL(x)|DBLE(x)|CMPLX(x) conversion of x to REAL|DOUBLE|COMPL
AIMAG(x) imaginary part of the complex data type x.
NINT(x) nearest integer to x
MAX(x,..) maximum of a comma separated list
MIN(x,..) minimum of a comma separated list
Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 12 / 58
VARIABLES Relational Logical Operators

New Style Old Style Meaning


== .EQ. Equal to
/= .NE. Not equal to
> .GT. Greater than
>= .GE. Greater than or equal to
< .LT. Less than
<= .LE. Less than or equal to

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 13 / 58


VARIABLES Combinational logic operators

Operator Function Result


l1 .AND.l2 Logical AND .TRUE. if both l1 and l2 are true
l1 .OR.l2 Logical OR .TRUE. if either or both l1 and l2 are true
.NOT.l1 Logical NOT .TRUE. if l1 is false, and .FALSE. if l1 is true

Combinational logic operators are evaluated after all arithmetic operations


and all relational operators are evaluated.
Parantheses can be used to change the default order of evaluation.

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 14 / 58


CONTROL STRUCTURES Block IF/ELSE

BLOCK IF
1 I F ( l o g i c a l e x p r 1 ) THEN
Statement 1
3 Statement 2
...
5 ELSE I F ( l o g i c a l e x p r 2 ) ! o p t i o n a l ( can h a v e more t h a n one )
Statement 3
7 ...
ELSE ! optional
9 Statement 4
...
11 END I F

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 15 / 58


CONTROL STRUCTURES Example 1

1 PROGRAM r o o t s
! Purpose :
3 ! T h i s program s o l v e s f o r t h e r o o t s o f a q u a d r a t i c e q u a t i o n
! ax 2+ bx+c=0
5 ! Record o f r e v i s i o n s :
! Date Programmer D e s c r i p t i o n o f Change
7 ! ==== ========== =====================
! 04/07/2016 RC O r i g i n a l code
9 IMPLICIT NONE
REAL : : a ! C o e f f i c i e n t o f x 2 term o f e q u a t i o n
11 REAL : : b ! C o e f f i c i e n t o f x term o f e q u a t i o n
REAL : : c ! C o n s t a n t term o f e q u a t i o n
13 REAL : : d ! discriminant
REAL : : r e a l p a r t ! Real p a r t ( f o r complex r o o t s )
15 REAL : : i m a g p a r t ! I m a g i n a r y p a r t ( f o r complex r o o t s )
REAL r1 , r 2 ! Solutions for real roots
17 WRITE ( , ) Q u a d r a t i c e q u a t i o n , a x 2 + b x + c = 0 , r o o t
solver
WRITE ( , ) E n t e r t h e c o e f f i c i e n t s a , b , c ( v a l u e s s e p a r a t e d
by s p a c e s )
19 READ ( , ) a , b , c
WRITE ( , ) The c o e f f i c i e n t s a , b , and c a r e : , a , b , c
Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 16 / 58
CONTROL STRUCTURES Example 1

d = b 2 4 . 0 a c ! c a l c u l a t e d i s c r i m i n a n t
2 I F ( d > 0 . 0 ) THEN ! Two r e a l r o o t s
r 1 = ( b + SQRT( d ) ) / ( 2 . 0 a )
4 r 2 = ( b SQRT( d ) ) / ( 2 . 0 a )
WRITE ( , ) Ths e q u a t i o n h a s two r e a l r o o t s : , r1 , r 2
6 ELSE I F ( d < 0 . 0 ) THEN ! c o m p l e x c o n j u g a t e r o o t s
r e a l p a r t = b / ( 2 . 0 a )
8 i m a g p a r t = SQRT( ABS( d ) ) / ( 2 . 0 a )
WRITE ( , ) T h i s e q u a t i o n h a s c o m p l e x c o n j u g a t e r o o t s :
10 WRITE ( , ) r e a l p a r t : , r e a l p a r t , i m a g i n a r y p a r t : ,
imag part
ELSE ! repeated root
12 r 1 = b / ( 2 . 0 a )
WRITE ( , ) Ths e q u a t i o n h a s r e p e a t e d r e a l r o o t s : , r 1
14 END I F
END PROGRAM r o o t s

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 17 / 58


CONTROL STRUCTURES DO loops

The general DO loop is used to repeat a block of code when it is not


known in advance how many times a block of code needs to be executed.
A logical expression is tested to exit the loop. The general syntax is:
1 DO
...
3 I F ( l o g i c a l e x p r e s s i o n ) EXIT
...
5 END DO

A special case of this is the DO WHILE loop, with the syntax:


1 DO WHILE ( l o g i c a l e x p r e s s i o n )
...
3 END DO

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 18 / 58


CONTROL STRUCTURES Iterative DO loops

Iterative DO loops are used to repeat a block of code a specified number


of times. The general syntax is:
1 DO i n d e x=i s t a r t , i e n d [ , i n c r ]
...
3 END DO

index starts with the value istart, with its value incremented by incr
each time through the loop, until index > iend.
CYCLE can be used to skip a section of code in the loop.
EXIT can be used to exit the loop
1 OUTER : DO i =1 ,5
INNER : DO j =1 ,7
3 x=r a n d ( )
I F ( x <0) CYCLE INNER ! s k i p t o end o f l o o p
5 I F ( x >1) EXIT OUTER ! e x i t l o o p
END DO INNER
7 END DO OUTER

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 19 / 58


CONTROL STRUCTURES Exercise 1

The Maclaurin (or Taylor) expansion for sin(x) gives

sin(x) = x x3 /3! + x5 /5! x7 /7! + x9 /9!...

Write a program to calculate the approximation to sin(x) given by the


series expansion and compare it with the exact value of sin(x) for various
values of x and n. Use the READ* command to input the value of x to
approximate and the number of terms n you want to use for the
approximation. At the end of your code, print out your results as follows:
1 PRINT , T h e a p p r o x i m a t i o n i s f o r x= ,x
PRINT , N u m b e r o f t e r m s i n t h e a p p r o x i m a t i o n = ,n
3 PRINT , T h e a p p r o x i m a t i o n = , sinx
PRINT , T h e t r u e v a l u e i s = , SIN ( x )
5 where s i n x i s your approximation .

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 20 / 58


CONTROL STRUCTURES FORALL block

1 [ name : ] FORALL ( i n 1= t r i p l e t 1 [ , i n 2=t r i p l e t 2 , ... , logical


expression ])
Statement 1
3 Statement 2
...
5 END FORALL [ name ]

1 FORALL ( i =1:n , j =1:m, work ( i , j ) /= 0 . 0 )


work ( i , j ) = 1 . 0 / work ( i , j )
3 END FORALL

replaces
1 DO i = 1 , n
DO j =1,m
3 I F ( work ( i , j ) /= 0 . 0 ) THEN
work ( i , j ) = 1 . / work ( i , j )
5 END I F
END DO
7 END DO

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 21 / 58


ARRAYS
An array is a collection of elements of the same data type.
Declaration: Arrays have to be declared before they are used.
Fortran supports four types of arrays: explicit-shape arrays,
assumed-shape arrays, deferred-shape arrays and assumed-size
arrays. Both explicit-shape arrays and deferred shape arrays are valid
in a main program. Assumed shape arrays and assumed size arrays
are only valid for arrays used as dummy arguments.
Deferred shape arrays, where the storage for the array is allocated
during execution, must be declared with either the ALLOCATABLE or
POINTER attributes.
The extent of an arrays dimension is the number of elements in the
dimension. Every array has properties of type rank (the number of
dimensions in the array), shape (vector representing the extents for
all dimensions) and size (product of the extents).
Storage Fortran follows a column-major convention for arrays, so
array elements are stored by column in memory.
The layout of arrays in memory is often important to know when
doing high-performance computing. It is also important to know this
in order to understand older Fortran programs.
Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 22 / 58
ARRAYS Array Types and Specifications

Explicit Shape Arrays Explicit shape arrays are defined with a specified
rank, each dimension must have an upper bound specified, and a lower
bound may be specified. Each bound is explicitly defined with a
specification of the form:
[lower-bound:] upper-bound
An array has a maximum of seven dimensions.
The following are valid explicit array declarations:
INTEGER NUM1(1,2,3) !Three dimensions
INTEGER NUM2(-12:6,10:100) !Two dimensions w lower & upper bounds
INTEGER NUM3(M:N,P:Q,L,99) !Array with 4 dimensions
There are two special cases of explicit arrays:
in a procedure, explicit arrays whose bounds are passed in from the calling
program are called automatic-arrays.
As a second type, in a procedure, where an array is a dummy array and the
bounds are passed from the calling program, is called an adjustable-array.

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 23 / 58


ARRAYS Array Types and Specifications

Assumed Shape Arrays An assumed shape array is always a dummy


argument whose bounds are determined from the actual array. Intrinsics
called from the called program can determine sizes of the extents in the
called programs dummy array. An assumed shape array has a specification
of the form:
[lower-bound] :
The number of colons (:) determines the arrays rank.
An assumed shape array cannot be an ALLOCATABLE or POINTER array.

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 24 / 58


ARRAYS Array Types and Specifications

Deferred Shape Arrays An deferred shape array is an array pointer or an


allocatable array. A deferred shape array is an array that is declared, but
not with an explicit shape. Upon declaration, the arrays type, its kind, and
its rank (number of dimensions) are determined. Deferred shape arrays are
of two varieties, allocatable arrays and array pointers. Allocatable: arrays
that are declared but for which no storage is allocated until an allocate
statement is executed when the program is running. Allocatable arrays are
declared with a rank specified with the : character rather than with
explicit extents, and they are given the ALLOCATABLE attribute.
Assumed shape array has a specification determines the arrays rank and
has the following form for each dimension:
:
For example:
INTEGER, POINTER ::NUM1(:,:,:,:)
INTEGER, ALLOCATABLE::NUM2(:)

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 25 / 58


ARRAYS Array Types and Specifications

Assumed Size Arrays An assumed size array is a dummy argument with


an assumed size. An assumed size array is a dummy array whose size is
determined from the corresponding array in the calling program. The
arrays rank and extents may not be declared the same as the original array,
but its total size (number of elements) is the same as the actual array.
This form of array should not need to be used in new Fortran
programs.
The arrays rank and bounds are specified with a declaration that has the
following form:
[explicit-shape-spec-list ,][lower-bound :]* For example:
1 SUBROUTINE YSUM1(M, B , C)
INTEGER M
3 REAL , DIMENSION (M, 4 , 5 , ) : : B , C

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 26 / 58


ARRAYS Static and Dynamic Arrays

Static arrays (on the stack)


1 D e c l a r e a 2D ( 2 x3 ) a r r a y ( by d e f a u l t a r r a y s a r e i n d e x e d
s t a r t i n g a t 1 ) \\
REAL , DIMENSION ( 2 , 3 ) :: a
3 REAL , DIMENSION ( 1 : 2 , 1 : 3 ) : : a
REAL : : a ( 2 , 3 ) , b ( 3 )
5 REAL : : a ( 1 : 2 , 0 : 3 ) , b ( 2 : 3 ) ! c h a n g e from d e f a u l t s t a r t i n g
indices

Fortran90 introduced the concept of dynamic memory allocation. To


dynamically allocate memory, it must be declared allocatable.
Allocatable arrays (on the heap)
REAL, DIMENSION(:,:), ALLOCATABLE :: a,c
ALLOCATE(a(2,3),b(n),stat=ierror)
Preferentially use ALLOCATE for large arrays.
Initialization
a = 1 ! all values of matrix a are set to 1
a(1,:) = [1,2,3] ! initialize first row
Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 27 / 58
ARRAYS Array operations

Fortran allows whole array operations and also operations on array


sections. Addition and subtraction
1 c = a + b ! a , b , and c a l l h a v e t o h a v e
c = a b ! t h e same s i z e and s h a p e
3 c ( 1 : 1 0 ) = a ( 1 1 : 2 0 )+b ( 2 : 1 1 ) ! A r r a y s e c t i o n s h a v e t o h a v e
! t h e same s i z e and s h a p e

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 28 / 58


ARRAYS Multiplication and Division

Element by element multiplication (a and b have the same size and


shape)
c = a*b

Matrix multiplication
To do matrix multiplication, you can use the intrinsic matmul
c = matmul(a,b) ! a and b have to be be compatible (No.
cols of A=No. rows of B)

For large matrices it may be more efficient to use a BLAS or Intel MKL
library function
Element by element division (a and b have the same size)
c = a/b

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 29 / 58


ARRAYS Arrays and Intrinsics

Since all array operations happen element wise, you can apply intrinsics to
an array
REAL , DIMENSION ( 1 0 , 1 0 ) : : a , b
2 REAL : : c

4 CALL random number ( a )


b = SIN ( a )
6 a = EXP( b )
c = SUM( a ) + PRODUCT( b )

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 30 / 58


ARRAYS Arrays and Intrinsics

There are many intrinsics to query arrays. For example, for:

1 INTEGER , DIMENSION ( 4 , 3 ) : : a
a ( 1 , : ) =[1 , 4 , 2 ]
3 a ( 2 , : ) =[4 , 6 , 0 ]
a ( 3 , : ) =[1 , 7 , 3 ]
5 a ( 4 , : ) =[6 , 5 , 2 ]

CALL Operation Result


SHAPE(a) array dimensions 43
SIZE(a [,dim]) number of elements 12
LBOUND(a [,dim]) lower bound of dimensions 11
UBOUND(a [,dim]) upper bound of dimensions 43
MAXLOC(a [,mask]) location of maximum value 32
MAXLOC(a, dim=2 [,mask])
MINLOC(a [,mask]) location of minimum value 23
MINLOC(a, dim=2 [,mask])

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 31 / 58


ARRAYS Mask Operations

There are also many conditional tests and masked intrinsics


1 I F ( ALL ( a == 0 . 0 ) ) WRITE ( , ) a i s z e r o
I F ( ANY ( a == 0 . 0 ) ) WRITE ( , ) a h a s a t l e a s t 1 z e r o
element
3 WRITE ( , ) a h a s , COUNT( a >= 1 . 0 ) , e l e m e n t s >= t o 1
a = MERGE( 1 . e 6 , a , a ==0.0) ! r e p l a c e z e r o s i n a w i t h 1 . e6
5 b = SUM( a , a >0.0) ! sum a l l p o s t i v i e t e r m s i n a
c = PRODUCT( a +1.0 , a >=1.0)

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 32 / 58


PROCEDURES

Procedures may be subroutines or functions.


Self-contained sub-tasks should be written as procedures.
A function returns a single value and does not usually alter the values
of its arguments
a subroutine can perform a more complicated task and return several
results through its arguments.
Procedures may be termed:
Internal - inside a program unit.
External - self contained (and not necessarily written in Fortran).
Module - contained within a module.
An Interface block is used to define the procedure argument details, and
must always be used for external procedures.

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 33 / 58


PROCEDURES Internal Procedures

Program units can contain internal procedures, which may NOT, however,
contain further internal procedures. The internal procedures are collected
together at the end of the program unit and are preceded by a CONTAINS
statement.
PROGRAM main
2 IMPLICIT NONE
REAL : : a , b , c , d
4 ...
d=add ( )
6 ...
CONTAINS
8
FUNCTION add ( )
10 IMPLICIT NONE
REAL : : add ! a , b , c , d e f i n e d i n main
12 add=a+b+c
END FUNCTION add
14
END PROGRAM main

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 34 / 58


PROCEDURES Internal Procedures

Variables defined in the program unit, remain defined in the internal


procedure, unless redefined there. It is good practice to declare all
variables used in subprograms in order to avoid the use of global variables
in the wrong context.
1 SUBROUTINE a r i t h m e t i c ( n , x , y , z )
IMPLICIT NONE
3 INTEGER : : n
REAL , DIMENSION ( 1 0 0 ) : : x , y , z
5 ...
CONTAINS
7
FUNCTION add ( a , b , c ) RESULT( sum )
9 IMPLICIT NONE
REAL , INTENT ( IN ) : : a , b , c
11 REAL : : sum
sum = a + b + c
13 END FUNCTION add

15 END SUBROUTINE a r i t h m e t i c

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 35 / 58


PROCEDURES Interface Blocks

In order to generate calls to subprograms correctly, the compiler needs to


know certain things about the subprogram, including name, number and
type of arguments. In the case of intrinsic subprograms, internal
subprograms and modules, this information is always known by the
compiler and is said to be explicit. However, when the compiler calls an
external subprogram, this information is not available and is said to be
implicit. The Fortran 90 interface block provides a means of making this
information available. The general form of the interface block is:
1 INTERFACE
i n t e r f a c e body
3 END INTERFACE
The interface body consists of the FUNCTION (or SUBROUTINE)
statement, argument type declaration statements, and the END
FUNCTION (or END SUBROUTINE) statement.
1 INTERFACE
FUNCTION f u n c ( x )
3 REAL , INTENT( IN ) : : x ! INTENT i s d e s c r i b e d i n n e x t s e c t i o n
END FUNCTION f u n c
5 END INTERFACE
Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 36 / 58
PROCEDURES Automatic Arrays

An automatic array is a local explicit-shape array with non-constant


bounds (the bounds are specified either by dummy arguments or through
data from modules.)
1 SUBROUTINE s 1 ( x , y , m, n )
IMPLICIT NONE
3 INTEGER , INTENT( IN ) : : m, n
REAL , INTENT( IN ) , DIMENSION (m, n ) : : x ! Dummy a r r a y
5 REAL , INTENT(OUT) , DIMENSION (m, n ) : : y ! Dummy a r r a y
REAL , DIMENSION (m, n ) : : temp ! Automatic a r r a y

Automatic arrays may not be initialize in their type declaration statements.


They may be passed as calling arguments to other procedures invoked by
the procedures in which they are created. However, they cease to exist
when the procedure in which they are created executes a RETURN or END
statement. A SAVE attribute should not be used for an automatic array.

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 37 / 58


PROCEDURES INTENT attribute

It is possible to specify whether a procedure argument is intended to be


used for input, output, or both, using the INTENT attribute.
INTEGER , INTENT( IN ) : : x
2 REAL , INTENT (OUT) : : y
REAL , INTENT(INOUT) : : Z

If the intent is IN, the argument value may not be changed within the
subprogram. If the intent is OUT, the argument may only be used to
return information from the procedure to the calling program. If the intent
is INOUT, then the argument may be used to transfer information in both
directions between the procedure and calling program.
1 SUBROUTINE s w a p r e a l ( a , b )
IMPLICIT NONE
3 REAL , INTENT (INOUT) : : a , b
REAL : : temp
5 temp = a
a = b
7 b = temp
END SUBROUTINE s w a p r e a l

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 38 / 58


PROCEDURES Keyword Arguments

When a procedure has several arguments, keywords are an excellent way of


avoiding confusion between arguments. The advantage of using keywords
is that you dont need to remember the order of the parameters, but you
do need to know the variable names used in the procedure.
REAL FUNCTION a r e a ( s t a r t , f i n i s h , t o l )
2 IMPLICIT NONE
REAL , INTENT( IN ) : : s t a r t , f i n i s h , t o l
4 ...
END FUNCTION a r e a

which could be called by: a=area(0.0,100.0,0.00001)


b=area(start=0.0,tol=0.00001,finish=100.0)
c=area(0.0,tol=0.00001,finish=100.0) where a, b and c are variables
declared as REAL. All arguments prior to the first keyword must match
once a keyword is used all the rest must use keywords.
Note that an interface is not required in the above example, and similarly
one would not be required for a module subprogram with keyword
arguments. This is because both have explicit interfaces. In the case of an
external procedure with argument procedures, one must be provided.
Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 39 / 58
PROCEDURES Optional Arguments

Subroutines and fuction can have optional arguments in Fortran90


1 REAL FUNCTION a r e a ( s t a r t , f i n i s h , t o l )
IMPLICIT NONE
3 REAL , INTENT ( IN ) ,OPTIONAL : : s t a r t , f i n i s h , t o l
...
5 END FUNCTION a r e a

This could be called by: a=area(0.0,100.0,0.010)


b=area(start=0.0,finish=100.0,tol=0.01) c=area(0.0)
d=area(0.0,tol=0.01) where a, b, c and d are variables declared as REAL.
The intrinsic logical function PRESENT is used to check for the presence
of an optional argument. For example, in the function example above it
may be necessary to both check for the presence of the variable tol, and
set a default if tol is absent. This is achieved as follows:
1 REAL : : t t o l
I F (PRESENT( t o l ) ) THEN
3 ttol = tol
ELSE
5 t t o l = 0.01
END I F
Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 40 / 58
MODULES
Modules provide a mechanism to package parameters, variables, arrays,
structures, functions, subroutines and interfaces together. Including a
module provides access to all public components within that module and
automatically defines interfaces to all functions and subroutines within.
MODULE module name
2 [ s p e c i f i c a t i o n s t a t e m e n t s ] ! D e c l a r e v a r i a b l e s
[ e x e c u t a b l e s t a t e m e n t s ]
4 [ CONTAINS
module p r o c e d u r e s ] ! Define s u b r o u t i n e s or f u n c t i o n s
6 END MODULE <module name>

Module procedures have exactly the same form as external procedures


except that the word SUBROUTINE or FUNCTION must be present on
the END statement.
A program or subroutine can use this module:
PROGRAM <NAME>
2 USE <MODULENAME>
! Declare v a r i a b l e s
4 ! Executable statements
END PROGRAM <NAME>
Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 41 / 58
MODULES Usage

1 MODULE msimp
REAL : : a
3 INTEGER : : b
CONTAINS
5 SUBROUTINE sub ( c , d )
INTEGER : : c
7 REAL : : d
d = d a c + b
9 END SUBROUTINE sub
END MODULE msimp

Benefits:
Allows consistency check by the compiler
Assumed-shape arrays, optional parameters, etc.

Compiling modules Modules must be compiled before any program units


that use the module.

When a module is compiled, a .o file is created, but also a .mod file is


created that must be present in order to compile a unit that uses the
module.
Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 42 / 58
MODULES Selective Inclusion

You can elect to use only certain variables/subroutines/functions from a


module
MODULE bbb
2 USE aaa , o n l y : a , b
...
4 END MODULE bbb

which only provides access to a and b from module aaa.

This is a recommended practice as it makes clear exactly what symbols are


coming from which module in the case where you use several modules.

EXERCISE 3 Write a short Fortran program to compute the integration


of 2(sin(x + y))2 over the domain 0.25 x 2.5 and 1 y 10. Then,
move the function evaluation into a module and use that module in your
main program.

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 43 / 58


MODULES Implicit and Explicit Interfaces

Multidimensional arrays can be passed to subroutines or function.


However, the subroutine or function will need to know both the number of
dimensions and the extent of each dimension. There are three possible
ways to pass this information to the subprogram:
1. Explicit-Shape Dummy Arrays The array and the extent of each
dimension of the array is passed to the subroutine.The extent values are
used to declare the size of the array in the subroutine. Since the size and
shape of each array is known it is possible to use array operations and
array sections with the dummy arrays.
2. Assumed-Shape Dummy Arrays Assumed-shape arrays are declared
by using colons as placeholders for each subscript of the array. This
requires an explicit interface. This is usually accomplished by placing the
subprogram in a module and USEing the module in the calling program.
Whole array operations, array sections and array intrinsic functions can be
used. If needed the size and extent, but not the bounds, of an
assumed-shape array can be determined by using the array inquiry
functions. If the actual bounds are needed, then an explicit shape dummy
array must be used.
Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 44 / 58
MODULES Implicit and Explicit Interfaces

3. Assumed-Size Dummy Arrays The third (and traditional) approach.


The length of all but the last dimension are declared explicitly, and the
length of the last array dimension is an asterisk. It is useful to know about
them for reading older programs, but they should never be used in any
new program.

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 45 / 58


MODULES SAVE attribute

The values of all the local variables and arrays in a procedure become
undefined whenever the procedure is exited.
The next time that the procedure is invoked, the values of the local
variables may or may not be the same as the last time the procedure was
exited.
The SAVE attribute must be used to guarantee that local variables and
arrays are saved unchanged between calls to a procedure.
1 REAL , SAVE : : a
REAL : : b =1.0 ! any v a r i a b l e t h a t i s i n i t i a l i z e d i s
a u t o m a t i c a l l y saved
3 SAVE : : v a r 1 , v a r 2 ! s a v e v a r 1 and v a r 2
SAVE ! a l l o f t h e l o c a l v a r i a b l e s w i l l be s a v e d

Dummy arguments, or data items declared with the PARAMETER


attribute may not appear associated with the SAVE attribute, or appear in
a SAVE statement.
The SAVE statement should be used in any module used to share data.

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 46 / 58


MODULES PUBLIC and PRIVATE attributes

In general it is a good idea to restrict access to any procedures or data


entities in a module to only those program units that must know about
them. This process is known as data hiding.
Objects within a module can be made publicly available or private.
MODULE o b j s
2 PRIVATE
PUBLIC : : c
4 REAL : : a
REAL , PUBLIC : : b
6 REAL , PROTECTED : : d
CONTAINS
8 SUBROUTINE c ( . . . )
...
10 END SUBROUTINE c
END MODULE o b j s

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 47 / 58


MODULES PUBLIC and PRIVATE attributes

All PUBLIC content can be used from outside of the module, i.e. by
subprograms that use the module.
PRIVATE items are only accessible from within the module.
Keywords PRIVATE or PUBLIC can stand alone, or be an attribute.
The default attribute for all data and procedures in a module is PUBLIC.
Protected variables can be accessed read-only from program units outside
the module and may be modified inside but not outside the module.
If a module contains a PRIVATE statement without a list of private items,
then by default every dtat item and procedure in the module is private.
Any items that should be public must be explicitly listed in a separate
PUBLIC statement. This is the recommended approach to design modules.

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 48 / 58


MODULES Modules Cascade

Modules can be cascaded.


1 MODULE aaa
...
3 END MODULE aaa

5 MODULE bbb
USE MODULE aaa
7 ...
END MODULE bbb
9
MODULE c c c
11 USE MODULE bbb
...
13 END MODULE c c c

Module ccc now has access to all public objects within module bbb and
module aaa

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 49 / 58


DERIVED TYPES AND OPERATORS

DERIVED TYPES Ofter more complex data types are required. Fortran90
allows this through derived types.
1 TYPE p a r t i c l e
REAL , DIMENSION ( 3 ) : : pos , v e l , a c c
3 REAL : : mass
INTEGER : : n
5 END TYPE p a r t i c l e

7 TYPE( p a r t i c l e ) : : p

9 p%mass = 1 . 0
p%n = 1
11 p%p o s = [ 1 . 0 , 2 . 0 , 4 . 0 ]
p%v e l = 0 . 0
13 p%a c c = 0 . 0

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 50 / 58


DERIVED TYPES AND OPERATORS More Complex Derived Types

Derived types may be quite complex


1 TYPE p a r t i c l e b o x
TYPE( p a r t i c l e ) , DIMENSION ( : ) , p o i n t e r :: particles
3 REAL : : l x , l y , l z
END TYPE p a r t i c l e b o x
5
TYPE( p a r t i c l e b o x ) : : box
7
ALLOCATE( box%p a r t i c l e s ( 1 0 0 ) )
9 box%p a r t i c l e s ( 1 0 )%mass = 1 . 0 d0

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 51 / 58


DERIVED TYPES AND OPERATORS Exercise 4

Write a Fortran90 program which uses a derived type to store the details
of box of particles
Length, width and height real
Number of particles integer
Mass of each particle real
Charge of each particle being -1.6*10**-19
This program should take input from the keyboard to setup the box of
particles.

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 52 / 58


DERIVED TYPES AND OPERATORS Operators

You can define your own operators with an interface block


1 MODULE a
TYPE p o i n t
3 REAL : : x , y
END TYPE p o i n t
5
INTERFACE o p e r a t o r ( . d i s t . )
7 MODULE PROCEDURE c a l c d i s t
END INTERFACE
9
CONTAINS
11
FUNCTION c a l c d i s t ( p1 , p2 )
13 TYPE( p o i n t ) : : p1 , p2
REAL : : c a l c d i s t
15
c a l c d i s t = s q r t ( ( p1%xp2%x ) 2 + ( p1%yp2%y ) 2 )
17 END FUNCTION c a l c d i s t

19 END MODULE a

which allows d=p1.dist.p2


Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 53 / 58
DERIVED TYPES AND OPERATORS Overloading

It is also possible to over load existing operators


1 MODULE aaa
TYPE p o i n t
3 REAL : : x , y
END TYPE p o i n t
5
INTERFACE o p e r a t o r (+)
7 MODULE p r o c e d u r e a d d p o i n t s
END INTERFACE
9
CONTAINS
11 FUNCTION a d d p o i n t s ( p1 , p2 )
TYPE( p o i n t ) : : p1 , p2 , a d d p o i n t s
13
a d d p o i n t s%x = p1%x+p2%x
15 a d d p o i n t s%y = p1%y+p2%y
END FUNCTION a d d p o i n t s
17
END MODULE aaa

which allows p1+p2


Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 54 / 58
Input Output OPEN Statement

The OPEN statement is used to connect a unit number to a file specifying


certain properties for that file which differ from the defaults. It can be
used to create or connect to an existing file. The OPEN statement has the
general form: OPEN (u, [olist] )
where:
u is a valid unit number specifier (with or without the keyword) olist is a
list of keyword clauses: keyword = value , keyword = value
For example:
OPEN(10)
OPEN (UNIT=10)
OPEN (UNIT=IFILE)

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 55 / 58


Input Output OPEN Statement

The following keywords are specified in the Fortran 90 language standard:


FILE=filename
where filename is a valid filename for the particular system.
STATUS=st
where st may be OLD, NEW, REPLACE, SCRATCH or
UNKNOWN. If OLD is specified the file must exist; if NEW the file
must not exist; if REPLACE and the file exists it will be deleted before a
new file is created; and if SCRATCH the file will be deleted when closed.
In general use OLD for input and NEW for output.
ERR=label
GOTO label if an error occurs opening the file.
For example:
OPEN (UNIT=10,FILE=fibonacci.out)
OPEN (UNIT=11,FILE=fibonacci.out,STATUS=NEW,ERR=10)

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 56 / 58


Input Output OPEN Statement

IOSTAT=ios
where ios is an integer variable which is set to zero if the statement is
executed successfully or to an implementation dependent constant
otherwise.
FORM=fm
where fm may be FORMATTED or UNFORMATTED, the default is
FORMATTED for sequential files and UNFORMATTED for direct
access files.
ACCESS=acc
where acc may be SEQUENTIAL or DIRECT
RECL=rl
where rl is the maximum record length (positive integer) for a direct
access file. For formatted files this is the number of characters and for
unformatted it is usually the number of bytes or words (system
dependent). BLANK=bl
where bl is either NULL or ZERO and determines how blanks in a
numeric field are interpreted.
Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 57 / 58
Input Output OPEN Statement

POSITION=pos
where pos may be ASIS, REWIND or APPEND which are interpreted
as positioning the file at the position it was previously accessed,
positioning the file at the start; and positioning the file after the previously
end of the file. Defaults to ASIS.
PAD=pad
where pad may be YES or NO. If YES formatted input is padded out
with blank characters; if NO the length of the input record should not be
exceeded.
DELIM=del
where del may be APOSTROPHE or QUOTE or NONE indicating
which character used when delimiting character expressions in list-directed
or NAMELIST output. Defaults to NONE.
ACTION=act
where act may be READ, WRITE or READWRITE specifying the
permitted modes of operation on the file. Default is processor dependent.

Ravi Chella (CBE) Modern Fortran (90/95/2003) May 10, 2016 58 / 58

Das könnte Ihnen auch gefallen