1 

2 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
3 
% 
4 
% Copyright (c) 20032010 by University of Queensland 
5 
% Earth Systems Science Computational Center (ESSCC) 
6 
% http://www.uq.edu.au/esscc 
7 
% 
8 
% Primary Business: Queensland, Australia 
9 
% Licensed under the Open Software License version 3.0 
10 
% http://www.opensource.org/licenses/osl3.0.php 
11 
% 
12 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
13 

14 
\begin{figure}[h!] 
15 
\centerline{\includegraphics[width=4.in]{figures/onedheatdiff001}} 
16 
\caption{Example 1: Temperature differential along a single interface between two granite blocks.} 
17 
\label{fig:onedgbmodel} 
18 
\end{figure} 
19 

20 
\section{Example 1: One Dimensional Heat Diffusion in Granite} 
21 
\label{Sec:1DHDv00} 
22 

23 
The first model consists of two blocks of isotropic material, for instance granite, sitting next to each other. 
24 
Initially, \textit{Block 1} is of a temperature 
25 
\verbT1 and \textit{Block 2} is at a temperature \verbT2. 
26 
We assume that the system is insulated. 
27 
What would happen to the temperature distribution in each block over time? 
28 
Intuition tells us that heat will transported from the hotter block to the cooler until both 
29 
blocks have the same temperature. 
30 

