A quick overview of Fortran 90 by hcw25539

VIEWS: 19 PAGES: 45

									                       Department of Earth Sciences
                            The University of Bergen




A quick overview of Fortran 90

           C. Thieulot



         September 2008




       / Madrid workshop 2008                          1/45
                                             Department of Earth Sciences
                                                  The University of Bergen




For instance, I will not cover
    pointers
    I/O
    fortran 95 features
    ...




                             / Madrid workshop 2008                          2/45
                                          Department of Earth Sciences
                                               The University of Bergen


Fortran History

   Fortran : a blend word derived from The IBM Mathematical Formula
   Translating System
   in continual use for over half a century in computationally intensive
   areas (climate modelling, numerical weather prediction, CFD,
   computational physics, ... )
   one of the most popular languages in the area of High-performance
   computing (HPC)
   FORTRAN (1956), FORTRAN II,III (1958), FORTRAN IV (1961)
   FORTRAN 66, FORTRAN 77
   FORTRAN 90, FORTRAN 95
   FORTRAN 2003, 2008


                          / Madrid workshop 2008                           3/45
                                           Department of Earth Sciences
                                                The University of Bergen


Introduction

            "I don’t know what the technical characteristics of
           the standard language for scientific and engineering
          computation in the year 2000 will be... but I know it
                         will be called Fortran."

                                                      John Backus
   Language of choice for Scientific programming
   Large installed user base.
   Fortran 90 has most of the features of C . . . and then some
   Principal language on the IBM SP Supercomputer and all Cray
   machines
   The compilers produce better programs

                           / Madrid workshop 2008                          4/45
                                         Department of Earth Sciences
                                              The University of Bergen


Survey of the New Fortran Standard



   Fortran 90 has many new features that make it a modern and robust
   language for numerical programming.
   Fortran 90 contains Fortran 77 as a subset
   ⇒ all Fortran 77 programs can be compiled and should produce
   identical results.
   a few aspects of Fortran 77 have been labeled as obsolete and may be
   removed from the next standard




                         / Madrid workshop 2008                          5/45
                                           Department of Earth Sciences
                                                The University of Bergen


New Source Form (1)

   Fortran statements may now appear anywhere on a source line,
   columns are no longer reserved.
   The semicolon, ‘ ;’, is used as a statement separator




                           / Madrid workshop 2008                          6/45
                                         Department of Earth Sciences
                                              The University of Bergen


New Source Form (2)

   Line continuation has also been improved and uses the & character at
   the end of source line to be continued.
   Trailing comments may be used and begin with a ‘ !’ character and
   continue to the end of the source line.




                         / Madrid workshop 2008                          7/45
                Department of Earth Sciences
                     The University of Bergen




/ Madrid workshop 2008
                                               Department of Earth Sciences
                                                   The University of Bergen


Array processing (1)


    whole array operations, masked assignment, array sections are part of
    the Fortran 90 standard. ⇒ These types of constructs are important for
    parallel and vector computers.
    Arithmetic and logical operations work elementally on arrays :
    Ex :
      •   C = A + B calculates the sum of two matrices, element-by-element,
          storing the result in C.
      •   Z = (A>0) creates a logical array with elements whose entries are .true.
          where the elements of A are greater than 0 and .false. elsewhere.
    most of the intrinsic functions act elementally on arrays :
    log(A) applies the scalar log function to each element in A



                              / Madrid workshop 2008                           9/45
                                         Department of Earth Sciences
                                               The University of Bergen


Array processing (2)

    Declaration :
    real,   dimension(10)          ::   tab1
    real,   dimension(-5:12)       ::   tab2
    real,   dimension(5,14)        ::   tab3
    real,   dimension(-1:7,5:18)   ::   tab4
    Constructors :
    real, dimension(5) :: tab1
    tab1 = (/ 1,2,5,4,8 /)
    tab1 = (/ (i,i=1,5) /)
    tab1 = (/ (i,i=1,9,2)/)
    do i=1,5
       tab1(i)=...
    end do


                         / Madrid workshop 2008                           10/45
                                          Department of Earth Sciences
                                               The University of Bergen


