# Diff of /trunk/doc/cookbook/example01.tex

revision 2904 by jfenwick, Thu Jan 28 02:03:15 2010 UTC revision 2905 by gross, Tue Feb 2 04:26:42 2010 UTC
# Line 11  Line 11
11  %  %
12  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
13
We will start by examining a simple one dimensional heat diffusion example. This problem will provide a good launch pad to build our knowledge of \esc and demonstrate how to solve simple partial differential equations (PDEs)\footnote{Wikipedia provides an excellent and comprehensive introduction to \textit{Partial Differential Equations} \url{http://en.wikipedia.org/wiki/Partial_differential_equation}, however their relevance to \esc and implementation should become a clearer as we develop our understanding further into the cookbook.}

\section{One Dimensional Heat Diffusion in an Iron Rod}

%\label{Sec:1DHDv0}
The first model consists of a simple cold iron bar at a constant temperature of zero \reffig{fig:onedhdmodel}. The bar is perfectly insulated on all sides with a heating element at one end. Intuition tells us that as heat is applied; energy will disperse along the bar via conduction. With time the bar will reach a constant temperature equivalent to that of the heat source.
14  \begin{figure}[h!]  \begin{figure}[h!]
15  \centerline{\includegraphics[width=4.in]{figures/onedheatdiff}}  \centerline{\includegraphics[width=4.in]{figures/onedheatdiff001}}
16  \caption{One dimensional model of an Iron bar.}  \caption{Temperature differential along a single interface between two granite blocks.}
17  \label{fig:onedhdmodel}  \label{fig:onedgbmodel}
18  \end{figure}  \end{figure}
19
20    \section{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    \verb|T1| and \textit{Block 2} is at a temperature \verb|T2|.
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}  \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}};  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:  which is defined as:
# Line 36  The heat source is defined by the right Line 42  The heat source is defined by the right
42
43  \subsection{PDEs and the General Form}  \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  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 modeler.  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  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  leave as with a steady linear PDE which is involving spatial derivatives only and needs to be solved in each time
# Line 70  Substituting \refEq{eqn:Tbeuler} into \r Line 76  Substituting \refEq{eqn:Tbeuler} into \r
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^{(n-1)}$. This  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^{(n-1)}$. This
77  approach is called the \textbf{forward Euler} scheme. This scheme can provide some computational advantages which  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  we are not discussed here but has the major disadvantage that depending on the
79  material parameter as well as the discretiztion 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  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 unphysical.  that the approximation of the temperature will not grow beyond its initial bounds and becomes non-physical.
81  The backward Euler which we use here is unconditionally stable meaning that under the assumption of  The backward Euler which we use here is unconditionally stable meaning that under the assumption of
82  physically correct problem set-up the temperature approximation remains physical for all times.  physically correct problem set-up 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}  The user needs to keep in mind that the discretization error introduced by \refEq{eqn:beuler}
# Line 112  u=T^{(n)}; Line 118  u=T^{(n)};
118  A = \kappa; D = \frac{\rho c \hackscore{p}}{h}; f = q \hackscore{H} + \frac{\rho c\hackscore p}{h} T^{(n-1)}  A = \kappa; D = \frac{\rho c \hackscore{p}}{h}; f = q \hackscore{H} + \frac{\rho c\hackscore p}{h} T^{(n-1)}
119
120
% Now that the general form has been established, it can be submitted to \esc. Note that it is necessary to establish the state of our system at time zero or $T^{(n=0)}$. This is due to the time derivative approximation we have used from \refEq{eqn:Tbeuler}. Our model stipulates a starting temperature in the iron bar of 0\textcelsius. Thus the temperature distribution is simply;
%
% T(x,0) = \left
%
% for all $x$ in the domain.

