You are on page 1of 11

M1 International - Arts et M´ etiers PariTech ”Programing and Numerical Methods” Fortran Project

deadline : November 23rd 2012

The second Fortran project is an homework due November 23rd 2012. It represents 25% of the total evaluation. You can send a pdf or doc file including your comments, results, figures, listings of routines to xavier.gloerfelt@paris.ensam.fr. To be sure that your email is well delivered, please verify that you have a confirmation by e-mail return specifying that your work is received.

1

The unsteady heat equation
In the first Fortran project, we have considered 2-D heat transfer problems in which the tem-

peratures are independent of time. In many applications, however the temperatures are varying with time, and we require the understanding of the complete time history of the temperature variation. For example, in metallurgy, the heat treating process can be controlled to directly affect the characteristics of the processed materials. Annealing (slow cool) can soften metals and improve ductility. On the other hand, quenching (rapid cool) can harden the strain boundary and increase strength. In order to characterize this transient behavior, the unsteady equation is needed. The onedimensional version is ∂φ ∂2φ = α 2 , 0 ≤ x ≤ L, t ≥ 0 (1) ∂t ∂x where φ = φ(x, t) is the dependent variable, and α is a constant coefficient. Equation (1) is a model of transient heat conduction in a slab of material with thickness L. The domain of solution is a semi-infinite strip of width L that continues indefinitely in time. The material property α is the thermal diffusivity. In a practical computation, the solution is obtained only for a finite time tmax . Solution to Equation (1) requires specification of boundary conditions at x = 0 and x = L, and initital conditions at t = 0. Simple boundary and initital conditions are : φ(0, t) = φ0 , φ(L, t) = φL , φ(x, 0) = f0 (x) (2)

2

Discretization
A finite-difference method is used for obtaining numerical solutions to Equation (1). Applying

finite differences, a discrete difference equation is obtained from the original PDE for φ(x, t). Then

1