Array processing (3)

    Arrays may now be dynamically allocated at run-time using pointers or
    allocatable arrays.
program example
   real, dimension (:,:), allocatable :: A
   integer n
   print *, ’Enter an integer for the array dimension: ’
   read *, n

   allocate(A(n,n)) ! Dynamically allocate an n x n matrix.
   ...
   use matrix A
   ...

   deallocate(A)
end program example



                          / Madrid workshop 2008                          11/45
                                                            Department of Earth Sciences
                                                                The University of Bergen


Array processing (4)
     the memory requirements scale with the number of particles
  program example_sph_code

  real, dimension (:), allocatable :: x,y,u,v,rho,p,ax,ay
  integer nx,ny

  print *, ’Enter nx, the nb of SPH ptcls in x direction’
  read *, nx
  print *, ’Enter ny, the nb of SPH ptcls in y direction’
  read *, ny

  np=nx*np   ! compute total number of particles

  allocate(x(np),y(np)
  allocate(u(np),v(np))
  allocate(ax(np),ay(np))
  allocate(rho(np),p(np))
  ...
  use arrays x,y,u,v,ax,ay,p,rho
  ...
  deallocate(x,y)
  deallocate(u,v)
  deallocate(ax,ay)
  deallocate(rho,p)

  end program example_sph_code




                                        / Madrid workshop 2008                             12/45
                                         Department of Earth Sciences
                                                    The University of Bergen


Nesting of subprograms
                               main program




                             internal subprograms




                   / Madrid workshop 2008                                      13/45
                                         Department of Earth Sciences
                                                    The University of Bergen


Nesting of subprograms
                               main program                external subprogram




                             internal subprograms




                   / Madrid workshop 2008                                        14/45
                                                    Department of Earth Sciences
                                                               The University of Bergen


Nesting of subprograms
                     module               main program                external subprogram




         module
       subprograms




                                        internal subprograms




                              / Madrid workshop 2008                                        15/45
                                          Department of Earth Sciences
                                               The University of Bergen


A- Main program


   program prog_name

   ...

   contains

   ...[internal subprograms]

   end program prog_name

   the ’contains’ statement flags the presence of one ot more internal
   subprograms


                          / Madrid workshop 2008                          16/45
                                          Department of Earth Sciences
                                               The University of Bergen


B- External subprograms

    subroutine subr_name
    ...
    contains
    ...[internal subprograms]
    end subroutine subr_name


    function fct_name
    ...
    contains
    ...[internal subprograms]
    end function fct_name

   the ’contains’ statement flags the presence of one ot more internal
   subprograms
                          / Madrid workshop 2008                          17/45
                                          Department of Earth Sciences
                                               The University of Bergen


C- Modules



   module mod_name
   ...
   contains
   ...[internal subprograms]
   end module mod_name

   the ’contains’ statement flags the presence of one ot more internal
   subprograms




                          / Madrid workshop 2008                          18/45
                                      Department of Earth Sciences
                                           The University of Bergen


D- Internal subprograms



    subroutine subr_name
    ...
    end subroutine subr_name


    function fct_name
    ...
    end function fct_name




                      / Madrid workshop 2008                          19/45
                                          Department of Earth Sciences
                                               The University of Bergen


Modules (1)


   Common blocks in Fortran 77 were the only portable means of achieving
   global access of data throughout a collection of subprograms
   ⇒ unsafe, error-prone, encourages bad programming practices
   Fortran 90 provides a new program unit, a module, that replaces the
   common block
   it also provides many other features that allow modularization and data
   hiding, key concepts in developing large, maintainable numerical code.
   Modules provide a means of packaging global data, derived types and
   their associated operations, interface blocks, and namelist groups.




                          / Madrid workshop 2008                          20/45
                                          Department of Earth Sciences
                                               The University of Bergen


Modules (2)



   Modules consist of a set of declarations and module procedures that are
   grouped under a single global name available for access in any other
   program unit via the use statement.
   Interfaces to the contained module procedures are explicit and permit
   compile time type-checking in all program units that use the module.
   Visibility of items in a module may be restricted by using the private
   attribute.




                          / Madrid workshop 2008                          21/45
                                       Department of Earth Sciences
                                           The University of Bergen


Modules (3)


module constants
double precision, parameter   ::   pi = 3.14159265358979323846264338
double precision, parameter   ::   Rgas = 8.31447215d0 !J.K-1.mol-1
double precision, parameter   ::   sqrt2 = 1.414213562373095048801688
double precision, parameter   ::   sqrt3 = 1.732050807568877293527446
end module constants

program physics
use constants

...

end program physics


                      / Madrid workshop 2008                          22/45
                                                Department of Earth Sciences
                                                      The University of Bergen


Modules (4)

                                          module magic
module magic
                                             type bag_of_tricks
   type bag_of_tricks
                                                real rtrick
      real rtrick
                                                integer itrick
      integer itrick
                                             end type bag_of_tricks
   end type bag_of_tricks
                                          end module magic
   type(bag_of_tricks) show
end module magic
                                          program tonight
                                          use magic
program tonight
                                          type(bag_of_tricks) show
use magic
                                          call rehearse (show)
call rehearse
                                          call perform (show)
call perform
                                          end program tonight
end program tonight
                                          subroutine rehearse (show)
                                          use magic
subroutine rehearse
                                          type(bag_of_tricks) show
use magic
                                          show%itrick = 1
show%itrick = 1
                                          show%rtrick = 0.333
show%rtrick = 0.333
                                          end subroutine rehearse
end subroutine rehearse
                                          subroutine perform (show)
subroutine perform
                                          use magic
use magic
                                          type(bag_of_tricks) show
print *,show%itrick
                                          print *,show%itrick
print *,show%rtrick
                                          print *,show%rtrick
end subroutine perform
                                          end subroutine perform



                              / Madrid workshop 2008                             23/45
                                                            Department of Earth Sciences
                                                                  The University of Bergen


Modules (5)

                                                      module magic
                                                         type bag_of_tricks
module magic
                                                            integer, dimension(:), allocatable :: iarray
   type bag_of_tricks
                                                         end type bag_of_tricks
      integer, dimension(:), allocatable :: iarray
                                                      end module magic
   end type bag_of_tricks
   type(bag_of_tricks) show
                                                      program tonight
end module magic
                                                      use magic
                                                      type(bag_of_tricks) show
program tonight
                                                      allocate(show%iarray(7))
use magic
                                                      call rehearse (show)
call rehearse
                                                      call perform (show)
call perform
                                                      end program tonight
end program tonight
                                                      subroutine rehearse (show)
subroutine rehearse
                                                      use magic
use magic
                                                      type(bag_of_tricks) show
allocate(show%iarray(7))
                                                      show%iarray = (/(i,i=1,7)/)
show%iarray = (/(i,i=1,7)/)
                                                      end subroutine rehearse
end subroutine rehearse
                                                      subroutine perform (show)
subroutine perform
                                                      use magic
use magic
                                                      type(bag_of_tricks) show
print *,show%iarray
                                                      print *,show%iarray
end subroutine perform
                                                      end subroutine perform




                                          / Madrid workshop 2008                                      24/45
                                                                   Department of Earth Sciences
                                                                       The University of Bergen


Modules (6)

module TypicalModule
   private swap   ! Make swap visible only within this module.
   contains
   subroutine order( x, y )   ! Public by default.
      integer, intent( inout ) :: x, y
      if ( abs( x ) < abs( y ) ) call swap( x, y )
   end subroutine order
   subroutine swap( x, y )
      integer, intent( inout ) :: x, y
      integer tmp
      tmp = x; x = y; y = tmp ! Swap x and y.
   end subroutine swap
end module TypicalModule

program UseTypicalModule
   use TypicalModule
   integer :: x = 10, y = 20   ! Declare and initialize x and y.
   print *, x, y
   call order( x, y )
   print *, x, y
end program UseTypicalModule




                                        / Madrid workshop 2008                                    25/45
                                          Department of Earth Sciences
                                               The University of Bergen


Derived Types and Generic Functions (1)


   Derived or user-defined types, similar to records or structures in other
   languages, are available in Fortran 90.
   Derived types are built from the intrinsic types or other derived types
   and allow the creation of data types that behave as if they were
   intrinsic types.
   Generic functions help to make the support for derived data types
   complete :
   A generic function such as ‘+’ may be extended to operate directly on a
   derived type




                          / Madrid workshop 2008                          26/45
                                          Department of Earth Sciences
                                               The University of Bergen


Derived Types and Generic Functions (2)

   A derived type may have a component that is of a previously defined
   derived type :
   type point
      real x,y,z
   end type point

   type triangle
      type(point) A,B,C
   end type triangle

   A variable of type triangle may be declared thus
   type (triangle) T

   T has components T%A, T%B and T%C
   T%A has components T%A%x,T%A%y, and T%A%z


                          / Madrid workshop 2008                          27/45
                                                                Department of Earth Sciences
                                                                         The University of Bergen


Derived Types and Generic Functions (3)
module IntervalArithmetic

   type interval
      real a ! Left endpoint
      real b ! Right endpoint
   end type interval

   interface operator (+)
      module procedure addIntervals
   end interface

   contains

   function addIntervals( first, second )
      type( interval ) addIntervals
      type( interval ), intent( in ) :: first, second
      addIntervals = interval( first%a + second%a,first%b + second%b )
   end function addIntervals

end module IntervalArithmetic

program Intervals
   use IntervalArithmetic
   type( interval ) :: x = interval( 1.0, 2.0 )
   type( interval ) :: y = interval( 3.0, 4.0 )
   type( interval ) z
   z = x + y
   print *, ’Interval sum: (’, z%a, ’,’, z%b, ’).’
end program Intervals


                                        / Madrid workshop 2008                                      28/45
                                    Department of Earth Sciences
                                         The University of Bergen


Arguments of procedures (1)


program game
   integer, dimension(52) :: cards
   call suffle (cards)
   call deal (cards)
   call play (cards)
end program game

subroutine shuffle (deck)
   integer, dimension(52) :: deck
   ...
end subroutine shuffle



                    / Madrid workshop 2008                          29/45
                                    Department of Earth Sciences
                                         The University of Bergen


Arguments of procedures (2)

program game
   integer, dimension, allocatable :: cards
   read *,ncards
   allocate(cards(ncards))
   call suffle (ncards,cards)
   call deal (ncards,cards)
   call play (ncards,cards)
end program game

subroutine shuffle (n,deck)
   integer n
   integer, dimension(n) :: deck
   ...
end subroutine shuffle

                    / Madrid workshop 2008                          30/45
                                        Department of Earth Sciences
                                             The University of Bergen


Argument intent

   if a dummy argument is specified with intent(in), it must not be
   redefined by the procedure.
   if a dummy argument is specified with intent(inout), the procedure
   uses its entry value and redefines it
   if a dummy argument is specified with intent(out), the procedure
   redefines it but is undefined on entry

subroutine shuffle (n,deck)
   integer, intent(in) :: n
   integer, intent(inout), dimension(n) :: deck
   ...
end subroutine shuffle


                        / Madrid workshop 2008                          31/45
                                               Department of Earth Sciences
                                                    The University of Bergen


Explicit/Implicit interface

    a call to an internal subprogram from a statement within the same
    program unit : explicit interface
    a call to a module subprogram either from another statement in the
    module or from a statement following a use statement of the module :
    explicit interface
    when compiling a call to an external procedure, the compiler normally
    does not have a mechanism to access this code : implicit interface
      •   to specify that a name is that of an external or dummy procedure :
          external proc_name
      •   the external statement specifies the name but not the interface, so it
          remains implicit
      •   a mechanism is provided for the interface to be specified :
          interface
             ...body...
          end interface


                               / Madrid workshop 2008                          32/45
                                             Department of Earth Sciences
                                                  The University of Bergen


Overloading and generic interface (1)


    another use of interfaces is for overloading, that is being able to call
    several procedures by the same generic name.
    example
    interface gamma
       function rgamma
          real rgamma
       end function rgamma
       function dpgamma
          double precision dpgamma
       end function dpgamma
    end interface

    this allows to both functions rgamma and dpgamma to be invoked using
    the generic name gamma



                            / Madrid workshop 2008                             33/45
                                               Department of Earth Sciences
                                                   The University of Bergen


Overloading and generic interface (2)

interface scanfile
   subroutine iscanfile (fnme,text,res,ires)
      character*(*) fnme,text
      integer,intent(out)::res
      integer,intent(out)::ires
   end subroutine iscanfile
   subroutine dscanfile (fnme,text,res,ires)
      character*(*) fnme,text
      double precision,intent(out)::res
      integer,intent(out)::ires
   end subroutine dscanfile
   subroutine cscanfile (fnme,text,res,ires)
      character*(*) fnme,text
      character*(*),intent(out)::res
      integer,intent(out)::ires
   end subroutine cscanfile
end interface




                             / Madrid workshop 2008                           34/45
                                           Department of Earth Sciences
                                                 The University of Bergen


Keyword and optional arguments

   argument lists can get long and many of the arguments may often not
   be needed
   example a constrained minimisation routine :
   subroutine mincon (n,f,x,upper,lower,eq,ineq,convex,xstart)
   all the dummy arguments that are not always needed can be declared
   real, optional, dimension(n) :: upper,lower
   if the first four arguments are the only wanted ones
   call mincon (n,f,x,upper)
   pick within the argument list
   call mincon (n,f,x,upper,ineq=alpha,xstart=x0)
   the called subprogram needs some way to detect whether an argument
   is present so that it can take appropriate action or not. This is provided
   by the following intrinsic function :
   if present(xstart) then ...



                           / Madrid workshop 2008                           35/45
                                                        Department of Earth Sciences
                                                             The University of Bergen


Recursive Subprograms

      although not possible in Fortran 77, Fortran 90 supports recursion.
      a recursive function is one that calls itself
      anything that can be done with a do loop can be done using a recursive
      function
      if a subprogram calls itself, directly or indirectly, the keyword recursive
      must appear in the subprogram statement
recursive function factorial( n ) result( f )
   integer f
   integer, intent( in ) :: n
   if ( n <= 0 ) then
      f = 1
   else
      f = n * factorial( n-1 )
   end if
end function factorial




                                        / Madrid workshop 2008                          36/45
                                           Department of Earth Sciences
                                                The University of Bergen


Intrinsic functions - Vector- and matrix-multiplication



    DOT_PRODUCT(VECTOR_A, VECTOR_B) makes a scalar product of
    two vectors, which must have the same length (same number of
    elements).
    MATMUL(MATRIX_A, MATRIX_B) makes the matrix product of two
    matrices, which must be consistent, i.e. have the dimensions like (M, K)
    and (K, N).




                           / Madrid workshop 2008                          37/45
                                          Department of Earth Sciences
                                                The University of Bergen


Intrinsic functions - Array functions
    ALL True if all values are true (LOGICAL)
    ANY True if any value is true (LOGICAL)
    COUNT Number of true elements in an array (LOGICAL)
    DOT_PRODUCT Dot product of two rank one arrays
    MAXLOC Location of a maximum value in an array
    MAXVAL Maximum value in an array
    MINLOC Location of a minimum value in an array
    MINVAL Minimum value in an array
    SUM Sum of array elements
    SHAPE,SIZE Returns the shape/size of an array
    PRODUCT Returns the product of all the elements in the array
    TRANSPOSE Transpose an array of rank two
                          / Madrid workshop 2008                           38/45
                                            Department of Earth Sciences
                                                 The University of Bergen


Intrinsic functions - Numerical functions
    INT Conversion to integer
    REAL Conversion to real
    DBLE Conversion to double precision
    CMPLX Conversion to complex
    AINT Truncation
    ANINT Rounding
    ABS Absolute value
    MOD Remainder
    CEILING, FLOOR Ceiling, Floor
    SIGN Transfer of sign
    MIN/MAX Minimum, Maximum
    AIMAG,CONJG Imaginary part, Conjugate
                            / Madrid workshop 2008                          39/45
                                        Department of Earth Sciences
                                             The University of Bergen


Intrinsic functions - Mathematical functions


    SQRT Square root
    EXP Exponential
    LOG Natural Logarithm
    LOG10 Common Logarithm
    SIN,COS,TAN Sine, Cosine, Tangent
    ASIN,ACOS,ATAN Arcsine, Arccosine, Arctangent
    SINH,COSH, TANH Hyperbolic Sine, Cosine and Tangent




                        / Madrid workshop 2008                          40/45
                                           Department of Earth Sciences
                                                The University of Bergen


Intrinsic functions - Character string functions (1)

    ACHAR(I) Returns the ASCII character which has number I
    ADJUSTL(STRING) Adjusts to the left
    ADJUSTR(STRING) Adjusts to the right
    CHAR(I, kind) Returns the character that has the number I
    IACHAR(C) Returns the ASCII number of the character C
    ICHAR(C) Returns the number of character C
    INDEX(STRING, SUBSTRING, back) Returns the starting position
    for a substring within a string. If BACK is true then you get the last
    starting position, in the other case, the first one.
    LEN_TRIM(STRING) Returns the length of the string without the
    possibly trailing blanks.


                           / Madrid workshop 2008                          41/45
                                          Department of Earth Sciences
                                               The University of Bergen


Intrinsic functions - Character string functions (2)

    REPEAT(STRING, NCOPIES) Concatenates a character string
    NCOPIES times with itself.
    SCAN(STRING, SET, back) Returns the position of the first
    occurrence of any character in the string SET in the string STRING. If
    BACK is true, you will get the rightmost such character.
    TRIM(STRING) Returns the character string STRING without trailing
    blanks.
    VERIFY(STRING, SET, back) Returns the position of the first
    character in STRING which is not in SET. If BACK is TRUE, you get
    the last one ! The result is zero if all characters are included !
    LEN(STRING) returns the length of a character string. There does not
    have to be assigned a value to the variable STRING


                          / Madrid workshop 2008                          42/45
                                          Department of Earth Sciences
                                              The University of Bergen


Control statements (1)


    GO TO statement → avoid if possible
    IF statement
    if (smthg) action
    IF construct
    if (smthg1) then
       action1
    else if (smthg2) then
       action2
    else
       action3
    end if



                         / Madrid workshop 2008                          43/45
                                       Department of Earth Sciences
                                            The University of Bergen


Control statements (2)

    CASE construct
    select case (expr)
    case (value1)
       action1
    case (value2, value3, value5)
       action2
    case (value4)
       action3
    case default
       action4
    DO construct
    do var=expr1,expr2[,expr3]
       action
    end do

                       / Madrid workshop 2008                          44/45
                                     Department of Earth Sciences
                                          The University of Bergen


Resources




   http ://people.scs.fsu.edu/ burkardt/ : pascal, C, C++,
   fortran, python, java, matlab, ... useful codes, FE, ...
   google ! ! !




                     / Madrid workshop 2008                          45/45

								
To top