31 
\subsection{1D Heat Diffusion Equation} 
32 
We can model the heat distribution of this problem over time using the one dimensional heat diffusion equation\footnote{A detailed discussion on how the heat diffusion equation is derived can be found at \url{http://online.redwoods.edu/instruct/darnold/DEProj/sp02/AbeRichards/paper.pdf}}; 
33 
which is defined as: 
34 
\begin{equation} 
35 
\rho c\hackscore p \frac{\partial T}{\partial t}  \kappa \frac{\partial^{2} T}{\partial x^{2}} = q\hackscore H 
36 
\label{eqn:hd} 
37 
\end{equation} 
38 
where $\rho$ is the material density, $c\hackscore p$ is the specific heat and $\kappa$ is the thermal 
39 
conductivity\footnote{A list of some common thermal conductivities is available from Wikipedia \url{http://en.wikipedia.org/wiki/List_of_thermal_conductivities}}. Here we assume that these material 
40 
parameters are \textbf{constant}. 
41 
The heat source is defined by the right hand side of \refEq{eqn:hd} as $q\hackscore{H}$; this can take the form of a constant or a function of time and space. For example $q\hackscore{H} = q\hackscore{0}e^{\gamma t}$ where we have the output of our heat source decaying with time. There are also two partial derivatives in \refEq{eqn:hd}; $\frac{\partial T}{\partial t}$ describes the change in temperature with time while $\frac{\partial ^2 T}{\partial x^2}$ is the spatial change of temperature. As there is only a single spatial dimension to our problem, our temperature solution $T$ is only dependent on the time $t$ and our position along the iron bar $x$. 
42 

43 
\subsection{PDEs and the General Form} 
44 
Potentially, it is now possible to solve PDE \refEq{eqn:hd} analytically and this would produce an exact solution to our problem. However, it is not always possible or practical to solve a problem this way. Alternatively, computers can be used to solve these kinds of problems. To do this, a numerical approach is required to discretised 
45 
the PDE \refEq{eqn:hd} in time and space so finally we are left with a finite number of equations for a finite number of spatial and time steps in the model. While discretization introduces approximations and a degree of error, we find that a sufficiently sampled model is generally accurate enough for the requirements of the modeller. 
46 

47 
Firstly, we will discretise the PDE \refEq{eqn:hd} in the time direction which will 
48 
leave as with a steady linear PDE which is involving spatial derivatives only and needs to be solved in each time 
49 
step to progress in time  \esc can help us here. 
50 

51 
For the discretization in time we will use is the Backwards Euler approximation scheme\footnote{see \url{http://en.wikipedia.org/wiki/Euler_method}}. It bases on the 
52 
approximation 
53 
\begin{equation} 
54 
\frac{\partial T(t)}{\partial t} \approx \frac{T(t)T(th)}{h} 
55 
\label{eqn:beuler} 
56 
\end{equation} 
57 
for $\frac{\partial T}{\partial t}$ at time $t$ 
58 
where $h$ is the time step size. This can also be written as; 
59 
\begin{equation} 
60 
\frac{\partial T}{\partial t}(t^{(n)}) \approx \frac{T^{(n)}  T^{(n1)}}{h} 
61 
\label{eqn:Tbeuler} 
62 
\end{equation} 
63 
where the upper index $n$ denotes the n\textsuperscript{th} time step. So one has 
64 
\begin{equation} 
65 
\begin{array}{rcl} 
66 
t^{(n)} & = & t^{(n1)}+h \\ 
67 
T^{(n)} & = & T(t^{(n1)}) \\ 
68 
\end{array} 
69 
\label{eqn:Neuler} 
70 
\end{equation} 
71 
Substituting \refEq{eqn:Tbeuler} into \refEq{eqn:hd} we get; 
72 
\begin{equation} 
73 
\frac{\rho c\hackscore p}{h} (T^{(n)}  T^{(n1)})  \kappa \frac{\partial^{2} T^{(n)}}{\partial x^{2}} = q\hackscore H 
74 
\label{eqn:hddisc} 
75 
\end{equation} 
76 
Notice that we evaluate the spatial derivative term at current time $t^{(n)}$  therefore the name \textbf{backward Euler} scheme. Alternatively, one can use evaluate the spatial derivative term at the previous time $t^{(n1)}$. This 
77 
approach is called the \textbf{forward Euler} scheme. This scheme can provide some computational advantages which 
78 
we are not discussed here but has the major disadvantage that depending on the 
79 
material parameter as well as the discretization of the spatial derivative term the time step size $h$ needs to be chosen sufficiently small to achieve a stable temperature when progressing in time. The term \textit{stable} means 
80 
that the approximation of the temperature will not grow beyond its initial bounds and becomes nonphysical. 
81 
The backward Euler which we use here is unconditionally stable meaning that under the assumption of 
82 
physically correct problem setup the temperature approximation remains physical for all times. 
83 
The user needs to keep in mind that the discretization error introduced by \refEq{eqn:beuler} 
84 
is sufficiently small so a good approximation of the true temperature is calculated. It is 
85 
therefore crucial that the user remains critical about his/her results and for instance compares 
86 
the results for different time and spatial step sizes. 
87 

88 
To get the temperature $T^{(n)}$ at time $t^{(n)}$ we need to solve the linear 
89 
differential equation \refEq{eqn:hddisc} which is only including spatial derivatives. To solve this problem 
90 
we want to to use \esc. 
91 

92 
\esc interfaces with any given PDE via a general form. For the purpose of this introduction we will illustrate a simpler version of the full linear PDE general form which is available in the \esc user's guide. A simplified form that suits our heat diffusion problem\footnote{In the form of the \esc users guide which using the Einstein convention is written as 
93 
$(A\hackscore{jl} u\hackscore{,l})\hackscore{,j}+D u =Y$} 
94 
is described by; 
95 
\begin{equation}\label{eqn:commonform nabla} 
96 
\nabla\cdot(A\cdot\nabla u) + Du = f 
97 
\end{equation} 
98 
where $A$, $D$ and $f$ are known values and $u$ is the unknown solution. The symbol $\nabla$ which is called the \textit{Nabla operator} or \textit{del operator} represents 
99 
the spatial derivative of its subject  in this case $u$. Lets assume for a moment that we deal with a onedimensional problem then ; 
100 
\begin{equation} 
101 
\nabla = \frac{\partial}{\partial x} 
102 
\end{equation} 
103 
and we can write \refEq{eqn:commonform nabla} as; 
104 
\begin{equation}\label{eqn:commonform} 
105 
A\frac{\partial^{2}u}{\partial x^{2}} + Du = f 
106 
\end{equation} 
107 
if $A$ is constant. To match this simplified general form to our problem \refEq{eqn:hddisc} 
108 
we rearrange \refEq{eqn:hddisc}; 
109 
\begin{equation} 
110 
\frac{\rho c\hackscore p}{h} T^{(n)}  \kappa \frac{\partial^2 T^{(n)}}{\partial x^2} = q\hackscore H + \frac{\rho c\hackscore p}{h} T^{(n1)} 
111 
\label{eqn:hdgenf} 
112 
\end{equation} 
113 
The PDE is now in a form that satisfies \refEq{eqn:commonform nabla} which is required for \esc to solve our PDE. This can be done by generating a solution for successive increments in the time nodes $t^{(n)}$ where 
114 
$t^{(0)}=0$ and $t^{(n)}=t^{(n1)}+h$ where $h>0$ is the step size and assumed to be constant. 
115 
In the following the upper index ${(n)}$ refers to a value at time $t^{(n)}$. Finally, by comparing \refEq{eqn:hdgenf} with \refEq{eqn:commonform} it can be seen that; 
116 
\begin{equation}\label{ESCRIPT SET} 
117 
u=T^{(n)}; 
118 
A = \kappa; D = \frac{\rho c \hackscore{p}}{h}; f = q \hackscore{H} + \frac{\rho c\hackscore p}{h} T^{(n1)} 
119 
\end{equation} 
120 

121 
\subsection{Boundary Conditions} 
122 
\label{SEC BOUNDARY COND} 
123 
With the PDE sufficiently modified, consideration must now be given to the boundary conditions of our model. Typically there are two main types of boundary conditions known as \textbf{Neumann} and \textbf{Dirichlet} boundary conditions\footnote{More information on Boundary Conditions is available at Wikipedia \url{http://en.wikipedia.org/wiki/Boundary_conditions}}, respectively. 
124 
A \textbf{Dirichlet boundary condition} is conceptually simpler and is used to prescribe a known value to the unknown  in our example the temperature  on parts of the boundary or on the entire boundary of the region of interest. 
125 
We discuss Dirichlet boundary condition in our second example presented in Section~\ref{Sec:1DHDv0}. 
126 

127 
We make the model assumption that the system is insulated so we need 
128 
to add an appropriate boundary condition to prevent 
129 
any loss or inflow of energy at boundary of our domain. Mathematically this is expressed by prescribing 
130 
the heat flux $\kappa \frac{\partial T}{\partial x}$ to zero. In our simplified one dimensional model this is expressed 
131 
in the form; 
132 
\begin{equation} 
133 
\kappa \frac{\partial T}{\partial x} = 0 
134 
\end{equation} 
135 
or in a more general case as 
136 
\begin{equation}\label{NEUMAN 1} 
137 
\kappa \nabla T \cdot n = 0 
138 
\end{equation} 
139 
where $n$ is the outer normal field \index{outer normal field} at the surface of the domain. 
140 
The $\cdot$ (dot) refers to the dot product of the vectors $\nabla T$ and $n$. In fact, the term $\nabla T \cdot n$ is the normal derivative of 
141 
the temperature $T$. Other notations which are used are\footnote{The \esc notation for the normal 
142 
derivative is $T\hackscore{,i} n\hackscore i$.}; 
143 
\begin{equation} 
144 
\nabla T \cdot n = \frac{\partial T}{\partial n} \; . 
145 
\end{equation} 
146 
A condition of the type \refEq{NEUMAN 1} defines a \textbf{Neuman boundary condition} for the PDE. 
147 

148 
The PDE \refEq{eqn:hdgenf} 
149 
and the Neuman boundary condition~\ref{eqn:hdgenf} (potentially together with the Dirichlet boundary condition set) define a \textbf{boundary value problem}. 
150 
It is a nature of a boundary value problem that it allows to make statements on the solution in the 
151 
interior of the domain from information known on the boundary only. In most cases 
152 
we use the term partial differential equation but in fact mean a boundary value problem. 
153 
It is important to keep in mind that boundary conditions need to be complete and consistent in the sense that 
154 
at any point on the boundary either a Dirichlet or a Neuman boundary condition must be set. 
155 

156 
Conveniently, \esc makes default assumption on the boundary conditions which the user may modify where appropriate. 
157 
For a problem of the form in~\refEq{eqn:commonform nabla} the default condition\footnote{In the form of the \esc users guide which is using the Einstein convention is written as 
158 
$n\hackscore{j}A\hackscore{jl} u\hackscore{,l}=0$.} is; 
159 
\begin{equation}\label{NEUMAN 2} 
160 
n\cdot A \cdot\nabla u = 0 
161 
\end{equation} 
162 
which is used everywhere on the boundary. Again $n$ denotes the outer normal field. 
163 
Notice that the coefficient $A$ is the same as in the \esc PDE~\ref{eqn:commonform nabla}. 
164 
With the settings for the coefficients we have already identified in \refEq{ESCRIPT SET} this 
165 
condition translates into 
166 
\begin{equation}\label{NEUMAN 2b} 
167 
\kappa \frac{\partial T}{\partial x} = 0 
168 
\end{equation} 
169 
for the boundary of the domain. This is identical to the Neuman boundary condition we want to set. \esc will take care of this condition for us. We will discuss the Dirichlet boundary condition later. 
170 

171 
\subsection{Outline of the Implementation} 
172 
\label{sec:outline} 
173 
To solve the heat diffusion equation (equation \refEq{eqn:hd}) we will write a simple \pyt script. At this point we assume that you have some basic understanding of the \pyt programming language. If not there are some pointers and links available in Section \ref{sec:escpybas}. The script we will discuss later in details will have four major steps. Firstly we need to define the domain where we want to 
174 
calculate the temperature. For our problem this is the joint blocks of granite which has a rectangular shape. Secondly we need to define the PDE 
175 
we need to solve in each time step to get the updated temperature. Thirdly we need to define the the coefficients of the PDE and finally we need to solve the PDE. The last two steps need to be repeated until the final time marker has been reached. As a work flow this takes the form; 
176 
\begin{enumerate} 
177 
\item create domain 
178 
\item create PDE 
179 
\item while end time not reached: 
180 
\begin{enumerate} 
181 
\item set PDE coefficients 
182 
\item solve PDE 
183 
\item update time marker 
184 
\end{enumerate} 
185 
\item end of calculation 
186 
\end{enumerate} 
187 
In the terminology of \pyt the domain and PDE are represented by \textbf{objects}. The nice feature of an object is that it defined by it usage and features 
188 
rather than its actual representation. So we will create a domain object to describe the geometry of the two 
189 
granite blocks. The main feature 
190 
of the object we will use is the fact that we can define PDEs and spatially distributed values such as the temperature 
191 
on a domain. In fact the domain object has many more features  most of them you will 
192 
never use and do not need to understand. Similar a PDE object is defined by the fact that we can define the coefficients of the PDE and solve the PDE. At a 
193 
later stage you may use more advanced features of the PDE class but you need to worry about them only at the point when you use them. 
194 

195 

196 
\begin{figure}[t] 
197 
\centering 
198 
\includegraphics[width=6in]{figures/functionspace.pdf} 
199 
\label{fig:fs} 
200 
\caption{\esc domain construction overview} 
201 
\end{figure} 
202 

203 
\subsection{The Domain Constructor in \esc} 
204 
\label{ss:domcon} 
205 
It is helpful to have a better understanding how spatially distributed value such as the temperature or PDE coefficients are interpreted in \esc. Again 
206 
from the user's point of view the representation of these spatially distributed values is not relevant. 
207 

208 
There are various ways to construct domain objects. The simplest form is as rectangular shaped region with a length and height. There is 
209 
a ready to use function call for this. Besides the spatial dimensions the function call will require you to specify the number 
210 
elements or cells to be used along the length and height, see \reffig{fig:fs}. Any spatially distributed value 
211 
and the PDE is represented in discrete form using this element representation\footnote{We will use the finite element method (FEM), see \url{http://en.wikipedia.org/wiki/Finite_element_method} for details.}. Therefore we will have access to an approximation of the true PDE solution only. 
212 
The quality of the approximation depends  besides other factors mainly on the number of elements being used. In fact, the 
213 
approximation becomes better the more elements are used. However, computational costs and compute time grow with the number of 
214 
elements being used. It therefore important that you find the right balance between the demand in accuracy and acceptable resource usage. 
215 

216 
In general, one can thinks about a domain object as a composition of nodes and elements. 
217 
As shown in \reffig{fig:fs}, an element is defined by the nodes used to describe its vertices. 
218 
To represent spatial distributed values the user can use 
219 
the values at the nodes, at the elements in the interior of the domain or at elements located at the surface of the domain. 
220 
The different approach used to represent values is called \textbf{function space} and is attached to all objects 
221 
in \esc representing a spatial distributed value such as the solution of a PDE. The three 
222 
function spaces we will use at the moment are; 
223 
\begin{enumerate} 
224 
\item the nodes, called by \verbContinuousFunction(domain) ; 
225 
\item the elements/cells, called by \verbFunction(domain) ; and 
226 
\item the boundary, called by \verbFunctionOnBoundary(domain) . 
227 
\end{enumerate} 
228 
A function space object such as \verbContinuousFunction(domain) has the method \verbgetX attached to it. This method returns the 
229 
location of the socalled \textbf{sample points} used to represent values with the particular function space attached to it. So the 
230 
call \verbContinuousFunction(domain).getX() will return the coordinates of the nodes used to describe the domain while 
231 
the \verbFunction(domain).getX() returns the coordinates of numerical integration points within elements, see 
232 
\reffig{fig:fs}. 
233 

234 
This distinction between different representations of spatial distributed values 
235 
is important in order to be able to vary the degrees of smoothness in a PDE problem. 
236 
The coefficients of a PDE need not be continuous thus this qualifies as a \verbFunction() type. 
237 
On the other hand a temperature distribution must be continuous and needs to be represented with a \verbContinuousFunction() function space. 
238 
An influx may only be defined at the boundary and is therefore a \verb FunctionOnBoundary() object. 
239 
\esc allows certain transformations of the function spaces. A \verb ContinuousFunction() can be transformed into a \verbFunctionOnBoundary() 
240 
or \verbFunction(). On the other hand there is not enough information in a \verb FunctionOnBoundary() to transform it to a \verb ContinuousFunction() . 
241 
These transformations, which are called \textbf{interpolation} are invoked automatically by \esc if needed. 
242 

243 
Later in this introduction we will discuss how 
244 
to define specific areas of geometry with different materials which are represented by different material coefficients such the 
245 
thermal conductivities $kappa$. A very powerful technique to define these types of PDE 
246 
coefficients is tagging. Blocks of materials and boundaries can be named and values can be defined on subregions based on their names. 
247 
This is simplifying PDE coefficient and flux definitions. It makes for much easier scripting. We will discuss this technique in Section~\ref{STEADYSTATE HEAT REFRACTION}. 
248 

249 

250 
\subsection{A Clarification for the 1D Case} 
251 
\label{SEC: 1D CLARIFICATION} 
252 
It is necessary for clarification that we revisit the general PDE from \refeq{eqn:commonform nabla} under the light of a two dimensional domain. \esc is inherently designed to solve problems that are greater than one dimension and so \refEq{eqn:commonform nabla} needs to be read as a higher dimensional problem. In the case of two spatial dimensions the \textit{Nabla operator} has in fact two components $\nabla = (\frac{\partial}{\partial x}, \frac{\partial}{\partial y})$. In full, \refEq{eqn:commonform nabla} assuming a constant coefficient $A$, takes the form; 
253 
\begin{equation}\label{eqn:commonform2D} 
254 
A\hackscore{00}\frac{\partial^{2}u}{\partial x^{2}} 
255 
A\hackscore{01}\frac{\partial^{2}u}{\partial x\partial y} 
256 
A\hackscore{10}\frac{\partial^{2}u}{\partial y\partial x} 
257 
A\hackscore{11}\frac{\partial^{2}u}{\partial y^{2}} 
258 
+ Du = f 
259 
\end{equation} 
260 
Notice that for the higher dimensional case $A$ becomes a matrix. It is also 
261 
important to notice that the usage of the Nabla operator creates 
262 
a compact formulation which is also independent from the spatial dimension. 
263 
So to make the general PDE \refEq{eqn:commonform2D} one dimensional as 
264 
shown in \refEq{eqn:commonform} we need to set 
265 
\begin{equation} 
266 
A\hackscore{00}=A; A\hackscore{01}=A\hackscore{10}=A\hackscore{11}=0 
267 
\end{equation} 
268 

269 

270 
\subsection{Developing a PDE Solution Script} 
271 
\label{sec:key} 
272 
\sslist{example01a.py} 
273 
We will write a simple \pyt script which uses the \modescript, \modfinley and \modmpl modules. 
274 
By developing a script for \esc, the heat diffusion equation can be solved at successive time steps for a predefined period using our general form \refEq{eqn:hdgenf}. Firstly it is necessary to import all the libraries\footnote{The libraries contain predefined scripts that are required to solve certain problems, these can be simple like sine and cosine functions or more complicated like those from our \esc library.} 
275 
that we will require. 
276 
\begin{python} 
277 
from esys.escript import * 
278 
# This defines the LinearPDE module as LinearPDE 
279 
from esys.escript.linearPDEs import LinearPDE 
280 
# This imports the rectangle domain function from finley. 
281 
from esys.finley import Rectangle 
282 
# A useful unit handling package which will make sure all our units 
283 
# match up in the equations under SI. 
284 
from esys.escript.unitsSI import * 
285 
\end{python} 
286 
It is generally a good idea to import all of the \modescript library, although if the functions and classes required are known they can be specified individually. The function \verbLinearPDE has been imported explicitly for ease of use later in the script. \verbRectangle is going to be our type of model. The module \verb unitsSI provides support for SI unit definitions with our variables. 
287 

288 
Once our library dependencies have been established, defining the problem specific variables is the next step. In general the number of variables needed will vary between problems. These variables belong to two categories. They are either directly related to the PDE and can be used as inputs into the \esc solver, or they are script variables used to control internal functions and iterations in our problem. For this PDE there are a number of constants which will need values. Firstly, the model upon which we wish to solve our problem needs to be defined. There are many different types of models in \modescript which we will demonstrate in later tutorials but for our granite blocks, we will simply use a rectangular model. 
289 

290 
Using a rectangular model simplifies our granite blocks which would in reality be a \textit{3D} object, into a single dimension. The granite blocks will have a lengthways cross section that looks like a rectangle. As a result we do not need to model the volume of the block. There are four arguments we must consider when we decide to create a rectangular model, the model \textit{length}, \textit{width} and \textit{step size} in each direction. When defining the size of our problem it will help us determine appropriate values for our model arguments. If we make our dimensions large but our step sizes very small we will to a point, increase the accuracy of our solution. Unfortunately we also increase the number of calculations that must be solved per time step. This means more computational time is required to produce a solution. In this \textit{1D} problem, the bar is defined as being 1 metre long. An appropriate step size \verbndx would be 1 to 10\% of the length. Our \verbndy need only be 1, this is because our problem stipulates no partial derivatives in the $y$ direction. Thus the temperature does not vary with $y$. Hence, the model parameters can be defined as follows; note we have used the \verb unitsSI convention to make sure all our input units are converted to SI. 
291 
\begin{python} 
292 
mx = 500.*m #meters  model length 
293 
my = 100.*m #meters  model width 
294 
ndx = 50 # mesh steps in x direction 
295 
ndy = 1 # mesh steps in y direction 
296 
boundloc = mx/2 # location of boundary between the two blocks 
297 
\end{python} 
298 
The material constants and the temperature variables must also be defined. For the granite in the model they are defined as: 
299 
\begin{python} 
300 
#PDE related 
301 
rho = 2750. *kg/m**3 #kg/m^{3} density of iron 
302 
cp = 790.*J/(kg*K) # J/Kg.K thermal capacity 
303 
rhocp = rho*cp 
304 
kappa = 2.2*W/m/K # watts/m.Kthermal conductivity 
305 
qH=0 * J/(sec*m**3) # J/(sec.m^{3}) no heat source 
306 
T1=20 * Celsius # initial temperature at Block 1 
307 
T2=2273. * Celsius # base temperature at Block 2 
308 
\end{python} 
309 
Finally, to control our script we will have to specify our timing controls and where we would like to save the output from the solver. This is simple enough: 
310 
\begin{python} 
311 
t=0 * day #our start time, usually zero 
312 
tend=1. * day #  time to end simulation 
313 
outputs = 200 # number of time steps required. 
314 
h=(tendt)/outputs #size of time step 
315 
#user warning statement 
316 
print "Expected Number of time outputs is: ", (tendt)/h 
317 
i=0 #loop counter 
318 
\end{python} 
319 
Now that we know our inputs we will build a domain using the \verb Rectangle() function from \verb finley . The four arguments allow us to define our domain \verb model as: 
320 
\begin{python} 
321 
#generate domain using rectangle 
322 
blocks = Rectangle(l0=mx,l1=my,n0=ndx, n1=ndy) 
323 
\end{python} 
324 
\verb blocks now describes a domain in the manner of Section \ref{ss:domcon}. T 
325 

326 
With a domain and all our required variables established, it is now possible to set up our PDE so that it can be solved by \esc. The first step is to define the type of PDE that we are trying to solve in each time step. In this example it is a single linear PDE\footnote{in comparison to a system of PDEs which will be discussed later.}. We also need to state the values of our general form variables. 
327 
\begin{python} 
328 
mypde=LinearPDE(blocks) 
329 
A=zeros((2,2))) 
330 
A[0,0]=kappa 
331 
mypde.setValue(A=A, D=rhocp/h) 
332 
\end{python} 
333 
In a many cases it may be possible to decrease the computational time of the solver if the PDE is symmetric. 
334 
Symmetry of a PDE is defined by; 
335 
\begin{equation}\label{eqn:symm} 
336 
A\hackscore{jl}=A\hackscore{lj} 
337 
\end{equation} 
338 
Symmetry is only dependent on the $A$ coefficient in the general form and the other coefficients $D$ as well as the right hand side $Y$ may take any value. From the above definition we can see that our PDE is symmetric. The \verb LinearPDE class provides the method \method{checkSymmetry} to check if the given PDE is symmetric. As our PDE is symmetrical we will enable symmetry via; 
339 
\begin{python} 
340 
myPDE.setSymmetryOn() 
341 
\end{python} 
342 
Next we need to establish the initial temperature distribution \verbT. We need to 
343 
assign the value \verbT1 to all sample points left to the contact interface at $x\hackscore{0}=\frac{mx}{2}$ 
344 
and the value \verbT2 right to the contact interface. \esc 
345 
provides the \verbwhereNegative function to construct this. In fact, 
346 
\verbwhereNegative returns the value $1$ at those sample points where the argument 
347 
has a negative value. Otherwise zero is returned. If \verbx are the $x\hackscore{0}$ 
348 
coordinates of the sample points used to represent the temperature distribution 
349 
then \verbx[0]boundloc gives us a negative value for 
350 
all sample points left to the interface and nonnegative value to 
351 
the right of the interface. So with; 
352 
\begin{python} 
353 
# ... set initial temperature .... 
354 
T= T1*whereNegative(x[0]boundloc)+T2*(1whereNegative(x[0]boundloc)) 
355 
\end{python} 
356 
we get the desired temperature distribution. To get the actual sample points \verbx we use 
357 
the \verbgetX() method of the function space \verbSolution(blocks) 
358 
which is used to represent the solution of a PDE; 
359 
\begin{python} 
360 
x=Solution(blocks).getX() 
361 
\end{python} 
362 
As \verbx are the sample points for the function space \verbSolution(blocks) 
363 
the initial temperature \verbT is using these sample points for representation. 
364 
Although \esc is trying to be forgiving with the choice of sample points and to convert 
365 
where necessary the adjustment of the function space is not always possible. So it is 
366 
advisable to make a careful choice on the function space used. 
367 

368 
Finally we will initialise an iteration loop to solve our PDE for all the time steps we specified in the variable section. As the right hand side of the general form is dependent on the previous values for temperature \verb T across the bar this must be updated in the loop. Our output at each time step is \verb T the heat distribution and \verb totT the total heat in the system. 
369 
\begin{python} 
370 
while t < tend: 
371 
i+=1 #increment the counter 
372 
t+=h #increment the current time 
373 
mypde.setValue(Y=qH+rhocp/h*T) # set variable PDE coefficients 
374 
T=mypde.getSolution() #get the PDE solution 
375 
totE = integrate(rhocp*T) #get the total heat (energy) in the system 
376 
\end{python} 
377 
The last statement in this script calculates the total energy in the system as volume integral 
378 
of $\rho c\hackscore{p} T$ over the block. As the blocks are insulated no energy should be get lost or added. 
379 
The total energy should stay constant for the example discussed here. 
380 

381 
\subsection{Running the Script} 
382 
The script presented so for is available under 
383 
\verbexample01a.py. You can edit this file with your favourite text editor. 
384 
On most operating systems\footnote{The you can use \texttt{runescript} launcher is not supported under {\it MS Windows} yet.} you can use the \program{runescript} command 
385 
to launch {\it escript} scripts. For the example script use; 
386 
\begin{verbatim} 
387 
runescript example01a.py 
388 
\end{verbatim} 
389 
The program will print a progress report. Alternatively, you can use 
390 
the python interpreter directly; 
391 
\begin{verbatim} 
392 
python example01a.py 
393 
\end{verbatim} 
394 
if the system is configured correctly (Please talk to your system administrator). 
395 

396 
\begin{figure} 
397 
\begin{center} 
398 
\includegraphics[width=4in]{figures/ttblockspyplot150} 
399 
\caption{Example 1b: Total Energy in the Blocks over Time (in seconds).} 
400 
\label{fig:onedheatout1} 
401 
\end{center} 
402 
\end{figure} 
403 

404 
\subsection{Plotting the Total Energy} 
405 
\sslist{example01b.py} 
406 

407 
\esc does not include its own plotting capabilities. However, it is possible to use a variety of free \pyt packages for visualisation. 
408 
Two types will be demonstrated in this cookbook; \mpl\footnote{\url{http://matplotlib.sourceforge.net/}} and \verb VTK \footnote{\url{http://www.vtk.org/}} visualisation. 
409 
The \mpl package is a component of SciPy\footnote{\url{http://www.scipy.org}} and is good for basic graphs and plots. 
410 
For more complex visualisation tasks in particular when it comes to two and three dimensional problems it is recommended to us more advanced tools for instance \mayavi \footnote{\url{http://code.enthought.com/projects/mayavi/}} 
411 
which bases on the \verbVTK toolkit. We will discuss the usage of \verbVTK based 
412 
visualization in Chapter~\ref{Sec:2DHD} where will discuss a two dimensional PDE. 
413 

414 
For our simple problem we have two plotting tasks: Firstly we are interested in showing the 
415 
behaviour of the total energy over time and secondly in how the temperature distribution within the block is 
416 
developing over time. Lets start with the first task. 
417 

418 
The trick is to create a record of the time marks and the corresponding total energies observed. 
419 
\pyt provides the concept of lists for this. Before 
420 
the time loop is opened we create empty lists for the time marks \verbt_list and the total energies \verbE_list. 
421 
After the new temperature as been calculated by solving the PDE we append the new time marker and total energy 
422 
to the corresponding list using the \verbappend method. With these modifications the script looks as follows: 
423 
\begin{python} 
424 
t_list=[] 
425 
E_list=[] 
426 
# ... start iteration: 
427 
while t<tend: 
428 
t+=h 
429 
mypde.setValue(Y=qH+rhocp/h*T) # set variable PDE coefficients 
430 
T=mypde.getSolution() #get the PDE solution 
431 
totE=integrate(rhocp*T) 
432 
t_list.append(t) # add current time mark to record 
433 
E_list.append(totE) # add current total energy to record 
434 
\end{python} 
435 
To plot $t$ over $totE$ we use the \mpl a module contained within \pylab which needs to be loaded before used; 
436 
\begin{python} 
437 
import pylab as pl # plotting package. 
438 
\end{python} 
439 
Here we are not using the \verbfrom pylab import * in order to avoid name clashes for function names 
440 
within \esc. 
441 

442 
The following statements are added to the script after the time loop has been completed; 
443 
\begin{python} 
444 
pl.plot(t_list,E_list) 
445 
pl.title("Total Energy") 
446 
pl.axis([0,max(t_list),0,max(E_list)*1.1]) 
447 
pl.savefig("totE.png") 
448 
\end{python} 
449 
The first statement hands over the time marks and corresponding total energies to the plotter. 
450 
The second statment is setting the title for the plot. The third statement 
451 
sets the axis ranges. In most cases these are set appropriately by the plotter. 
452 
The last statement renders the plot and writes the 
453 
result into the file \verbtotE.png which can be displayed by (almost) any image viewer. 
454 
As expected the total energy is constant over time, see \reffig{fig:onedheatout1}. 
455 

456 
\subsection{Plotting the Temperature Distribution} 
457 
\label{sec: plot T} 
458 
\sslist{example01c.py} 
459 
For plotting the spatial distribution of the temperature we need to modify the strategy we have used 
460 
for the total energy. Instead of producing a final plot at the end we will generate a 
461 
picture at each time step which can be browsed as slide show or composed to a movie. 
462 
The first problem we encounter is that if we produce an image in each time step we need 
463 
to make sure that the images previously generated are not overwritten. 
464 

465 
To develop an incrementing file name we can use the following convention. It is convenient to 
466 
put all image file showing the same variable  in our case the temperature distribution  
467 
into a separate directory. As part of the \verbos module\footnote{The \texttt{os} module provides 
468 
a powerful interface to interact with the operating system, see \url{http://docs.python.org/library/os.html}.} \pyt 
469 
provides the \verbos.path.join command to build file and 
470 
directory names in a platform independent way. Assuming that 
471 
\verbsave_path is name of directory we want to put the results the command is; 
472 
\begin{python} 
473 
import os 
474 
os.path.join(save_path, "tempT%03d.png"%i ) 
475 
\end{python} 
476 
where \verbi is the time step counter. 
477 
There are two arguments to the \verb join command. The \verb save_path variable is a predefined string pointing to the directory we want to save our data in, for example a single subfolder called \verb data would be defined by; 
478 
\begin{verbatim} 
479 
save_path = "data" 
480 
\end{verbatim} 
481 
while a subfolder of \verb data called \verb example01 would be defined by; 
482 
\begin{verbatim} 
483 
save_path = os.path.join("data","example01") 
484 
\end{verbatim} 
485 
The second argument of \verb join \xspace contains a string which is the file name or subdirectory name. We can use the operator \verb% to increment our file names with the value \verbi denoting a incrementing counter. The substring \verb %03d does this by defining the following parameters; 
486 
\begin{itemize} 
487 
\item \verb 0 becomes the padding number; 
488 
\item \verb 3 tells us the amount of padding numbers that are required; and 
489 
\item \verb d indicates the end of the \verb % operator. 
490 
\end{itemize} 
491 
To increment the file name a \verb %i is required directly after the operation the string is involved in. When correctly implemented the output files from this command would be place in the directory defined by \verb save_path as; 
492 
\begin{verbatim} 
493 
blockspyplot.png 
494 
blockspyplot.png 
495 
blockspyplot.png 
496 
... 
497 
\end{verbatim} 
498 
and so on. 
499 

500 
A subfolder check/constructor is available in \esc. The command; 
501 
\begin{verbatim} 
502 
mkDir(save_path) 
503 
\end{verbatim} 
504 
will check for the existence of \verb save_path and if missing, make the required directories. 
505 

506 
We start by modifying our solution script from before. 
507 
Prior to the \verbwhile loop we will need to extract our finite solution points to a data object that is compatible with \mpl. First we create the node coordinates of the sample points used to represent 
508 
the temperature as a \pyt list of tuples or a \numpy array as requested by the plotting function. 
509 
We need to convert thearray \verbx previously set as \verbSolution(blocks).getX() into a \pyt list 
510 
and then to a \numpy array. The $x\hackscore{0}$ component is then extracted via an array slice to the variable \verbplx; 
511 
\begin{python} 
512 
import numpy as np # array package. 
513 
#convert solution points for plotting 
514 
plx = x.toListOfTuples() 
515 
plx = np.array(plx) # convert to tuple to numpy array 
516 
plx = plx[:,0] # extract x locations 
517 
\end{python} 
518 

519 
\begin{figure} 
520 
\begin{center} 
521 
\includegraphics[width=4in]{figures/blockspyplot001} 
522 
\includegraphics[width=4in]{figures/blockspyplot050} 
523 
\includegraphics[width=4in]{figures/blockspyplot200} 
524 
\caption{Example 1c: Temperature ($T$) distribution in the blocks at time steps $1$, $50$ and $200$.} 
525 
\label{fig:onedheatout} 
526 
\end{center} 
527 
\end{figure} 
528 

529 
For each time step we will generate a plot of the temperature distribution and save each to a file. We use the same 
530 
techniques provided by \mpl as we have used to plot the total energy over time. 
531 
The following is appended to the end of the \verb while loop and creates one figure of the temperature distribution. We start by converting the solution to a tuple and then plotting this against our \textit{x coordinates} \verb plx we have generated before. We add a title to the diagram before it is rendered into a file. 
532 
Finally, the figure is saved to a \verb*.png file and cleared for the following iteration. 
533 
\begin{python} 
534 
# ... start iteration: 
535 
while t<tend: 
536 
.... 
537 
T=mypde.getSolution() #get the PDE solution 
538 
tempT = T.toListOfTuples() # convert to a tuple 
539 
pl.plot(plx,tempT) # plot solution 
540 
# set scale (Temperature should be between Tref and T0) 
541 
pl.axis([0,mx,Tref*.9,T0*1.1]) 
542 
# add title 
543 
pl.title("Temperature across the blocks at time %e minutes"%(t/day)) 
544 
#save figure to file 
545 
pl.savefig(os.path.join(save_path,"tempT","blockspyplot%03d.png") %i) 
546 
\end{python} 
547 
Some results are shown in \reffig{fig:onedheatout}. 
548 

549 
\subsection{Make a video} 
550 
Our saved plots from the previous section can be cast into a video using the following command appended to the end of the script. \verb mencoder is Linux only however, and other platform users will need to use an alternative video encoder. 
551 
\begin{python} 
552 
# compile the *.png files to create a *.avi videos that show T change 
553 
# with time. This operation uses Linux mencoder. For other operating 
554 
# systems it is possible to use your favourite video compiler to 
555 
# convert image files to videos. 
556 

557 
os.system("mencoder mf://"+save_path+"/tempT"+"/*.png mf type=png:\ 
558 
w=800:h=600:fps=25 ovc lavc lavcopts vcodec=mpeg4 oac copy o \ 
559 
example01tempT.avi") 
560 
\end{python} 
561 