121  \subsection{Boundary Conditions}  \subsection{Boundary Conditions}
122  \label{SEC BOUNDARY COND}  \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.  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 or the entire boundary of the region of interest.  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  For our model problem we want to keep the initial temperature setting on the left side of the  We discuss Dirichlet boundary condition in our second example presented in Section~\ref{Sec:1DHDv0}.
126  iron bar over time. This defines a Dirichlet boundary condition for the PDE \refEq{eqn:hddisc} to be solved at each time step.
127    We make the model assumption that the system is insulated so we need
128  On the other end of the iron rod we want to add an appropriate boundary condition to define insulation to prevent  to add an appropriate boundary condition to prevent
129  any loss or inflow of energy at the right end of the rod. Mathematically this is expressed by prescribing  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 on the right end of the rod  the heat flux $\kappa \frac{\partial T}{\partial x}$  to zero. In our simplified one dimensional model this is expressed
In our simplified one dimensional model this is expressed
131  in the form;  in the form;
132
133  \kappa \frac{\partial T}{\partial x}  = 0  \kappa \frac{\partial T}{\partial x}  = 0
# Line 138  or in a more general case as Line 137  or in a more general case as
137  \kappa \nabla T \cdot n  = 0  \kappa \nabla T \cdot n  = 0
138
139  where $n$  is the outer normal field \index{outer normal field} at the surface of the domain.  where $n$  is the outer normal field \index{outer normal field} at the surface of the domain.
140  For the iron rod the outer normal field on the right hand side is the vector $(1,0)$. The $\cdot$ (dot) refers to the  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
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  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$.};  derivative is $T\hackscore{,i} n\hackscore i$.};
143
# Line 147  derivative is $T\hackscore{,i} n\hacksco Line 145 derivative is$T\hackscore{,i} n\hacksco
145
146  A condition of the type \refEq{NEUMAN 1} defines a \textbf{Neuman boundary condition} for the PDE.  A condition of the type \refEq{NEUMAN 1} defines a \textbf{Neuman boundary condition} for the PDE.
147
148  The PDE \refEq{eqn:hdgenf} together with the Dirichlet boundary condition set on the left face of the rod  The PDE \refEq{eqn:hdgenf}
149  and the Neuman boundary condition~\ref{eqn:hdgenf} define a \textbf{boundary value problem}.  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  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  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.  we use the term partial differential equation but in fact mean a boundary value problem.
# Line 168  condition translates into Line 166  condition translates into
166  \label{NEUMAN 2b}  \label{NEUMAN 2b}
167  \kappa \frac{\partial T}{\partial x} = 0  \kappa \frac{\partial T}{\partial x} = 0
168
169  for the right hand side of the rod. 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.  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}  \subsection{Outline of the Implementation}
172  \label{sec:outline}  \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  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 iron rod which has a rectangular shape. Secondly we need to define the PDE  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;  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}  \begin{enumerate}
177   \item create domain   \item create domain
# Line 187  we need to solve in each time step to ge Line 185  we need to solve in each time step to ge
185  \item end of calculation  \item end of calculation
186  \end{enumerate}  \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  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 our iron rod. The main feature  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  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  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  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
# Line 208  from the user's point of view the repres Line 207  from the user's point of view the repres
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  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  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 Figure~\ref{fig:fs}. Any specially distributed value  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}i for details.}. Therefore we will have access to an approximation of the true PDE solution only.  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  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  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.  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.  In general, one can thinks about a domain object as a composition of nodes and elements.
217  As shown in Figure~\ref{fig:fs}, an element is defined by the nodes used to describe its vertices.  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  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.  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  The different approach used to represent values is called \textbf{function space} and is attached to all objects
# Line 230  A function space object such as \verb|Co Line 229  A function space object such as \verb|Co
229  location of the so-called \textbf{sample points} used to represent values with the particular function space attached to it. So the  location of the so-called \textbf{sample points} used to represent values with the particular function space attached to it. So the
230  call \verb|ContinuousFunction(domain).getX()| will return the coordinates of the nodes used to describe the domain while  call \verb|ContinuousFunction(domain).getX()| will return the coordinates of the nodes used to describe the domain while
231  the  \verb|Function(domain).getX()| returns the coordinates of numerical integration points within elements, see  the  \verb|Function(domain).getX()| returns the coordinates of numerical integration points within elements, see
232  Figure~\ref{fig:fs}.  \reffig{fig:fs}.
233
234  This distinction between different representations of spatial distributed values  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.  is important in order to be able to vary the degrees of smoothness in a PDE problem.
# Line 271  A\hackscore{00}=A; A\hackscore{01}=A\hac Line 270  A\hackscore{00}=A; A\hackscore{01}=A\hac
270  \label{sec:key}  \label{sec:key}
271  \sslist{onedheatdiffbase.py}  \sslist{onedheatdiffbase.py}
272  We will write a simple \pyt script which uses the \modescript, \modfinley and \modmpl modules.  We will write a simple \pyt script which uses the \modescript, \modfinley and \modmpl modules.
273  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.}  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.}
274  that we will require.  that we will require.
275  \begin{python}  \begin{python}
276  from esys.escript import *  from esys.escript import *
# Line 285  from esys.escript.unitsSI import * Line 284  from esys.escript.unitsSI import *
284  \end{python}  \end{python}
285  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 \verb|LinearPDE| has been imported explicitly for ease of use later in the script. \verb|Rectangle| is going to be our type of model. The module \verb unitsSI  provides support for SI unit definitions with our variables.  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 \verb|LinearPDE| has been imported explicitly for ease of use later in the script. \verb|Rectangle| is going to be our type of model. The module \verb unitsSI  provides support for SI unit definitions with our variables.
286
287  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 iron rod, we will simply use a rectangular model.  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.
288
289  Using a rectangular model simplifies our rod which would be a \textit{3D} object, into a single dimension. The iron rod will have a lengthways cross section that looks like a rectangle.  As a result we do not need to model the volume of the rod because a cylinder is symmetrical about its centre. 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 \verb|ndx| would be 1 to 10\% of the length. Our \verb|ndy| 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.  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 \verb|ndx| would be 1 to 10\% of the length. Our \verb|ndy| 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.
290  \begin{python}  \begin{python}
291  #Domain related.  mx = 500.*m #meters - model length
292  mx = 1*m #meters - model length  my = 100.*m #meters - model width
293  my = .1*m #meters - model width  ndx = 50 # mesh steps in x direction
294  ndx = 100 # mesh steps in x direction  ndy = 1 # mesh steps in y direction
295  ndy = 1 # mesh steps in y direction - one dimension means one element  boundloc = mx/2 # location of boundary between the two blocks
296  \end{python}  \end{python}
297  The material constants and the temperature variables must also be defined. For the iron rod in the model they are defined as:  The material constants and the temperature variables must also be defined. For the granite in the model they are defined as:
298  \begin{python}  \begin{python}
299  #PDE related  #PDE related
300  rho = 7874. *kg/m**3 #kg/m^{3} density of iron  rho = 2750. *kg/m**3 #kg/m^{3} density of iron
301  cp = 449.*J/(kg*K) # J/Kg.K thermal capacity  cp = 790.*J/(kg*K) # J/Kg.K thermal capacity
302  rhocp = rho*cp  rhocp = rho*cp
303  kappa = 80.*W/m/K   # watts/m.Kthermal conductivity  kappa = 2.2*W/m/K   # watts/m.Kthermal conductivity
304  qH=0 * J/(sec*m**3) # J/(sec.m^{3}) no heat source  qH=0 * J/(sec*m**3) # J/(sec.m^{3}) no heat source
305  T0=100 * Celsius # initial temperature at left end of rod  T1=20 * Celsius # initial temperature at Block 1
306  Tref=20 * Celsius # base temperature  T2=2273. * Celsius # base temperature at Block 2
307  \end{python}  \end{python}
308  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:  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:
309  \begin{python}  \begin{python}
# Line 316  h=(tend-t)/outputs #size of time step Line 315  h=(tend-t)/outputs #size of time step
315  print "Expected Number of time outputs is: ", (tend-t)/h  print "Expected Number of time outputs is: ", (tend-t)/h
316  i=0 #loop counter  i=0 #loop counter
317  \end{python}  \end{python}
318  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 rod  as:  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:
319  \begin{python}  \begin{python}
320  #generate domain using rectangle  #generate domain using rectangle
321  rod = Rectangle(l0=mx,l1=my,n0=ndx, n1=ndy)  blocks = Rectangle(l0=mx,l1=my,n0=ndx, n1=ndy)
322  \end{python}  \end{python}
323  \verb rod  now describes a domain in the manner of Section \ref{ss:domcon}. There is an easy way to extract  \verb blocks  now describes a domain in the manner of Section \ref{ss:domcon}. T
the coordinates of the nodes used to describe the domain \verb|rod| using the
domain property function \verb|getX()| . This function sets the vertices of each cell as finite points to solve in the solution. If we let \verb|x| be these finite points, then;
\begin{python}
#extract data points - the solution points
x=rod.getX()
\end{python}
The data locations of specific function spaces can be returned in a similar manner by extracting the relevant function space from the domain followed by the \verb|.getX()| method.
324
325  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.  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.
326  \begin{python}  \begin{python}
327  mypde=LinearSinglePDE(rod)  mypde=LinearPDE(blocks)
328  A=zeros((2,2)))  A=zeros((2,2)))
329  A[0,0]=kappa  A[0,0]=kappa
330  q=whereZero(x[0])  mypde.setValue(A=A, D=rhocp/h)
mypde.setValue(A=A, D=rhocp/h, q=q, r=T0)
331  \end{python}  \end{python}
The argument \verb|q| has not been discussed yet: In fact the arguments \verb|q| and \verb|r| are used to define
Dirichlet boundary condition as discussed in Section~\ref{SEC BOUNDARY COND}. In the \esc
PDE from the argument \verb|q| indicates by a positive value for which nodes we want to apply a
Dirichlet boundary condition, ie. where we want to prescribe the value of the PDE solution
rather then using the PDE. The actually value for the solution to be taken is set by the argument \verb|r|.
In our case we want to keep the initial temperature $T0$ on the left face of the rode for all times. Notice,
that as set to a constant value \verb|r| is assumed to have the same value
at all nodes, however only the value at those nodes marked by a positive value by \verb|q| are actually used.

