54
Programming and Modelling Module 1 Introduction to Fortran Programming A.P. van den Berg, C. Thieulot September 2012 Institute of Earth Sciences Utrecht University 1

Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

Embed Size (px)

Citation preview

Page 1: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

Programming and Modelling

Module 1

Introduction to Fortran Programming

A.P. van den Berg, C. Thieulot

September 2012

Institute of Earth SciencesUtrecht University

1

Page 2: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 2

Contents

1 Introduction 4

2 Fortran programming exercises 5

2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2.2 Tutorial exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2.2.1 Hello World . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2.2.2 A 2×2 equation solver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2.2.3 Tables of multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2.2.4 computepi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

2.2.5 Golden Ratio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

2.2.6 Computing and writing function tables to file . . . . . . . . . . . . . . . . . . 7

2.2.7 A modelling experiment using input and output files . . . . . . . . . . . . . . 8

2.3 Extended exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

2.3.1 Modelling stochastic processes using random number generators . . . . . . . 9

2.3.2 Matrix vector calculations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

2.3.3 Iterative solution of a linear system of equations . . . . . . . . . . . . . . . . 14

2.3.4 Fourier synthesis of a periodic boxcar function . . . . . . . . . . . . . . . . . 16

A A Fortran Tutorial 19

A.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

A.2 Installing and executing a Fortran program . . . . . . . . . . . . . . . . . . . . . . . 19

A.2.1 Input/output redirection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

A.3 Fortran source text formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

A.4 Program variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

A.4.1 Variables of type character . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

A.5 Indexed variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

A.6 Program Control Structures (constructs) . . . . . . . . . . . . . . . . . . . . . . . . . 23

A.6.1 Program loop statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

A.6.2 Conditional Statements and logical expressions . . . . . . . . . . . . . . . . . 24

A.7 Program Input/Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

A.8 Procedures, subroutines and functions . . . . . . . . . . . . . . . . . . . . . . . . . . 25

A.8.1 A subroutine for writing table data to a 2-column text file . . . . . . . . . . . 27

A.8.2 A subroutine for making a printplot frame . . . . . . . . . . . . . . . . . . . . 27

B Supplementary Fortran programming exercises 29

B.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

B.1.1 Computation of arithmetic, geometric and harmonic mean values . . . . . . . 29

B.1.2 Computation of the p-norm of a vector . . . . . . . . . . . . . . . . . . . . . 29

B.1.3 The bubble-sort procedure for sorting numbers . . . . . . . . . . . . . . . . . 29

B.1.4 A function to determine the length of a 2-column data file . . . . . . . . . . . 30

B.1.5 A function to read data from a 2-column data file . . . . . . . . . . . . . . . 30

B.1.6 Printplot of a 2-column data table . . . . . . . . . . . . . . . . . . . . . . . . 31

B.1.7 Removal of the mean value of a time series . . . . . . . . . . . . . . . . . . . 32

Page 3: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 3

C A Scilab Tutorial 33C.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33C.2 Program variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34C.3 Indexed variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35C.4 Program Control Structures (constructs) . . . . . . . . . . . . . . . . . . . . . . . . . 36

C.4.1 Program loop statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36C.4.2 Conditional Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

C.5 Program Input/Output Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38C.6 Procedures and functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39C.7 Example functions for 2-column table data file read/write I/O . . . . . . . . . . . . . 40C.8 Scilab graphics functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

C.8.1 Plotting function tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41C.8.2 Plotting histograms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

C.9 Example script using the Scilab ode solver . . . . . . . . . . . . . . . . . . . . . . . . 43C.9.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43C.9.2 Using the Scilab ODE solver . . . . . . . . . . . . . . . . . . . . . . . . . . . 43C.9.3 Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44C.9.4 Example Script bullit.sci . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

D Scilab exercises 47D.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47D.2 Tables of multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48D.3 Plotting and writing tables of functions . . . . . . . . . . . . . . . . . . . . . . . . . 48D.4 Histogram analysis of random data . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

D.4.1 Writing random generator data to file . . . . . . . . . . . . . . . . . . . . . . 49D.4.2 Analyzing arbitrary random data from file . . . . . . . . . . . . . . . . . . . . 50

E Some useful Linux commands 51

F Using plot program xmgrace to plot 2-D x,y data sets 53

Page 4: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 4

1 Introduction

The course in ‘programming and modelling’ starts with a two week module on basic computerprogramming. This module will focus on program development and applications using the Fortranprogramming language. This first two week module consists of several instruction sessions andcomputer lab sessions, for which a total of four half days have been scheduled. The instructionsessions introduce the programming tools and the computer lab experiments to be done by thestudents. The experiments of the computer labs are done in the computer workstation rooms of theBuys Ballot Building, where (limited) assistence will be available, during the sessions scheduled forthe course.

Students work together in groups of two and each group produces a Lab report that has to besubmitted on the first monday after this module ends.

Concerning the course software: the course will be taught using the Linux operating system theGNU Fortran compiler.

The Scilab programming environment that was originally also applied in this course module isno longer used in the current set up. Information on Scilab is still available in the appendix of thissyllabus as a tutorial and set of programming problems.

Useful references on Fortran programming are,

• A.P. van den Berg, J. van Hunen and J.H. de Smet, Cursus Programmeren, (Dutch) CourseNotes, Institute of Earth Sciences, Utrecht University, 1999.(available on http://www.geo.uu.nl/~berg/progmod2)

• M. Metcalf, J. Reid and M. Cohen, FORTRAN 95/2003 explained, Oxford University Press,2008.

• S.J. Chapman, Fortran 90/95 for Scientists and Engineers, McGraw-Hill, 1998.

• http://www.dmoz.org/Computers/Programming/Languages/Fortran

• http://gcc.gnu.org/wiki/GFortran

• http://gcc.gnu.org/onlinedocs/gfortran

Page 5: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 5

2 Fortran programming exercises

2.1 Introduction

A tutorial overview of the main elements of the Fortran programming language is given in AppendixA. To get acquainted with the basics of applying Fortran, study the examples in the Appendix andwork through the exercises in the following sections. Include a short description of each exercise,together with the program source text and input plus output in your lab report for this coursemodule.

To get started with Fortran program development perform the exercises stated below. Useinput/output redirection such that you can save your input and output files for your lab report (seeAppendix A.2).

2.2 Tutorial exercises

2.2.1 Hello World

To test the different steps in the procedure of program development and excution write a rudimentaryfortran program hello_world (see Appendix A.2) that prints the text hello world in the terminalwindow.

2.2.2 A 2×2 equation solver

Write a program which prompts for the values a, b, c, d, f, g and returns the solution x, y of thefollowing linear system:{

ax+ by = fcx+ dy = g

1 Test the proper working of your program in the following way: 1) for a given test vector pairx = x0, y = y0 compute the corresponding vector pair f = f0, g = g0 by matrix-vector multiplicationand 2) solve the system of equations with the pair f0, g0 as the righthand side vector and 3) comparethe computed solution vector with the pair x0, y0.

2.2.3 Tables of multiplication

In all Fortran program units, (program, subroutine, function) you must put an implicit none

declaration after the first line of source code. This will enforce explicit typing of all variables usedin the program unit and removes an important source of programming errors.

You will use Fortran arrays and do-loop constructs to fill arrays with tables of multiplication(see A.6.1). Necessary input will be read from stdin and output will be written to stdout (seeA.2.1).

1Use the Cramer formula for the inverse A−1 of a matrix A with,

A =

(a bc d

), A−1 =

1

det(A)

(d −b−c a

)where det(A) = ad− bc is the determinant of matrix A.

Page 6: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 6

1. Write a Fortran program that can produce a single multiplication table. Use a one-dimensionalarray table1, which must be declared as a fixed length (10) array in the declaration block ofyour program.

Read the table number from stdin, denoted by ‘logical unit number’ 5, using ‘list directed’input (free format input), denoted by the asterisk character ‘*’.

read(5,*) numtable

Fill the table in a do-loop,

do i=1, 10

...

end do

The table array can be written using a ‘list directed output’ statement,

write(6,*) (table1(i),i=1,10)

Use output redirection to write the table data to a text file table1.dat.

2. Compute multiplication tables for n = 1, ...,m in a two-dimensional array table2.

Use an array declaration with fixed array lengths in both dimensions and make sure to declaresufficient array space. Fill the two-dimensional array table2 in a program control structure(construct) with two nested do-loops, see Appendix A.6 for an example.

do i=1,m

do j=1, 10

...

end do

end do

Check what happens if the array has been declared with insufficient arraysize. Print the 2-Dtable when it has been filled in a loop over table rows,

do i=1,m

write(6,*) (table2(i,j),j=1,10)

end do

Produce an output text file containing the 2-D table data.

Page 7: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 7

2.2.4 computepi

One can show that the number π can be computed as follows:

π = 4∞∑n=0

(−1)n1

2n+ 1

In practice∞ is a mathematical abstraction which computers cannot represent nor process. Thisis why we shall use

π = 4m∑n=0

(−1)n1

2n+ 1with m >> 1

Write a Fortran program that evaluates the series expression and prints the computed (approxi-mate) value of π. Compare the outcome of your calculation with the analytic value π = 4 ·arctan(1)that can be computed within machine precision using the Fortran intrinsic function atan. 2

To investigate the effect of different number representations (single or double precision realvariables - see Apppendix A.4) do the following tests and comment on the differences in the outcomefor different parameters and declarations of the real variables:

• declare the variable pi r as a (single precision) real

• compute and print pi r by means of the above formula with m=103, 106, 109.

• declare now the variable pi dp as a double precision real

• compute and print pi dp by means of the above formula with m=103, 106, 109.

2.2.5 Golden Ratio

Write a program which computes the Golden ratio φ through the Fibonacci numbers:

u0 = 1 u1 = 1 . . . un+1 = un + un−1

where the ratio un+1/un converges towards φ.

Compare your outcome with the formula φ = 1+√5

2 and determine how many Fibonacci numbersare necessary to get a correspondence in 5 decimals. 3

2.2.6 Computing and writing function tables to file

As in section D.3, compute a sine and cosine table for a single period and write the tables ofxi, sin(xi) and xi, cos(xi), i = 1, . . . , n to separate two-column output files. Apply the fortran proce-dure writdat listed in Appendix A.8.1 to write the different function tables to file. Inspect the datain these files by plotting them in a single frame using the graphics program xmgrace (see AppendixF). Produce a single graph showing both curves. The graph should include axis labelling and alegend to distinguish both curves. Export your completed plot to a graphics output file in a suitableformat. Include this plot in your lab report.

2http://gcc.gnu.org/onlinedocs/gfortran/ATAN.html3http://en.wikipedia.org/wiki/Golden ratio

Page 8: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 8

2.2.7 A modelling experiment using input and output files

The program for writing function tables, developed in the previous section, can be modified to obtaina simple modelling program for the computation of the trajectory of a point mass (bullet) launchedwith a given initial velocity in a uniform gravity field that falls back and impacts at the surface.

Consider a point mass launched vertically in a gravity field with given uniform gravitationalaccelleration g and initial velocity v0. Write a Fortran program that will read the values of g and v0from the standard input file. The program computes trajectory data of the point mass in separatetables, stored as 1-D Fortran arrays, containing the vertical coordinate and its corresponding verticalvelocity. The table entries correspond to discrete time values, ti = (i − 1) ·∆t, i = 1, . . . , n, for afixed time step ∆t. The tables are filled in a Fortran do-loop over n relevant time values betweenlaunch and impact. The time window covered in the computation should start with the launch andend with the final impact when the point mass returns at the point of departure. Use a subroutine tocompute the coordinate and velocity of the point mass for a given single time value ti. Use sufficienttable points to be able to produce smooth plot curves of the vertical coordinate and the velocity asfunctions of time in separate frames and label the axes of both graphs properly.

Write tables of your results to file for plotting with xmgrace using procedure writdat, describedAppendix A.8.1.

