1 / 72

Introduction to Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Introduction to Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University dsavas@clemson.edu. Summary of Part 3. Program Units: Subroutines Functions Modules Common Blocks Include Statements More on Pointers Input/Output and File Handling. Program Units.

Download Presentation

Introduction to Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University dsavas@clemson.edu

  2. Summary of Part 3 • Program Units: Subroutines Functions Modules Common Blocks Include Statements • More on Pointers • Input/Output and File Handling

  3. Program Units • Main Program • External Procedures • Subroutines • Functions • Internal Procedures • Subroutines • Functions • Modules • Common Blocks

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

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

  6. Main program containing external procedure(s) [PROGRAM[program_name] ] [ declaration_statements] executable_statements END [ PROGRAM [program_name] ] [procedure] : [procedure] ! Procedure= function or subroutine. ! Note that procedures can be contained in separate files.

  7. 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.

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

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

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

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

  12. 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 )

  13. 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.

  14. Scope of Variables PROGRAM TEST REAL :: BASE ,X(10) ,Y(20) BASE = 123.4 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 All variables BASE, X and Y are available for use in subroutine NORMALISE.

  15. 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!

  16. 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

  17. 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.

  18. 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

  19. 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

  20. Using Keyword & OPTIONAL 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.

  21. Optional Arguments OPTIONAL Arguments and & Keyword Arguments cont.. 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

  22. 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 )

  23. 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

  24. 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.

  25. 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 - MIN) / (MAX-MIN) RETURN END FUNCTION NORM

  26. 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

  27. 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.

  28. 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.

  29. 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.

  30. 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.

  31. MODULES • Think of Modules as the next step from 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.

  32. Module Example MODULE DECK INTEGER :: CARD(52) , LASTCARD 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

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

  34. USE Statement Syntax .. SYNTAX: USE module USE module , renamelist USE module, ONLY :namelistwhere; 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 END

  35. USE statement continued.. 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

  36. 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.

  37. 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

  38. 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.

  39. 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

  40. Defining operators continued... 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)

  41. 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

  42. 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 ! p2 into the location pointed by p2. P2 => P1 ! a pointer assignment ! ! p1 t1 ! p2 1.0

  43. Pointer Assignmentarray pointers REAL,DIMENSION(:),POINTER :: P REAL,TARGET :: T(0:9) 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) ...so on Pointers can be used just like variables in expressions. e.g. Y = 0.5*sin(P)

  44. 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.

  45. 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.

  46. 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.

  47. Input/Output Data can be read into the program by means of the READ statement, the simplest syntax of which is: READ( unit , format ) list Where;unit is either UNIT= n or n , n being an integer representing the input channel number and format is FMT=format_labeloracharacter string/variableand list is the list of variables to read into. Similarly data output from a program is achieved by means of the WRITE or PRINT statements the simplest syntax of which is: WRITE(unit,format,) list PRINT format , list

  48. Input/Output • READ and WRITE examples: READ(*,*) N READ( 5,* ) N READ(UNIT=5,100) N 100 FORMAT( I8 ) READ(UNIT=5,FMT=110) A 110 FORMAT( F12.4 ) Substituting WRITE for READ in the above statements will yield a valid WRITE statements with the data flowing in the opposite direction.

  49. Examining the I/O units Write(*, …. ) Fortran program Read(*, … ) or Print … • A Fortran program will always have default connections to the standard input and standard output. In the case of an interactive job this will be Screen and Keyboard as shown here. • * Will always imply default i/o. Different compilers associate different unit ‘channel’ numbers with default i/o devices. Usually 5 => keyboard , 6=>display • Therefore ( READ(5, … means READ(*, … ) and WRITE(6,.. ) means WRITE(*,…)

  50. Reading from a file Fortran program Data.fil Open( Unit=12,File=‘data.fil’,action=‘read’) READ(12, … ) READ(12, … ) READ(12, … ) REWIND( UNIT=12 ) CLOSE( UNIT=12 )

More Related