In order to set \verb|q| we use
\verb|whereZero| function. The function returns the value (positive) one for those data points (=nodes) where the argument is equal to zero and otherwise returns (non-positive) value zero.
As \verb|x[0]| given the $x$-coordinates of the nodes for the domain,
\verb|whereZero(x[0])| gives the value $1$ for the nodes at the left end of the rod $x=x_0=0$ and
zero elsewhere which is exactly what we need.

332  In a many cases it may be possible to decrease the computational time of the solver if the PDE is symmetric.  In a many cases it may be possible to decrease the computational time of the solver if the PDE is symmetric.
333  Symmetry of a PDE is defined by;  Symmetry of a PDE is defined by;
334  \label{eqn:symm}  \label{eqn:symm}
# Line 362  Symmetry is only dependent on the $A$ co Line 338  Symmetry is only dependent on the $A$ co
338  \begin{python}  \begin{python}
339   myPDE.setSymmetryOn()   myPDE.setSymmetryOn()
340  \end{python}  \end{python}
341  Next we need to establish the initial temperature distribution \verb|T|. We want to have this initial  Next we need to establish the initial temperature distribution \verb|T|. We need to
342  value to be \verb|Tref| except at the left end of the rod $x=0$ where we have the temperature \verb|T0|. We use;  assign the value \verb|T1| to all sample points left to the contact interface at $x\hackscore{0}=\frac{mx}{2}$
343    and the value \verb|T2| right to the contact interface. \esc
344    provides the \verb|whereNegative| function to construct this. In fact,
345    \verb|whereNegative| returns the value $1$ at those sample points where the argument
346    has a negative value. Otherwise zero is returned. If \verb|x| are the $x\hackscore{0}$
347    coordinates of the sample points used to represent the temperature distribution
348    then \verb|x[0]-boundloc| gives us a negative value for
349    all sample points left to the interface and non-negative value to
350    the right of the interface. So with;
351  \begin{python}  \begin{python}
352  # ... set initial temperature ....  # ... set initial temperature ....
353  T = T0*whereZero(x[0])+Tref*(1-whereZero(x[0]))  T= T1*whereNegative(x[0]-boundloc)+T2*(1-whereNegative(x[0]-boundloc))
354  \end{python}  \end{python}
355  Finally we will initialize 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.  we get the desired temperature distribution. To get the actual sample points \verb|x| we use
356    the  \verb|getX()| method of the function space \verb|Solution(blocks)|
357    which is used to represent the solution of a PDE;
358    \begin{python}
359    x=Solution(blocks).getX()
360    \end{python}
361    As \verb|x| are the sample points for the function space \verb|Solution(blocks)|
362    the initial temperature \verb|T| is using these sample points for representation.
363    Although \esc is trying to be forgiving with the choice of sample points and to convert
364    where necessary the adjustment of the function space is not always possible. So it is
365    advisable to make a careful choice on the function space used.
366
367    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.
368  \begin{python}  \begin{python}
369  while t < tend:  while t < tend:
370      i+=1 #increment the counter      i+=1 #increment the counter
# Line 378  while t < tend: Line 374  while t < tend:
374      totE = integrate(rhocp*T) #get the total heat (energy) in the system      totE = integrate(rhocp*T) #get the total heat (energy) in the system
375  \end{python}  \end{python}
376  The last statement in this script calculates the total energy in the system as volume integral  The last statement in this script calculates the total energy in the system as volume integral
377  of $\rho \c_p T$ over the rod.    of $\rho c\hackscore{p} T$ over the block. As the blocks are insulated no energy should be get lost or added.
378    The total energy should stay constant for the example discussed here.
379
380    \subsection{Running the Script}
381    The script presented so for is available under
382    \verb|onedheatdiffbase.py|. You can edit this file with your favourite text editor.
383    On most operating systems\footnote{The you can use \texttt{escript} launcher is not supported under {\it MS Windows} yet.} you can use the \program{escript} command
384    to launch {\it escript} scripts. For the example script use;
385    \begin{verbatim}
386    escript onedheatdiffbase.py
387    \end{verbatim}
388    The program will print a progress report. Alternatively, you can use
389    the python interpreter directly;
390    \begin{verbatim}
391    python onedheatdiffbase.py
392    \end{verbatim}
393    if the system is configured correctly (Please talk to your system administrator).
394
395    \begin{figure}
396    \begin{center}
397    \includegraphics[width=4in]{figures/ttblockspyplot150}
398    \caption{Total Energy in the Blocks over Time (in seconds).}
399    \label{fig:onedheatout1}
400    \end{center}
401    \end{figure}
402
403  \subsection{Plotting the Total Energy}  \subsection{Plotting the Total Energy}
404  \sslist{onedheatdiff001.py}  \sslist{onedheatdiff001.py}
405
406  \esc does not include its own plotting capabilities. However, it is possible to use a variety of free \pyt packages for visualization.  \esc does not include its own plotting capabilities. However, it is possible to use a variety of free \pyt packages for visualisation.
407  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.  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.
408  The \mpl package is a component of SciPy\footnote{\url{http://www.scipy.org}} and is good for basic graphs and plots.  The \mpl package is a component of SciPy\footnote{\url{http://www.scipy.org}} and is good for basic graphs and plots.
409  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/}}  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/}}
410  which bases the \verb|VTK| toolkit. We will discuss the usage of \verb|VTK| based  which bases on the \verb|VTK| toolkit. We will discuss the usage of \verb|VTK| based
411  visualization in Chapter~\ref{Sec:2DHD} where will discuss a two dimensional PDE.  visualization in Chapter~\ref{Sec:2DHD} where will discuss a two dimensional PDE.
412
413  For our simple problem we have two plotting tasks: Firstly we are interested in showing the  For our simple problem we have two plotting tasks: Firstly we are interested in showing the
414  behavior of the total energy over time and secondly in how the temperature distribution within the rod is  behaviour of the total energy over time and secondly in how the temperature distribution within the block is
416
\begin{figure}
\begin{center}
\includegraphics[width=4in]{figures/ttrodpyplot150}
\caption{Total Energy in Rod over Time (in seconds).}
\label{fig:onedheatout1}
\end{center}
\end{figure}