Necessary program input should be read from the standard input file. Use program inputredirection to read the input parameters from an input text file produced in advance and includethe input file in your lab report.

An example solution using Scilab and based on numerical integration of the equation of motion,Newtons second law, is described in Appendix C.9.

Page 9: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 9

2.3 Extended exercises

The previous sections contain several short tutorial exercises in Fortran programming. Here youwill encounter a number of exercises where a Fortran program and procedures must be written inorder to perform ‘numerical experiments’ where the results of the experiments are written to file forlater visualisation with available graphics software. This is characteristic for numerical modelling.

The computer programs to be written contain the following elements of the Fortran programminglanguage,

• arrays (A.5)

• program loops using different do-end do constructs (A.6.1)

• conditional statements and if then else constructs (A.6)

• subroutines and functions (A.8)

• file input/output with file control (open/close) statements (A.7)

• write statements for writing formatted data files (A.7)

2.3.1 Modelling stochastic processes using random number generators

In statistical physics processes are described mathematically in terms of stochastic processes. Thismeans that time dependent physical quantities are represented as stochastic variables with a certainprobability distribution. An example of this is a model for diffusion of heat or chemical substancewhere the physical quantity; temperature T or concentration C is modelled by the volume densityof virtual particles and the time dependent position of the particles is described by a random walkproces (brownian motion).

In geophysics one encounters random processes in the description of the subsurface as a randommedium where the material properties such as seismic wave velocity are defined as random variablesof the space coordinates. In reflection seismic exploration random series of seismic reflectors (1-Ddepth functions) are used as a model of the seismic structure to be resolved by analysis of reflectionseismograms.

In every day life you find less abstract applications of stochastic processes in games, with repeatedthrowing of a dice as a familiar example. The outcome of an experiment where a dice is thrownn times, producing a series of n integer numbers 1 ≤ xi ≤ 6, i = 1, . . . , N can be represented as astochastic proces.

A random variable is characterized by a probability density function P (x) wich has the propertythat integration (for continuous distributions a ≤ x ≤ b) or summation (for cases involving onlydiscrete values xi, i = 1, . . . , N), over all possible values of the random variable, gives a unit result,

∫ b

aP (x)dx = 1, (continuous x) ,

N∑i=1

P (xi) = 1, (discrete xi) (1)

In this exercise you will experiment with random numbers with different probability distributionsin particular the uniform distribution and the gaussian or normal distribution.

Page 10: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 10

A continous and a discrete uniform distribution which satisfy the normalisation conditions (1)are described respectively by,

P (x) =1

b− a, P (xi) =

1

N(2)

The normal or gaussian distribution, on (−∞,∞), with zero mean value is described as,

P (x) =1

σ√

2πexp

(−x2

2σ2

)(3)

where σ2 is the variance and σ is known as the standard deviation.The central-limit theoreme of probability theory states that the distribution of the mean value

of a large number N of independent random variables converges to a normal distribution in the limitfor large N . This means that the random variable y defined as,

y(N)i =

1

N

N∑j=1

xj (4)

approximates a gaussian distribution for sufficiently large N , for arbitrary distribution of x. Theindex i in yi indicates that we can obtain a new ‘sample’ of the random variable by forming asummation of N new independent samples of x.

This theoreme can be applied in the construction of a random generator with an approximatelygaussian distribution with mean value µ and standard deviation σ from summation of N samplesof a uniform random variable on the unit interval,

gi = µ+ σ

√12

N

N∑j=1

(xj −

1

2

)(5)

The normalisation numbers used in (5) are the mean value, 1/2, and variance, 1/12, of the variablex with uniform distribution on [0, 1].

Experiments with random number generators

Pseudo-random numbers with a uniform probability distribution can be computed recursively 4

and algorithms for these computations are available in intrinsic functions or subroutines in Fortranimplementations. The intrinsic subroutine random_number returns through its single parameter x arandom number with pseudo-uniform distribution between zero and one, P (x) = 1, 0 ≤ x < 1.

1. In a first experiment you will construct a ‘digital dice’ i.e. a computer program that canproduce a series of random numbers with discrete values di ∈ {1, . . . , 6}.Write a Fortran program that generates n dice samples, using the intrinsic subroutinerandom_number. Consider how you can convert the real numbers 0 ≤ x < 1 produced by therandom generator with uniform distribution on [0, 1) into integer numbers d with the correctdiscrete probability distribution.

4W.H. Press, S.A. Teukolsky, W.T. Vetterling, B.P. Flannery, Numerical recipes in Fortran 77 (second edition),Cambridge University Press, 1992.

See also: http://en.wikipedia.org/wiki/Pseudorandom number generator

Page 11: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 11

Hint: You should be able to write the transformation in a single line of Fortran code using theintrinsic function int which truncates real variables to integers by ‘removing’ the mantissapart of the real number value.

Store the sample values di in a 1-D array dice_data. The sample values are written to a twocolumn text file where the first and second columns contain the sequence number i and thesample value di respectively. To test the uniformity and statistic moments (mean value andvariance) of your ‘digital dice’ you should inspect the corresponding histograms and computedmean value and variance.

Histograms can be produced using the graphics program xmgrace, as explained in AppendixF.To characterise a series of random data the mean value and variance can be computed. Tothis end write a subroutine with the following subroutine header,

subroutine moments(ndata,data,meanvalue,variance)

implicit none

integer ndata

real, dimension(1:ndata) :: data

real meanvalue,variance

where the input parameters are, ndata the number of data in your sample and data the1-D array containing the sample data. Note that the program variable ndata is used here todeclare the length of the array, making the subroutine applicable for arbitrary data lengths.This way of array declaration in subroutines requires that both the array name and the variabledefining the array length are formal parameters, i.e. they both appear in the parameter listof the routine.

meanvalue and, variance are the output parameters giving the statistical estimates computedby the subroutine, defined by the following expressions,

µ =1

n

n∑j=1

dj , σ2 =1

n− 1

n∑j=1

(dj − µ)2 (6)

Investigate the effect of the sample length n on the testresult of your program and compare theresults of computations with the statistical values µ = 3.5, σ2 = 35/12. Include a histogramplot and values of µ and σ2 for a number of values of n in your report. Also include an xmgrace

plot of the random sequence dj .

2. In a second experiment you will construct a gaussian random number generator using theexpression (5). Write a subroutine that computes a single sample of a pseudo-gaussian randomnumber with a subroutine gaussn with the following subroutine header,

subroutine gaussn(xmu,sigma,samp,nsum)

implicit none

real xmu, sigma, samp

integer nsum

where the input parameters are, xmu the mean value, sigma the standard deviation, nsum thenumber of terms used in the summation in (5) and samp is the gaussian sample value computedin the routine.

Test your gaussian generator by writing random sequences of sample data to file as in theprevious item and

Page 12: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 12

• Compute the mean value and standard deviation of the random sequence with subroutinemoments from the previous item and check the resulting values with the input parametersof your subroutine gaussn. Comment on the level of agreement.

• Analyse a histogram of the generated data. Produce an overlay plot with the curve ofthe corresponding gaussian distribution (3).

Page 13: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 13

2.3.2 Matrix vector calculations

In many computational applications linear algebraic operations such as matrix-vector multiplicationplay an important role. In this exercise you will investigate alternative algorithms for the compu-tation of matrix-vector products and compare their efficiency in terms of compute time. For agiven n× n matrix A, with matrix coefficients aij , i, j = 1 . . . n and vector x with vector elementsxi, i = 1, . . . n, a product vector y = Ax, can be computed using the following expression,

yi =n∑j=1

aijxj (7)

An implementation of (7), where the coefficients aij are accessed sequentially along matrixrows, is given in the example of Appendix A.6.1, where the matrix coefficients are declared as theelements of a two-dimensional array variable. In fortran programs two-dimensional arrays are storedin memory in a columnwise way, i.e. a single index, say k, is used for specifying the memory address.In terms of the row and column indices i and j this index is k = n · (j − 1) + i.

With this memory organisation, accessing matrix coefficients sequentially along matrix rowsimplies that memory access will not be from adjacent memory locations, because neighboring coef-ficients aij , aij+1 are n memory positions, or one column length, apart. This causes delays in thetransport of the necessary data from memory, compared to access methods that are organised alongmatrix columns.

Therefore it may be more effcient to use an alternative algorithm organised with matrix columnsin stead of rows. This can be done by interpreting the result vector (7) as a weighted sum of matrixcollumn vectors,

y =n∑j=1

a(j)xj (8)

where a(j), j = 1, . . . , n are the column vectors of the matrix A, a(j)i = aij .

AssignmentCompare the computational efficiency of both alternative algorithms for matrix-vector productsby measuring the time elapsed during computation with the (gfortran) intrinsic system_clock. 5

Investigate how the compute time for the matrix-vector product depends on the dimension parametern of the matrix and vector. Produce a table of the elapsed system time versus the problem sizeand a corresponding (double logarithmic) plot with xmgrace. Indicate the data points by discrete(filled) symbols in your plot. Do a powerlaw regression with xmgrace on your data and interpretthe powerlaw exponent found in your results.

Write a fortran program for these experiments according to the following specifications:

• The program contains a 2-D array for the n × n matrix and 1-D arrays for the necessaryn-vectors.

• A convenient way to declare array sizes in a consistent way is by applying a fortran integer,say nsize with parameter attribute as in the following example for a 100× 100 matrix.

integer, parameter :: nsize=100

real, dimension(nsize,nsize) :: matrix

real, dimension(nsize) :: vector_x, vector_y

5http://gcc.gnu.org/onlinedocs/gfortran/SYSTEM 005fCLOCK.html

Page 14: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 14

This way you can easily adapt your program for different problem sizes by adapting a singleprogram parameter in your program source code.

In module two of the course ‘programming and modelling’ the use of dynamic arrays in fortranwill be introduced that provides further flexibility in defining problem sizes without having tochange the source code.

• Implement the ‘row-acces’ algorithm for the matrix-vector product in a fortran subroutinewith the subroutine header,

subroutine matrix_vector_mult_rowwise(nsize,matrix,vector_in,vector_out)

implicit none

integer nsize

real, dimension(nsize,nsize) :: matrix

real, dimension(nsize) :: vector_in,vector_out

• Implement the ‘column-acces’ algorithm for the matrix-vector product in a fortran subroutinewith the following header,

subroutine matrix_vector_mult_colwise(nsize,matrix,vector_in,vector_out)

implicit none

integer nsize

real, dimension(nsize,nsize) :: matrix

real, dimension(nsize) :: vector_in,vector_out

2.3.3 Iterative solution of a linear system of equations

The matrix-vector multiplications investigated in 2.3.2 can be applied in the classical iterative Jacobimethod for the solution of linear systems of algebraic equations. This method requires only matrix-vector multiplications besides vector summations. 6 The system to be solved is written as Ax = bwhere A is an n×n matrix, x is an unknown n-vector vector to be solved and b is a known righthandside n-vector.

Suppose the matrix is split in A = D + R where D is a diagonal matrix with Dii = aii andRii = 0. Then the original equation can be rewritten as,

Ax + Dx = Dx + b→ x = x−D−1Ax + D−1b (9)

The latter equation can be solved by the iterative method of succesive substitution,

x(k+1) = x(k) −D−1Ax(k) + D−1b , k = 0, 1, 2, . . . (10)

beginning from a suitable startvector x(0). Rewriting (10) in terms of vector elements, and explicitmatrix-vector multiplication we have,

x(k+1)i = x

(k)i +

1

aii

bi − n∑j=1

aijx(k)j

, i = 1, . . . , n (11)

It can be shown that this method converges for so called diagonally dominant matrices with|aii| >

∑j 6=i |aij |.

The expression (11) is a vector recursion that can be iterated until the solution vector hassufficiently converged in a suitable vector norm, i.e. the iteration is stopped when,

||x(k+1) − x(k)||||x(k+1)||

< ε (12)

