By Deniz Savas, CiCS, Shef. Univ., 2015

Slides:



Advertisements
Similar presentations
Question Bank. Explain the syntax of if else statement? Define Union Define global and local variables with example Concept of recursion with example.
Advertisements

Chapter 7 Introduction to Procedures. So far, all programs written in such way that all subtasks are integrated in one single large program. There is.
Chapter 7: User-Defined Functions II
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room A, Chris Hill, Room ,
Road Map Introduction to object oriented programming. Classes
Sub Programs To Solve a Problem, First Make It Simpler.
Fortran 9x HTML version. New F90 features Free source form Modules User-defined data types and operators Generic user-defined procedures Interface blocks.
6 April, 2000 CS1001 Lecture 15 EXAM1 - results SUBPROGRAM - - revisit FUNCTION.
27 March, 2000 CS1001 Lecture 16 FUNCTIONS SUBROUTINES SCOPE MODULES EXTERNAL SUBPROGRAMS.
Chapter 10 Modules and programming with subroutines.
FORTRAN.  Fortran or FORmula TRANslation was developed in the 1950's by IBM as an alternative to Assembly Language. First successfull high level language.
6 April, 2000 CS1001 Lecture 13 PRACTICE EXAM - revisit SUBPROGRAM FUNCTION.
Chapter 9 Introduction to Procedures Dr. Ali Can Takinacı İstanbul Technical University Faculty of Naval Architecture and Ocean Engineering İstanbul -
Chapter 12 Pointers and linked structures. 2 Introduction  The data structures that expand or contract as required during the program execution is called.
Functions. Program complexity the more complicated our programs get, the more difficult they are to develop and debug. It is easier to write short algorithms.
Fortran- Subprograms Chapters 6, 7 in your Fortran book.
Chapter 4:Functions| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2005 Slide 1 Functions Lecture 4 by Jumail Bin.
Fortran: Specification Statements Session Six ICoCSIS.
1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010.
Imperative Programming
Fortran: Program Units and Procedures Session Four ICoCSIS.
CSC141 Introduction to Computer Programming
Multi-Dimensional Arrays
MAHENDRAN CHAPTER 6. Session Objectives Explain Type of Functions Discuss category of Functions Declaration & Prototypes Explain User Defined Functions.
Scientific Computing Division A tutorial Introduction to Fortran Siddhartha Ghosh Consulting Services Group.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Functions. Type of Subprograms Fortran 90/95 allows for two types of subprograms: –Functions, and –Subroutines. In general, there are two forms of subprograms:
Module and Data Sharing. Programming in the Large Software, in general, is large having multiple units Multiple units designed and developed independently.
7 1 User-Defined Functions CGI/Perl Programming By Diane Zak.
Procedures and Modular Programming Part # 2. Interface Block ► Functions do not have to be internal to main program ► They can be stand-alone ► In this.
12. MODULES Rocky K. C. Chang November 6, 2015 (Based on from Charles Dierbach. Introduction to Computer Science Using Python and William F. Punch and.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
Introduction to Fortran95 Programming Part II By Deniz Savas, CiCS, 2007
A First Book of ANSI C Fourth Edition
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Implementing Subprograms
Operator Overloading Introduction
Chapter 9: Value-Returning Functions
Chapter 10 : Implementing Subprograms
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
User-Written Functions
VBA - Excel VBA is Visual Basic for Applications
Chapter 13: Overloading and Templates
Functions and Subroutines
Introduction to Programming
Chapter 7: User-Defined Functions II
Lesson #6 Modular Programming and Functions.
Computer Programming Fundamentals
Lesson #6 Modular Programming and Functions.
Functions and Structured Programming
Principles of programming languages 4: Parameter passing, Scope rules
The Selection Structure
Programmazione I a.a. 2017/2018.
Chapter 5 - Functions Outline 5.1 Introduction
Subroutine Comp 208 Yi Lin.
Lesson #6 Modular Programming and Functions.
CHAPTER FOUR Functions.
Implementing Subprograms
First Python Program Professor Hugh C. Lauer CS-1004 — Introduction to Programming for Non-Majors (Slides include materials from Python Programming: An.
By Deniz Savas, CiCS, Shef. Univ., 2015
Operator overloading Dr. Bhargavi Goswami
Chapter 6: User-Defined Functions I
Lesson #6 Modular Programming and Functions.
9-10 Classes: A Deeper Look.
mdul-cntns-sub-cmmnts2.f90
Introduction to C Programming
9-10 Classes: A Deeper Look.
Implementing Subprograms
Presentation transcript:

By Deniz Savas, CiCS, Shef. Univ., 2015 Introduction to Fortran95 Programming Part III By Deniz Savas, CiCS, Shef. Univ., 2015

Course Summary Program Units: Subroutines Functions Modules Common Blocks Include Statements More on Pointers

Program Units Main Program External Procedures Internal Procedures Subroutines Functions Internal Procedures Modules Common Blocks

Program Structure [PROGRAM [program_name] ] [ Data specification & declaration_statements] [executable_statements] [contains] [internal_procedures] END [ PROGRAM [program_name]

Main program containing internal procedure(s) [PROGRAM [program_name] ] [ declaration_statements] executable_statements CONTAINS [ internal procedure(s)] : END [ PROGRAM [program_name] ] Note: Everything is contained in one file.

Main program containing external procedure(s) [PROGRAM [program_name] ] [ declaration_statements] executable_statements END [ PROGRAM [program_name] ] [procedure] : Note: Procedures can be contained in separate files.

Procedures There are two types of procedures, namely SUBROUTINE and FUNCTION The only difference between a subroutine and a function is that a function returns results as its value. There is no specification difference between internal and external procedures. Functions are utilised by referencing their name in an expression where as subroutines are CALL’ed.

A typical program structure with internal procedures. PROGRAM declarations executable statements CONTAINS SUBROUTINE abc (… ) END SUBROUTINE def(…) FUNCTION ghi( … )

A typical program structure. PROGRAM declarations executable statements END SUBROUTINE abc (… ) SUBROUTINE def(…) FUNCTION ghi( … )

Subroutines SUBROUTINE name [ ( argument_list ) ] declaration executable statements END EXAMPLE: SUBROUTINE FILTER ( VOLTAGE, CURRENT) REAL , INTENT(IN) :: VOLTAGE REAL,INTENT(INOUT) :: CURRENT executable_statements

Functions [type] FUNCTION name [ ( argument_list ) ] declaration executable statements END EXAMPLE: REAL FUNCTION ENERGY ( MASS, VELOCITY) REAL , INTENT(IN) :: MASS , VELOCITY ENERGY = MASS*VELOCITY*VELOCITY

Subroutines & Functions SUBROUTINE SUB1 ( A , B , C ) REAL , INTENT(IN) :: A,B REAL INTENT(OUT) :: C : C= ….. RETURN C= …. END PROGRAM xxxx CALL SUB1( A,B,C) : : Y= FUNC1( D,E) END SENDING A and B RETURNING C RETURNING C SENDING D and E REAL FUNCTION FUNC1 ( D , E ) REAL , INTENT(IN) :: D , E : FUNC1 = ……. RETURN END RETURNING VALUE FOR FUNC1

Using Subroutines and Functions Assuming the declarations in the previous two slides, the following are valid statement which use these procedures. REAL :: VOLT(10) , CUR(10) , REAL :: MASS,V , A , ENERGY : DO I = 1, 10 CALL FILTER(V(I) , CUR(I) ) END DO A = SQRT(MASS)*ENERGY(MASS,V )

Scope of Variables The rules governing this ‘Referability’ is called the scoping rules. For any variable or label scoping rules define the parts of the program where this item is visible. Variables declared within a program or subroutine or function (referred to as ‘program units’) are accessible from anywhere within that program unit and also other program units CONTAIN’ed within it.

Scope of Variables PROGRAM TEST REAL :: BASE ,X(10) ,Y(20) CALL NORMALISE(X) CALL NORMALISE(Y) CONTAINS ! Thus the subroutine is internal to program test …. SUBROUTINE NORMALISE(ARRAY) REAL :: ARRAY(:) ARRAY = ARRAY/BASE END SUBROUTINE NORMALISE END PROGRAM TEST Variables BASE, X and Y are available for use in subroutine NORMALISE.

Scope of Variables continued … PROGRAM test REAL :: BASE ,X(10) ,Y(20) BASE = 123.4 CALL NORMALISE(X) CALL NORMALISE(Y) END program test SUBROUTINE NORMALISE(ARRAY) REAL :: ARRAY(:) ARRAY = ARRAY/BASE END subroutine normalise None of the variables BASE,X or Y are available in the subroutine NORMALISE. Because BASE is not available, this program will not work!

When should I use Internal Procedures PREFER AN INTERNAL PROCEDURE; If it is needed to be called from only one program unit. If you are accessing a lot of variables which will make the argument list rather large. If you do not want that routine to be available from any other routine. Otherwise use the EXTERNAL form

Subroutine & Function Arguments Arguments enable data exchange between the calling/ invoking and the called/invoked subroutine/function. The way the data is exchanged can be specified more precisely by the following keywords. Intent : Defines the ability to modify the arguments. Keyword : Enables us to pass arguments in an order independent way. Optional : Allows us to make some arguments optional. Recursive, Result : Needed for recursive invocation. Array valued functions allow array values to be returned.

The Use of Intent Attribute SUBROUTINE DISTANCE( P1 , P2 , DIST,N) INTEGER , INTENT(IN) :: N REAL ,INTENT(IN) :: P1(N) , P2(N) REAL , INTENT(OUT) : DIST DIST = 0.0 DO I = 1 , N DIST = DIST + ( P1(I) -P2(I) ) **2 END DO DIST = SQRT ( DIST ) RETURN END

Intent Examples cont. REAL FUNCTION SWAPNSUM ( A , B ) REAL , INTENT(INOUT) : A , B REAL :: TEMP TEMP = A A = B B = TEMP SWAPNSUM = A + B END

Using Keyword Arguments INTERFACE SUBROUTINE GETDET ( AREA , DENSIT ,C , D , ELEV ) REAL, OPTIONAL,INTENT(INOUT) :: AREA,DENSIT,C,D,ELEV END SUBROUTINE GETDET END INTERFACE : CALL GETDET ( X,Y,Z,W,Q ) CALL GETDET ( X,Y, ELEV=Q,D=W, C=Z) CALL GETDET ( AREA=X,DENSIT=Y ,ELEV=Q ,C=Z,D=W) ! All above three calls are identical in effect.

Optional Arguments OPTIONAL & KEYWORD ARGUMENTS CALL GETDET(V,W, X,Y,Z ) CALL GETDET(V,W,X) CALL GETDET( C=X, ELEV=Z ) CALL GETDET(V,W,D=Y) : SUBROUTINE GETDET ( AREA , DENSIT ,C , D , ELEV ) REAL, OPTIONAL,INTENT(INOUT) :: AREA,DENSIT,C,D,ELEV END

Always Use INTERFACE to declare External Routines with Optional Arguments PROGRAM MAIN INTERFACE SUBROUTINE SOLVE ( A , B ,C , D , E ) REAL , OPTIONAL, INTENT(INOUT) :: A,B,C,D,E END SUBROUTINE SOLVE FUNCTION ZZZ : END FUNCTION ZZZ END INTERFACE CALL SOLVE ( NEWX , E=DELTA_SOFAR )

USE function PRESENT to check the presence of an optional argument SUBROUTINE SOLVE ( A , B ,C , D , E ) REAL , OPTIONAL, INTENT(INOUT) :: A,B,C,D,E : IF ( PRESENT( D) ) THEN DD = D ELSE DD = 0.001 ENDIF END

Result Clause & Recursive Functions RECURSIVE FUNCTION FACTORIAL ( N ) RESULT (MULT) INTEGER :: MULT INTEGER, INTENT(IN) :: N IF( N = = 1 ) THEN MULT = 1 ELSE MULT = N*FACTORIAL( N-1) ENDIF RETURN END ! Note: INTEGER RECURSIVE FUNCTION( ...) is also valid syntax.

Array Valued Functions FUNCTION NORM( A ) REAL, INTENT=IN :: A REAL , DIMENSION(SIZE(A) ) :: NORM REAL : MINI , MAXI MINI = MINVAL(A) MAXI = MAXVAL(A) IF ( MINI - MAXI .LE. 0.0 ) THEN NORM = 0.0 ELSE NORM = ( A - MINI) / (MAXI-MINI) RETURN END FUNCTION NORM

Exercises on PC platforms We shall use the Salford FTN95 compiler. Integrated development environment is PLATO. Just as easy to develop using COMMAND SHELL and a few commands: ftn95 filename.f95 /link ( to compile and link ) filename (to run the executable filename.exe) ftn95 filename.f95 /debug (to compile for debugging) sbdg filename.exe ( start the debugger ) (1) Try compiling fortran_examples/ex7.95 - Now run it. - Now run it with the debugger (2) Repeat it for example 9a

Common Blocks Common blocks can be used to make a set of variables available to a selected set of program units without having to use INTERNAL program units. Syntax: COMMON /name/ variables_list EXAMPLE: REAL :: ARATIO , RATE(10,10) INTEGER :: TEMP COMMON /RATIOS/ ARATIO, RATE, TEMP

Common Blocks Variables which are declared to be in a COMMON BLOCK can be made available to any program unit by declaring the same set of variables and the common block. A common block is a continuous area of memory where the variables are stored in the order of declaration in the COMMON statement, rather than the names. Therefore it is vitally important to keep to the same order in all declarations of the same COMMON BLOCK.

Common Blocks & INCLUDE Files To avoid mistakes use INCLUDE files. INCLUDE statement is not part of the FORTRAN specifications but all known compilers accept it. The statement: INCLUDE ‘filename’ makes the compiler read the contents of the specified file at that point, pretending that it is all part of the source inserted at that point.

Common Blocks & INCLUDE Files By putting the declarations for all the variables within a common block and the COMMON statement which follows it into a file and using the INCLUDE ‘filename’ statement in every subroutine or function which uses that common block, we can ensure that there are no problems arising from misspelling or mis-declaration of common block variables.

INCLUDE: examples Create a file called RATIOS.INC which contains the following set of lines. REAL :: ARATIO , RATE(10,10) INTEGER :: TEMP COMMON /RATIOS/ ARATIO, RATE, TEMP Now in every program unit where you intend to use this common block simply add the line: INCLUDE ‘RATIOS.INC’ within the declarations section.

MODULES Think of Modules as the next generation of the COMMON BLOCKS concept. The idea of common blocks was to make the same set of variables available to as many different routines as required. Modules take this concept further to make a set of variables ( and optionally subroutines&functions which act on that data) available in a unified manner. Modules can also deliver the functionality that INCLUDE statements have provided in the past.

Module Example MODULE DECK INTEGER :: CARD(52) , LASTONE , ACARD CONTAINS SUBROUTINE DRAWONE( ACARD ) INTEGER ACARD LASTONE = LASTONE - 1 IF ( LASTONE.LE.0 ) LASTONE = 52 ACARD = CARD(LASTONE) RETURN END SUBROUTINE DRAWONE END MODULE DECK

Module Example continued … SUBROUTINE DEAL USE DECK : CALL DRAWONE(ACARD) END Note: Modules are also useful for containing the INTERFACE definitions.

Use Statement Syntax .. SYNTAX: USE module EXAMPLE: USE module , renamelist USE module, ONLY :namelist where; renamelist is newname=>oldname This form of usage is needed when there is a chance of a clash of local names with the variable of procedure names in a USEd module. EXAMPLE: SUBROUTINE DEAL REAL :: drawone USE DECK, GETNEXT=> DRAWONE : CALL GETNEXT(acard) END

Use statement syntax .. ONLY Clause is useful when only a sub-set of names defined in a module is to be used and the others remained invisible. Example: MODULE PHY_CONSTANTS REAL :: G = 9.81 REAL :: PLANK = 6.624E-27 REAL :: C = 2.99796E8 END MODULE PHY_CONSTANTS SUBROUTINE CALC : USE PHY_CONSTANTS, ONLY : G

Operator Overloading Operator overloading means extending the definition of intrinsic operators when they are applied to user-defined-types. For example:*,+,-,/ are intrinsic operators and their effect when applied to intrinsic types ( ie REAL,INTEGER etc.) are clear ( and can not be changed ). But we have the freedom to define the meaning of *,/,+ etc. when we apply them to user defined types.

operator overloading cont... EXAMPLE: MODULE CHAR_FEATURES : INTERFACE OPERATOR(+) MODULE PROCEDURE joinup END INTERFACE CONTAINS FUNCTION joinup( str1,str2) CHARACTER*(*) , INTENT(IN) :: str1 , str2 CHARACTER(LEN=LEN_TRIM(str1)+LEN_TRIM(str2):: joinup joinup = TRIM(str1)//TRIM(str2) END FUNCTION joinup END MODULE CHAR_FEATURES We can now write astring = bstring+cstring

operator overloading cont... We can also define completely new operations and apply them to all ( intrinsic and user-defined ) types: A user defined operator have the syntax: .name. for example .sum. , .invert.

Defining a New Operator MODULE GEOM TYPE POINT REAL :: X,Y END TYPE POINT INTERFACE OPERATOR ( .DIST. ) MODULE PROCEDURE CALCDIST END INTERFACE CONTAINS REAL FUNCTION CALCDIS( P1,P2) TYPE(POINT),INTENT(IN) :: P1 , P2 CALCDIS = SQRT((P1%X-P2%X)**2+(P1%Y-P2%Y)& **2 ) END FUNCTION CALCDIST END MODULE GEOM

continued... use geom type(point) :: vertex(100) , origin We can now use this module in a program to calculates the distance between points. program main use geom type(point) :: vertex(100) , origin real :: distance(100) , odist : odist (i) = vertex(i).dist.origin distance(i) = vertex(j) .dist. vertex(k)

More about Pointers INTEGER, POINTER :: IVAR , JVAR REAL, DIMENSION(:), POINTER:: RVEC REAL, DIMENSION(:,:),POINTER :: RMATRX Pointers can point to existing variables or They can be given fresh storage

Pointing To Existing Variables REAL ,POINTER :: P1 , P2 REAL ,TARGET :: T1 = 1.0 , T2 = 2.0 P1 => T1 ; P2 => T2 P2 = P1 ! an ordinary assignment.copy contents of ! p1 into the location pointed by p2. P2 => P1 ! a pointer assignment ! ! p1 t1 ! p2 1.0

Pointer Assignment array pointers REAL,DIMENSION(:),POINTER :: P REAL,DIMENSION(0:9),TARGET :: T REAL :: X(10) , Y(5) P => T ; X=P ! x(1:10) is set to t(0:9) P => T(:) ; X(1)=P(1) ! x(1) will be set to t(0) P => T(0:8:2) ; Y=P ! y(1)=t(0),y(2)=t(2) ... Pointers can be used just like variables in expressions. e.g. Y = 0.5*sin(P)

Pointer Status UNDEFINED - as at start of the program NULL – Exists but not associated with anything yet. ASSOCIATED – It is associated with a target: points to something! REAL,POINTER :: P REAL,TARGET :: T ,U ,V NULLIFY(P) P => T PRINT * , ASSOCIATED(P ) ! .TRUE. P => U ! We decides to point P to U from now on.

Allocating Memory To Pointers REAL POINTER , DIMENSION(:,:) :: WORK : N = 111 ALLOCATE ( WORK(N,N) ) : !use (work) as an array pointer. DEALLOCATE( WORK ) RETURN END Note: When a pointer is declared so as to access an array, only the shape of the array it will point to should be specified by the DIMENSION statement.

Pointer Arguments INTERFACE SUBROUTINE sub1 (B ) REAL DIMENSION(:,:) :: B END SUBROUTINE sub1 SUBROUTINE sub2( B ) REAL,DIMENSION(: , :),POINTER :: B END SUBROUTINE sub2 END INTERFACE REAL DIMENSION(:,:) :: AMATRX REAL DIMENSION(:,:) , POINTER :: WORK ALLOCATE( WORK(20,40) ) ALLOCATE ( AMATRX(20,30) CALL SUB1(AMATRX) ! No pointers involved or needed (usually the case) CALL SUB1(WORK) ! in sub1 work is an array. CALL SUB2(WORK) ! in sub2 a pointer to an array.

Acknowledgement &References: Thanks to Manchester and North High Performance Computing, Training & Education Centre for the Student Notes. See APPENDIX A of the above notes for a list of useful reference books Fortran 90 for Scientists and Engineers, Brian D Hahn, ISBN 0-340-60034-9 Fortran 90 Explained by Metcalf & Reid is available from Blackwells ‘ St Georges Lib.’ Oxford Science Publications, ISBN 0-19-853772-7

THE END