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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2961 - (show annotations)
Wed Mar 3 00:56:59 2010 UTC (9 years, 6 months ago) by jfenwick
File MIME type: application/x-tex
File size: 37532 byte(s)
Hacking cookbook

1
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %
4 % Copyright (c) 2003-2010 by University of Queensland
5 % Earth Systems Science Computational Center (ESSCC)
6 % http://www.uq.edu.au/esscc
7 %
8 % Primary Business: Queensland, Australia
9 % Licensed under the Open Software License version 3.0
10 % http://www.opensource.org/licenses/osl-3.0.php
11 %
12 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
13
14 \begin{figure}[h!]
15 \centerline{\includegraphics[width=4.in]{figures/onedheatdiff001}}
16 \caption{Example 1: Temperature differential along a single interface between two granite blocks.}
17 \label{fig:onedgbmodel}
18 \end{figure}
19
20 \section{Example 1: One Dimensional Heat Diffusion in Granite}
21 \label{Sec:1DHDv00}
22
23 The first model consists of two blocks of isotropic material, for instance granite, sitting next to each other.
24 Initial temperature in \textit{Block 1} is \verb|T1| and in \textit{Block 2} is \verb|T2|.
25 We assume that the system is insulated.
26 What would happen to the temperature distribution in each block over time?
27 Intuition tells us that heat will be transported from the hotter block to the cooler one until both
28 blocks have the same temperature.
29
30 \subsection{1D Heat Diffusion Equation}
31 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 which is defined as:
33 \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 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 The heat source is defined by the right hand side of \refEq{eqn:hd} as $q\hackscore{H}$; this can take the form of a constant or a function of time and space. For example $q\hackscore{H} = q\hackscore{0}e^{-\gamma t}$ where we have the output of our heat source decaying with time. There are also two partial derivatives in \refEq{eqn:hd}; $\frac{\partial T}{\partial t}$ describes the change in temperature with time while $\frac{\partial ^2 T}{\partial x^2}$ is the spatial change of temperature. As there is only a single spatial dimension to our problem, our temperature solution $T$ is only dependent on the time $t$ and our position along the iron bar $x$.
41
42 \subsection{PDEs and the General Form}
43 Potentially, 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 a problem this way. Alternatively, computers can be used to solve these kinds of problems. To do this, a numerical approach is required to discretise
44 the PDE \refEq{eqn:hd} in time and space, then we left with a finite number of equations for a finite number of spatial points and time steps in the model. While discretisation introduces approximations and a degree of error, a sufficiently sampled model is generally accurate enough to satisfy the requirements of the modeller.
45
46 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
48 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 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 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 are not discussed here. However, this scheme has a major disadvantage, namely 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. The term \textit{stable} means
77 that the approximation of the temperature will not grow beyond its initial bounds and become non-physical.
78 The backward Euler scheme, which we use here, is unconditionally stable meaning that under the assumption of
79 physically correct problem set-up the temperature approximation remains physical for all time steps.
80 The user needs to keep in mind that the discretization error introduced by \refEq{eqn:beuler}
81 is sufficiently small, thus a good approximation of the true temperature is computed. It is
82 therefore crucial that the user remains critical about his/her results and for instance compares
83 the results for different time and spatial step sizes.
84
85 To get the temperature $T^{(n)}$ at time $t^{(n)}$ we need to solve the linear
86 differential equation \refEq{eqn:hddisc} which only includes spatial derivatives. To solve this problem
87 we want to use \esc.
88
89 In \esc any given PDE described by 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
90 $-(A\hackscore{jl} u\hackscore{,l})\hackscore{,j}+D u =Y$}
91 is described by;
92 \begin{equation}\label{eqn:commonform nabla}
93 -\nabla\cdot(A\cdot\nabla u) + Du = f
94 \end{equation}
95 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
96 the spatial derivative of its subject - in this case $u$. Lets assume for a moment that we deal with a one-dimensional problem then ;
97 \begin{equation}
98 \nabla = \frac{\partial}{\partial x}
99 \end{equation}
100 and we can write \refEq{eqn:commonform nabla} as;
101 \begin{equation}\label{eqn:commonform}
102 -A\frac{\partial^{2}u}{\partial x^{2}} + Du = f
103 \end{equation}
104 if $A$ is constant. To match this simplified general form to our problem \refEq{eqn:hddisc}
105 we rearrange \refEq{eqn:hddisc};
106 \begin{equation}
107 \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)}
108 \label{eqn:hdgenf}
109 \end{equation}
110 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
111 $t^{(0)}=0$ and $t^{(n)}=t^{(n-1)}+h$ where $h>0$ is the step size and assumed to be constant.
112 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;
113 \begin{equation}\label{ESCRIPT SET}
114 u=T^{(n)};
115 A = \kappa; D = \frac{\rho c \hackscore{p}}{h}; f = q \hackscore{H} + \frac{\rho c\hackscore p}{h} T^{(n-1)}
116 \end{equation}
117
118 \subsection{Boundary Conditions}
119 \label{SEC BOUNDARY COND}
120 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.
121 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.
122 We discuss Dirichlet boundary condition in our second example presented in Section~\ref{Sec:1DHDv0}.
123
124 We make the model assumption that the system is insulated so we need
125 to add an appropriate boundary condition to prevent
126 any loss or inflow of energy at boundary of our domain. Mathematically this is expressed by prescribing
127 the heat flux $\kappa \frac{\partial T}{\partial x}$ to zero. In our simplified one dimensional model this is expressed
128 in the form;
129 \begin{equation}
130 \kappa \frac{\partial T}{\partial x} = 0
131 \end{equation}
132 or in a more general case as
133 \begin{equation}\label{NEUMAN 1}
134 \kappa \nabla T \cdot n = 0
135 \end{equation}
136 where $n$ is the outer normal field \index{outer normal field} at the surface of the domain.
137 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
138 the temperature $T$. Other notations used here are\footnote{The \esc notation for the normal
139 derivative is $T\hackscore{,i} n\hackscore i$.};
140 \begin{equation}
141 \nabla T \cdot n = \frac{\partial T}{\partial n} \; .
142 \end{equation}
143 A condition of the type \refEq{NEUMAN 1} defines a \textbf{Neuman boundary condition} for the PDE.
144
145 The PDE \refEq{eqn:hdgenf}
146 and the Neuman boundary condition~\ref{eqn:hdgenf} (potentially together with the Dirichlet boundary conditions) define a \textbf{boundary value problem}.
147 It is the nature of a boundary value problem to allow making statements about the solution in the
148 interior of the domain from information known on the boundary only. In most cases
149 we use the term partial differential equation but in fact it is a boundary value problem.
150 It is important to keep in mind that boundary conditions need to be complete and consistent in the sense that
151 at any point on the boundary either a Dirichlet or a Neuman boundary condition must be set.
152
153 Conveniently, \esc makes default assumption on the boundary conditions which the user may modify where appropriate.
154 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
155 $n\hackscore{j}A\hackscore{jl} u\hackscore{,l}=0$.} is;
156 \begin{equation}\label{NEUMAN 2}
157 -n\cdot A \cdot\nabla u = 0
158 \end{equation}
159 which is used everywhere on the boundary. Again $n$ denotes the outer normal field.
160 Notice that the coefficient $A$ is the same as in the \esc PDE~\ref{eqn:commonform nabla}.
161 With the settings for the coefficients we have already identified in \refEq{ESCRIPT SET} this
162 condition translates into
163 \begin{equation}\label{NEUMAN 2b}
164 \kappa \frac{\partial T}{\partial x} = 0
165 \end{equation}
166 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.
167
168 \subsection{Outline of the Implementation}
169 \label{sec:outline}
170 To solve the heat diffusion equation (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 we discuss later in details have four major steps. Firstly, we need to define the domain where we want to
171 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 is as follows:
172 \begin{enumerate}
173 \item create domain
174 \item create PDE
175 \item while end time not reached:
176 \begin{enumerate}
177 \item set PDE coefficients
178 \item solve PDE
179 \item update time marker
180 \end{enumerate}
181 \item end of calculation
182 \end{enumerate}
183 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
184 rather than its actual representation. So we will create a domain object to describe the geometry of the two
185 granite blocks. Then we define PDEs and spatially distributed values such as the temperature
186 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.
187
188
189 \begin{figure}[t]
190 \centering
191 \includegraphics[width=6in]{figures/functionspace.pdf}
192 \label{fig:fs}
193 \caption{\esc domain construction overview}
194 \end{figure}
195
196 \subsection{The Domain Constructor in \esc}
197 \label{ss:domcon}
198 It is helpful to have a better understanding how spatially distributed value such as the temperature or PDE coefficients are interpreted in \esc. Again
199 from the user's point of view the representation of these spatially distributed values is not relevant.
200
201 There are various ways to construct domain objects. The simplest form is as rectangular shaped region with a length and height. There is
202 a ready to use function call for this. Besides the spatial dimensions the function call will require you to specify the number
203 elements or cells to be used along the length and height, see \reffig{fig:fs}. Any spatially distributed value
204 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.
205 The quality of the approximation depends - besides other factors- mainly on the number of elements being used. In fact, the
206 approximation becomes better the more elements are used. However, computational costs and compute time grow with the number of
207 elements being used. It therefore important that you find the right balance between the demand in accuracy and acceptable resource usage.
208
209 In general, one can thinks about a domain object as a composition of nodes and elements.
210 As shown in \reffig{fig:fs}, an element is defined by the nodes used to describe its vertices.
211 To represent spatial distributed values the user can use
212 the values at the nodes, at the elements in the interior of the domain or at elements located at the surface of the domain.
213 The different approach used to represent values is called \textbf{function space} and is attached to all objects
214 in \esc representing a spatial distributed value such as the solution of a PDE. The three
215 function spaces we will use at the moment are;
216 \begin{enumerate}
217 \item the nodes, called by \verb|ContinuousFunction(domain)| ;
218 \item the elements/cells, called by \verb|Function(domain)| ; and
219 \item the boundary, called by \verb|FunctionOnBoundary(domain)| .
220 \end{enumerate}
221 A function space object such as \verb|ContinuousFunction(domain)| has the method \verb|getX| attached to it. This method returns the
222 location of the so-called \textbf{sample points} used to represent values with the particular function space attached to it. So the
223 call \verb|ContinuousFunction(domain).getX()| will return the coordinates of the nodes used to describe the domain while
224 the \verb|Function(domain).getX()| returns the coordinates of numerical integration points within elements, see
225 \reffig{fig:fs}.
226
227 This distinction between different representations of spatial distributed values
228 is important in order to be able to vary the degrees of smoothness in a PDE problem.
229 The coefficients of a PDE need not be continuous thus this qualifies as a \verb|Function()| type.
230 On the other hand a temperature distribution must be continuous and needs to be represented with a \verb|ContinuousFunction()| function space.
231 An influx may only be defined at the boundary and is therefore a \verb FunctionOnBoundary() object.
232 \esc allows certain transformations of the function spaces. A \verb ContinuousFunction() can be transformed into a \verb|FunctionOnBoundary()|
233 or \verb|Function()|. On the other hand there is not enough information in a \verb FunctionOnBoundary() to transform it to a \verb ContinuousFunction() .
234 These transformations, which are called \textbf{interpolation} are invoked automatically by \esc if needed.
235
236 Later in this introduction we will discuss how
237 to define specific areas of geometry with different materials which are represented by different material coefficients such the
238 thermal conductivities $kappa$. A very powerful technique to define these types of PDE
239 coefficients is tagging. Blocks of materials and boundaries can be named and values can be defined on subregions based on their names.
240 This is simplifying PDE coefficient and flux definitions. It makes for much easier scripting. We will discuss this technique in Section~\ref{STEADY-STATE HEAT REFRACTION}.
241
242
243 \subsection{A Clarification for the 1D Case}
244 \label{SEC: 1D CLARIFICATION}
245 It is necessary for clarification that we revisit the general PDE from \refeq{eqn:commonform nabla} under the light of a two dimensional domain. \esc is inherently designed to solve problems that are greater than one dimension and so \refEq{eqn:commonform nabla} needs to be read as a higher dimensional problem. In the case of two spatial dimensions the \textit{Nabla operator} has in fact two components $\nabla = (\frac{\partial}{\partial x}, \frac{\partial}{\partial y})$. In full, \refEq{eqn:commonform nabla} assuming a constant coefficient $A$, takes the form;
246 \begin{equation}\label{eqn:commonform2D}
247 -A\hackscore{00}\frac{\partial^{2}u}{\partial x^{2}}
248 -A\hackscore{01}\frac{\partial^{2}u}{\partial x\partial y}
249 -A\hackscore{10}\frac{\partial^{2}u}{\partial y\partial x}
250 -A\hackscore{11}\frac{\partial^{2}u}{\partial y^{2}}
251 + Du = f
252 \end{equation}
253 Notice that for the higher dimensional case $A$ becomes a matrix. It is also
254 important to notice that the usage of the Nabla operator creates
255 a compact formulation which is also independent from the spatial dimension.
256 So to make the general PDE \refEq{eqn:commonform2D} one dimensional as
257 shown in \refEq{eqn:commonform} we need to set
258 \begin{equation}
259 A\hackscore{00}=A; A\hackscore{01}=A\hackscore{10}=A\hackscore{11}=0
260 \end{equation}
261
262
263 \subsection{Developing a PDE Solution Script}
264 \label{sec:key}
265 \sslist{example01a.py}
266 We will write a simple \pyt script which uses the \modescript, \modfinley and \modmpl modules.
267 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.}
268 that we will require.
269 \begin{python}
270 from esys.escript import *
271 # This defines the LinearPDE module as LinearPDE
272 from esys.escript.linearPDEs import LinearPDE
273 # This imports the rectangle domain function from finley.
274 from esys.finley import Rectangle
275 # A useful unit handling package which will make sure all our units
276 # match up in the equations under SI.
277 from esys.escript.unitsSI import *
278 \end{python}
279 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.
280
281 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.
282
283 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.
284 \begin{python}
285 mx = 500.*m #meters - model length
286 my = 100.*m #meters - model width
287 ndx = 50 # mesh steps in x direction
288 ndy = 1 # mesh steps in y direction
289 boundloc = mx/2 # location of boundary between the two blocks
290 \end{python}
291 The material constants and the temperature variables must also be defined. For the granite in the model they are defined as:
292 \begin{python}
293 #PDE related
294 rho = 2750. *kg/m**3 #kg/m^{3} density of iron
295 cp = 790.*J/(kg*K) # J/Kg.K thermal capacity
296 rhocp = rho*cp
297 kappa = 2.2*W/m/K # watts/m.Kthermal conductivity
298 qH=0 * J/(sec*m**3) # J/(sec.m^{3}) no heat source
299 T1=20 * Celsius # initial temperature at Block 1
300 T2=2273. * Celsius # base temperature at Block 2
301 \end{python}
302 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:
303 \begin{python}
304 t=0 * day #our start time, usually zero
305 tend=1. * day # - time to end simulation
306 outputs = 200 # number of time steps required.
307 h=(tend-t)/outputs #size of time step
308 #user warning statement
309 print "Expected Number of time outputs is: ", (tend-t)/h
310 i=0 #loop counter
311 \end{python}
312 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:
313 \begin{python}
314 #generate domain using rectangle
315 blocks = Rectangle(l0=mx,l1=my,n0=ndx, n1=ndy)
316 \end{python}
317 \verb blocks now describes a domain in the manner of Section \ref{ss:domcon}. T
318
319 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.
320 \begin{python}
321 mypde=LinearPDE(blocks)
322 A=zeros((2,2)))
323 A[0,0]=kappa
324 mypde.setValue(A=A, D=rhocp/h)
325 \end{python}
326 In a many cases it may be possible to decrease the computational time of the solver if the PDE is symmetric.
327 Symmetry of a PDE is defined by;
328 \begin{equation}\label{eqn:symm}
329 A\hackscore{jl}=A\hackscore{lj}
330 \end{equation}
331 Symmetry is only dependent on the $A$ coefficient in the general form and the other coefficients $D$ as well as the right hand side $Y$ may take any value. From the above definition we can see that our PDE is symmetric. The \verb LinearPDE class provides the method \method{checkSymmetry} to check if the given PDE is symmetric. As our PDE is symmetrical we will enable symmetry via;
332 \begin{python}
333 myPDE.setSymmetryOn()
334 \end{python}
335 Next we need to establish the initial temperature distribution \verb|T|. We need to
336 assign the value \verb|T1| to all sample points left to the contact interface at $x\hackscore{0}=\frac{mx}{2}$
337 and the value \verb|T2| right to the contact interface. \esc
338 provides the \verb|whereNegative| function to construct this. In fact,
339 \verb|whereNegative| returns the value $1$ at those sample points where the argument
340 has a negative value. Otherwise zero is returned. If \verb|x| are the $x\hackscore{0}$
341 coordinates of the sample points used to represent the temperature distribution
342 then \verb|x[0]-boundloc| gives us a negative value for
343 all sample points left to the interface and non-negative value to
344 the right of the interface. So with;
345 \begin{python}
346 # ... set initial temperature ....
347 T= T1*whereNegative(x[0]-boundloc)+T2*(1-whereNegative(x[0]-boundloc))
348 \end{python}
349 we get the desired temperature distribution. To get the actual sample points \verb|x| we use
350 the \verb|getX()| method of the function space \verb|Solution(blocks)|
351 which is used to represent the solution of a PDE;
352 \begin{python}
353 x=Solution(blocks).getX()
354 \end{python}
355 As \verb|x| are the sample points for the function space \verb|Solution(blocks)|
356 the initial temperature \verb|T| is using these sample points for representation.
357 Although \esc is trying to be forgiving with the choice of sample points and to convert
358 where necessary the adjustment of the function space is not always possible. So it is
359 advisable to make a careful choice on the function space used.
360
361 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.
362 \begin{python}
363 while t < tend:
364 i+=1 #increment the counter
365 t+=h #increment the current time
366 mypde.setValue(Y=qH+rhocp/h*T) # set variable PDE coefficients
367 T=mypde.getSolution() #get the PDE solution
368 totE = integrate(rhocp*T) #get the total heat (energy) in the system
369 \end{python}
370 The last statement in this script calculates the total energy in the system as volume integral
371 of $\rho c\hackscore{p} T$ over the block. As the blocks are insulated no energy should be get lost or added.
372 The total energy should stay constant for the example discussed here.
373
374 \subsection{Running the Script}
375 The script presented so for is available under
376 \verb|example01a.py|. You can edit this file with your favourite text editor.
377 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
378 to launch {\it escript} scripts. For the example script use;
379 \begin{verbatim}
380 run-escript example01a.py
381 \end{verbatim}
382 The program will print a progress report. Alternatively, you can use
383 the python interpreter directly;
384 \begin{verbatim}
385 python example01a.py
386 \end{verbatim}
387 if the system is configured correctly (Please talk to your system administrator).
388
389 \begin{figure}
390 \begin{center}
391 \includegraphics[width=4in]{figures/ttblockspyplot150}
392 \caption{Example 1b: Total Energy in the Blocks over Time (in seconds).}
393 \label{fig:onedheatout1}
394 \end{center}
395 \end{figure}
396
397 \subsection{Plotting the Total Energy}
398 \sslist{example01b.py}
399
400 \esc does not include its own plotting capabilities. However, it is possible to use a variety of free \pyt packages for visualisation.
401 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.
402 The \mpl package is a component of SciPy\footnote{\url{http://www.scipy.org}} and is good for basic graphs and plots.
403 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/}}
404 which bases on the \verb|VTK| toolkit. We will discuss the usage of \verb|VTK| based
405 visualization in Chapter~\ref{Sec:2DHD} where will discuss a two dimensional PDE.
406
407 For our simple problem we have two plotting tasks: Firstly we are interested in showing the
408 behaviour of the total energy over time and secondly in how the temperature distribution within the block is
409 developing over time. Lets start with the first task.
410
411 The trick is to create a record of the time marks and the corresponding total energies observed.
412 \pyt provides the concept of lists for this. Before
413 the time loop is opened we create empty lists for the time marks \verb|t_list| and the total energies \verb|E_list|.
414 After the new temperature as been calculated by solving the PDE we append the new time marker and total energy
415 to the corresponding list using the \verb|append| method. With these modifications the script looks as follows:
416 \begin{python}
417 t_list=[]
418 E_list=[]
419 # ... start iteration:
420 while t<tend:
421 t+=h
422 mypde.setValue(Y=qH+rhocp/h*T) # set variable PDE coefficients
423 T=mypde.getSolution() #get the PDE solution
424 totE=integrate(rhocp*T)
425 t_list.append(t) # add current time mark to record
426 E_list.append(totE) # add current total energy to record
427 \end{python}
428 To plot $t$ over $totE$ we use the \mpl a module contained within \pylab which needs to be loaded before used;
429 \begin{python}
430 import pylab as pl # plotting package.
431 \end{python}
432 Here we are not using the \verb|from pylab import *| in order to avoid name clashes for function names
433 within \esc.
434
435 The following statements are added to the script after the time loop has been completed;
436 \begin{python}
437 pl.plot(t_list,E_list)
438 pl.title("Total Energy")
439 pl.axis([0,max(t_list),0,max(E_list)*1.1])
440 pl.savefig("totE.png")
441 \end{python}
442 The first statement hands over the time marks and corresponding total energies to the plotter.
443 The second statment is setting the title for the plot. The third statement
444 sets the axis ranges. In most cases these are set appropriately by the plotter.
445 The last statement renders the plot and writes the
446 result into the file \verb|totE.png| which can be displayed by (almost) any image viewer.
447 As expected the total energy is constant over time, see \reffig{fig:onedheatout1}.
448
449 \subsection{Plotting the Temperature Distribution}
450 \label{sec: plot T}
451 \sslist{example01c.py}
452 For plotting the spatial distribution of the temperature we need to modify the strategy we have used
453 for the total energy. Instead of producing a final plot at the end we will generate a
454 picture at each time step which can be browsed as slide show or composed to a movie.
455 The first problem we encounter is that if we produce an image in each time step we need
456 to make sure that the images previously generated are not overwritten.
457
458 To develop an incrementing file name we can use the following convention. It is convenient to
459 put all image file showing the same variable - in our case the temperature distribution -
460 into a separate directory. As part of the \verb|os| module\footnote{The \texttt{os} module provides
461 a powerful interface to interact with the operating system, see \url{http://docs.python.org/library/os.html}.} \pyt
462 provides the \verb|os.path.join| command to build file and
463 directory names in a platform independent way. Assuming that
464 \verb|save_path| is name of directory we want to put the results the command is;
465 \begin{python}
466 import os
467 os.path.join(save_path, "tempT%03d.png"%i )
468 \end{python}
469 where \verb|i| is the time step counter.
470 There are two arguments to the \verb join command. The \verb save_path variable is a predefined string pointing to the directory we want to save our data in, for example a single sub-folder called \verb data would be defined by;
471 \begin{verbatim}
472 save_path = "data"
473 \end{verbatim}
474 while a sub-folder of \verb data called \verb example01 would be defined by;
475 \begin{verbatim}
476 save_path = os.path.join("data","example01")
477 \end{verbatim}
478 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;
479 \begin{itemize}
480 \item \verb 0 means that small numbers should have leading zeroes;
481 \item \verb 3 means that numbers should be written using at least 3 digits; and
482 \item \verb d means that the value to substitute will be an integer.
483 \end{itemize}
484 To actually substitute the value of \verb|i| into the name write \verb %i after the string.
485 When done correctly, the output files from this command would be place in the directory defined by \verb save_path as;
486 \begin{verbatim}
487 blockspyplot001.png
488 blockspyplot002.png
489 blockspyplot003.png
490 ...
491 \end{verbatim}
492 and so on.
493
494 A sub-folder check/constructor is available in \esc. The command;
495 \begin{verbatim}
496 mkDir(save_path)
497 \end{verbatim}
498 will check for the existence of \verb save_path and if missing, make the required directories.
499
500 We start by modifying our solution script from before.
501 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
502 the temperature as a \pyt list of tuples or a \numpy array as requested by the plotting function.
503 We need to convert thearray \verb|x| previously set as \verb|Solution(blocks).getX()| into a \pyt list
504 and then to a \numpy array. The $x\hackscore{0}$ component is then extracted via an array slice to the variable \verb|plx|;
505 \begin{python}
506 import numpy as np # array package.
507 #convert solution points for plotting
508 plx = x.toListOfTuples()
509 plx = np.array(plx) # convert to tuple to numpy array
510 plx = plx[:,0] # extract x locations
511 \end{python}
512
513 \begin{figure}
514 \begin{center}
515 \includegraphics[width=4in]{figures/blockspyplot001}
516 \includegraphics[width=4in]{figures/blockspyplot050}
517 \includegraphics[width=4in]{figures/blockspyplot200}
518 \caption{Example 1c: Temperature ($T$) distribution in the blocks at time steps $1$, $50$ and $200$.}
519 \label{fig:onedheatout}
520 \end{center}
521 \end{figure}
522
523 For each time step we will generate a plot of the temperature distribution and save each to a file. We use the same
524 techniques provided by \mpl as we have used to plot the total energy over time.
525 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.
526 Finally, the figure is saved to a \verb|*.png| file and cleared for the following iteration.
527 \begin{python}
528 # ... start iteration:
529 while t<tend:
530 ....
531 T=mypde.getSolution() #get the PDE solution
532 tempT = T.toListOfTuples() # convert to a tuple
533 pl.plot(plx,tempT) # plot solution
534 # set scale (Temperature should be between Tref and T0)
535 pl.axis([0,mx,Tref*.9,T0*1.1])
536 # add title
537 pl.title("Temperature across the blocks at time %e minutes"%(t/day))
538 #save figure to file
539 pl.savefig(os.path.join(save_path,"tempT","blockspyplot%03d.png") %i)
540 \end{python}
541 Some results are shown in \reffig{fig:onedheatout}.
542
543 \subsection{Make a video}
544 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.
545 \begin{python}
546 # compile the *.png files to create a *.avi videos that show T change
547 # with time. This operation uses Linux mencoder. For other operating
548 # systems it is possible to use your favourite video compiler to
549 # convert image files to videos.
550
551 os.system("mencoder mf://"+save_path+"/tempT"+"/*.png -mf type=png:\
552 w=800:h=600:fps=25 -ovc lavc -lavcopts vcodec=mpeg4 -oac copy -o \
553 example01tempT.avi")
554 \end{python}
555

  ViewVC Help
Powered by ViewVC 1.1.26