6http://en.wikipedia.org/wiki/Jacobi method

Page 15: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 15

with ε a given relative precision. We choose the euclidean norm,

||x|| =

n∑j=1

x2j

12

(13)

AssignmentInvestigate the iterative Jacobi method for suitable, diagonally dominant matrices A with matrixcoefficients,

aij =1

(1 + |i− j|)p(14)

where p is a parameter that can be applied to control the diagonal dominance of the matrix.Write a fortran program in accordence with the following specifications:

• Fill the coefficients of matrix A using formula (14). Investigate the effect of different parametervalues p = 1, 2, 3, . . .

• A convenient target solution vector x, for testing purposes, can be defined with xi = i. Thecorresponing right hand side vector b can then be computed as b = Ax. Apply the procedurefor matrix-vector multiplication from (2.3.2) to evaluate this formula.

• The fortran program evaluates the recursion formula (11) until the convergence criterium (12)is satisfied.

• Use the nul-vector x0 = 0 as a startvector.

• Compute the matrix-vector product in (11) with the procedure developed in (2.3.2) and storethe result in an array that can be used in the recursion (11).

• A fortran function is used for the computation of the relative vector norm specified in (12)and (13), with the following function header,

real function rel_diff_norm(nsize,vec1,vec2)

implicit none

integer nsize

real, dimension(1:nsize) :: vec1,vec2

where nsize is the number of vector elements and vec1,vec2 are the two vectors involved.

• Compute a similar relative vector norm (12) of the actual error in the solution vector after theiteration has converged, using the exact solution vector xi = i as the reference vector.

• The highest attainable precision is dictated by the relative machine precission which is aboutεmach ∼ 10−7 for the single precision calculations applied. Investigate which precision isattainable by your program.

• Investigate how the number of Jacobi iterations required for a given precision, say ε = 10−4,depends on the dimension of the system nsize. Produce a plot showing the number ofiterations versus the dimension. Indicate data points as discrete filled symbols.

• (Optional) Investigate how the norm of the residue vector ||r|| = ||b−Ax|| decreases during theiterations. This could be used as an alternative stopping criterium for the iterative procedure.

Page 16: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 16

2.3.4 Fourier synthesis of a periodic boxcar function

Many (geo)physical modelling problems are defined in terms of equations that can not easily besolved directly but which can be solved by expanding the solution in a series of simple functions likesines and cosines. These series are named after Fourier, their ‘inventor’. These simple expansionfunctions can then be specified such that a suitable linear combination satisfies the original problemto be solved. Geophysical examples of this are the problem of a cooling layer with given boundarytemperature (Fouriers original problem), propagation of seismic waves, decomposed in plane har-monic waves, and the classical solution for the postglacial rebound problem where the time evolutionof the surface topography after melting of an ice-cap is determined.

In this exercise we concentrate on a part of this type of problem, namely the determinationof the minimum number of terms in a Fourier series, required to approximate the function with aspecified precision.

The purpose of the program to be developed is to investigate a Fourier series expansion of aperiodic boxcar (block pulse) function with a periodicity interval length of two, defined as,

b(x) =

1, 0 < x < 1−1, 1 < x < 2

0, x = n, n ∈ Z (integer numbers)(15)

This function b(x) can be expanded in a Fourier series defined as,

b(x) =∞∑m=0

am sin(mπx) (16)

The coefficients am of the Fourier series are known as the spectral coefficients or as ‘the Fourierspectrum’. For the coefficients of the Fourier series it can be shown that,

am =