417  The trick is to create a record of the time marks and the corresponding total energies observed.  The trick is to create a record of the time marks and the corresponding total energies observed.
418  \pyt provides the concept of lists for this. Before  \pyt provides the concept of lists for this. Before
419  the time loop is opened we create empty lists for the time marks \verb|t_list| and the total energies \verb|E_list|.  the time loop is opened we create empty lists for the time marks \verb|t_list| and the total energies \verb|E_list|.
# Line 423  To plot $t$ over $totE$ we use the \mpl Line 435  To plot $t$ over $totE$ we use the \mpl
435  \begin{python}  \begin{python}
436  import pylab as pl # plotting package.  import pylab as pl # plotting package.
437  \end{python}  \end{python}
438  Here we are not using the \verb|from pylab import *| in order to name clashes for function names  Here we are not using the \verb|from pylab import *| in order to avoid name clashes for function names
439  with \esc.  within \esc.
440
441  The following statements are added to the script after the time loop has been completed;  The following statements are added to the script after the time loop has been completed;
442  \begin{python}  \begin{python}
443  pl.plot(t_list,E_list)  pl.plot(t_list,E_list)
444  pl.title("Total Energy")  pl.title("Total Energy")
445    pl.axis([0,max(t_list),0,max(E_list)*1.1])
446  pl.savefig("totE.png")  pl.savefig("totE.png")
447  \end{python}  \end{python}
448  The first statement hands over the time marks and corresponding total energies to the plotter.  The first statement hands over the time marks and corresponding total energies to the plotter.
449  The second statement is setting the title for the plot. The last statement renders the plot and writes the  The second statment is setting the title for the plot. The third statement
450  result into the file \verb|totE.png| which can be displayed by (almost) any image viewer. Your result should look  sets the axis ranges. In most cases these are set appropriately by the plotter.
451  similar to Figure~\ref{fig:onedheatout1}.  The last statement renders the plot and writes the
452    result into the file \verb|totE.png| which can be displayed by (almost) any image viewer.
453    As expected the total energy is constant over time, see \reffig{fig:onedheatout1}.
454
455  \subsection{Plotting the Temperature Distribution}  \subsection{Plotting the Temperature Distribution}
456  \sslist{onedheatdiff001b.py}  \sslist{onedheatdiff001b.py}
# Line 465  while a sub-folder of \verb data  called Line 480  while a sub-folder of \verb data  called
480  \begin{verbatim}  \begin{verbatim}
481  save_path = os.path.join("data","onedheatdiff001")  save_path = os.path.join("data","onedheatdiff001")
482  \end{verbatim}  \end{verbatim}
483  The second argument of \verb join \xspace contains a string which is the filename or subdirectory name. We can use the operator \verb|%| to increment our file names with the value \verb|i| denoting a incrementing counter. The substring \verb %03d  does this by defining the following parameters;  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 \verb|i| denoting a incrementing counter. The sub-string \verb %03d  does this by defining the following parameters;
484  \begin{itemize}  \begin{itemize}
485   \item \verb 0  becomes the padding number;   \item \verb 0  becomes the padding number;
486   \item \verb 3  tells us the amount of padding numbers that are required; and   \item \verb 3  tells us the amount of padding numbers that are required; and
# Line 473  The second argument of \verb join \xspac Line 488  The second argument of \verb join \xspac
488  \end{itemize}  \end{itemize}
489  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;  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;
490  \begin{verbatim}  \begin{verbatim}
491  rodpyplot.png  blockspyplot.png
492  rodpyplot.png  blockspyplot.png
493  rodpyplot.png  blockspyplot.png
494  ...  ...
495  \end{verbatim}  \end{verbatim}
496  and so on.  and so on.
# Line 487  mkDir(save_path) Line 502  mkDir(save_path)
502  will check for the existence of \verb save_path  and if missing, make the required directories.  will check for the existence of \verb save_path  and if missing, make the required directories.
503
504  We start by modifying our solution script from before.  We start by modifying our solution script from before.
505  Prior to the \verb|while| 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 data points used to represent  Prior to the \verb|while| 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
506  the temperature as a \pyt list of tuples. As a solution of a PDE  the temperature as a \pyt list of tuples or a \numpy array as requested by the plotting function.
507  the temperature has the \verb|Solution(rod)| function space attribute. We use  We need to convert thearray \verb|x| previously set as \verb|Solution(blocks).getX()| into a \pyt list
508  the \verb|getX()| method to get the coordinates of the data points as an \esc object  and then to a \numpy array. The $x\hackscore{0}$ component is then extracted via an array slice to the variable \verb|plx|;
which is then converted to a \numpy array. The $x$ component is then extracted via an array slice to the variable \verb|plx|;
509  \begin{python}  \begin{python}
510  import numpy as np # array package.  import numpy as np # array package.
511  #convert solution points for plotting  #convert solution points for plotting
512  plx = Solution(rod).getX().toListOfTuples()  plx = x.toListOfTuples()
513  plx = np.array(plx) # convert to tuple to numpy array  plx = np.array(plx) # convert to tuple to numpy array
514  plx = plx[:,0] # extract x locations  plx = plx[:,0] # extract x locations
515  \end{python}  \end{python}
516
517  \begin{figure}  \begin{figure}
518  \begin{center}  \begin{center}
519  \includegraphics[width=4in]{figures/rodpyplot001}  \includegraphics[width=4in]{figures/blockspyplot001}
520  \includegraphics[width=4in]{figures/rodpyplot050}  \includegraphics[width=4in]{figures/blockspyplot050}
521  \includegraphics[width=4in]{figures/rodpyplot200}  \includegraphics[width=4in]{figures/blockspyplot200}
522  \caption{Temperature ($T$) distribution in rod at time steps $1$, $50$ and $200$.}  \caption{Temperature ($T$) distribution in the blocks at time steps $1$, $50$ and $200$.}
523  \label{fig:onedheatout}  \label{fig:onedheatout}
524  \end{center}  \end{center}
525  \end{figure}  \end{figure}
# Line 524  while t<tend: Line 538  while t<tend:
538      # set scale (Temperature should be between Tref and T0)      # set scale (Temperature should be between Tref and T0)
539          pl.axis([0,mx,Tref*.9,T0*1.1])          pl.axis([0,mx,Tref*.9,T0*1.1])
540          # add title          # add title
541      pl.title("Temperature across rod at time %e minutes"%(t/minutes))      pl.title("Temperature across the blocks at time %e minutes"%(t/day))
542      #save figure to file      #save figure to file
543      pl.savefig(os.path.join(save_path,"tempT","rodpyplot%03d.png") %i)      pl.savefig(os.path.join(save_path,"tempT","blockspyplot%03d.png") %i)
544  \end{python}  \end{python}
545  Some results are shown in Figure~\ref{fig:onedheatout}.  Some results are shown in \reffig{fig:onedheatout}.
546
547  \subsection{Make a video}  \subsection{Make a video}
548  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.  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.
549  \begin{python}  \begin{python}
550  # compile the *.png files to create a *.avi videos that show T change  # compile the *.png files to create a *.avi videos that show T change
551  # with time. This operation uses Linux mencoder. For other operating  # with time. This operation uses Linux mencoder. For other operating
552  # systems it is possible to use your favorite video compiler to  # systems it is possible to use your favourite video compiler to
553  # convert image files to videos.  # convert image files to videos.
554
555  os.system("mencoder mf://"+save_path+"/tempT"+"/*.png -mf type=png:\  os.system("mencoder mf://"+save_path+"/tempT"+"/*.png -mf type=png:\

Legend:
 Removed from v.2904 changed lines Added in v.2905