Introduction to Fortran 90/95/2003 - to Fortran 90/95/2003 ... First version 1954 FORTRAN 66 ... computer. Array expressions examples

Download Introduction to Fortran 90/95/2003 -   to Fortran 90/95/2003 ... First version 1954 FORTRAN 66 ... computer. Array expressions examples

Post on 25-Mar-2018

228 views

Category:

Documents

13 download

TRANSCRIPT

  • Introduction toFortran90/95/2003NGSSCCource:ProgramminginScienceandTechnology2008JonasLindemann

  • History

  • FortranDevelopment

    Firstversion1954

    FORTRAN66FORTRAN77

    Fortran90 Backwardscompatible

    (TheFprogramminglanguage)Fortran95

    Fortran2003,(2004)

  • Pascalprogram tpk(input,output);var i : integer;y : real;a : array [0..10] of real;

    function f ( t : real) : real;beginf := sqrt(abs(t)) + 5*t*t*t

    end;

    beginfor i := 0 to 10 do read(a[i]);for i := 10 downto 0 dobeginy := f(a[i]);if y > 400 then writeln(i,' TOO LARGE')

    else writeln(i,y);

    end;end;

    end.

  • C#include #include #include

    double f (double t){

    double temp;temp = sqrt(fabs(t)) + 5*pow(t,3);return temp;

    }

    int main(){

    int i;double y;double a[11];for ( i = 0; i = 0; i = i - 1 ) {

    y = f(a[i]);if ( y > 400 ) {

    printf(" %d",i); printf(" TOO LARGE\n");

    }else {

    printf(" %d",i); printf(" %lf",y); printf(" \n");

    }}return 0;

    }

  • FORTRAN0

    DIMENSION A(11)READ A

    2 DO 3,8,11 J=1,113 I=11-J

    Y=SQRT(ABS(A(I+1)))+5*A(I+1)**3IF (400>=Y) 8,4

    4 PRINT I,999.GOTO 2

    8 PRINT I,Y11 STOP

  • FORTRANI

    C FORTRAN I STYLEFUNF(T)=SQRTF(ABSF(T))+5.0*T**3DIMENSION A(11)

    1 FORMAT(6F12.4)READ 1,ADO 10 J=1,11I=11-JY=FUNF(A(I+1))IF(400.0-Y)4,8,8

    4 PRINT 5,I5 FORMAT(I10,10H TOO LARGE)

    GOTO 108 PRINT 9,I,Y9 FORMAT(I10,F12.7)

    10 CONTINUESTOP 52525

  • FORTRANIVellerFortran66

    C FORTRAN IV STYLEDIMENSION A(11)FUN(T) = SQRT(ABS(T)) + 5.0*T**3READ (5,1) A

    1 FORMAT(5F10.2)DO 10 J = 1, 11

    I = 11 - JY = FUN(A(I+1))IF (400.0-Y) 4, 8, 8

    4 WRITE (6,5) I5 FORMAT(I10, 10H TOO LARGE)

    GO TO 108 WRITE(6,9) I, Y

    FORMAT(I10, F12.6)10 CONTINUE

    STOPEND

  • Fortran77PROGRAM TPK

    C FORTRAN 77 STYLEREAL A(0:10)READ (5,*) ADO 10 I = 10, 0, -1

    Y = FUN(A(I))IF ( Y .LT. 400) THEN

    WRITE(6,9) I, Y9 FORMAT(I10, F12.6)

    ELSEWRITE (6,5) I

    5 FORMAT(I10,' TOO LARGE')ENDIF

    10 CONTINUEEND

    REAL FUNCTION FUN(T)REAL TFUN = SQRT(ABS(T)) + 5.0*T**3END

  • Fortran90/95program tpk! Fortran 90 styleimplicit noneinteger :: ireal :: yreal, dimension(0:10) :: Aread (*,*) Ado i = 10, 0, -1 ! Backwards

    y = fun(A(I))if ( y < 400.0 ) then

    write (*,*) i, yelse

    write (*,*) i, ' Too large'end if

    end docontains ! Local functionfunction fun(t)

    real :: funreal, intent(in) :: tfun = sqrt(abs(t)) + 5.0*t**3

    end function funend program tpk

  • Fprogram tpk! Fortran F styleimplicit noneinteger :: ireal :: yreal, dimension(0:10) :: Aread *, Ado i = 10, 0, -1 ! Backwards

    y = fun(A(I))if ( y < 400.0 ) then

    print *, i, yelse

    print *, i, "Too large"end if

    end docontains ! Local functionfunction fun(t) result(fun_result)

    real :: fun_resultreal, intent(in) :: tfun_result = sqrt(abs(t)) + 5.0*t**3

    end function funend program tpk

  • Languageelements

  • Sourceform

    Freeform Fixed form

    Source format Max 132characters Code inpositions772, linenumbers inposition25

    Comments ! anywhere onaline !, Cor*atposition1

    Continuation &atend of line character atposition6oncontinuation line

    Multiplestatements perline

    ;between statements Onstatement perrow

  • ExampleofFortran90/95codeprogramexample

    implicitnone

    integer,parameter:: ap=selected_real_kind(15,300)real(ap)::x,yREAL(ap)::K(20,20)

    x=6.0_ap!Thisislinecomment

    y= &0.25_ap+&0.25_ap

    write(*,*)x;write(*,*)ywrite(*,*)ap

    callmyproc(K)

    stop

    endprogramexample

  • Variablenames

    Max31characters

    Lettersaz,AZ(not,,)Numbers 09

    Underscore _

    Firstcharacter mustbealetterLower case lettersequivalent withupper caseletters

  • Variabletypes

    integer Integer

    real Floating point

    complex Complex numbers

    logical Boolean variables

    character Characters andstrings

  • Variabledeclaration

    integer ::i Scalar integer

    real::p Floating point scalar

    integer,parameter::a=5 Integer constant

    integer,dimension(10) ::b Integer array with10elements

    real::C(10) Floating point array with10elements

    real ::K(20,20) Floating point array with 20x20elements

  • Variabletype parameters

    integer(kind=4)::ainteger(4)::b!Short form

    real(kind=8)::creal(8)::a!Short form

    character(len=20)::textstringcharacter(20)::textstring2character(len=20,kind=1)::textstring3!english stringcharacter(len=20,kind=kanji)::textstring4!kanji string

    integer andrealtypeparameterssystem

    dependent.

  • Determining appropriate type

    selected_int_kind(r) returns theappropriatetype parametertorepresent allinteger values,n,intherange 10r

  • Appropriatetype example

    integer,parameter::rk =selected_real_kind(15,300)

    integer,parameter::ik =selected_real_kind(6)

    real(kind=rk)::xreal(rk)::y

    integer(kind=ik)::zinteger(ik)::c

  • Generaltyperule

    Undeclared variablesaredefined asinteger if thevariablename startswithi,j,k,l,m,n,otherwisereal.

    Theimplicitnone directive forces declarationofallvariables.Recommended.

  • Arraystorage

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

    1 9

    2 10

    3 11

    4 12

    5 13

    6 14

    7 15

    8 16

    1 3

    2 4

    5 7

    6 8

    9 11

    10 12

    13 15

    14 16

    real::A(16)

    real::A(8,2)

    real::A(2,8)

  • Characterandstrings

    Declaration Description

    Character ::ch Character

    character, dimension(60)::chv array ofcharacters

    character ::chv(60) array ofcharacters

    character(len=80)::line character string

    character ::line*80 character string

    character(len=80),dimension(60)::page array ofstrings

    character(len=80) ::page(60) array ofstrings

  • Derived datatypes

    type pointreal::xreal::yreal::size

    end type point

    Type definition:

    type(point)::point !Structure

    Declaration statement:

    Accessing structure member variables:

    point%x =1.0point%y =2.0point%size =4.0

  • Assignments

    integer::mm

    integer,parameter::ap =8

    real(kind=ap)::pi

    mm=113

    pi=3.141592653589793_ap

    m = 113

    pi = 3.141592653589793

    Python:

    datatype parameter

  • Assignments

    integer,parameter::ap =&selected_real_kind(15,300)

    real(kind=ap)::K(20,20)

    Element(5,6)isassignedavalueof5.0

    AllelementsofKareassignedavalueof5.0

    K(5,6)=5.0_ap

    K=5.0_ap

  • Assignments

    integer,parameter::ap=&selected_real_kind(15,300)

    real(kind=ap)::A(3,3)

    Row2isassigned1,2,3

    Column2isassigned4,5,6

    A(2,:)=(/1.0_ap,2.0_ap,3.0_ap/)

    A(:,2)=(/4.0_ap,5.0_ap,3.0_ap/)

  • Assignments

    programpi_testinteger,parameter::&

    ap =selected_real_kind(15,300)real(ap)pi1,pi2

    pi1=3.141592653589793pi2=3.141592653589793_apwrite(*,*)pi1=',pi1write(*,*)pi2=',pi2stopendprogrampi_test

    pi1=3.14159274101257pi2=3.14159265358979

  • Assignments

    logical::flag

    character(40)::first_name

    flag=.false.

    first_name=Jan

  • Defined andundefined variables

    Avariableissaid tobeundefined until ithasbeen assigned avaluereal::speed!variablespeedexists,but isundefined

    Anundefined variablemustnotbereferencedWhen avariableisassigned avalue itisconsidered definedspeed=42.0!variablespeedisdefinedItcan now bereferenced byother expressions

    Anarray issaid tobedefined when allelementshave been assigned values

  • Arithmeticoperators

    ** exponentiation

    * Multiplication

    / Division

    + ddition

    Subbtraction

    Orderofprecedence

  • Unary operators

    xor+x

    Notallowed tofollow directly afterordinaryoperator,hence:x**y isillegal

    x**(y)isok

  • Expressionsa+b+c

    ((a)+b)+c

    Evaluated fromleft toright as:

    a**b**c

    a**(b**c)

    Evaluated as:

  • Integer expressions

    Results ofdivisionswill betruncated towards 0

    6/3=28/3=28/3=2

    Awarning!

    2**3=82**(3)=1/(2**3)=0

  • Mixedmode expressions

    Numeric expressionswithoperands ofdifferingdatatypes

    Weaker oftodatatypes will becoerced tothestronger oneResult will beofthestronger type

    real::ainteger ::ireal::b

    b=a*i

    icoerced toreal

  • Arrayexpressions

    Intrinsic operationscan also apply toarrays

    Sameshape arrays areassumedOneormore operands can bescalarscalar values broadcasttoarray operands

    Orderofarray operationsisnotspecified inthestandardEnabling efficient execution onavector orparallelcomputer

  • Arrayexpressionsexamples

    real,dimension(10,20)::a,b

    real,dimension(5)::v

    a/b!Arrayofshape (10,20),withelementsa(i,j)/b(i,j)

    v+1.!Arrayofshape (5),withelementsv(i)+1.0

    5/v+a(1:5,5)!Arrayofshape (5),withelements5/v(i)+a(i,5)

    a.eq.b !.true.if a(i,j)==b(i,j)and.false.otherwise

  • Relationaloperators

    Operator Meaning Python

    < .lt. less than = .ge. greater than orequal >=

  • Logiskaoperatorer

    Operator Meaning Python

    .and. and and

    .or. or or

    .not. not not

  • Controlconstructs

  • Ifstatements

    if(x>1000)thenx=1000

    endif

    if(x>1000)x=1000

    ifx>1000:x=1000

    Fortran Python

  • Ifstatements

    if(x>1000)theny=100

    elsey=200

    endif

    if x>1000:y=100

    else:y=200

    Fortran Python

  • Ifstatements

    if(x>1000)theny=10

    elseif(x1000:y=10

    elif x

  • casestatements

    selectcase(display_mode)case(0)...case(1)...casedefault...endselect

  • casestatements

    selectcase(number)case(:1)...case(0)...case(1:)...casedefault...endselect

    case(low:high) low

  • dostatements(loops)

    doi=1,10j=j+i

    enddo

    doi=2,30,4j=j+i

    enddo

    startvalue endvalue

    startvalue endvalue

    step

    1 2 3 4 5 6 7 8 9 10

    2 6 10 14 18 22 26 30

    loopvariable isnotallowed tobemodified indostatement

  • dostatements (loops)

    doi=1,1000:if(x>50)thenexit

    elseif(x

  • Programunits andprocedures

  • Mainprogram

    [programprogramname][specification statements][executable statements]

    [containsinternalsubprograms]

    end [program[programname]]

    AFortranprogramcontains only onemain program.

    Theendstatement signalstheend oftheprogramunit andalso terminatestheprogramexecution.

  • Thestopstatement

    Stopsprogramexecution

    Canbeused inallprogramunitsWellbehavedprogramsreturns control tothemain program,sostopstatements should appearinthemain program

    Astopstatement can contain stopcodesNumber orstrings

  • Subprograms

    External subprogramsPlaced inseparatesource files.Implicitinterface.

    Canbeimplemented inother languages

    Internal subprogramssubprograms contained inside programunits,externalsubprograms andinmodule subprograms

    Module subprogramsubprogram contained inamodule

  • External subprogram

    subroutine statement[specification statements][executable statements]

    [contains[internal subprograms]

    end [subroutine [subroutinesname]]

    function statement[specification statements][executable statements]

    [contains[internal subprograms]

    end [subroutine [subroutinesname]]

  • Externalsubprogram Example

    subroutinemyproc(a,B,C)integer,intent(in)::areal,dimension(:,:)intent(in)::Breal,dimension(:),intent(out)::C

    :

    returnendsubroutinemyproc

  • Callingexternalsubprogram

    programmaininteger,parameter::areal::B(a,a)real::C(a)

    :

    callmyproc(a,B,C)

    :

    endprogrammain

  • Modules

    Packagesglobaldata

    derived types andassociated operations

    subprograms

    interfaceblocks

    namelist definitions

    Package everything associated withsome kindoftaskinterval arithmetic

    FEMelementsofacertain type

  • Modulesmodule modulename

    [specification statements][contains

    modulesubprograms]end [module [programname]]

    module constantsinteger,parameter::&

    ik6=selected_int_kind(6)end module constants

    :use constants

    integer(ik6)::myint

  • Modulermoduletruss

    integer...real,private...:public::bar2e:

    contains

    subroutinebar2e(...)...return

    endsubroutinebar2e:endmoduletruss

    variablesandsubprogramscan bemade privateandpublicusing thepublicandprivateattributes.

  • Moduler

    programmainusetruss:callbar2e:

    endprogrammain

    Allpublicvariables,subprograms anddatatypesfromtruss now available inprogramunit

  • Argumentsofprocedures

    ParamterspassedasreferenceChangingaparameterinasubroutineaffectsvariableincallingroutine

    Quickersubroutinecalls

    Undesiredsideeffects

    DeclarationofparametersDonthavetobethesameasthecallingroutine

    Lastdimensioncanbeleftoutforarrays.

  • Subroutinesexampleprogramsub_declaration1

    real(8),dimension(4,4)::Ainteger,dimension(3)::v

    A=0.0_8v=0

    calldowork(A,4,4,v,3)

    print*,A(4,4)print*,v(3)

    endprogramsub_declaration1

    subroutinedowork(A,rows,cols,v,elements)

    integer::rows,cols,elementsreal(8),dimension(rows*cols)::Ainteger,dimension(elements)::v

    A=42.0_8v=42

    return

    endsubroutinedowork

  • Subroutineinterfaces

    2flavorsexternal/implicitinterfaceInternal/explicitinterface

    Implicit(Fortran77)Separatelycompiled.f90filesCompilerdoesnothaveallinformation

    Explicit(Fortran9x/200x)Declaredinmodules,programcontainsectionorwithinterfacedeclarationCompilerhasallinformationonthesubroutineinterface

  • SubroutinesandFortran90/95/2003

    Arraysandvectorscanbedeclaredwith(:,:)or(:)dimensions

    TheexplicitinterfacegivesthecompilerallinformationtodeterminethesizesoftheparametersShortersubroutineparameterlists

    Actualdimensionsofthearrayscanbequeriedusingthesize(array,dimension)function.

  • Example Implicitinterfaceprogramtest

    real(8),dimension(20,30)::A

    A=0.0_8

    callmysub(A,20,30)

    endprogramtestsubroutinemysub(A,rows,cols)

    integer::rows,colsreal(8),dimension(rows,cols)::A

    A=42.0_8

    print*,'rows=',size(A,1)print*,'cols=',size(A,2)

    return

    endsubroutinemysub

  • Example(Module)

    moduleutils

    contains

    subroutinemysub2(A)

    real(8),dimension(:,:)::A

    A=42.0_8

    print*,'rows=',size(A,1)print*,'cols=',size(A,2)

    return

    endsubroutinemysub2

    endmoduleutils

    programtest

    useutils

    real(8),dimension(20,30)::A

    A=0.0_8

    callmysub2(A)

    endprogramtest

    Assumedshapearray

  • Example Internalsubprogramprogramtest

    real(8),dimension(20,30)::A

    A=0.0_8

    callmysub3(A)

    contains

    subroutinemysub3(A)

    real(8),dimension(:,:)::A

    A=42.0_8

    print*,'rows=',size(A,1)print*,'cols=',size(A,2)

    endsubroutinemysub3

    endprogramtest

    Assumedshapearray

  • Example Explicitinterfaceprogramtest

    interfacesubroutinemysub4(A)

    real(8),dimension(:,:)::Aendsubroutinemysub4

    endinterface

    real(8),dimension(20,30)::A

    A=0.0_8

    callmysub4(A)

    endprogramtest

    subroutinemysub4(A)

    real(8),dimension(:,:)::A

    A=42.0_8

    print*,'rows=',size(A,1)print*,'cols=',size(A,2)

    return

    endsubroutinemysub4

    Assumedshapearray

  • Automaticfields

    Temporaryfieldsinsubroutines

    CreatedonthestackMustfitinthestack

  • Automaticfields

    programautomatic_arrays

    real(8),dimension(20,30)::A

    callmysub(A)

    contains

    subroutinemysub(A)

    real(8),dimension(:,:)::Ainteger,dimension(size(A,1),size(A,2))::B

    B=0

    print*,"rows=",size(B,1)print*,"cols=",size(B,2)

    endsubroutinemysub

    endprogramautomatic_arrays

  • Arrayfeatures

  • Allocatablearrays

    SizeofarraysnotalwaysknownatcompiletimeDeclaredusingtheallocatable attributeThearrayrankisdefinedatdeclarations,butboundsundefineduntilarrayhasbeenallocatedAllocatestatementsusedtoallocatethearrayWorkarrayswhereusedinFortran77asareplacementforallocatablearraysDeallocatedwithdeallocatestatementAllocatablearraysautomaticallydeallocatedwhenreturningfromafunctionorsubroutine

  • Allocatablearrays

    real,dimension(:),allocatable ::f

    real,dimension(:,:),allocatable ::K

    allocate(f(20))

    allocate(K(20,20))

    deallocate(f)

    deallocate(K)

    deallocate(f,K)

    or

    allocate(f(20),K(20,20))

  • Wherestatement

    Oftendesiredtoperformoperationsononlycertainelementsofanarray

    where(logicalarrayexpr)arrayvariable=expr

    where(logicalarrayexpr)arrayassignments

    endwhere

    where(logicalarrayexpr)arrayassignments

    elsewherearrayassignments

    endwhere

  • Wherestatementexample

    where(a>0.0)a=1.0/a

    where(pressure0.0)a=log(a)

    functionisonlycalledwhenconditionisfulfilled.

    a,pressure,temparearrays

  • forallstatement

    IndoloopstheprocessormusteachsuccesiveiterationinorderandaftereachotherPerformancepenalties(especiallyonparallelmachines)

    forallstatementareplacementwhenoperationscanbeexecutedinanyorderArrayassignmentsexpressedwithindices

  • forallstatement

    doi=1,na(i,i)=2.0*x(i)

    enddo

    forall(i=1:n)a(i,i)=2.0*x(i)

    forall(i=1:n,j=1:m)a(i,j)=i+j

    forall(i=1:n,j=1:n,y(i,j)/=0.)x(i,j)=1.0/y(i,j)

    Maskingcondition

    Riskofdividingbyzero

  • Pureprocedures

    UsingfunctionswithsideeffectsinforallcanaffectperformanceandresultspurefunctionsmustbeusedinforallstatementsAprocedureinFortraninconsideredpure

    ifitdoesnotalteranydummyargumentdoesnotalteranypartofavariableaccessedbyhostoruseassociationcontainsnolocalvariablewithsaveattributeperformsnooperationsonexternalfilescontainsnostopstatement

    pureattributeusedtoindicatepurefunction

  • Elementalprocedures

    Subroutinesoperatingonelementsofarrays

    Elementalsubroutinesmustbepure(definedautomatically)

    elementalsubroutineswap(a,b)real,intent(inout)::a,breal::work

    work=aa=bb=work

    endsubroutineswap

    :

    real,dimension(20,20)::areal,dimension(20,20)::b

    callswap(a,b)

  • Arraysubobjects

    Usedtoextractfields/arraysfromotherarrays

    CanbeusedasparametersinsubroutinecallsCompareMatlabsindexnotation

  • Arraysubobjectexampleprogramarray_subobjects

    integer,dimension(5,10)::Ainteger::i,j

    doi=1,5doj=1,10

    A(i,j)=(i1)*10+jenddo

    enddo

    print*,"Entirearray:"callwriteArray(A)

    print*,"A(1,5:10)"callwriteVector(A(1,5:10))

    print*,"A(1:5,5:10)"callwriteArray(A(1:5,5:10))

    print*,"A(1:5,5:10)"callwriteArray(A(1:5,5:10))

    print*,"A((/1,3/),(/2,4/))"callwriteArray(A((/1,3/),(/2,4/)))

  • ArraysubobjectsexampleEntire array:1 2 3 4 5 6 7 8 9 1011 12 13 14 15 16 17 18 19 2021 22 23 24 25 26 27 28 29 3031 32 33 34 35 36 37 38 39 4041 42 43 44 45 46 47 48 49 50A(1, 5:10)5 6 7 8 9 10A(1:5, 5:10)5 6 7 8 9 1015 16 17 18 19 2025 26 27 28 29 3035 36 37 38 39 4045 46 47 48 49 50A(1:5, 5:10)5 6 7 8 9 1015 16 17 18 19 2025 26 27 28 29 3035 36 37 38 39 4045 46 47 48 49 50A((/1,3/), (/2,4/))2 422 24

  • Intrinsic procedures

  • Intrinsicprocedures(builtin...)

    Elementalprocedures

    InquiryfunctionsReturnspropertiesoftheargumentsthatdoesnotdependontheirvalues,kind,rangeetc...

    TransformationalfunctionsHasarrayargumentsandreturnsarraysdependingonallelementsoftheinputarrays

    Nonelementalsubroutines

  • Elementalfunctions

    abs(x) absolutevalue ofx

    int(x) converts xtointegere,truncatestowards0

    nint(x) returnsinteger, nearesttox

    real(x) convertstofloatingpointvalue

    ...

    sin(x) returns thesineofx

    sqrt(x) returnsthesquareroot ofx

    atan2(y,x) returns thearctangentforpairsofreals

    ... convertstofloatingpointvalue

    Routinesthatmayconvert

    Mathematicalfunctions

  • Vectorandmatrixmultiplication

    Matrixmultiplicationmatmul(A,B),whereAandBarematrices

    Scalarproductdot_product(a,b),whereaandbarevectors

  • Vectorandmatrixmultiplication

    programmatrix_multiply

    real(8),dimension(4,4)::Areal(8),dimension(4,8)::Breal(8),dimension(4,8)::C

    callrandomMatrix(A)callrandomMatrix(B)callrandomMatrix(C)

    C=matmul(A,B)

    print*,"A="callwriteArray(A)print*,"B="callwriteArray(B)print*,"C="callwriteArray(C)

    endprogrammatrix_multiply

  • Vectorandmatrixmultiplication

    A=.984.700.275.661.810.910.304.484.985.347.548.614.971.882.129.929B=

    .763.534.711E01.404.731.636.879.689

    .786.231.238.951.621.528.733.588E01

    .466.302.209.294.598.461.911.343

    .690E01.619.305.326E01.438.202.617.851C=

    1.481.18.4961.171.611.262.041.381.511.03.4861.301.551.231.961.131.321.15.455.9091.531.192.001.411.561.34.5891.301.741.332.191.56

  • Reductionroutines

    allTrueifallelement=.true.

    anyTrueifanyelement=.true.

    maxval/minvalMax/minvalueinthefield

    productProductofallelementsinthefield

    sumSumofallelementsinthefield

  • Reductionfunctions

    print*,'ProductofA=',product(A)print*,'SumofA=',sum(A)print*,'MaxofA=',maxval(A)print*,'MinofA=',minval(A)

    A=.984.700.275.661.810.910.304.484.985.347.548.614.971.882.129.929...ProductofA=0.00016095765496870103SumofA=10.534961942117661MaxofA=0.9853920286986977MinofA=0.12899155798368156

  • Informationfunctions

    lboundReturnslowerfieldindex

    uboundReturnupperfieldindex

    shapeReturnsthematrixshapeinanarray[rows,columns]

    sizeReturnsthesizeofmatrixinaspecificdimension

  • Inputandoutput

  • Readingandwritingfiles

    OnerowforeachREAD/WRITEstatement

    FortranautomaticallyconvertstextinafiletotypedvariablevaluesSeveralvariablescanbereadinthesamestatementusingacommanseparatedlistofvariables

    Tohandlealargenumberofvaluesonarowanimplicitloopcanbeused

  • Example

    !Read8floatingpointvaluesfromunitir

    read(ir,*)a(1),a(2),a(3),a(4),a(5),a(6),a(7),a(8)

    !orperhapsevenbetter...

    read(ir,*)(a(i),i=1,8)

    !Sameprocedureforwriting

    write(iw,*)(a(i),i=1,8)

  • FormattedIO

    SecondparameterintheWRITEstatementdefinestheoutputformat

    *representsthedefaultformatwhichoftendisplaysatfullprecisionAformatparameterisastringdescribingtheoutputformat

    Theformatisdefinedusingformatcodes

  • FormattedIO

    CommoncodesA[n] characterstringwiththewidthn

    I[n] integerwiththewidthn

    G[m.n] floatingpointvaluewithwidthmandndecimals

    Formatcodescanberepeatedbygivingaintegerinfrontofthecode(6I5)=6integerswiththewidth5

  • Exampleprogramformat_print

    real(8),dimension(3)::ainteger,dimension(4)::binteger::i,j

    !Writetableheader

    a=(/1.0,2.0,3.0/)b=(/4,5,6,7/)

    write(*,'(3A8,4A5)')'aaaaaaaa',&'bbbbbbbb','cccccccc','ddddd','eeeee','fffff',&'ggggg

    !Writetable

    doj=1,10write(*,'(3G8.3,4I5)')(a(i),i=1,3),(b(i),i=1,4)

    enddo

    endprogramformat_print

  • Example

    aaaaaaaabbbbbbbbccccccccdddddeeeeefffffggggg1.002.003.0045671.002.003.0045671.002.003.0045671.002.003.0045671.002.003.0045671.002.003.0045671.002.003.0045671.002.003.0045671.002.003.0045671.002.003.004567

  • Dynamicformatcodes

    Formatstringsarestaticstrings

    HowtocreateaformatcodethatcanhandledynamicnumberofvaluesWRITEcanuseacharacterstringasafile

  • ExamplesubroutinewriteArray(A)

    real(8),dimension(:,:)::Ainteger::rows,cols,i,jcharacter(255)::fmt

    rows=size(A,1)cols=size(A,2)

    write(fmt,'(A,I1,A)')'(',cols,'G8.3)'

    doi=1,rowsprintfmt,(A(i,j),j=1,cols)

    enddo

    return

    endsubroutinewriteArray

    Stringthatwillcontainfinalformatcodes.

    WritetofmtstringusingawritestatementcolsG8.3.

    Usethefmtstringasaformatstringwhenprintingthearray.

  • Reading

    read(*,*)Aread(5,*)A

    integer,parameter::ir=15

    open(unit=ir,file=example.dat)read(ir,*)Aclose(unit=ir)

    Keyboard

    File

    Pleasesee,Metcalfformoreparametersfortheopenstatement

  • Writing

    write(*,*)Awrite(6,*)Awrite(*,(TR1,A,G15.6))A=,A

    integer,parameter::iw=16

    open(unit=iw,file=example.dat)write(iw,(A,G15.6))Aclose(unit=iw)

    Screen

    File

    Pleasesee,Metcalfformoreparametersfortheopenstatement

  • Code structuring

  • Structuringofprojects

    Forsmallerprojectmodularisationnotnecessary

    ForlargerprojectitisamusttobeabletomaintainthecodeInFortran95thekeytomodularisationisthemodule

    Modulesshouldbeusedtogrouprelatedsubroutinesanddata

  • Codestructuring

    inputdata outputdatafem solve

    utils

    program

  • Examplecode

    programstress

    useinputdatauseoutputdatausefemusesolve

    .

    .

    endprogramstress

    modulefem

    useutils

    .

    .

    endmodulefem

    moduleutils

    .

    .

    endmoduleutils

  • UsingthePhotran IDE

  • Selectingworkspace

    Aworkspace isadirectorycontaining settings fortheenviroment andasetofdevelopment projects.

  • Welcomescreen

    Clickhere

  • Workbenchscreen

    File/New/other

  • CreateaFortranproject

    ClickNext

  • Selectprojecttypeandname

    1

    2

    3

    ClickFinish

  • SwitchtoFortranPerspective

  • Workbenchwithemptyproject

  • AddingaFortransourcefileFile/New/Other

    ClickNext

  • Namesourcefile

    ClickFinish

    Enternameofsourcefile

  • Makefile generationwithpymkmf

    Select thesource directoryusing thebrowse button.

    Click Generatetocreate aMakefile forsource files.

  • Refreshingprojecttree

    Right click andselect RefreshtodisplaythegeneratedMakefile

  • BuildingtheprojectRight click andselect BuildProjecttostartthebuildprocess.

  • Runningtheproject

    Click torun project

    Click Ok

  • Programoutput

  • DebuggingwithPhotran

  • SpecialFX

  • Proceduresasarguments

    proceduresinFortran95cantakeproceduresasarguments

    PropertiesofdummyprocedureargumentsmustagreeTheproceduretypeisdeclaredinthespecificationpart

    Internalprocedurescantbeused

  • Proceduresasargumentsmoduleutils

    implicitnone

    contains

    real(8)functionmyfunc(x)

    real(8),intent(in)::x

    myfunc =sin(x)

    endfunctionmyfunc

    subroutinetabulate(startInterval,endInterval,step,func)

    real(8),intent(in)::startInterval,endInterval,stepreal(8)::x

    interfacereal(8)functionfunc(x)

    real(8),intent(in)::xendfunctionfunc

    endinterface

    x=startIntervaldowhile(x

  • Proceduresasarguments

    programprocedures_as_arguments

    useutils

    implicitnone

    calltabulate(0.0_8,3.14_8,0.1_8,myfunc)

    endprogramprocedures_as_arguments

  • Proceduresasarguments0.00000000000000000.00000000000000000.100000000000000019.98334166468281548E0020.200000000000000010.198669330795061220.300000000000000040.295520206661339600.400000000000000020.389418342308650520.500000000000000000.479425538604203010.599999999999999980.564642473395035370.699999999999999960.644217687237691020.799999999999999930.717356090899522680.899999999999999910.783326909627483300.999999999999999890.841470984807896391.09999999999999990.891207360061435311.20000000000000000.932039085967226291.30000000000000000.963558185417192961.40000000000000010.985449729988460251.50000000000000020.997494986604054451.60000000000000030.999573603041505111.70000000000000040.991664810452468571.80000000000000050.973847630878195041.90000000000000060.946300087687414252.00000000000000040.909297426825681492.10000000000000050.863209366648873492.20000000000000060.808496403819589872.30000000000000070.745705212176719702.40000000000000080.675463180551150292.50000000000000090.598472144103955772.60000000000000100.515501371821463382.70000000000000110.427379880233828952.80000000000000120.334988150155903832.90000000000000120.239249329213981123.00000000000000130.141120008059865913.10000000000000144.15806624332891589E002

  • Keywordandoptionalarguments

    ManyprocedureshavelongargumentlistsAllargumentsnotneeded

    ProceduralargumentsinFortrancanbegiventheattributeoptionalreal,optional::a

    OptionalargumentscanbeomittedintheprocedurecallPresenceofanargumentcanbetestedwiththepresentfunction.

    Argumentscanbespecifiedwithkeywords

  • Keywordandoptionalarguments

    subroutineorder_icecream(number,flavor,topping)

    integer::numberinteger,optional::flavorinteger,optional::topping

    print*,number,'icecreams ordered.'

    if(present(flavor))thenprint*,'Flavoris',flavor

    elseprint*,'Noflavorwasgiven.'

    endif

    if(present(topping))thenprint*,'Toppingis',topping

    elseprint*,'Notoppingwasgiven.'

    endif

    endsubroutineorder_icecream

    callorder_icecream(2)callorder_icecream(2,1)callorder_icecream(4,4,2)callorder_icecream(4,topping=3)

  • Overloading

    Procedurecalltodifferentproceduresdependingondatatype

    DeclareaninterfacewithproceduralinterfacesforalluseddatatypesExplicitinterfaces(modules)canuseasimplerformmoduleprocedureprocedurenamelist

  • Overloadingmodulespecial

    interfacefuncmoduleprocedureifunc,rfunc

    endinterface

    contains

    integerfunctionifunc(x)

    integer,intent(in)::xifunc =x*42

    endfunctionifunc

    real(8)functionrfunc(x)

    real(8),intent(in)::xrfunc =x/42.0_8

    endfunctionrfunc

    endmodulespecial

    programoverloading

    usespecial

    implicitnone

    integer::a=42real(8)::b=42.0_8

    a=func(a)b=func(b)

    print*,aprint*,b

    endprogramoverloading

    17641.00000000000000000

  • Operatoroverloading

    Defineoperationsonderivedtypes

    Vector/Matrixoperationsinterfaceoperator(operator) usedtodefineafunctionimplementingtheoperationsforthisoperator

    Functionhastheformtype(derivedtypename)functionname(operand1,operand2)

  • Operatoroverloading

    modulevector_operations

    typevectorreal(8)::components(3)

    endtypevector

    interfaceoperator(+)moduleprocedurevector_plus_vector

    endinterface

    contains

    type(vector)functionvector_plus_vector(v1,v2)

    type(vector),intent(in)::v1,v2vector_plus_vector%components =v1%components+v2%components

    endfunctionvector_plus_vector

    endmodulevector_operations

  • Operatoroverloading

    programoperator_overloading

    usevector_operations

    implicitnone

    type(vector)::v1type(vector)::v2type(vector)::v

    v1%components=(/1.0,0.0,0.0/)v2%components=(/0.0,1.0,0.0/)

    v=v1+v2

    print*,v

    endprogramoperator_overloading

    1.000000000000000001.000000000000000000.0000000000000000

  • Publicandprivateattributes

    Controlvisibilityofvariablesandfunctions

    HidemoduleimplementationdetailsPreventsideeffectsinmodules

    Visibilityofvariablescontrolledbyprivate andpublic attributes

    procedurevisibilitycontrolledbyprivateaccesslist

    publicisthedefaultforallmodulevariablesandprocedures

  • Publicandprivate

    modulemymodule

    implicitnone

    integer,public::visibleinteger,private::invisible

    privateprivatefuncpublicpublicfunc

    contains

    subroutineprivatefunc

    print*,'Thisfunctioncanonlybecalledfromwithinamodule.'

    endsubroutineprivatefunc

    subroutinepublicfunc

    callprivatefunc

    endsubroutinepublicfunc

    endmodulemymodule

  • Publicandprivateprogramprivate_entities

    usemymodule

    implicitnone

    callpublicfunc

    endprogramprivate_entities

    Thisfunctioncanonlybecalledfromwithinamodule.

    programprivate_entities

    usemymodule

    implicitnone

    callprivatefunc

    endprogramprivate_entities

    makeallgfortran gfboundscheckWallWtabs cmain.f90gfortran oprivate_entities mymodule.o main.omain.o:Infunction`private_entities':D:\edu\lunarc\sciprog\workspace\private_entities/main.f90:7:undefinedreferenceto`privatefunc_'collect2:ldreturned1exitstatusmake:***[private_entities]Error1

  • Pointers

    Pointer=referencetoavariable

    StrictlytypedPointertargetsmusthavetarget attributeForcompileroptimisation

    Enablesthereturnofallocatable arraysfromprocedures

    nullify(pointer)disassociatespointerfromtarget=> operatorisusedtoassociatedapointerwithatarget

  • Pointersprogrampointers

    implicitnone

    integer,allocatable,dimension(:,:),target::Ainteger,dimension(:,:),pointer::B,C

    allocate(A(20,20))

    B=>A

    print*,size(B,1),size(B,2)

    callcreateArray(C)

    print*,size(C,1),size(C,2)

    deallocate(C)

    B=>null()

    B(1,1)=0!Dangerous!

    contains

    subroutinecreateArray(D)

    integer,dimension(:,:),pointer::D

    allocate(D(10,10))

    endsubroutinecreateArray

    endprogrampointers

    Bpoints toA

    Bcan bequeried justlikeanormalarray

    Anunassociatedpointercan bepassedtoasubroutine andbereturned asanallocated array

  • AdvancedI/O

  • ListdirectedI/O

    Fortranusesaspecificformatforreadingandwritingvariablestofiles

    Variablesoutputfromwrite(*,*)areseparatedwithspace/blanksComplexnumberssurroundedby()

    Stringsmustbeenclosedinorwhenoutput

    Readingvariablesrequirethesameformat

  • ListdirectedI/Oprogramlist_io

    implicitnone

    integer,parameter::ir =15integer,parameter::iw =16

    integer::a=42real::b=42.0*42.0character(len=20)::string='Hello,string!'logical::topping=.true.complex::c=(1.0,2.0)

    open(unit=iw,file='list.txt',status='replace')write(iw,*)a,b,'"',string,'"',topping,cclose(unit=iw)

    open(unit=ir,file='list.txt',status='old')read(ir,*)a,b,string,topping,cclose(unit=ir)

    print*,aprint*,bprint*,toppingprint*,c

    endprogramlist_io

    421764.0000"Hello,string!"F(1.00000000,2.0000000)

    .true.and.false.canalso beused asinputforlogical variables

  • Namelist I/O

    Readinglistofnamedvalues

    ValuenamesdefinedinanamelistInputmustconsistoflistsofnamedvaluepairsseparatedwithcomma&name=value,name=value/

    Cancontainarraysname=1,2,3,4,5

    Fortrancanalsowritenamedvalues

  • Namelist I/O

    programnamelist_io

    implicitnone

    integer,parameter::ir =15integer,parameter::iw =16integer::no_of_eggs,litres_of_milk,kilos_of_butter,list(5)namelist /food/no_of_eggs,litres_of_milk,kilos_of_butter,list

    list=0

    open(unit=ir,file='food.txt',status='old')read(ir,nml=food)close(unit=ir)

    print*,no_of_eggs,litres_of_milk,kilos_of_butter

    open(unit=iw,file='food2.txt',status='new')write(iw,nml=food)close(unit=iw)

    endprogramnamelist_io

    namelist definedvariablestobereadfromfile

    namelist definedvariablestobewrittentofile.

  • Namelist I/O

    &foodlitres_of_milk=5,no_of_eggs=12,kilos_of_butter=42,list=1,2,3,4,5/

    &FOODNO_OF_EGGS=12,LITRES_OF_MILK=5,KILOS_OF_BUTTER=42,LIST=1,2,3,4,5,/

    food.txt:

    food2.txt:

    writing namelistalways producesuppercase variablenames

  • UnformattedI/O

    Writingdatausingatextualrepresentationnotefficientinallcases

    Noformatneeded,binaryoutputread(unit=xx)a

    write(unit=xx)b

    OutputfromunformattedI/Ooftensystemdependent

    Scratchfiles andtemporaryfiles

  • Directaccessfiles

    Usedwhenarandomaccesspatternisneeded

    FileconsistsofasetofequalsizedrecordsAnyrecordinthefilecanbeaccessedrandomly

    Iftherecordischangeddatacannotbereadbackfromfile

    Sizeofarecordcanbefoundusinginquire(iolength=variablename)recordLength

  • Directaccessfiles/unformattedIOprogramunformatted_io

    implicitnone

    typeaccountcharacter(len=40)::account_holderreal::balance

    endtypeaccount

    integer,parameter::iw =15type(account)::accountAtype(account)::accountBinteger::recordSize

    inquire(iolength=recordSize)accountA

    print*,'Recordsize=',recordSize

    accountA%account_holder ='Olle'accountA%balance =400

    accountB%account_holder ='Janne'accountB%balance =800

    open(unit=iw,file='bank.dat',access='direct',recl=recordSize,status='replace')write(iw,rec=1)accountAwrite(iw,rec=2)accountBclose(unit=iw)

    endprogramunformatted_io

    Derived datatypesgood candidates forstoring asrecords inarandom accessfile

    Inquire fortherequired record length

    access=directcreatesadirect accessfile.

    Therec attributedetermines thelocation tostore/readtherecord

  • Filepositioning

    Filepointer Invisiblecursorinthefile

    backspaceunitMovefilepointerback1record

    rewindunitMovefilepointertobeginningoffile

    endfile unitMovefilepointertotheendofthefile.

  • Errorhandlinginfileoperations

    open,close,readandwritehaveanerr attributethatcanbesettoaspecificlabeltojumptowhenanerroroccurs

    Wellbehavedprogramsshouldimplementerrorhandlingwhenreadingandwritingfiles

  • Errorhandlinginfileoperationsprogramerror_handling

    implicitnone

    integer,parameter::ir =15integer::a

    open(unit=ir,file='test.txt',status='old',err=99)read(ir,*,err=99)aclose(unit=ir,err=99)

    stop

    99 print*,'Anerroroccured readingthefile.'

    endprogramerror_handling

  • Fortran2003extensions

  • Allocatable arrayextensions

    Removetheneedforpointerstouseallocatablearraysasdummyarguments

    Inefficient

  • Allocatable dummyargumentsprogramallocatable_dummy

    implicitnone

    real,allocatable ::A(:,:)

    callcreateArray(A)

    print*,size(A,1),size(A,2)

    deallocate(A)

    contains

    subroutinecreateArray(A)

    real,allocatable,intent(out)::A(:,:)

    allocate(A(20,20))

    endsubroutinecreateArray

    endprogramallocatable_dummy

    Apointerdummyargumentwas neededtoimplement thisiFortran95

  • Allocatable functions

    programallocatable_function

    implicitnone

    real::A(20)

    A=createVector(20)print*,size(A,1)

    contains

    functioncreateVector(n)

    real,allocatable,dimension(:)::createVectorinteger,intent(in)::n

    allocate(createVector(n))

    endfunctioncreateVector

    endprogramallocatable_function

    Vector allocated infunction will beautomaticallydeallocated when ithasbeen used.

  • Allocatable components

    typestackinteger::indexinteger,allocatable ::content(:)

    endtypestack

    Pointersused inFortran95,but noautomaticdeallocation available

  • Submodules

    TheFortran95moduleconceptadequateformoderatesizeprojects

    DifficulttomodularizemodulesthemselvesDividingmodulesintoseveralmodulesexposesinternalstructure

    nameclashes

    Changestomodulefeaturesrequirerecompilationofallfilesusingthismodule

  • Submodules

    SeparationofmoduleintoInterface definedinthemodule

    Body definedinsubmodule

  • Submodulesmodulepoints

    typepointreal::x,y

    endtypepoint

    interfacerealmodulefunctionpoint_dist(a,b)

    type(point),intent(in)::a,bendfunctionpoint_dist

    endinterfaceendmodulepoints

    submodule (points)points_a

    contains

    realmodulefunctionpoint_dist(a,b)type(point),intent(in)::a,bpoint_dist =sqrt((a%xb%x)**2+(a%yb%y)**2)

    endfunctionpoint_dist

    endsubmodule points_a

    Notavailable ingfortran yet.

  • Cinteroperability

    NocleardefinitionsexistedbetweenFortran95andtheClanguage

    C/FortranprogrammingisimportantInterfacingwithClibraries

    CuserinterfaceapplicationinterfacingwithFortrancode

    Newintrinsicmodule,iso_c_binding,includedContainsdefinitionsofalltheCdatatypes mappedtoFortrantypes

  • Cinteroperability

    programc_interop

    useiso_c_binding

    implicitnone

    integer(c_int)::areal(c_float)::breal(c_double)::c

    a=42b=42.0_c_floatc=84.0_c_double

    print*,a,b,c

    endprogramc_interop

  • Cinteroperability

    Fortranalwayspassesallvariablesbyreference

    InCscalarargumentsareoftenpassedbyvalueArgumentvalueiscopiedtoprocedure

    Thevariableattributevalue isaddedforcompatibilitywithCcode

    EnablesdirectlinkingwithC

  • Objectorientedprogramming

    modulemytype_module

    typemytypereal::myvalue(4)=0.0

    containsprocedure::write=>write_mytypeprocedure::reset

    endtypemytype

    private::write_mytype,reset

    contains

    subroutinewrite_mytype(this,unit)class(mytype)::thisinteger,optional::unitif(present(unit))then

    write(unit,*)this%myvalueelse

    print*,this%myvalueendif

    endsubroutinewrite_mytype

    subroutinereset(variable)class(mytype)::variablevariable%myvalue =0.0

    endsubroutinereset

    endmodulemytype_module

    class(mtype)::x

    callx%write(6)callx%reset

    Notavailable ingfortran yet.

  • Accesstocomputingenvironment

    get_environment_variable()Queryenvironmentvariables

    command_argument_count()Retrievethenumberofcommandlinearguments

    get_command_argument()Retrievespecificcommandlineargument

    Introduction to Fortran 90/95/2003HistoryFortran DevelopmentPascalCFORTRAN 0FORTRAN IFORTRAN IV eller Fortran 66Fortran 77Fortran 90/95FLanguage elementsSource formExample of Fortran 90/95 codeVariable namesVariabletypesVariable declarationVariable type parametersDetermining appropriate typeAppropriate type - exampleGeneral type ruleArray storageCharacter and stringsDerived data typesAssignmentsAssignmentsAssignmentsAssignmentsAssignmentsDefined and undefined variablesArithmetic operatorsUnary operatorsExpressionsInteger expressionsMixed-mode expressionsArray expressionsArray expressions examplesRelational operatorsLogiska operatorerControl constructsIf-statementsIf-statementsIf-statementscase-statementscase-statementsdo-statements (loops)do-statements (loops)Program units and proceduresMain programThe stop-statementSubprogramsExternal subprogramExternal subprogram - ExampleCalling external subprogramModulesModulesModulerModulerArguments of proceduresSubroutines exampleSubroutine interfacesSubroutines and Fortran 90/95/2003Example Implicit interfaceExample (Module)Example Internal subprogramExample Explicit interfaceAutomatic fieldsAutomatic fieldsArray featuresAllocatable arraysAllocatable arraysWhere-statementWhere-statement exampleforall-statementforall-statementPure proceduresElemental proceduresArray subobjectsArray subobject exampleArray subobjects exampleIntrinsic proceduresIntrinsic procedures (builtin...)Elemental functionsVector and matrix multiplicationVector and matrix multiplicationVector and matrix multiplicationReduction routinesReduction functionsInformation functionsInput and outputReading and writing filesExampleFormatted IOFormatted IOExampleExampleDynamic format codesExampleReadingWritingCode structuringStructuring of projectsCode structuringExample codeUsing the Photran IDESelecting workspaceWelcome screenWorkbench screenCreate a Fortran projectSelect project type and nameSwitch to Fortran PerspectiveWorkbench with empty projectAdding a Fortran source fileName source fileMakefile generation with pymkmfRefreshing project treeBuilding the projectRunning the projectProgram outputDebugging with PhotranSpecial FXProcedures as argumentsProcedures as argumentsProcedures as argumentsProcedures as argumentsKeyword and optional argumentsKeyword and optional argumentsOverloadingOverloadingOperator overloadingOperator overloadingOperator overloadingPublic and private attributesPublic and private Public and privatePointersPointersAdvanced I/OList directed I/OList directed I/ONamelist I/ONamelist I/ONamelist I/OUnformatted I/ODirect access files Direct access files / unformatted IOFile positioningError handling in file operationsError handling in file operationsFortran 2003 extensionsAllocatable array extensionsAllocatable dummy argumentsAllocatable functionsAllocatable componentsSubmodulesSubmodulesSubmodulesC interoperabilityC interoperabilityC interoperabilityObject-oriented programming Access to computing environment

Recommended

View more >