{0, m even

4mπ , m odd

(17)

It can also be shown that a simple relation exists for the ‘energy’ of the function and its ‘power-spectrum’, expressed in the following,

E2 =

∫ 2

0b2(x)dx =

∞∑m=0

a2m (18)

This formula can be used to obtain a truncation criterium for the Fourier series expansion in anactual calculation. This way the Fourier series is truncated when the partial sum of the powerspectral series has sufficiently approached the total energy of the function or when,

δE2N = E2 − E2

N =

∫ 2

0b2(x)dx−

N∑m=0

a2m < ε (19)

for some specified small value say ε = 10−3.

Experiments with a truncated Fourier series

Write a Fortran program to investigate the effect of truncating the infinite Fourier series of theperiodic boxcar function after a finite number of terms. The program should be in accordance withthe following specifications.

Page 17: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 17

1. In the first part the minimum number of series terms necessary according to the energy cri-terium (19) is determined. This is done by computing the energy ‘deficiency’ δE2

N in a pro-gram loop over the series coefficients. The loop exits when the criterium (19) is met. Relevantquantities like the series coefficient am, the powerspectral coefficient a2m and δE2

N are storedin separate arrays for later plotting. Use an infinite do-end do construct for this program loopthat can be exited when the convergence criterium is met. After convergence and exit of thisloop the coefficients stored in separate arrays must be written to file in a suitable format forplotting with xmgrace. Include plots using logaritmic scaling in your labreport.

In order to output different arrays to file, a Fortran subroutine should be used. This routinewrites a two-column table contained in two 1-D arrays to a text file. Each line of the outputfile contains two numbers corresponding to a single table row. The output routine has thefollowing interface,

subroutine writdatfile(ndata,xdata,fdata,filename)

implicit none

integer ndata

real xdata(*), fdata(*)

character(LEN=*) filename

Apply this routine to write tables of the series coefficient am, the powerspectrum coefficienta2m and the energy deficiency δE2 to separate output files.

2. In the second part of the program the truncated Fourier series is evaluated up to the numberof terms Nconv, determined in part one. A table is filled with the function values of thetruncated Fourier series for a sufficient number of points, say 1000, to resolve the parts withsteep gradients of this function. Here the value of the truncated series is computed in a grid ofevaluation points, xi = xmin+(i−1)∆x, i = 1, 2, . . . , nx, where ∆x = (xmax−xmin)/(nx−1).

The truncated series,

bN (xi) =N∑m=0

am sin(mπxi), i = 1, 2, . . . , nx (20)

is stored in an array with index i. This array is filled in two nested program loops over thefunction grid points and the F-series terms respectively, using the recursion formula,

bN (xi) = bN−1(xi) + aN sin(Nπxi), i = 1, 2 . . . , nx (21)

Write tables of the first few truncated series bN (xi) to file, say the first 50, N = 0, 1, . . . 50, toseparate output files with subroutine writdatfile specified above under item 1.

Use the Fourier series index m encoded in the file names to distinguish the different results.This can be done using a Fortran ‘internal file’ with

write(datfname,’(’’./DATA/fpartial.’’,i3.3)’) m

where datfname is a character type variable which must be declared with sufficent length tohold the pathname of the target data file. The integer format specification i3.3 will producea three-digit number padded by leading zero’s.

Page 18: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 18

Include xmgrace plots of the computed tables of am, a2m and δE2 in your lab report. Alsoproduce a single figure with 2X2 frames (see arrange graphs option in Appendix F) showinggraphs of two truncated Fourier series per frame ntrunc = (0, 1), (2,3), (5,10) and (20,50). Useplotlegends to identify the different curves in the frames.

Page 19: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 19

Appendix

A A Fortran Tutorial

A.1 Introduction

Fortran is the predominant programming language in the field of scientific and numerical comput-ing. In order to use a Fortran program, the program source text, possibly extended with externalprocedures must be translated in to machine language (compiled) using a compiler program. OnLinux/unix systems an open software (GNU) Fortran 77 compiler g77 is available. Recently theGNU Fortran 95/2003 compiler (gfortran)has also become available. This compiler has been in-stalled on the institute network and will be used in this course.

A.2 Installing and executing a Fortran program

To create a simple Fortran program, the Fortran source text of the program must be written in atext file, say prog.f90, using a text editor, similar as with the preparation of a Scilab script. Thefile name extension .f90 is a (compiler) requirement for the use of the Fortran 90 extended sourcetext format (see below). When the complete program text is available the program can be installedusing the Fortran compiler, gfortran, by typing on the command line,

gfortran prog.f90

If no syntax errors are found by the compiler, this command will produce an executable file with thedefault name a.out, or when using the -o option as in,

gfortran -o exec-file prog.f90

the executable will be written to the file exec-file. The program can then be executed by typing onthe command line the name of the executable file, either a.out or exec-file. More information onthe many possible compiler options is available through the online Linux manual page which can beaccessed by typing man gfortran from the command line.

Page 20: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 20

Figure 1: From Fortran source text file to resulting program output (text/graphics). An executableprogram file prog is made from (a) Fortran source text file(s) with a compiler/linker programgfortran.

As a first example of installing and running a rudimentary Fortran program consider the followingthree line ‘main program’,

program hello_world

print *, ’hello world’

end program

This program is compiled and installed in a default executable file a.out in the working directoryby typing the command,

gfortran hello_world.f90

Typing a.out from the command line will then produce the output line

hello world

A.2.1 Input/output redirection

Programs often read input from ascii (text) input files and write output results to output text files.In case your program uses a single input and/or output file, a convenient way to implement thisis through the use of the standard input (stdin) and output (stdout) device. When reading fromstdin your program will expect input from the keyboard, when writing to stdout your programwrites output to the screen. This is convenient while developing a small program, but in case ofextended program input and output, it is more convenient to read input from a text file which hasbeen prepared in advance and print results to another text file which can be inspected using a texteditor, instead of printing on the screen. A program which has been prepaired to use stdin andstdout can be used without modification to read from a named input file, prog.in and write outputto the named file prog.out using so called input/ouput redirection by typingprog < prog.in > prog.out

A.3 Fortran source text formats

Fortran text is not case sensitive, upper and lower case text are not distinguished by the Fortrancompiler. Fortran source texts come in two alternative formats, known as fixed and free source

Page 21: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 21

format, distinguished by the two filename extensions .f and .f90 respectively. The fixed format isrequired by the older Fortran 77 standard. Here source text lines are truncated after position 72 andthe first 6 positions are reserved. Position 1 through 5 can be used for 5 digit numerical statementlabel fields and postion 6 for a continuation character (see below).

Comment lines in fixed format files are specified by a c or * in position 1. In free format source,text following the ! character up to the end of the text line is interpreted as comment text.

Fortran source lines can be continued over several text lines. In the fixed source format thisis done by having a blank (space) in position 6 of the initial statement line and a non-blank (andnon-zero) character in position 6 of the continuation lines. In free source format a source line endedby the & character is continued on the next text line.

A.4 Program variables

All variables used in Fortran programming units must be declared with an explicit type declaration.This is enforced by including the statement implicit none as the second line of code of everyprogram unit. The main intrinsic data types of the Fortran language are integer, real, logicaland character. Integer and real variabeles can have the value of integer and (rounded) real numbersrespectively. 7

Logical variables take the values true or false, denoted as .true. and .false. in Fortranassignment statements. Character variables are used to hold text strings of characters. Besidesintrinsic data types Fortran 90 and later versions also support so called derived types which can bedefined by the user.

Program units are split in two blocks

1. A declaration block containing all the necessary declaration statements.

2. An execution block containing all the executable statements, i.e. all statements that result inprogram actions.

The following example shows the declaration of several real variables and a number of assignmentstatements where values are assigned to program variables. Arithmetic expressions are used in theassignments containing, the arithmetic operators +,-,*,/ for summation, subtraction, multiplica-tion and division and the ** for exponentiation. Also used is the Fortran intrinsic function for thesquare root sqrt. Finally values of variables are written on the screen in a print statement.

program quad_polynom_roots

implicit none

real a,b,c,x1,x2

a = 1

b = -6

c = 6

x1 = ( -b - sqrt( b**2 -4*a*c ) ) / (2*a)

x2 = ( -b + sqrt( b**2 -4*a*c ) ) / (2*a)

7Real numbers are represented with finite precision using binary number representation. The precision depends onthe number of binary digits (bits) used in the representation. The default is 32 bit (4 bytes) representation. Whenhigher precision is required to prevent loss of accuracy real type variables should be declared with double (8 byte)precision using real*8 as type declarator.

Page 22: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 22

print *, ’x1=’,x1,’ x2=’,x2

end

A.4.1 Variables of type character

Character type variables are used in Fortran programs to manipulate text strings. This is particularlyapplied in the definition of filenames (see A.8.1).

Character variables must be declared with a length parameter as in the following example.

program exm_char

implicit none

character(len=5) text_string

text_string(1:2) = ’aa’

text_string(3:4) = ’bb’

text_string(5:5) = ’c’

print *, text_string

end program exm_char

This produces the output aabbc. In this example a substring mechanism is used to define subsetsof the character string. A.8.2 contains an example of character variables in producing simple ‘print-plots’ of numerical data.

A.5 Indexed variables

Fortran contains a rich syntax for dealing with indexed variables or arrays. We only mention somesimple applications of 1-D and 2-D arrays here, illustrated in the following program example.

Array variables must be declared as such and this can be done in several alternative ways. We usehere only one type of array declaration that can be used in case the array index starts at the defaultvalue one. The array attribute of the variables is implied here by specification of the bracketedupper value of the array indices in the respective dimensions.

program mat_vec

implicit none

real vec(2)

real res(2)

real mat(2,2)

vec(1) = 1.0

vec(2) = 0.5

print *, ’vec’, vec

mat(1,1) = 1.1

mat(1,2) = 1.2

mat(2,1) = 2.1

mat(2,2) = 2.2

print *, ’mat’, mat

res(1) = mat(1,1)*vec(1) + mat(1,2)*vec(2)

res(2) = mat(2,1)*vec(1) + mat(2,2)*vec(2)

print *, ’res’, res

end

This program produces the following screen output,

Page 23: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 23

vec 1.000000 0.5000000

mat 1.100000 2.100000 1.200000 2.200000

res 1.700000 3.200000

A.6 Program Control Structures (constructs)

A.6.1 Program loop statements

To work with indexed variables in so called program loops, the Fortran do-end do construct is used.The syntax of this construct can be specified by,

do i = i_begin, i_end, i_step

... executable statements ...

end do

The statements between do and end do will be executed repeatedly for subsequent valuesof the index variable, i = i_begin, i_begin + i_step, i_begin + 2*i_step, ..., i_end.Note that the index increment may be negative. The loop statement block is not executed ifthe index exceeds i_end in the first loop cycle.

program mat_vec_do_loop

implicit none

real vec(2)

real res(2)

real mat(2,2)

integer i,j,n

n=2

vec = 0.0 ! initialise array using vector syntax

do i=1, n ! fill

vec(i) = 1.0/i ! the vector

end do ! array

print *, ’vec=’,vec ! write the vector array on the screen

mat = 0.0 ! initialise the (2X2) matrix

do i=1,n ! fill the matrix

do j=1,n ! in nested loops over

mat(i,j) = 1.0/(1+ abs(i-j)) ! columns (inner loop j)

end do ! and rows (outer loop i)

end do

print *, ’mat=’, mat ! write the matrix

res = 0.0

do i=1,n ! matrix-vector multiplication

do j=1,n ! in nested loops over

res(i) = res(i) + mat(i,j)*vec(j) ! columns (inner loop j)

end do ! and rows (outer loop i)

end do !

print *, ’res=’, res ! write the result vector

end program mat_vec_do_loop

This program produces the following screen output,

vec= 1.000000 0.5000000

mat= 1.000000 0.5000000 0.5000000 1.000000

res= 1.250000 1.000000

Page 24: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 24

A special case of a Fortran do-loop is used when the number of loop cycles is not known in advance.This is implemented as an infinite loop which exits when an explicit stop criterium is met.

do

... executable statements ...

if ( logical expression ) exit

... executable statements ...

end do

The loop iteration is stopped when logical expression results in the value .true. and programcontrol continues at the first exectutable statement following end do. This construct is used incontrolling the convergence of iterative computations such as evaluation of series expansions, oriterative computation of the roots (zero points) of a non linear function.

A.6.2 Conditional Statements and logical expressions

To control the program flow in computer programs conditional statements are used. The if ( ...

) exit in the above infinite do-loop is an example of this. Conditional statements switch theprogram control flow depending on the value of a logical expression as in the example below. Themain construct involving a conditional statement is the if then else end if construct.

program exm_ifthenelse

implicit none

integer i, nmax

logical even

character(len=5) label

nmax = 3

do i=-nmax,nmax

even = mod(i,2) == 0 ! intrinsic modulo function

if ( even ) then

label = ’even’

else

label = ’odd’

end if

if (i <=-2) then

print *, i, ’ is ’,label, ’ and less or equal minus two’

else if (i > -2 .and. i < 0) then

print *, i, ’ is ’,label, ’ and negative’

else if (i == 0) then

print *, i, ’ is ’,label, ’ and zero’

else

print *, i, ’ is ’,label, ’ and positive’

end if

end do

end program

Note the use of the ==, <=, > and < relational operators in the if then statements. Thisprogram illustrates also the use of logical expressions and logical variables. The program producesthe following screen output,

-3 is odd and less or equal minus two

-2 is even and less or equal minus two

-1 is odd and negative

Page 25: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 25

0 is even and zero

1 is odd and positive

2 is even and positive

3 is odd and positive

A.7 Program Input/Output

In general it is advisable, in setting up a modelling experiment, to enter the model parametersin a text file from which they can be read by a modelling program. This way a flexible programset-up can be used which will be applicable, not just for a single modelrun, but for a range ofmodels. Reading input data from files and echoing input data to a program log-file is essential fordocumenting modelling experiments. Writing modelling results to output data files is necessary forpostprocessing and reporting.

To read data from input files and write results to output files several input/output (I/O) functionsare available. We show here the open and close statemens for connecting respectively disconnectingdata files to your Fortran program and the read, write and print statements.

program exm_io

implicit none

integer unitin, unitlog, unitout

integer i,ndata_out

character(len=80) fname_data_out

unitin = 11

open(unitin,FILE=’exm_io.in’) ! open the input file

read(unitin,*) ndata_out ! read # output data

read(unitin,*) fname_data_out ! read filename output data

unitlog = 12

open(unitlog,FILE=’exm_io.log’) ! open the log file

write(unitlog,*) ’ndata_out =’, ndata_out

write(unitlog,*) ’fname_data_out=’, fname_data_out

unitout = 13

open(unitout,FILE=fname_data_out) ! open the output file

do i=1,ndata_out ! write output data

write(unitout,*) i, i**2

end do

close(unitin) ! close all open files

close(unitlog)

close(unitout)

end program

In this example different files are connected to the program simultaneously that can be accessedthrough a unique logical unitnumber. Note how file names are specified either as literal characterconstants or as character variables in the open statements.

A Fortran equivalent of the external Scilab I/O procedure writdat in C.7 is given in sectionA.8.1.

A.8 Procedures, subroutines and functions

Two types of program procedures exist in Fortran, subroutines and functions. Subroutines must beexecuted through an explicit ’procedure call’ statement, where a list of parameters is passed to the

Page 26: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 26

procedure as in the example below.

program exm_subroutine

implicit none

real xtable(10),ytable(10)

integer i,n

real a,b,dx,xmin,xmax

n=3

xmin = 0.0; ! set range of x table

xmax = 2.0; !

dx = (xmax-xmin)/(n-1); !

a = 2.0; ! set parameters passed

b = 1.0; ! to the subroutine

do i=1,n

xtable(i) = xmin + (i-1)*dx

call subr(a,b,xtable(i),ytable(i))

print *, ’i=’,i,’ x=’,xtable(i),’ y=’,ytable(i)

end do

end program

!-------------------------------------------------------------------

subroutine subr(a,b,x,y)

implicit none

real a,b,x,y

y = a * x + b

end subroutine

Note how individual elements of the table x, y arrays are passed as so-called actual parametersfrom the main program to the subroutine. The corresponding parameter in the subroutime sourcetext is referred to as a formal parameter. The names of the actual and formal parameters may bedifferent as in this example.

A number of often used program procedures is available in Fortran as intrinsic functions. Examplesare procedures for the evalution of math functions like the square root, sine and cosine ( sqrt, sin,cos) etc. In the following example a similar procedure as in the foregoing example is implementedas an external (non-intrinsic) function. The function is declared as a variable of the same nameas the function and the external procedure nature is specified as a so called attribute. A list ofattributes is terminated by a double semicolon.

program exm_function

implicit none

real xtable(10),ytable(10)

integer i,n

real a,b,dx,xmin,xmax

real, external :: func ! declare func as external function

n=3 ! def. table length <= 10

xmin = 0.0; ! set range of x table

xmax = 2.0; !

dx = (xmax-xmin)/(n-1); !

a = 2.0; ! set function parameters

b = 1.0; !

do i=1,n

xtable(i) = xmin + (i-1)*dx

ytable(i) = func(a,b,xtable(i))

Page 27: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 27

print *, ’i=’,i,’ x=’,xtable(i),’ y=’,ytable(i)

end do

end program exm_function

!-------------------------------------------------------------------

real function func(a,b,x)

implicit none

real x,a,b

func = a * x + b

end function func

These programs produce the following screen output,

i= 1 x= 0.0000000 y= 1.000000

i= 2 x= 1.000000 y= 3.000000

i= 3 x= 2.000000 y= 5.000000

Note the difference between the use of the subroutine and the function in returning the computedresult from the procedure to the ‘calling program unit’. In the subroutine example the result is passedas a procedure parameter. In case of a function the result must be returned by assigning the resultvalue to a function variable with the same variable name as the function procedure. Note also thatin every program unit, main program, subroutine or function, all the occuring variables must bedeclared locally in an explicit type declaration.

A.8.1 A subroutine for writing table data to a 2-column text file

A Fortran equivalent of the external Scilab I/O procedure writdat in C.7 is the following subroutinefor writing table data to a two-column text file,

subroutine writdat(ndata,xdata,fdata,filename)

implicit none

integer ndata

real, dimension(ndata) :: xdata, fdata

character(LEN=*) filename

!* locals

integer i

open(UNIT=9,FILE=filename)

do i=1,ndata

write(9,*) xdata(i),fdata(i)

end do

close (9)

return

end subroutine writdat

A.8.2 A subroutine for making a printplot frame

In previous times when graphics screens where not widely available simple print plots were used forthe visualization of digital measurement data such as seismograms. In such printplots the graphof a datacurve is approximated by a series of character symbols printed to a low resolution outputdevice - (text) terminal screen of (text) file.

The following figure shows an example of a sine function plot produced in this way, using 20rows of 100 characters each.

Page 28: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 28

|---------+---------+---------+---------+---------+---------+---------+---------+---------+--------|

| *********** |

| **** **** |

| *** *** |

| ** ** |

| ** ** |

| ** ** |

| ** ** |

| ** ** **

** * ** |

| ** ** |

| ** * |

| ** ** |

| ** ** |

| ** ** |

| ** *** |

| *** ** |

| *** **** |

| ************ |

|---------+---------+---------+---------+---------+---------+---------+---------+---------+--------|

The subroutine fill_frame listed below has been applied to initialize the character arrayscreenbuf with blank characters and fill the empty buffer with a simple plot frame.

subroutine fill_frame(nrow,ncol,screenbuf)

implicit none

integer nrow,ncol

character(LEN=ncol) screenbuf(nrow)

integer i,i_inv,j

character(len=1) symbol

character(len=1), parameter::blanc=’ ’,dash=’-’,bar=’|’,tic=’+’

! clear buffer

do i=1,nrow

screenbuf(i) = blanc

end do

do j = 1, ncol ! fill horizontal frame boundaries

if( mod(j-1, 10) .eq. 0) then

symbol = tic

else

symbol = dash

end if

screenbuf(nrow)(j:j) = symbol

screenbuf(1)(j:j) = symbol

end do

do i = 1, nrow ! * vertical boundaries

i_inv = nrow-i+1

if( mod(i_inv, 10) .eq. 0) then

symbol = tic

else

symbol = dash

end if

screenbuf(i_inv)(1:1) = bar

screenbuf(i_inv)(ncol:ncol) = bar

end do

return

end subroutine fill_frame

Page 29: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 29

B Supplementary Fortran programming exercises

B.1 Introduction

B.1.1 Computation of arithmetic, geometric and harmonic mean values

One can define the arithmetic, geomteric and harmonic averages of n values as follows

A =1

n

n∑i=1

xi G = n

√√√√ n∏i=1

xi H =nn∑i=1

1xi

• create an array tab of size m=33

• fill it with random numbers between 0 and 1

• compute A, G, and H with do loops

• compute A, G, and H in one line of code by means of intrinsic functions

• multiply the array tab by 1023. Compute A,G,H again. Do the results conform with yourexpectations ? How could we compute G differently ?

B.1.2 Computation of the p-norm of a vector

The Euclidean norm of a vector a = (a1, a2, a3) in three dimensions is given by

|a|2 =√a21 + a22 + a23 or |a|2 = (a21 + a22 + a23)

1/2

One can generalise this by defining the p-norm of an n−dimensional object u as follows:

|u|p = (|u1|p + |u2|p + |u3|p + |u4|p + ...|un|p)1/p =

(n∑i=1

|ui|p)1/p

• write a subroutine pnorm which computes the p-norm of an array uuu of size n

• write a simple program which

1. creates an array of size m=123

2. fills the array with random numbers between -π and π,

3. computes and displays the 1, 2, 5, 10, 100-norm of this array

B.1.3 The bubble-sort procedure for sorting numbers

The bubble-sort algorithm is a simple method for sorting a list of numbers, ai, i = 1, . . . , n, inascending order that works according to the following stepwise specification,

1. Compare a1 and a2 and swap the numbers if a2 < a1

2. Compare a2 and a3. If a3 < a2 swap a3, a2 and repeat item 1

Page 30: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 30

3. Repeat item 2 and for all subsequent numbers in the list: comparing it succesively with itspredecessor in the list and swapping until a smaller number is encountered.

Write a subroutine with the following header that will apply the bubble-sort algorithm to a listof integers

subroutine bubblesort(ndata,numbers)

implicit none

integer ndata, numbers(*)

...

end subroutine bubblesort

B.1.4 A function to determine the length of a 2-column data file

Subroutine writdat A.8.1 is used frequently in this course for writing 2-column data tables to atext file. In order to read the data from such 2-column files in your programs it is necessary todetermine first the length of the file. This way it can be verified that arrays of sufficient length areused to store the file data in memory.

To this end write a fortran function with the following header to determine the number of dataon the file.

integer function scandat(filename)

implicit none

character(LEN=*) filename

...

end function scandat

The number of data is returned through the function name.

Hints:

• Use an endless-do construct as in A.6 to read the data lines on the file.

• Apply an extended version of the read statement, specifying the END clause, reading thecharacter variable textstring

do

...

read(UNIT=logical_unit,FMT=’(a)’,END=100) textstring

...

end do

100 continue

This causes the program to continue at the 100 continue line when the end of file conditionoccurs.

B.1.5 A function to read data from a 2-column data file

Subroutine writdat A.8.1 can be used for writing 2-column data tables to a text file. The numberof data on an existing file can be determined by scanning the file with function scandat definedabove in B.1.4.

Once the number of data on a file is known one can read the 2-column data from the file intwo 1-D arrays of sufficient size. This can be done in a similar way as in writing the data to file insubroutine writdat listed in A.8.1.

To this end write a fortran subroutine readdat with the following header to read the 2-columndata from the input data file.

Page 31: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 31

subroutime readdat(ndata,xdata,ydata,filename)

implicit none

integer ndata

character(LEN=*) filename

...

end subroutime readdat

Hints:

• Test your implementation of readdat by applying it in a main program where the call toreaddat is preceded by a call to scandat.

• Build an array length check in your program that produces an error message and a programSTOP when the number of file data exceeds the declared array length.

B.1.6 Printplot of a 2-column data table

In section A.8.2 printplots of 2-column data sets have been introduced. A subroutine for initializinga simple plotframe in a Fortran character array is listed there.

Once the plot frame has been initialized a 2-column data set can be plotted. To this end thendata data points must be mapped in the 2-D rectangular character buffer screenbuf of nrow linesand ncol columns using substring operations in a similar way as in the example in A.8.2 in A.8.2.

Write a subroutine printplot with the following header for mapping the 2-column data in thecharacter array screenbuf

subroutine printplot(xdata,ydata,ndata, &

xmin,xmax,ymin,ymax, &

nrow,ncol,screenbuf)

implicit none

real, dimension(*):: xdata, ydata

real xmin,xmax,ymin,ymax

integer ndata,nrow,ncol

character(LEN=ncol) screenbuf(nrow)

...

end subroutine printplot

Hints:

• Parameters xmin,xmax,ymin,ymax define the represented data window. This allows to zoomin on the data.

• Mapping data points xi, yi, i = 1, . . . ndata within the data window [xmin, xmax]× [ymin, ymax]is done by the following transformation,

irow = 1 + nint((nrow-1)*(ydata(i)-ymin)/(ymax-ymin))

jcol = 1 + nint((ncol-1)*(xdata(i)-xmin)/(xmax-xmin))

screenbuf(nrow-irow+1)(jcol:jcol) = symdata

• Test your implementation of printplot by applying it in a main program where the call toprintplot is preceded by a call to fill_frame (A.8.2) and followed by a call to a printoutof the screenbuffer by a call to the following routine print_screenbuf

Page 32: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 32

subroutine print_screenbuf(nrow,ncol,screenbuf)

implicit none

integer nrow, ncol

character(LEN=ncol) screenbuf(nrow)

integer i

! print the screen buffer array

do i =1, nrow

write(6,’(a)’) screenbuf(i)(1:len_trim(screenbuf(i)))

end do

return

end subroutine print_screenbuf

B.1.7 Removal of the mean value of a time series

Problem (Exam) Imagine you want make a computer program that can perform simple dataprocessing on measurement data that are read from an input file. The measurement data arerepresented by a time series si = s(ti), i = 1, . . . , N that correspond to signal values from a digitalmeasurement device, say a seismograph.

A single time series is stored as a 2-column text file, containing real number data, where thefirst column represents the measurement times ti, i = 1, . . . , N and the second column contains themeasurement data values si, i = 1, . . . , N .

Suppose you want to process the measurement time series by removing the meanvalue from thedata. To this end you want to transform the input time series data si into a output time seriess′i = si − µ, where µ = 1

N

∑Ni=1 si is the mean value of the input data.

After procesing the data you want to write the resulting time series to an output file with anidentical file structure as used for the input data.

Assignment Write a fortran program for the data processing task described in the introduction.The program must be created according to the following specifications:

• The program applies two 1-D allocatable arrays for the measurement time values and themeasurement data values respectively.

• The program reads the number of avalailable data, N , from the standard input device (unit6).

• The program reads the input time series data from an input file named timeseries_in.dat

and writes the processed time series to an output file name timeseries_out.dat

• The output file is written using a fortran subroutine writdat with the following routine header,

subroutine writdat(ndata,xdata,ydata,filename)

integer ndata

real xdata(*),ydata(*)

character(LEN=*) filename

N.B. you don’t have to write this subroutine.

• Input data are processed in a do-loop over the avaible data points and the output data valuesare overwriting the input data, thereby using a single array for both input- and output data.

Page 33: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 33

C A Scilab Tutorial

C.1 Introduction

Scilab is an integrated tool for program development and application: including extensive graphicsfacilities for direct visualization of computational results.

Documentation for the Scilab environment is available in the online integrated help manual,accessible through a help menu button in the Scilab program. There is also an introductory manualavailable online from the scilab home page http://www.scilab.org.

The software for the Scilab programming environment is open software that can be downloadedfrom the Scilab home page. Scilab is also available for the Windows environment which makes italso useful for student home computers which may still be running Windows.

Figure 2: From a Scilab script file to resulting model output (text/graphics).

The common way to use Scilab is through a script (text) file containing program statements inthe Fortran like syntax of the Scilab programming language. Such a program script file is madewith a text editor like vi, or gedit. The Scilab package comes with it’s own ‘intuitive’ text editorscipad that highlights different syntax elements.

The scriptfile must be prepared in a text file say script.sce. Filename extensions .sce or .sci

ar not obligatory but are used to denote such scripts also in the on-line manual. After preparationof the scriptfile the latter can be executed by the Scilab program.

To this end the program is invoked by typing on the Linux command line scilab. The programis then started and a window opens with several menu buttons and a Scilab command line whereinteractive commands can be typed. To execute the script file type on the command line exec

script.sce. To modify the program script during development you can use the text editor. Aftersaving your modifications in the script file you can execute the script again by repeating the exec

command. This can be done conveniently by using the cursor arrow key ↑. A history list of previouscommands typed on the Scilab command line is stored and specific lines from this list can be editedusing the cursor arrow keys and the backspace key. A similar command line editing facility alsoexists for the Linux shell (command interpreter).

In the following a number of basic language elements of the Scilab program are introduced inshort examples. A concise description of these elements can also be obtained using the integratedon-line Scilab manual, accessible through the help menu button of the Scilab window.

Page 34: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 34

C.2 Program variables

Program variables are used to refer to data objects that are operated on by the program. Suchvariables are represented by symbolic names in the program source text. In contrast to programminglanguages such as Fortran or C, variables do not have to be declared explicitly in Scilab scripts beforethey are actually used.

Sourcetext files may contain comment text preceded by ’//’. Characters following ’//’ on aline of source text are interpreted as comment text that can be used to increase the readability.Comment text is ignored by the scilab interpreter. Source statements (commands) may be brokenup in several lines, where a double dot ‘..’ is used as the continuation sign. If a semicolon ’;’ isused to close a Scilab program statement the statement will be exectuted without screen output.Without the semicolon Scilab will print the result of the statement on the screen.

As an example of the use of variables in arithmetic expressions consider the following text linesspecifying the computation of the roots of a quadratic equation one can execute the following script,

a = 1

b = -6

c = 6

x1 = ( -b - sqrt( b**2 -4*a*c ) ) / (2*a)

x2 = ( -b + sqrt( b**2 -4*a*c ) ) / (2*a)

producing the following output,

a =

1.

b =

- 6.

c =

6.

x1 =

1.2679492

x2 =

4.7320508

Adding semicolons to every statement as in the following suppresses screen output of interimresults,

a = 1;

b = -6;

c = 6;

x1 = ( -b - sqrt( b**2 -4*a*c ) ) / (2*a);

x2 = ( -b + sqrt( b**2 -4*a*c ) ) / (2*a);

write(%io(2),[x1,x2],’(’’x1=’’,e13.6,’’ x2=’’,e13.6)’)

This produces the following screen output,

--> a = 1;

--> b = -6;

--> c = 6;

Page 35: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 35

--> x1 = ( -b - sqrt( b**2 -4*a*c ) ) / (2*a);

--> x2 = ( -b + sqrt( b**2 -4*a*c ) ) / (2*a);

--> write(%io(2),[x1,x2],’(’’x1=’’,e13.6,’’ x2=’’,e13.6)’)

x1= 0.126795E+01 x2= 0.473205E+01

where the screen output of the results is now produced by an explicit write statement, where thetwo output numbers are treated as a single object, a list, denoted by the square brackets.(see help > Input/Output Functions > write).

C.3 Indexed variables

Indexed variables are generally denoted as arrays. Variables with a single index, one-dimensional(1-D) arrays, are called vectors and variables with two indices, two-dimensional (2-D) arrays, arecalled matrices in the Scilab documentation. The example below illustrates the use of a 2-vectorand 2× 2 matrix.

clear;

vec(1) = 1.0;

vec(2) = 0.5;

write(%io(2),vec,’(’’vec’’,e13.6)’)

mat(1,1) = 1.0;

mat(1,2) = 0.5;

mat(2,1) = 0.5;

mat(2,2) = 1.0;

write(%io(2),mat,’(2e13.6)’)

res(1) = mat(1,1)*vec(1) + mat(1,2)*vec(2);

res(2) = mat(2,1)*vec(1) + mat(2,2)*vec(2);

write(%io(2),res,’(’’res’’,e13.6)’)

producing the following output,

--> clear;

--> vec(1) = 1.0;

--> vec(2) = 0.5;

--> write(%io(2),vec,’(’’vec’’,e13.6)’)

vec 0.100000E+01

vec 0.500000E+00

--> mat(1,1) = 1.0;

--> mat(1,2) = 0.5;

--> mat(2,1) = 0.5;

--> mat(2,2) = 1.0;

--> write(%io(2),mat,’(2e13.6)’)

0.100000E+01 0.500000E+00

0.500000E+00 0.100000E+01

--> res(1) = mat(1,1)*vec(1) + mat(1,2)*vec(2);

Page 36: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 36

--> res(2) = mat(2,1)*vec(1) + mat(2,2)*vec(2);

--> write(%io(2),res,’(’’res’’,e13.6)’)

res 0.125000E+01

res 0.100000E+01

C.4 Program Control Structures (constructs)

C.4.1 Program loop statements

To work with indexed variables the use of program loops over blocks of program statements is anessential tool. This can be done with a for loop construct, (see help > Programming > for).

An elementary example is the following implementation of the ’gauss’ algorithm for the summa-tion of the first n natural numbers.

n = 100

data = [1:1:n];

result = 0

for i=1:n,

result = result + data(i);

end

an = n*(n+1)/2

fprintf(%io(2),’result=%5i, an=%5i’,result,an)

The matrix-vector multiplication shown in C.3 can be rewritten for arbitrary vector length n andn×n matrix in the following way using program loop constructs. Note that text indentation (variablenumber of leading blanc characters) and comment text are used to increase the readability of thesource code in this example.

clear; // initialise scilab

n=2;

vec = zeros(n); // initialise the (n) vector with zero values

for i=1:n, // fill

vec(i) = 1.0/i; // the

end // lefthand side vector

write(%io(2),vec,’(’’vec’’,e13.6)’)

mat = zeros(n,n); // initialise the (nXn) matrix

for i=1:n, //

for j=1:n, // fill the matrix

mat(i,j) = 1.0/(1+ abs(i-j)); // in nested loop over

end, // columns (inner loop j)

end // and rows (outer loop i)

write(%io(2),mat,’(2e13.6)’)

for i=1:n,

res(i) = 0.0;

for j=1:n

res(i) = res(i) + mat(i,j)*vec(j);

end,

end

write(%io(2),res,’(’’res’’,e13.6)’)

producing the following output,

--> clear; // initialise scilab

Page 37: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 37

--> n=2;

--> vec = zeros(n); // initialise the (n) vector with zero values

--> for i=1:n, // fill

--> vec(i) = 1.0/i; // the

--> end // lefthand side vector

--> write(%io(2),vec,’(’’vec’’,e13.6)’)

vec 0.100000E+01

vec 0.500000E+00

--> mat = zeros(n,n); // initialise the (nXn) matrix

--> for i=1:n, //

--> for j=1:n, // fill the matrix

--> mat(i,j) = 1.0/(1+ abs(i-j)); // in nested loop over

--> end; // columns (inner loop j)

--> end // and rows (outer loop i)

--> write(%io(2),mat,’(2e13.6)’)

0.100000E+01 0.500000E+00

0.500000E+00 0.100000E+01

--> for i=1:n,

--> res(i) = 0.0;

--> for j=1:n

--> res(i) = res(i) + mat(i,j)*vec(j);

--> end;

--> end

--> write(%io(2),res,’(’’res’’,e13.6)’)

res 0.125000E+01

res 0.100000E+01

C.4.2 Conditional Statements

To control the program flow, so called conditional statements can be used. We only show the use ofthe if then else construct here (see help > Programming > if then else), other conditionalstatements are provided by the case and while constructs (see on-line help).

An example of an if then else construct is,

clear;

nmax = 3;

for i=-nmax:1:nmax,

if i <=-2 then

fprintf(%io(2),’%3i is less or equal minus two’,i)

elseif i > -2 & i < 0 then

fprintf(%io(2),’%3i is a negative number’,i)

elseif i == 0 then

fprintf(%io(2),’%3i is zero’,i)

else

fprintf(%io(2),’%3i is a positive number’,i)

end,

end

which results in the following screen output,

--> clear;

--> nmax = 3;

Page 38: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 38

--> for i=-nmax:1:nmax,

--> if i <=-2 then

--> fprintf(%io(2),’%3i is less or equal minus two’,i)

--> elseif i > -2 & i < 0 then

--> fprintf(%io(2),’%3i is a negative number’,i)

--> elseif i == 0 then

--> fprintf(%io(2),’%3i is zero’,i)

--> else

--> fprintf(%io(2),’%3i is a positive number’,i)

--> end,

--> end

-3 is less or equal minus two

-2 is less or equal minus two

-1 is a negative number

0 is zero

1 is a positive number

2 is a positive number

3 is a positive number

The relational operators <, <=, ==, >=, > that occur in the boolean expressions of the [else]ifstatements are similuar to the ones used in the Fortran language. The fprintf statement emulatesthe file print statement from the C programming language (see help > Input/Output Functions

> fprintf and the section below.

C.5 Program Input/Output Functions

In general it is advisable, in setting up a modelling experiment, to enter the model parametersin a text file from which they can be read by a modelling program. This way a flexible programset-up can be used which will be applicable, not just for a single modelrun, but for a range ofmodels. Reading input data from files and echoing input data to a program log-file is essential fordocumenting modelling experiments. Writing modelling results to output data files is necessary forpostprocessing and reporting. An example of this good practice can be found in appendix C.9.

To read data from input files and write results to output files several input/output (I/O) functionsare available. We treat here the file statement for connecting data files to your Scilab script andthe read, write and fprintf statements. The syntax description of these statements can be foundin the on-line help manual in the section Input/Output Functions.

An example of file Input/Output (I/O) is given in the following script,

clear

unitin = file(’open’,’io_exm.in’,status=’unknown’) // open input file

ndata = read(unitin,1,1) // read value ndata

unitlog = file(’open’,’io_exm.log’,status=’unknown’) // open log file - echo input

fprintf(unitlog,’ndata = %5i’, ndata)

unitdat = file(’open’,’io_exm.dat’,status=’unknown’) // open data output file

for i=1:1:ndata, // write output data

write(unitdat,[i,i**2])

end

// close all files

file(’close’,unitin)

file(’close’,unitlog)

file(’close’,unitdat)

Page 39: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 39

The file function is used to ‘open’ and ‘close’ files to be used by the program. When openinga file a unique ‘unit number’ is assigned to the file that must be used in all subsequent file accessoperations. The fprintf statement is used to write lines of text, including program data, into aformatted text file, using format specifications. The write statement can be used to write a vectoror matrix into a formatted text file allowing optional format specification.

C.6 Procedures and functions

In Scilab scripts a large number of intrinsic functions can be called (see help > ElementaryFunctions). Besides these predefined functions one can also define new functions either inter-nally in the calling script file or externally in separate script files containing the Scilab source codeof the function. An example of the use of an internally defined function is the following script forthe computation of the function table of a linear function.

clear; // initialise scilab

n=3; // set length of table to be computed

xmin = 0.0; // set range of x table

xmax = 2.0; //

dx = (xmax-xmin)/(n-1); // define the x-table increment

a = 2.0; // set function parameters

b = 1.0; //

function [y]=func(x,a,b) // define an inline function y=f(x)

y = a * x + b //

endfunction //

xtable=zeros(n); // initialise x table 1-D array

ytable=zeros(n); // initialise y table 1-D array

for i=1:n, // fill

x = xmin + (i-1)*dx ; // the function table

xtable(i) = x ; // in a loop over

ytable(i) = func(x,a,b) ; // function calls

end

for i=1:n,

fprintf(%io(2),’i= %3i x= %10.4f y= %10.4f’, i,xtable(i),ytable(i) );

end

which produces the following output,

i= 1 x= 0.0000 y= 1.0000

i= 2 x= 1.0000 y= 3.0000

i= 3 x= 2.0000 y= 5.0000

A more flexible setup is obtained by using an external function stored in a separate source file, sayfunc_ext.sce, which is activated by the getf command as in the in the following example script,

clear; // initialise scilab

n=3; // set length of table to be computed

xmin = 0.0; // set range of x table

xmax = 2.0; //

dx = (xmax-xmin)/(n-1); //

a = 2.0; // set function parameters

b = 1.0; //

getf(’func_ext.sce’) // get external function y=f(x) script file

Page 40: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 40

xtable=zeros(n); // initialise x table space

ytable=zeros(n); // initialise y table space

for i=1:n, // fill

x = xmin + (i-1)*dx ; // the function table

xtable(i) = x ; // in a loop over

ytable(i) = func(x,a,b) ; // function calls

end

for i=1:n,

fprintf(%io(2),’i= %3i x= %10.4f y= %10.4f’, i,xtable(i),ytable(i) );

end

C.7 Example functions for 2-column table data file read/write I/O

A useful example of an external procedure is listed in the following scilab script where 2-columntabulated data is written to a text file.

clear;

xmin=0.0; xmax=1.0; xstp=0.01;

n=(xmax-xmin)/xstp + 1;

x=[xmin:xstp:xmax];

for i=1:1:n,

y(i)=sin(2*%pi*x(i));

end

getf(’writdat.sci’)

writdat(n,x,y,’xy.dat’)

As in the previous example the external function writdat is activated in the calling program bya getf(’writdat.sci’) command, assuming that the sourcetext of this procedure is available in afile named writdat.sci. An implementation of the function writdat is given below,

function writdat(ndata,xarray,yarray,filename)

unit =file(’open’,filename,’unknown’)

for i=1:1:ndata,

write(unit,[xarray(i),yarray(i)]);

end

file(’close’,unit)

endfunction

The arguments of this function are: ndata is the number of entries in the 2-column table,xarray, yarray are the x and y 1-D table arrays respectively and filename is a character variablerepresenting the name of the outputfile to be created and written. Note that the names of theactual variables passed to an external function may be different from the formal parameter namesin the source text of the external function. This is essential for flexible use of libraries of externalfunctions.

A similar function procedure for reading data from file requires a slightly different set up becausevariables in the parameterlist of scilab functions can not be assigned new values during execution ofthe function. Therefore data resulting from the operation of the function must be specified throughthe left hand side of the function call as illustrated in the following example script,

clear;

// initialise data arrray

n=11

x=zeros(n); y=zeros(n)

Page 41: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 41

// read x,y data table from file

getf(’readdat.sci’);

[x,y] = readdat(n,’xy.dat’); // data assignment in function call

for i=1:n, // print data read from file

write(%io(2),[x(i),y(i)],’(2e12.4)’)

end

Where the function readdat is shown below,

function [xdata,ydata]=readdat(ndata,filename)

unit =file(’open’,filename,’unknown’)

datapoint = zeros(2);

for i=1:1:ndata,

datapoint=read(unit,1,2);

xdata(i)=datapoint(1); ydata(i)=datapoint(2);

end

file(’close’,unit)

endfunction

C.8 Scilab graphics functions

The Scilab program offers an integrated graphics environment. This means that computed resultscan be visualized directly on the screen and the graphical results can be exported into graphics filesthat can be included in reports.

C.8.1 Plotting function tables

As a first example we describe the use of a simple procedure 2-D line graph here. Description ofmore extensive options are given in the online help manual.

In the following example script a function table is filled in two 1-D arrays and these array arepassed to the Scilab 2-D graph plotting function plot2d.

clear;

xmin=0.0;

xmax=2*%pi;

nx =101;

dx =(xmax-xmin)/(nx-1)

for i=1: 1: nx,

x(i) = xmin + (i-1)*dx ;

sintable(i) = sin(x(i)) ;

end

// plot vector of numerical results

stylsin=2

plot2d([x],[sintable],style=[stylsin],rect=[xmin,-1,xmax,1.0]) // plot vector

legends([’sin(x)’],[stylsin],3) // legend + label

xtitle(’Sine functions’,’x’,’sin(x)’) // frame title + axis labels

For an example of the use of the procedure plot2d for multiple data sets in an overlay plot in asingle frame, combined in a multiple frame Figure, see Appendix C.9.

Page 42: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 42

C.8.2 Plotting histograms

A further example of the use of integrated Scilab graphics in combination with an intrinsic randomnumber generator rand is the following script which illustrates the use the of a graphics procedurehistplot for plotting histograms of tabulated data. Typing histplot() from the scilab commandline starts a demo-execution of the script listed below which first plots the normalized frequencydistribution of a 1 × 2000 sample of a pseudo gaussian random variable together with the analyticprobability density function of a gaussian stochastic variable.

-->histplot()

xbasc()

histplot([-4.5:0.25:4.5],rand(1,20000,’n’),style=2);

deff(’[y]=f(x)’,’y=exp(-x.*x/2)/sqrt(2*%pi);’);

x=-4.5:0.125:4.5;x=x’;plot2d(x,f(x),26,"000");

titre= ’macro histplot : (normalized) histogram plot’;

xtitle(titre,’C (Classes)’,’N(C)/(Nmax length(C))’);

legends([’gaussian random sample histogram’ ’exact gaussian density’],[2 26],1)

-->

Figure 3: Example histogram plot of a random variable and corresponding Gaussian distribution.

Page 43: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 43

C.9 Example script using the Scilab ode solver

C.9.1 Introduction

In this example the 1-D parabolic trajectory (vertical coordinate y(t) as a function of time) of anobject in a uniform gravity field is computed using Scilab. This is done in two different ways.First the ordinary differential equation (ODE) corresponding to Newton’s law a = F/m, is solvednumerically using the Scilab ODE solver function ode to compute the solution of the governingdifferential equation, corresponding to Newton’s second law. Then the analytical solution, in theform of a parabolic trajectory is computed. Both solutions are then plotted in the same frame, tovalidate the numerical solution. Different parameters values such as the acceleration of gravity g,and the initial conditions, startvalues of the vertical coordinate y(0) and velocity dy(0)/dt are readfrom an input file.

This example illustrates the general procedure of computer modelling experiments. Program inputdefining model parameters are read from a file. The desired model response is computed, and theresults are plotted on the computer screen and also written to several output files for later use.

The example illustrates the following general programming aspects:

• Program input specifying model parameters is read from a text file, which has been madeseparately with a text editor.

• Program results are computed in program loops over time steps.

• Program results are stored in indexed variables, vectors or matrices also referred to as array’sthat are one or two dimensional.

• Certain tasks are carried out in special parts of the code designated as functions. Some of thesefunctions are spelled out in the Scilab script and others are provided by the Scilab library.

• Program output is written to several ‘named’ outputfiles.

• Graphics output is produced to the screen using a 2-D graph drawing routine from the Scilablibrary.

C.9.2 Using the Scilab ODE solver

Written as a differential equation, Newton’s law is,

d2y

dt2= a =

F

m= −g (22)

where y(t) is the time dependent vertical coordinate (increasing upward) F is the total gravityforce on the object and m is the objects mass. g is the uniform gravity acceleration (pointingdownward). The Scilab function ode is used to solve the equation (22). Use the help button andselect Optimization and simulation > ode for an explanation of the syntax of the solver function.

Page 44: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 44

To use the Scilab solver ode, the second order differential equation (22) must be written as a systemof two first order ODE’s. Writing for the vertical coordinate and velocity y1(t) = y(t), y2(t) = dy/dt,(22) is rewritten as,

d

dt

(y1y2

)=

(00

10

)(y1y2

)+

(0−g

)(23)

C.9.3 Results

Results of Scilab computations, using the script listed in the next section, are plotted in Fig.1. Thefigure shows the vertical coordinate y(t), top frame and velocity dy/dt, bottom frame. Analyticalvalues for a subset of evaluation times are plotted as discrete symbols.

Figure 4: Numerical (solid) and analytical (symbols) results: elevation y(t) (top) and velocity dy/dt(bottom) versus time.

Page 45: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 45

C.9.4 Example Script bullit.sci

// 1-D trajectory of an object falling in a uniform gravity field

// numerical integration using scilab function ode

// plot numerical + analytical solution

// read model parameters from input file:

unit = file(’open’,’bullit.in’,’unknown’)

g_ac =read(unit,1,1)

y0 =read(unit,1,1)

dydt0 =read(unit,1,1)

tmax =read(unit,1,1)

fname_log =read(unit,1,1,’(a)’)

fname_ycoor_num =read(unit,1,1,’(a)’)

fname_veloc_num =read(unit,1,1,’(a)’)

fname_ycoor_analyt =read(unit,1,1,’(a)’)

fname_veloc_analyt =read(unit,1,1,’(a)’)

file(’close’,unit)

// max. y coord.

ymax = y0 + 0.5*(dydt0**2)/g_ac

// print model parameters in the logfile

u_log = file(’open’,fname_log,’unknown’)

fprintf(u_log,’g_ac =%10.3f’,y0 )

fprintf(u_log,’y0 =%10.3f’,y0 )

fprintf(u_log,’dydt0 =%10.3f’,dydt0 )

fprintf(u_log,’tmax =%10.3f’,tmax )

fprintf(u_log,’ymax =%10.3f’,ymax )

fprintf(u_log,’fname_log =%s’,fname_log )

fprintf(u_log,’fname_ycoor_num =%s’,fname_ycoor_num )

fprintf(u_log,’fname_veloc_num =%s’,fname_veloc_num )

fprintf(u_log,’fname_ycoor_analyt =%s’,fname_ycoor_analyt )

fprintf(u_log,’fname_veloc_analyt =%s’,fname_veloc_analyt )

file(’close’,u_log)

// * define r.h.s. vector function ODE: dy/dt = f(t,y)

// | y1 | |0 1| |y1| | 0|

// d/dt | | = | | | | + | |

// | y2 | |0 0| |y2| |-g|

//

function[ydot]=f(t,y)

ydot(1) = y(2)

ydot(2) = - g_ac

endfunction

// * define analytic solution as a vector function

// | y1 | |y1(0)| |y2(0)| |-g_ac|

// | | = | | + t * | | + 0.5*t**2 * | |

// | y2 | |y2(0)| |-g_ac| | 0 |

//

function[y1,y2]=sol_analyt(t)

y1 = y0 + t*dydt0 - 0.5*g_ac*t**2

y2 = dydt0 - t*g_ac

endfunction

// * define time interval and discretisation

t0=0; tstpnum=0.1

t=[t0: tstpnum: tmax];

ntimes = (tmax-t0)/(tstpnum) + 1

tmax = t0 + ntimes*tstpnum

// * numerical solution

ynum=ode([y0,dydt0],t0,t,f)

Page 46: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 46

// * reshape the resulting 2*ntimes vector into a matrix

yode_result = matrix(ynum,2,ntimes);

// * write numerical results to *.dat files

// * ycoordinate

unit1 =file(’open’,fname_ycoor_num,’unknown’)

unit2 =file(’open’,fname_veloc_num,’unknown’)

for j=1: 1: ntimes,

// store y1,y2 for later plot

y1_num(j) = yode_result(1,j);

y2_num(j) = yode_result(2,j);

datapoint = [t(j),yode_result(1,j)];

write(unit1,datapoint);

datapoint = [t(j),yode_result(2,j)];

write(unit2,datapoint);

end

file(’close’,unit1)

file(’close’,unit2)

// * compute the analytical solution and write results to file

unit1 =file(’open’,fname_ycoor_analyt,’unknown’)

unit2 =file(’open’,fname_veloc_analyt,’unknown’)

for j=1: 1: ntimes,

[y1,y2] = sol_analyt(t(j));

// store y1,y2 for later plot

y1_analyt(j) = y1;

y2_analyt(j) = y2;

datapoint = [t(j),y1_analyt(j)];

write(unit1,datapoint);

datapoint = [t(j),y2_analyt(j)];

write(unit2,datapoint);

end

file(’close’,unit1)

file(’close’,unit2)

// * plot results

// switch off color -> dash/dot pattern

xset("use color",0)

subplot(2,1,1)

plot2d([t],[y1_num ],style=[ 1],rect=[t0,0,tmax,ymax])

plot2d([t],[y1_analyt],style=[-2],rect=[t0,0,tmax,ymax])

// legends + grid + labels

legends([’num.’,’analyt.’],[1,-2],3)

xgrid()

xtitle(’Elevation versus time’,’Time /s’,’Elevation /m’)

subplot(2,1,2)

plot2d([t],[y2_num ],style=[ 1],rect=[t0,-dydt0,tmax,dydt0])

plot2d([t],[y2_analyt],style=[-2],rect=[t0,-dydt0,tmax,dydt0])

// legends + grid + labels

legends([’num.’,’analyt.’],[1,-2],3)

xgrid()

xtitle(’Velocity versus time’,’Time /s’,’Velocity /m/s’)

Page 47: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 47

D Scilab exercises

D.1 Introduction

A tutorial overview with examples of the use of the Scilab program is given in Appendix C. Toget acquainted with the use of Scilab first work through the introductory exercises listed below. Tohelp you organize the material for the different projects involved in this course, store all the filesof a project in a unique project directory. It is advisable to split such a project directory in threesubdirectories for 1) software, program source files or scripts, 2) input and output data, and 3)documentation like the project report with supporting graphics files.