m = 1.M where M is the total number oftime steps and ∆t is the size of a time step ∆t = tmax M −1 Both the time and space derivatives are replaced by finite differences. t) = φ(L... t) = 0. . Given L and N . The first one is an explicit scheme. t). The second method is implicit and will require the inversion of a system (with a tridiagonal matrix).the solution method. the discrete x are uniformly spaced in the interval 0 ≤ x ≤ L such that : xj = (j − 1)∆x . and the time step is limited by Fourier criterion. 4 Fortran program The proposed structure of the program could be – a module part.N where N is the total number of spatial nodes. and initial condition f0 = sin(πx/L). The exact solution for this problem is derived in the Appendix. . 2.. 3 Test problem The finite difference codes are tested by solving the heat equation with boundary condition φ(0. will provide an approximation φm j to φ(x. you will use a second-order central difference (as in the first Fortran project). including those on the boundary. For the second-order spatial operator. where specification of variables which are used in several subroutines are defined : specif. 2. coded in Fortran. j = 1. the discrete time t are uniformly spaced in 0 ≤ t ≤ tmax : tm = (m − 1)∆t . the spacing between the xj is computed with ∆x = L N −1 Similarly..f90 2 . Two different time integration will be used : – Forward Euler scheme – Crank-Nicolson scheme This is respectively Adams-Bashforth of order 1 and Adams-Moulton of order 2. For the codes you have to develop.

forward_euler.f90 including the forward and backward substitution steps for solving a system given its LU decomposition (here provided by tridiag.f90 forward_euler. and output in a file of the solution and error to be plotted with Matlab. You then have to change consequently the makefile.o main.f90 tridiag.o tridiag.f90 OBJS = specif.f90 where the Thomas algorithm is used to obtain directly the LU decomposition. computation of the final error.o LIBS = # for CYGWIN with gfortran F90 = gfortran F90FLAGS = -fdefault-real-8 # for LINUX PC with intel fortran #F90 = ifort #F90FLAGS = -O3 -r8 -fpe0 LDFLAGS = all: $(PROG) $(PROG): $(OBJS) $(F90) -o $@ $(OBJS) $(LIBS) $(LDFLAGS) clean: rm -f $(PROG) $(OBJS) *.o solve_LU.f90. crank_nicolson.o forward_euler.f90 forward_euler.o main. where the following operations are realized : initialization of the variables. A sample makefile is provided using these names for the f90-files.f90 main. calls to solving algorithm (Forward Euler or Crank-Nicolson). – a subroutine to solve a tridiagonal system tridiag.o forward_euler.f90 #OBJS = specif.– a main program main.o crank_nicolson. – a subroutine solve_LU. – a subroutine for the Forward Euler/Centered differences method.f90). – a subroutine for the Crank-Nicolson/Centered differences method.f90 main.o SRCS = specif. Example makefile PROG = prog #SRCS = specif.f90 crank_nicolson.f90 solve_LU.mod *.out 3 . You are free to change routine names or the number or scope of the subroutines.f90.f90.

o Example specif.out .f90 .o: specif.o forward_euler.o: specif. dimension(:). allocatable :: x ! location of finite difference nodes ! time discretization integer :: nt ! number of steps real :: tmax ! maximum time for the simulation real :: dt ! time step ! constants real :: alpha ! diffusivity real :: pi ! constant pi end module variables 4 real. allocatable :: u ! spatial boundary conditions at x=0 and x=L real :: u0.:). dimension(:).o crank_nicolson.o: specif.f90 !============================================================================ ! Common variables !============================================================================ module variables implicit none ! unknown variable (first dimension nx for space and second nt for time) real.debug: $(F90) -g $(SRCS) $(LIBS) dxladebug a. dimension(:. allocatable :: t ! values of time at which solution is obtained (time nod .f90.SUFFIXES: $(SUFFIXES) .uL ! space discretization integer :: nx ! number of mesh points in x direction real :: L ! length of the domain real :: dx ! mesh size real.o: $(F90) $(F90FLAGS) -c $< main.

nt print*.5 ires=1 !!$ !!$ !!$ !!$ !!$ !!$ !!$ !!$ !!$ !!$ 5 print*.Example main.) ! Values of parameters nt = 10 nx = 20 alpha = 0.f90 ! ================================= ! main program ! ================================= program unsteady_heat ! USE ZONE: common variables use variables ! put implicit none to avoid declaration problem implicit none ! Local variables integer:: i. allocatable :: ue ! analytical solution (for each spatial node nx) real :: err ! error at last time step nt ! Constant Pi pi=acos(-1.t_cpu integer:: done real.’tmax’ read*.L . dimension(:).ires real :: t_final.tmax print*.t_initial.’L’ read*.m.1 L = 1 tmax = 0.’Size of the problem?’ print*.’nt’ read*.nx print*.’nx’ read*.

/(nt-1) ! uniform mesh t do i=1.!!$ !!$ print *. ! u is initialized at initial time (f0) do i=1.ires call cpu_time(t_initial) ! Memory allocations for dynamic variables ! ======================================== allocate(x(nx)) allocate(t(nt)) allocate(u(nx./(nx-1) ! uniform mesh x do i=1.nt t(i)=(i-1)*dt end do ! Initialization stage ! ==================== u=0.nx u(i.nx x(i)=(i-1)*dx end do ! Time step dt=1.nt)) allocate(ue(nx)) ! Compute mesh spacing and time step ! ================================== ! Mesh size dx=1.1)=sin(pi*x(i)/L) end do ! Initialization of the boundary values ! needed to apply BC inside time step loop u0 = 0 6 .’choice of the method ->1: FE/CD . 2: CN/CD’ read *.

do i=1.*) err close(10) ! The final solution is written in a file 7 .nx err=err+abs(u(i.uL = 0 ! Exact solution (used to compute the error) ! ============== ! at end of simulation ue = sin(pi*x/L)*exp(-t(nt)*alpha*(pi/L)**2) ! Choice of the method ! ==================== select case (ires) case (1) call forward_euler case (2) call crank_nicolson case default print*.file=’error.nt)-ue(i)) end do err=err/nx ! Opening of output files to store the errors ! =========================================== open(10.’the option is not defined’ stop end select ! Error computation ! ================= err=0.dat’) rewind(10) write(10.

m=1.ue) end program unsteady_heat Hereafter an example of visualization file reading a binary file is proposed.t_cpu ! The dynamic arrays are deallocated ! ================================== deallocate(x.nt) ! write the computed solution write(40) ((u(i. 8 .m).nx print *.err print *.i=1.’Error L2 : ’.nt) ! write the analytical solution write(40) (ue(i).m=1.’CPU time’.! ======================================= ! MATLAB file (particular BINARY file) open(40.nx) close(40) ! Note that no format is used for a binary file ! That’s why the ASCII file is also named FORMATTED file ! by default.’Mesh size: ’.form=’unformatted’. You can of course improve the visualization and add other plot such as error.nx).status=’unknown’) write(40) nx write(40) nt ! write the meshgrid and time nodes write(40) (x(i).nx) write(40) (t(m).i=1.log10(err) call cpu_time(t_final) t_cpu=t_final-t_initial print *.t.nt print *.’Log(Error L2 norm) : ’.u. the "format" attribute is "formatted" ! Some informations are written to the screen ! =========================================== print *.i=1.file=’solution.bin’.’Number of iterations: ’.

bin’).Example Matlab file vizu.1.precision). x = fread(f1.’float’).’float’). nt = fread(f1. arg = fread(f1.m clear all close all opengl neverselect precision = ’double’.’float’).’float’). disp(’Start reading file solution.’float’).1.’float’). % for big_endian binary %f1= fopen(’solution.’float’).’r’.bin’.’int’).1). u = zeros(nx. arg = fread(f1.precision). arg = fread(f1. arg = fread(f1.’int’). 9 . t = fread(f1.1.1. arg = fread(f1.1.1. ue = zeros(nx.nt).1. nx = fread(f1.nt.’float’). arg = fread(f1. arg = fread(f1.’float’). arg = fread(f1.nx. frewind(f1).1. arg = fread(f1.1. % for little_endian binary f1= fopen(’solution.1.bin’.’r’).’ieee-be’). %%precision = ’float’.1.

’a4letter’).10).’position’. axes(’units’.u(:.’float’).precision).u(:. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% fig = figure(1).u(:. fclose(f1).[2. set(fig.’centimeters’. 8.u(:.’paperunits’.’centimeters’).’Fontsize’.’b’) plot(x.u(:.’paperposition’. arg = fread(f1.1. 12.’k’) hold on plot(x.13). ylabel(’T(x. set(fig.13).bin’). arg = fread(f1. colordef(fig.’units’.’papertype’.]).1. plot(x.’r’) plot(x. 12.4). set(fig.’none’).6).[nx nt].1. you are asked to write your own fortran files to solve the one-dimensional unsteady heat equation using second-order central finite differences for space and both forward Euler and Crank-Nicolson schemes for time integration.’g’) plot(x. 5 Work In summary.[2. whitebg(fig.8). 8.1).’float’).’position’. 1.u = fread(f1. orient portrait. 2.]). it is recommended to use Thomas’ algorithm to solve the resulting tridiagonal matrix system.t)’.precision). arg = fread(f1.[2. 12. In the case of the implicit scheme. 12. disp(’End reading file solution.’float’).’Fontsize’.’m’) xlabel(’x’. 10 .]). ue = fread(f1.’w’).nx. set(fig. 1.’centimeters’.

. t) = 0 .. 6 Appendix : Exact solution The general solution of Equation (1) with the boundary an d initial conditions φ(0. 0) = f0 (x) (3) is φ(x. stability ..). φ(x. t) = φ(L. You can for instance change the resolution parameter (nx. bn = 0 . nt or tmax) to illustrate stability issues.. .f90) to start your computation. 3. cost. It is recommended to use Matlab to visualize the results. you must compare the two integration schemes (accuracy. The exact solution to Equation (1) is thus φ(x. You can use the default values (in the example program main. Your comments and plots will be included in the report. t) = ∞ bn sin n=1 nπx αn2 π 2 t exp − L L2 (4) where the bn are obtained from bn = Example : f0 = sin(πx/L) Compute bn = but 0 L 2 L L f0 (x) sin 0 πx dx L (5) 2 L L sin 0 πx πx sin dx L L L/2 if n=1 0 otherwise sin Therefore πx πx sin dx = L L b1 = 1 . t) = sin απ 2 t πx exp − 2 L L n = 2.You can use the previous examples freely to develop your program. 11 . All the routines must be included in your report file (in pdf or doc format). In your report.