/[escript]/trunk/doc/cookbook/example01.tex
ViewVC logotype

Annotation of /trunk/doc/cookbook/example01.tex

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2975 - (hide annotations)
Thu Mar 4 05:44:12 2010 UTC (9 years, 10 months ago) by ahallam
File MIME type: application/x-tex
File size: 37774 byte(s)
Cookbook modifications Review -> Not quite finished yet.
New figure.
1 ahallam 2401
2     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3     %
4 jfenwick 2881 % Copyright (c) 2003-2010 by University of Queensland
5 ahallam 2401 % 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/osl-3.0.php
11     %
12     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
13    
14 gross 2905 \begin{figure}[h!]
15     \centerline{\includegraphics[width=4.in]{figures/onedheatdiff001}}
16 gross 2952 \caption{Example 1: Temperature differential along a single interface between two granite blocks.}
17 gross 2905 \label{fig:onedgbmodel}
18     \end{figure}
19 ahallam 2801
20 gross 2949 \section{Example 1: One Dimensional Heat Diffusion in Granite}
21 gross 2905 \label{Sec:1DHDv00}
22 gross 2878
23 gross 2905 The first model consists of two blocks of isotropic material, for instance granite, sitting next to each other.
24 artak 2957 Initial temperature in \textit{Block 1} is \verb|T1| and in \textit{Block 2} is \verb|T2|.
25 gross 2905 We assume that the system is insulated.
26     What would happen to the temperature distribution in each block over time?
27 artak 2958 Intuition tells us that heat will be transported from the hotter block to the cooler one until both
28 gross 2905 blocks have the same temperature.
29    
30 ahallam 2495 \subsection{1D Heat Diffusion Equation}
31 artak 2957 We can model the heat distribution of this problem over time using 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}};
32 ahallam 2494 which is defined as:
33 ahallam 2401 \begin{equation}
34     \rho c\hackscore p \frac{\partial T}{\partial t} - \kappa \frac{\partial^{2} T}{\partial x^{2}} = q\hackscore H
35     \label{eqn:hd}
36     \end{equation}
37 gross 2861 where $\rho$ is the material density, $c\hackscore p$ is the specific heat and $\kappa$ is the thermal
38     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
39     parameters are \textbf{constant}.
40 ahallam 2975 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 signed distance from the the block-block interface $x$.
41 ahallam 2401
42 gross 2861 \subsection{PDEs and the General Form}
43 ahallam 2975 It is possible to solve PDE \refEq{eqn:hd} analytically and obtain an exact solution to our problem. However, it is not always possible or practical to solve the problem this way. Alternatively, computers can be used to find the solution. To do this, a numerical approach is required to discretise
44     the PDE \refEq{eqn:hd} across time and space, this reduces the problem to a finite number of equations for a finite number of spatial points and time steps. These parameters together define the model. While discretisation introduces approximations and a degree of error, a sufficiently sampled model is generally accurate enough to satisfy the accuracy requirements for the final solution.
45 gross 2477
46 artak 2958 Firstly, we discretise the PDE \refEq{eqn:hd} in time. This leaves us with a steady linear PDE which involves spatial derivatives only and needs to be solved in each time step to progress in time. \esc can help us here.
47 gross 2861
48 artak 2958 For time discretization we use the Backwards Euler approximation scheme\footnote{see \url{http://en.wikipedia.org/wiki/Euler_method}}. It is based on the
49 gross 2861 approximation
50     \begin{equation}
51     \frac{\partial T(t)}{\partial t} \approx \frac{T(t)-T(t-h)}{h}
52     \label{eqn:beuler}
53     \end{equation}
54     for $\frac{\partial T}{\partial t}$ at time $t$
55     where $h$ is the time step size. This can also be written as;
56     \begin{equation}
57     \frac{\partial T}{\partial t}(t^{(n)}) \approx \frac{T^{(n)} - T^{(n-1)}}{h}
58     \label{eqn:Tbeuler}
59     \end{equation}
60     where the upper index $n$ denotes the n\textsuperscript{th} time step. So one has
61     \begin{equation}
62     \begin{array}{rcl}
63     t^{(n)} & = & t^{(n-1)}+h \\
64     T^{(n)} & = & T(t^{(n-1)}) \\
65     \end{array}
66     \label{eqn:Neuler}
67     \end{equation}
68     Substituting \refEq{eqn:Tbeuler} into \refEq{eqn:hd} we get;
69     \begin{equation}
70     \frac{\rho c\hackscore p}{h} (T^{(n)} - T^{(n-1)}) - \kappa \frac{\partial^{2} T^{(n)}}{\partial x^{2}} = q\hackscore H
71     \label{eqn:hddisc}
72     \end{equation}
73 artak 2958 Notice that we evaluate the spatial derivative term at current time $t^{(n)}$ - therefore the name \textbf{backward Euler} scheme. Alternatively, one can evaluate the spatial derivative term at the previous time $t^{(n-1)}$. This
74     approach is called the \textbf{forward Euler} scheme. This scheme can provide some computational advantages, which
75 ahallam 2975 are not discussed here. However, the \textbf{forward Euler} scheme has a major disadvantage. Depending on the
76     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. Stabiliy is achieved if the temperature does not grow beyond its initial bounds and become non-physical.
77 artak 2958 The backward Euler scheme, which we use here, is unconditionally stable meaning that under the assumption of
78     physically correct problem set-up the temperature approximation remains physical for all time steps.
79 gross 2861 The user needs to keep in mind that the discretization error introduced by \refEq{eqn:beuler}
80 artak 2958 is sufficiently small, thus a good approximation of the true temperature is computed. It is
81 ahallam 2975 therefore crucial that the user remains sceptical about their results and for instance compares
82     the results for different time and spatial step sizes for correlation.
83 gross 2861
84     To get the temperature $T^{(n)}$ at time $t^{(n)}$ we need to solve the linear
85 artak 2958 differential equation \refEq{eqn:hddisc} which only includes spatial derivatives. To solve this problem
86     we want to use \esc.
87 gross 2861
88 ahallam 2975 In \esc any given PDE can be described by the general form. For the purpose of this introduction we illustrate a simpler version of the general form for full linear PDEs which is available in the \esc user's guide. A simplified form that suits our heat diffusion problem\footnote{The form in the \esc users guide which uses the Einstein convention is written as
89 gross 2477 $-(A\hackscore{jl} u\hackscore{,l})\hackscore{,j}+D u =Y$}
90 ahallam 2606 is described by;
91 gross 2477 \begin{equation}\label{eqn:commonform nabla}
92 jfenwick 2657 -\nabla\cdot(A\cdot\nabla u) + Du = f
93 ahallam 2411 \end{equation}
94 gross 2861 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
95 ahallam 2495 the spatial derivative of its subject - in this case $u$. Lets assume for a moment that we deal with a one-dimensional problem then ;
96 gross 2477 \begin{equation}
97     \nabla = \frac{\partial}{\partial x}
98     \end{equation}
99 gross 2861 and we can write \refEq{eqn:commonform nabla} as;
100 ahallam 2411 \begin{equation}\label{eqn:commonform}
101 gross 2477 -A\frac{\partial^{2}u}{\partial x^{2}} + Du = f
102 ahallam 2411 \end{equation}
103 gross 2861 if $A$ is constant. To match this simplified general form to our problem \refEq{eqn:hddisc}
104     we rearrange \refEq{eqn:hddisc};
105 ahallam 2411 \begin{equation}
106 ahallam 2645 \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^{(n-1)}
107 ahallam 2494 \label{eqn:hdgenf}
108     \end{equation}
109 ahallam 2775 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
110 ahallam 2495 $t^{(0)}=0$ and $t^{(n)}=t^{(n-1)}+h$ where $h>0$ is the step size and assumed to be constant.
111 artak 2958 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} one can see that;
112 gross 2862 \begin{equation}\label{ESCRIPT SET}
113 gross 2861 u=T^{(n)};
114 ahallam 2494 A = \kappa; D = \frac{\rho c \hackscore{p}}{h}; f = q \hackscore{H} + \frac{\rho c\hackscore p}{h} T^{(n-1)}
115     \end{equation}
116    
117 ahallam 2495 \subsection{Boundary Conditions}
118 gross 2878 \label{SEC BOUNDARY COND}
119 gross 2862 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.
120 artak 2958 A \textbf{Dirichlet boundary condition} is conceptually simpler and is used to prescribe a known value to the unknown solution (in our example the temperature) on parts of the boundary or on the entire boundary of the region of interest.
121 gross 2905 We discuss Dirichlet boundary condition in our second example presented in Section~\ref{Sec:1DHDv0}.
122 ahallam 2495
123 ahallam 2975 However, for this example we have made the model assumption that the system is insulated, so we need
124 gross 2905 to add an appropriate boundary condition to prevent
125 ahallam 2975 any loss or inflow of energy at the boundary of our domain. Mathematically this is expressed by prescribing
126 gross 2905 the heat flux $\kappa \frac{\partial T}{\partial x}$ to zero. In our simplified one dimensional model this is expressed
127 gross 2862 in the form;
128 ahallam 2494 \begin{equation}
129 gross 2862 \kappa \frac{\partial T}{\partial x} = 0
130 ahallam 2494 \end{equation}
131 gross 2862 or in a more general case as
132     \begin{equation}\label{NEUMAN 1}
133     \kappa \nabla T \cdot n = 0
134     \end{equation}
135     where $n$ is the outer normal field \index{outer normal field} at the surface of the domain.
136 gross 2905 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
137 artak 2958 the temperature $T$. Other notations used here are\footnote{The \esc notation for the normal
138 gross 2862 derivative is $T\hackscore{,i} n\hackscore i$.};
139 ahallam 2645 \begin{equation}
140 gross 2862 \nabla T \cdot n = \frac{\partial T}{\partial n} \; .
141 ahallam 2645 \end{equation}
142 gross 2862 A condition of the type \refEq{NEUMAN 1} defines a \textbf{Neuman boundary condition} for the PDE.
143 ahallam 2494
144 gross 2905 The PDE \refEq{eqn:hdgenf}
145 artak 2958 and the Neuman boundary condition~\ref{eqn:hdgenf} (potentially together with the Dirichlet boundary conditions) define a \textbf{boundary value problem}.
146     It is the nature of a boundary value problem to allow making statements about the solution in the
147 gross 2862 interior of the domain from information known on the boundary only. In most cases
148 artak 2958 we use the term partial differential equation but in fact it is a boundary value problem.
149 gross 2862 It is important to keep in mind that boundary conditions need to be complete and consistent in the sense that
150     at any point on the boundary either a Dirichlet or a Neuman boundary condition must be set.
151    
152 gross 2878 Conveniently, \esc makes default assumption on the boundary conditions which the user may modify where appropriate.
153 gross 2862 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
154     $n\hackscore{j}A\hackscore{jl} u\hackscore{,l}=0$.} is;
155     \begin{equation}\label{NEUMAN 2}
156 gross 2948 -n\cdot A \cdot\nabla u = 0
157 gross 2862 \end{equation}
158     which is used everywhere on the boundary. Again $n$ denotes the outer normal field.
159     Notice that the coefficient $A$ is the same as in the \esc PDE~\ref{eqn:commonform nabla}.
160     With the settings for the coefficients we have already identified in \refEq{ESCRIPT SET} this
161     condition translates into
162 gross 2867 \begin{equation}\label{NEUMAN 2b}
163 gross 2862 \kappa \frac{\partial T}{\partial x} = 0
164     \end{equation}
165 artak 2958 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 discuss the Dirichlet boundary condition later.
166 gross 2862
167 gross 2870 \subsection{Outline of the Implementation}
168     \label{sec:outline}
169 ahallam 2975 To solve the heat diffusion equation (\refEq{eqn:hd}) we 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 (discussed in \refSec{sec:key}) has four major steps. Firstly, we need to define the domain where we want to
170     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 to solve in each time step to get the updated temperature. Thirdly, we need to define 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. The work flow described in \reffig{fig:wf}.
171     % \begin{enumerate}
172     % \item create domain
173     % \item create PDE
174     % \item while end time not reached:
175     % \begin{enumerate}
176     % \item set PDE coefficients
177     % \item solve PDE
178     % \item update time marker
179     % \end{enumerate}
180     % \item end of calculation
181     % \end{enumerate}
182    
183     \begin{figure}[h!]
184     \centering
185     \includegraphics[width=1in]{figures/workflow.png}
186     \caption{Workflow for developing an \esc model and solution.}
187     \label{fig:wf}
188     \end{figure}
189    
190 artak 2959 In the terminology of \pyt, the domain and PDE are represented by \textbf{objects}. The nice feature of an object is that it is defined by its usage and features
191 gross 2905 rather than its actual representation. So we will create a domain object to describe the geometry of the two
192 artak 2959 granite blocks. Then we define PDEs and spatially distributed values such as the temperature
193     on this domain. Similarly, to define a PDE object we use the fact that one needs only to define the coefficients of the PDE and solve the PDE. The PDE object has advanced features, but these are not required in simple cases.
194 gross 2870
195    
196     \begin{figure}[t]
197     \centering
198     \includegraphics[width=6in]{figures/functionspace.pdf}
199 ahallam 2975 \caption{\esc domain construction overview}
200 gross 2870 \label{fig:fs}
201     \end{figure}
202    
203     \subsection{The Domain Constructor in \esc}
204     \label{ss:domcon}
205 ahallam 2975 While it is not strictly relevant or necessary, it can be helpful to have a better understanding of how values are spatially distributed and how PDE coefficients are interpreted in \esc. The example in this case would be temperature.
206 gross 2870
207 artak 2963 There are various ways to construct domain objects. The simplest form is a rectangular shaped region with a length and height. There is
208     a ready to use function for this named \verb rectangle(). Besides the spatial dimensions this function requires to specify the number of
209 gross 2905 elements or cells to be used along the length and height, see \reffig{fig:fs}. Any spatially distributed value
210 artak 2963 and the PDE is represented in discrete form using this element representation\footnote{We 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.
211 gross 2870 The quality of the approximation depends - besides other factors- mainly on the number of elements being used. In fact, the
212 ahallam 2975 approximation becomes better when more elements are used. However, computational costs and time grow with the number of
213 artak 2963 elements being used. It is therefore important that you find the right balance between the demand in accuracy and acceptable resource usage.
214 gross 2870
215 artak 2963 In general, one can think about a domain object as a composition of nodes and elements.
216     As shown in \reffig{fig:fs}, an element is defined by the nodes that are used to describe its vertices.
217 gross 2870 To represent spatial distributed values the user can use
218 artak 2963 the values at the nodes, at the elements in the interior of the domain or at the elements located at the surface of the domain.
219 gross 2870 The different approach used to represent values is called \textbf{function space} and is attached to all objects
220     in \esc representing a spatial distributed value such as the solution of a PDE. The three
221 artak 2963 function spaces we use at the moment are;
222 gross 2870 \begin{enumerate}
223     \item the nodes, called by \verb|ContinuousFunction(domain)| ;
224     \item the elements/cells, called by \verb|Function(domain)| ; and
225     \item the boundary, called by \verb|FunctionOnBoundary(domain)| .
226     \end{enumerate}
227     A function space object such as \verb|ContinuousFunction(domain)| has the method \verb|getX| attached to it. This method returns the
228 artak 2963 location of the so-called \textbf{sample points} used to represent values of the particular function space. So the
229 gross 2870 call \verb|ContinuousFunction(domain).getX()| will return the coordinates of the nodes used to describe the domain while
230     the \verb|Function(domain).getX()| returns the coordinates of numerical integration points within elements, see
231 gross 2905 \reffig{fig:fs}.
232 gross 2870
233 artak 2963 This distinction between different representations of spatially distributed values
234 gross 2870 is important in order to be able to vary the degrees of smoothness in a PDE problem.
235 ahallam 2975 The coefficients of a PDE do not need to be continuous, thus this qualifies as a \verb|Function()| type.
236 gross 2870 On the other hand a temperature distribution must be continuous and needs to be represented with a \verb|ContinuousFunction()| function space.
237     An influx may only be defined at the boundary and is therefore a \verb FunctionOnBoundary() object.
238     \esc allows certain transformations of the function spaces. A \verb ContinuousFunction() can be transformed into a \verb|FunctionOnBoundary()|
239     or \verb|Function()|. On the other hand there is not enough information in a \verb FunctionOnBoundary() to transform it to a \verb ContinuousFunction() .
240 gross 2878 These transformations, which are called \textbf{interpolation} are invoked automatically by \esc if needed.
241 gross 2870
242 artak 2963 Later in this introduction we discuss how
243 gross 2870 to define specific areas of geometry with different materials which are represented by different material coefficients such the
244 ahallam 2975 thermal conductivities $\kappa$. A very powerful technique to define these types of PDE
245 gross 2870 coefficients is tagging. Blocks of materials and boundaries can be named and values can be defined on subregions based on their names.
246 ahallam 2975 This is a method for simplifying PDE coefficient and flux definitions. It makes scripting much easier and we will discuss this technique in Section~\ref{STEADY-STATE HEAT REFRACTION}.
247 gross 2870
248    
249     \subsection{A Clarification for the 1D Case}
250 gross 2931 \label{SEC: 1D CLARIFICATION}
251 artak 2963 It is necessary for clarification that we revisit our general PDE from \refeq{eqn:commonform nabla} for 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})$. Assuming the coefficient $A$ is constant, the \refEq{eqn:commonform nabla} takes the following form;
252 gross 2477 \begin{equation}\label{eqn:commonform2D}
253     -A\hackscore{00}\frac{\partial^{2}u}{\partial x^{2}}
254     -A\hackscore{01}\frac{\partial^{2}u}{\partial x\partial y}
255     -A\hackscore{10}\frac{\partial^{2}u}{\partial y\partial x}
256     -A\hackscore{11}\frac{\partial^{2}u}{\partial y^{2}}
257     + Du = f
258     \end{equation}
259 ahallam 2606 Notice that for the higher dimensional case $A$ becomes a matrix. It is also
260 ahallam 2495 important to notice that the usage of the Nabla operator creates
261     a compact formulation which is also independent from the spatial dimension.
262 artak 2963 To make the general PDE \refEq{eqn:commonform2D} one dimensional as
263 gross 2861 shown in \refEq{eqn:commonform} we need to set
264 ahallam 2606 \begin{equation}
265 ahallam 2494 A\hackscore{00}=A; A\hackscore{01}=A\hackscore{10}=A\hackscore{11}=0
266 gross 2477 \end{equation}
267    
268 gross 2867
269 ahallam 2495 \subsection{Developing a PDE Solution Script}
270 ahallam 2801 \label{sec:key}
271 gross 2949 \sslist{example01a.py}
272 artak 2963 We write a simple \pyt script which uses the \modescript, \modfinley and \modmpl modules.
273 gross 2905 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 ahallam 2495 that we will require.
275 ahallam 2775 \begin{python}
276 ahallam 2495 from esys.escript import *
277 ahallam 2606 # This defines the LinearPDE module as LinearPDE
278     from esys.escript.linearPDEs import LinearPDE
279     # This imports the rectangle domain function from finley.
280     from esys.finley import Rectangle
281     # A useful unit handling package which will make sure all our units
282     # match up in the equations under SI.
283     from esys.escript.unitsSI import *
284 ahallam 2775 \end{python}
285 artak 2963 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 domain. The module \verb unitsSI provides support for SI unit definitions with our variables.
286 gross 2477
287 artak 2963 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 need values. Firstly, the domain upon which we wish to solve our problem needs to be defined. There are different types of domains in \modescript which we demonstrate in later tutorials but for our granite blocks, we simply use a rectangular domain.
288 ahallam 2401
289 ahallam 2975 Using a rectangular domain 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 due to symmetry. There are four arguments we must consider when we decide to create a rectangular domain, the domain \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 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 ahallam 2775 \begin{python}
291 gross 2905 mx = 500.*m #meters - model length
292     my = 100.*m #meters - model width
293     ndx = 50 # mesh steps in x direction
294     ndy = 1 # mesh steps in y direction
295     boundloc = mx/2 # location of boundary between the two blocks
296 ahallam 2775 \end{python}
297 gross 2905 The material constants and the temperature variables must also be defined. For the granite in the model they are defined as:
298 ahallam 2775 \begin{python}
299 ahallam 2495 #PDE related
300 gross 2905 rho = 2750. *kg/m**3 #kg/m^{3} density of iron
301     cp = 790.*J/(kg*K) # J/Kg.K thermal capacity
302 gross 2878 rhocp = rho*cp
303 gross 2905 kappa = 2.2*W/m/K # watts/m.Kthermal conductivity
304 gross 2878 qH=0 * J/(sec*m**3) # J/(sec.m^{3}) no heat source
305 gross 2905 T1=20 * Celsius # initial temperature at Block 1
306     T2=2273. * Celsius # base temperature at Block 2
307 ahallam 2775 \end{python}
308 ahallam 2495 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 ahallam 2775 \begin{python}
310 gross 2878 t=0 * day #our start time, usually zero
311     tend=1. * day # - time to end simulation
312 ahallam 2495 outputs = 200 # number of time steps required.
313     h=(tend-t)/outputs #size of time step
314 ahallam 2606 #user warning statement
315     print "Expected Number of time outputs is: ", (tend-t)/h
316     i=0 #loop counter
317 ahallam 2775 \end{python}
318 gross 2905 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 ahallam 2775 \begin{python}
320 ahallam 2606 #generate domain using rectangle
321 gross 2905 blocks = Rectangle(l0=mx,l1=my,n0=ndx, n1=ndy)
322 ahallam 2775 \end{python}
323 artak 2963 \verb blocks now describes a domain in the manner of Section \ref{ss:domcon}.
324 ahallam 2658
325 artak 2963 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 we discuss later.}. We also need to state the values of our general form variables.
326 ahallam 2775 \begin{python}
327 gross 2905 mypde=LinearPDE(blocks)
328 gross 2878 A=zeros((2,2)))
329     A[0,0]=kappa
330 gross 2905 mypde.setValue(A=A, D=rhocp/h)
331 ahallam 2775 \end{python}
332 gross 2878 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;
334 ahallam 2495 \begin{equation}\label{eqn:symm}
335     A\hackscore{jl}=A\hackscore{lj}
336     \end{equation}
337 artak 2963 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$. 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 enable symmetry via;
338 ahallam 2775 \begin{python}
339 ahallam 2495 myPDE.setSymmetryOn()
340 ahallam 2775 \end{python}
341 gross 2905 Next we need to establish the initial temperature distribution \verb|T|. We need to
342     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 gross 2878 \begin{python}
352     # ... set initial temperature ....
353 gross 2905 T= T1*whereNegative(x[0]-boundloc)+T2*(1-whereNegative(x[0]-boundloc))
354 gross 2878 \end{python}
355 gross 2905 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 gross 2878 \begin{python}
359 gross 2905 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 artak 2963 Finally we 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 gross 2905 \begin{python}
369 gross 2878 while t < tend:
370     i+=1 #increment the counter
371     t+=h #increment the current time
372     mypde.setValue(Y=qH+rhocp/h*T) # set variable PDE coefficients
373     T=mypde.getSolution() #get the PDE solution
374     totE = integrate(rhocp*T) #get the total heat (energy) in the system
375     \end{python}
376     The last statement in this script calculates the total energy in the system as volume integral
377 gross 2905 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 ahallam 2401
380 gross 2905 \subsection{Running the Script}
381 ahallam 2975 The script presented so far is available under
382 gross 2949 \verb|example01a.py|. You can edit this file with your favourite text editor.
383 jfenwick 2911 On most operating systems\footnote{The you can use \texttt{run-escript} launcher is not supported under {\it MS Windows} yet.} you can use the \program{run-escript} command
384 gross 2905 to launch {\it escript} scripts. For the example script use;
385     \begin{verbatim}
386 gross 2949 run-escript example01a.py
387 gross 2905 \end{verbatim}
388     The program will print a progress report. Alternatively, you can use
389     the python interpreter directly;
390     \begin{verbatim}
391 gross 2949 python example01a.py
392 gross 2905 \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 gross 2952 \caption{Example 1b: Total Energy in the Blocks over Time (in seconds).}
399 gross 2905 \label{fig:onedheatout1}
400     \end{center}
401     \end{figure}
402    
403 gross 2878 \subsection{Plotting the Total Energy}
404 gross 2949 \sslist{example01b.py}
405 gross 2878
406 gross 2905 \esc does not include its own plotting capabilities. However, it is possible to use a variety of free \pyt packages for visualisation.
407 gross 2878 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.
409 ahallam 2975 For more complex visualisation tasks in particular, two and three dimensional problems we recommend the use of more advanced tools. For instance, \mayavi \footnote{\url{http://code.enthought.com/projects/mayavi/}}
410     which is based upon the \verb|VTK| toolkit. The usage of \verb|VTK| based
411     visualization is discussed in Chapter~\ref{Sec:2DHD} which focusses on a two dimensional PDE.
412 gross 2878
413 ahallam 2975 For our simple granite block problem, we have two plotting tasks. Firstly, we are interested in showing the
414     behaviour of the total energy over time and secondly, how the temperature distribution within the block is
415 gross 2878 developing over time. Lets start with the first task.
416    
417     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
419     the time loop is opened we create empty lists for the time marks \verb|t_list| and the total energies \verb|E_list|.
420 ahallam 2975 After the new temperature has been calculated by solving the PDE we append the new time marker and the total energy value for that time
421 artak 2964 to the corresponding list using the \verb|append| method. With these modifications our script looks as follows:
422 ahallam 2775 \begin{python}
423 gross 2878 t_list=[]
424     E_list=[]
425     # ... start iteration:
426     while t<tend:
427     t+=h
428     mypde.setValue(Y=qH+rhocp/h*T) # set variable PDE coefficients
429     T=mypde.getSolution() #get the PDE solution
430     totE=integrate(rhocp*T)
431     t_list.append(t) # add current time mark to record
432     E_list.append(totE) # add current total energy to record
433 ahallam 2775 \end{python}
434 ahallam 2975 To plot $t$ over $totE$ we use \mpl a module contained within \pylab which needs to be loaded before used;
435 ahallam 2775 \begin{python}
436 gross 2878 import pylab as pl # plotting package.
437 ahallam 2775 \end{python}
438 gross 2905 Here we are not using the \verb|from pylab import *| in order to avoid name clashes for function names
439     within \esc.
440 ahallam 2401
441 gross 2878 The following statements are added to the script after the time loop has been completed;
442 ahallam 2775 \begin{python}
443 gross 2878 pl.plot(t_list,E_list)
444     pl.title("Total Energy")
445 gross 2905 pl.axis([0,max(t_list),0,max(E_list)*1.1])
446 gross 2878 pl.savefig("totE.png")
447 ahallam 2775 \end{python}
448 gross 2878 The first statement hands over the time marks and corresponding total energies to the plotter.
449 gross 2905 The second statment is setting the title for the plot. The third statement
450     sets the axis ranges. In most cases these are set appropriately by the plotter.
451     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 ahallam 2401
455 gross 2878 \subsection{Plotting the Temperature Distribution}
456 gross 2931 \label{sec: plot T}
457 gross 2949 \sslist{example01c.py}
458 gross 2878 For plotting the spatial distribution of the temperature we need to modify the strategy we have used
459     for the total energy. Instead of producing a final plot at the end we will generate a
460 ahallam 2975 picture at each time step which can be browsed as a slide show or composed into a movie.
461     The first problem we encounter is that if we produce an image at each time step we need
462 gross 2878 to make sure that the images previously generated are not overwritten.
463    
464     To develop an incrementing file name we can use the following convention. It is convenient to
465     put all image file showing the same variable - in our case the temperature distribution -
466     into a separate directory. As part of the \verb|os| module\footnote{The \texttt{os} module provides
467     a powerful interface to interact with the operating system, see \url{http://docs.python.org/library/os.html}.} \pyt
468     provides the \verb|os.path.join| command to build file and
469     directory names in a platform independent way. Assuming that
470     \verb|save_path| is name of directory we want to put the results the command is;
471 ahallam 2775 \begin{python}
472 gross 2878 import os
473     os.path.join(save_path, "tempT%03d.png"%i )
474 ahallam 2775 \end{python}
475 gross 2878 where \verb|i| is the time step counter.
476 artak 2964 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, for example a single sub-folder called \verb data would be defined by;
477 gross 2878 \begin{verbatim}
478     save_path = "data"
479     \end{verbatim}
480 gross 2949 while a sub-folder of \verb data called \verb example01 would be defined by;
481 gross 2878 \begin{verbatim}
482 gross 2949 save_path = os.path.join("data","example01")
483 gross 2878 \end{verbatim}
484 jfenwick 2961 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 use the value of \verb|i| as part of our filename. The sub-string \verb %03d indicates that we want to substitude a value into the name;
485 gross 2878 \begin{itemize}
486 jfenwick 2961 \item \verb 0 means that small numbers should have leading zeroes;
487     \item \verb 3 means that numbers should be written using at least 3 digits; and
488     \item \verb d means that the value to substitute will be an integer.
489 gross 2878 \end{itemize}
490 artak 2963 To actually substitute the value of \verb|i| into the name write \verb %i after the string.
491 jfenwick 2961 When done correctly, the output files from this command would be place in the directory defined by \verb save_path as;
492 gross 2878 \begin{verbatim}
493 jfenwick 2961 blockspyplot001.png
494     blockspyplot002.png
495     blockspyplot003.png
496 gross 2878 ...
497     \end{verbatim}
498     and so on.
499    
500     A sub-folder 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 artak 2964 We start by modifying our solution script.
507 gross 2905 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
508     the temperature as a \pyt list of tuples or a \numpy array as requested by the plotting function.
509 artak 2964 We need to convert the array \verb|x| previously set as \verb|Solution(blocks).getX()| into a \pyt list
510 gross 2905 and then to a \numpy array. The $x\hackscore{0}$ component is then extracted via an array slice to the variable \verb|plx|;
511 ahallam 2775 \begin{python}
512 gross 2878 import numpy as np # array package.
513     #convert solution points for plotting
514 gross 2905 plx = x.toListOfTuples()
515 gross 2878 plx = np.array(plx) # convert to tuple to numpy array
516     plx = plx[:,0] # extract x locations
517 ahallam 2775 \end{python}
518 gross 2878
519 ahallam 2645 \begin{figure}
520     \begin{center}
521 gross 2905 \includegraphics[width=4in]{figures/blockspyplot001}
522     \includegraphics[width=4in]{figures/blockspyplot050}
523     \includegraphics[width=4in]{figures/blockspyplot200}
524 gross 2952 \caption{Example 1c: Temperature ($T$) distribution in the blocks at time steps $1$, $50$ and $200$.}
525 ahallam 2645 \label{fig:onedheatout}
526     \end{center}
527     \end{figure}
528    
529 artak 2964 We use the same techniques provided by \mpl as we have used to plot the total energy over time.
530     For each time step we generate a plot of the temperature distribution and save each to a file.
531 gross 2878 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 ahallam 2775 \begin{python}
534 gross 2878 # ... 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 gross 2905 pl.title("Temperature across the blocks at time %e minutes"%(t/day))
544 gross 2878 #save figure to file
545 gross 2905 pl.savefig(os.path.join(save_path,"tempT","blockspyplot%03d.png") %i)
546 ahallam 2775 \end{python}
547 gross 2905 Some results are shown in \reffig{fig:onedheatout}.
548 jfenwick 2657
549 ahallam 2606 \subsection{Make a video}
550 artak 2964 Our saved plots from the previous section can be cast into a video using the following command appended to the end of the script. The \verb mencoder command is Linux only, so other platform users need to use an alternative video encoder.
551 ahallam 2775 \begin{python}
552 gross 2878 # 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 gross 2905 # systems it is possible to use your favourite video compiler to
555 ahallam 2606 # convert image files to videos.
556 gross 2477
557 ahallam 2606 os.system("mencoder mf://"+save_path+"/tempT"+"/*.png -mf type=png:\
558 gross 2878 w=800:h=600:fps=25 -ovc lavc -lavcopts vcodec=mpeg4 -oac copy -o \
559 gross 2949 example01tempT.avi")
560 ahallam 2775 \end{python}
561 gross 2477

  ViewVC Help
Powered by ViewVC 1.1.26