To start with this good practice, create a new directory, using the unix shell command mkdir,for each of the introductory exercises specified below. 8 Organise these directories in the followingway in your home directory,

user_home_directory

|

ex_scilab

|

-------------------

| ... |

ex1 exn

| |

----------- ------------

| | | | | |

doc data source doc data source

For each exercise first prepare a Scilab script in a text file, say ex.sci, with one of the text editorslike gedit or kedit or the Scilab editor scipad, in the source directory of the experiment. Next youinvoke Scilab from the directory where you created the file ex.sci by typing on the Linux commandline,scilab

In the Scilab window that will open on your computer screen you type on the Scilab command line,exec ex.sci

In a slightly different procedure the subdivision in source and data diretories of the above diagramcan be utilized. To this end you change your working directory to the data subdirectory beforestarting Scilab by typing on the command line,cd data

From the directory data you start Scilab from the command line and in the Scilab window thatopens you type on the command line,exec ../source/ex.sci

where the .. (parent directory) notation is explained in Appendix E.

8A list of useful Linux (Unix) commands can be found in Appendix E.

Page 48: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 48

D.2 Tables of multiplication

In these exercises you will use a Scilab array, i.e. an indexed variable, and loop constructs to fill thearray variable with one or more tables of multiplication. Before you work through these exercisescheck the relevant syntax descriptions and examples in Appendix C.

1. As a first exercise compute a single table of multiplication for a number n. n should be used asa variable in your script. First assign a value to n, and initialize the array or vector, that willbe used to store the table of multiplication, using the Scilab zeros function (see online infowith help > Elementary Functions > zeros). Next fill a one dimensional array, a Scilabvector, with the table of multiplication for the number n. Use a for end loop construct to fillthe vector (check the online manual on the for construct by typing help for on the Scliabcommand line). Finally write the table to the screen using a write(%io(2),table,’(10i3)’)

command, see online info with help > Input/Output Functions > write). Copy the screenoutput to a textfile, to be included in your labreport. 9

2. Next compute and print multiple tables of multiplication for n = 1, ..., ntables in a singleScilab script, applying two nested for loops.

for i=1: 1: ntables,

for j=1: 1: 10,

...

end

end

Use a 2-D Scilab array (see Appendix C.3) for the ntables × 10 matrix, storing the tables ofmultiplication as matrix rows in a 2-D array table(ntables,10). Inspect the contents ofthe 2-D array on te screen, after it has been filled, by typing the array name on the Scilabcommand line.

D.3 Plotting and writing tables of functions

In this exercise you will fill tables of function values, plot the function values on the screen and writethe table values to a text file, for later use.

1. Compute function tables of the sine and cosine functions and plot the result on the screenusing the Scilab plot2d command as in the example shown in Appendix C.

2. Export the resulting plot to a graphics file using the File > Export menu buttons. Choosethe Postscript format for use of the network printers. Inspect the resulting file before sendingit to a printer with the ghostview viewer program by typing on the linux command line gv

postscript filename. Choose one of the available Gif or PPM graphics file formats for any plotoutput you want to include in your labreport.

9Screen output can be copied to a text file by using the (gnome or kde) window manager by pressing the lefthandmouse button and dragging the cursor over the screentext to be copied, thereby highlighting the text. This copies thetext to a buffer from where it can be ‘pasted’ into a text file, opened with a text editor in another window, by pressingthe middle button.

Page 49: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 49

3. Extend your scilab script from the previous item with lines of code to write the function tablesto separate two-column ascii text files func sintable.dat and func costable.dat, (see theexamples in Appendix C.6 Hint: apply the scilab function writdat for writing 2-column tablesto file, introduced in C.7. Check the syntax of the file ‘open’ and ‘close’ statements in theonline manual.

4. Make a plot of the data in the files func sintable.dat, func costable.dat in a single plotframe using the graphics program xmgrace (see Appendix F). Save your plot in a postscriptgraphics file. Use the menu buttons File > print set up, select print to file and fill inthe file name, using a .ps filename extension in the dialog box and click accept. Next click themain menu button File > print. The resulting graphics file can be inspected (and printed)with the postscript viewer gv (ghostview). 10

5. Adapt the previous Scilab script to produce tables with graph and file output for a user definedscilab function (use your ‘favorite function’ for this assignment). Check Appendix C for anexample of the use of internal- and externally defined functions. Apply an external function,say menufunc, called from your scilab script to compute tables of several optional functionsincluding the sin and cos functions. Organise your function menufunc with an integer functionparameter ifunc and if then else construct (see C.4.2) to select the function value to becomputed from your list of implemented functions. Implement an ‘error trap’ through anelse clause to detect undefined values of ifunc that do not correspond to any implementedfunction.

For an extended example see Appendix C.9 for the use of a ‘user function’ sol analyt forthe time dependent vertical coordinate of an object launched vertically in a uniform grav-ity field. For an explanation of the syntax of a function definition use the Scilab com-mand help function or the menu button help > Handling of functions and libraries

> function.

D.4 Histogram analysis of random data

In the following we will investigate the problem of analysing a series of random data by computinghistograms and statistic moments, mean value and standard deviation.

D.4.1 Writing random generator data to file

Appendix C.8.2 contains an example scilab script where a histogram is plotted for a sequence ofrandom numbers generated by a random number generator function rand. 11 Adapt this exampleinto a script rand1 such that the random numbers generated with a Gaussian distribution are firststored in a 1-D table. This table is then written to a 2-column text file with the sequence number

10To include graphics files in your lab report you have to convert the postscript files to another graphics format pngor jpg. This can be done using the Linux command convert as in the following example where 300 pixels per inchare specified, to obtain sufficient resolution for reproduction,convert -density 300 fig-example.ps fig-example.png.xmgrace output can also be written directly in other formats than postscript (including png) through the print setup

menu button.11A complete array can be filled with random data values in a single assigment statement using the scilab function

rand as illustrated in Appendix C.8.2.

Page 50: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 50

i and corresponding random number yi in the first and second column respectively. Include anxmgrace plot of the file data in your report.

D.4.2 Analyzing arbitrary random data from file

Write a separate scilab script rand2 for the analysis of a general random number data sequencewhere you read the random data to be analyzed from a similar file as produced by your random1

script. Use the example script readdat in Appendix C.7 to read the 2-column data file. Produce ahistogram plot of the data using the scilab histplot function as in the example script in AppendixC.8.2. Compute the mean value and the variance of the random number data 12 and include theoutcome in your report. Write your own external function procedure for the computation of themean value and variance of the input data sequence, according to the following specifications:

• The function has two input arguments (ndata,data), for the numer of data in the table andfor the table of random numbers respectively.

• The function returns two output numbers, the mean value and variance, computed from theinput random numbers.

• Use a for ... end loop to compute the required summation expressions and check youroutcome by an independent calculation using the scilab intrinsic functions mean and variance

(see the online manual).Hint: First write down the full algorithm for the computation of the mean value of a sequenceof n numbers, including initialization of the result and normalization by the number n (seeAppendix C.4.1).

Apply your script rand2 to several types of random data that can be generated by the scilabrandom generator function, including uniform and gaussian types. Include xmgrace plots of these‘noise’ sequences in your Lab report. Compare your outcome of mean value and variance with thetheoretical value for a) a uniform distribution and b) a Gaussian distribution. Consult the onlinescilab help manual for the parameters for selecting different probability distributions in the scilabfunction rand.

12Weisstein, Eric W. ”Variance.” From MathWorld–A Wolfram Web Resource.http://mathworld.wolfram.com/Variance.html

Page 51: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 51

E Some useful Linux commands

ls gives a list of the files and subdirectories thatare located in this directory

ls -l print also access attributes, time-stamp and sizels q* list all files and directories that begin with the letter ’q’ls *q or end with qls q*p or begin with ’q’ and end with ’p’ls *.3* or contain ’.3’

pwd gives the pathname (string) of the current directory(your location in the directory tree)

. means the current directory

.. the parent directory above the current directoryls ../.. gives a list of files in the directory two levels up in

the directory tree

cd dirname change to directory dirnamecd .. go one level up in the directory treecd go to home-directory (this is your home base and

usually the top of the directory tree of your file space)

prog < inputfile redirection: instead of typing input for prog yourself,prog uses input from inputfile (very useful forlarge programs or programs that are executed many times!)

program < inputfile > outputfile the same goes for output data (into file instead of screen)

rm file remove filerm p* remove all files that begin with ’p’

cp a b copy file a to file bcp path/file1 . copy file1 in directory path to current directorycp path1/file1 ../path2 copy path1/file1 to ../path2’cp -a ∼home/examples . copy all contents from the tree ∼home/examples to the current directory

-a means archive (preserves timestamps)

mv ../file . move: works just like cp, except that the originalis thrown away

mv name1 name2 move can also be used for renaming files

mkdir dirname make a new directory dirnamermdir dirname remove directory dirname

if the directory is not empty try ’rm -rf dirname’make first sure you don’t throw anything important away,data cannot be revived in Linux!

Page 52: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 52

CTRL C kill the job that is executingCTRL L clean up the screenprog & execute a program and continue working in Linux

(so that you don’t have to wait for your program to be finished,this also works with redirection)

man online command manual. For instance, try ‘man grep’if you want to know more about matching strings in a file.Or ’man diff’ if you want to know how you can check thedifferences between two files.

make when a ’Makefile’ is available, make automatically compilesyour program. An executable ’example’ is made usingthe source code in ’example.f90’

rehash Refreshes your system search tables.Apply this after first time installation of a new programto prevent ‘command not found’ when executing your program

which prog Prints pathname of the exectutable prog

lpr -Plw print on printer ’lw’ (third floor)lpq -Plw which printing jobs are is the cue for printer ’lw’lprm -Plw jobnumber kill the job jobnumber on ’lw’

(in case you are busy printing something you don’t want to)

In the end it will save you a lot of time if you organise your files in a directory tree. This meansthat below your home directory you make several subdirectories. In those subdirectories you makesubsubdirectories, etc. Then order your files in the directories, which have logical names such as:∼home/exercise2/part3/data/.

There are many more combinations in Linux. Try ’h’, ’ls -l’, ’ls -la’, ’l’, ls -la’ or try your owncombinations.

Want to know more about Linux/UNIX? There is a good manual available atwww.cs.uu.nl/∼piet/docs/unix.pdf (in Dutch).

Page 53: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 53

F Using plot program xmgrace to plot 2-D x,y data sets

A documentation set (tutorial, userguide) can be found in the directory, /usr/local/grace/doc.Some information on how to get started with xmgrace and specific elements used in the course isgiven below.

1. Starting xmgracefrom the command line type: xmgrace

2. Data input from file

• Each data set is available in an (ASCII) text file consisting of a series of text lines witha single pair of x y values, separated by space(s) per text line.

• Your data can be read from file using the following menus:

Data > Import > ASCII...

Fill in the file name in the bottom dialog box and click the OK button

• Multiple files can be read into the same graph in this way.

When all required data have been read, click cancel.

3. Formatting your graph

• Choosing between lineplots or disconnected symbols and setting line/symbol color andsize

Plot > Set Appearance

set line properties and symbols properties and legend entries and when done click theApply button.

• A plot legend is created by

Plot > Set Appearance

and typing a legend text string for the selected data set

• Graph titles and frame box parameters can be set in the menu

Plot > Graph Appearance

The first tab Main allows you to set the title and subtitle of the graph. Note that everychange requires a click on either Apply or Accept to actually apply it.

xmgrace uses a rectangular plot frame ‘view port’ with aspect ratio (width/height) > 1.This can be modified by changing the viewport parameters in the Graph Appearance >

Main menu.

The location of the legend box can be set on the tab Leg. box, and its size (throughthe size of the font) on the tab Legends.

• The menu Plot > Axis properties allows you to set axis labels (on the tab Main) andaxis ranges. The axis to which changes should be applied can be selected with the Edit

button.

Page 54: Programming and Modelling - Universiteit Utrechtberg/progmod1/Progmod1.pdf · 2.3.3 Iterative solution of a linear system ... FORTRAN 95/2003 explained, Oxford University Press, 2008

12/09 54

4. Making more than one plot frame on the screen/pagexmgrace can also be used to plot several frames on one page. The menu

Edit > Arrange graphs

allows you to set the number of columns and rows of frames/graphs which are required, andtheir size, location and spacing.

All the operations which are described above can be applied to each of the graphs on the page.The action is applied to the active graph, which is indicated by four black square dots on thecorners of the graph frame. The currently active graph can be set by pointing the cursor andclicking on it.

5. Data regressionData regression for the investigation of powerlaw trends in your data can be done in the fol-lowing way:Use the menu buttons: Data > Transformations > Regression and choose as Type of fit:

the option Power y=A*x^B. The resulting formula expression of the fit will appear in a separatewindow and can be copied by the mouse (copy-paste) for use, for instance, in plot legends.

6. Making histogram plotsA histogram of a series of data can be made in the following way:

• Organize your data as a single column ascii text file, say series.dat

• Import your data in the usual way data > import > ascii etc., or directly from thecommand line with xmgrace series.dat

• Set histogram preferences using data > transformation > histograms

• Click once on the Set: identification in the lefthand Set: window

• Select values where to start and stop on the X axis and the number of bins in yourhistogram in the Start at:, Stop at: and # of bins windows

• Click apply. The histogram plot will appear in the same plot frame as the original dataset. At the same time a new set identification will appear in the Set: window. Youcan ‘hide’ the original data set in the plot frame by (right mouse button) selecting theoriginal data in the Set: window and selecting the Hide option.

• Click the blue AS (autoscale) button on the left hand button panel of the main xmgrace

window.

7. Saving your graphThe project-file of the graph, including its layout, can be saved through the menu

File > Save as.. select file or type filename > OK

The graph can be re-opened later through the menu

File > Open ... > Selection

8. Printing your graphFor printing the graph using File > Print, the printer setup can be accessed following File

> Device setup.., where the paper size can be selected, and also whether to print to theprinter or to file.