ViewVC logotype

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

Parent Directory Parent Directory | Revision Log Revision Log

Revision 2958 - (show annotations)
Tue Mar 2 06:00:39 2010 UTC (12 years, 5 months ago) by artak
File MIME type: application/x-tex
File size: 37748 byte(s)
more corrections on exmaple 1, up to section 2.1.5
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 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
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}
20 \section{Example 1: One Dimensional Heat Diffusion in Granite}
21 \label{Sec:1DHDv00}
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.
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$.
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.
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.
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.
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.
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}
118 \subsection{Boundary Conditions}
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}.
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.
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.
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.
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. The main feature
186 of the object we use, is the fact that we can define PDEs and spatially distributed values such as the temperature
187 on a domain. In fact the domain object has many more features - most of them you will
188 never use and do not need to understand. 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. At a later stage you may use more advanced features of the PDE class, but you need to worry about them only at the point when you use them.
191 \begin{figure}[t]
192 \centering
193 \includegraphics[width=6in]{figures/functionspace.pdf}
194 \label{fig:fs}
195 \caption{\esc domain construction overview}
196 \end{figure}
198 \subsection{The Domain Constructor in \esc}
199 \label{ss:domcon}
200 It is helpful to have a better understanding how spatially distributed value such as the temperature or PDE coefficients are interpreted in \esc. Again
201 from the user's point of view the representation of these spatially distributed values is not relevant.
203 There are various ways to construct domain objects. The simplest form is as rectangular shaped region with a length and height. There is
204 a ready to use function call for this. Besides the spatial dimensions the function call will require you to specify the number
205 elements or cells to be used along the length and height, see \reffig{fig:fs}. Any spatially distributed value
206 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.
207 The quality of the approximation depends - besides other factors- mainly on the number of elements being used. In fact, the
208 approximation becomes better the more elements are used. However, computational costs and compute time grow with the number of
209 elements being used. It therefore important that you find the right balance between the demand in accuracy and acceptable resource usage.
211 In general, one can thinks about a domain object as a composition of nodes and elements.
212 As shown in \reffig{fig:fs}, an element is defined by the nodes used to describe its vertices.
213 To represent spatial distributed values the user can use
214 the values at the nodes, at the elements in the interior of the domain or at elements located at the surface of the domain.
215 The different approach used to represent values is called \textbf{function space} and is attached to all objects
216 in \esc representing a spatial distributed value such as the solution of a PDE. The three
217 function spaces we will use at the moment are;
218 \begin{enumerate}
219 \item the nodes, called by \verb|ContinuousFunction(domain)| ;
220 \item the elements/cells, called by \verb|Function(domain)| ; and
221 \item the boundary, called by \verb|FunctionOnBoundary(domain)| .
222 \end{enumerate}
223 A function space object such as \verb|ContinuousFunction(domain)| has the method \verb|getX| attached to it. This method returns the
224 location of the so-called \textbf{sample points} used to represent values with the particular function space attached to it. So the
225 call \verb|ContinuousFunction(domain).getX()| will return the coordinates of the nodes used to describe the domain while
226 the \verb|Function(domain).getX()| returns the coordinates of numerical integration points within elements, see
227 \reffig{fig:fs}.
229 This distinction between different representations of spatial distributed values
230 is important in order to be able to vary the degrees of smoothness in a PDE problem.
231 The coefficients of a PDE need not be continuous thus this qualifies as a \verb|Function()| type.
232 On the other hand a temperature distribution must be continuous and needs to be represented with a \verb|ContinuousFunction()| function space.
233 An influx may only be defined at the boundary and is therefore a \verb FunctionOnBoundary() object.
234 \esc allows certain transformations of the function spaces. A \verb ContinuousFunction() can be transformed into a \verb|FunctionOnBoundary()|
235 or \verb|Function()|. On the other hand there is not enough information in a \verb FunctionOnBoundary() to transform it to a \verb ContinuousFunction() .
236 These transformations, which are called \textbf{interpolation} are invoked automatically by \esc if needed.
238 Later in this introduction we will discuss how
239 to define specific areas of geometry with different materials which are represented by different material coefficients such the
240 thermal conductivities $kappa$. A very powerful technique to define these types of PDE
241 coefficients is tagging. Blocks of materials and boundaries can be named and values can be defined on subregions based on their names.
242 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}.
245 \subsection{A Clarification for the 1D Case}
247 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;
248 \begin{equation}\label{eqn:commonform2D}
249 -A\hackscore{00}\frac{\partial^{2}u}{\partial x^{2}}
250 -A\hackscore{01}\frac{\partial^{2}u}{\partial x\partial y}
251 -A\hackscore{10}\frac{\partial^{2}u}{\partial y\partial x}
252 -A\hackscore{11}\frac{\partial^{2}u}{\partial y^{2}}
253 + Du = f
254 \end{equation}
255 Notice that for the higher dimensional case $A$ becomes a matrix. It is also
256 important to notice that the usage of the Nabla operator creates
257 a compact formulation which is also independent from the spatial dimension.
258 So to make the general PDE \refEq{eqn:commonform2D} one dimensional as
259 shown in \refEq{eqn:commonform} we need to set
260 \begin{equation}
261 A\hackscore{00}=A; A\hackscore{01}=A\hackscore{10}=A\hackscore{11}=0
262 \end{equation}
265 \subsection{Developing a PDE Solution Script}
266 \label{sec:key}
267 \sslist{example01a.py}
268 We will write a simple \pyt script which uses the \modescript, \modfinley and \modmpl modules.
269 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.}
270 that we will require.
271 \begin{python}
272 from esys.escript import *
273 # This defines the LinearPDE module as LinearPDE
274 from esys.escript.linearPDEs import LinearPDE
275 # This imports the rectangle domain function from finley.
276 from esys.finley import Rectangle
277 # A useful unit handling package which will make sure all our units
278 # match up in the equations under SI.
279 from esys.escript.unitsSI import *
280 \end{python}
281 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.
283 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.
285 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.
286 \begin{python}
287 mx = 500.*m #meters - model length
288 my = 100.*m #meters - model width
289 ndx = 50 # mesh steps in x direction
290 ndy = 1 # mesh steps in y direction
291 boundloc = mx/2 # location of boundary between the two blocks
292 \end{python}
293 The material constants and the temperature variables must also be defined. For the granite in the model they are defined as:
294 \begin{python}
295 #PDE related
296 rho = 2750. *kg/m**3 #kg/m^{3} density of iron
297 cp = 790.*J/(kg*K) # J/Kg.K thermal capacity
298 rhocp = rho*cp
299 kappa = 2.2*W/m/K # watts/m.Kthermal conductivity
300 qH=0 * J/(sec*m**3) # J/(sec.m^{3}) no heat source
301 T1=20 * Celsius # initial temperature at Block 1
302 T2=2273. * Celsius # base temperature at Block 2
303 \end{python}
304 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:
305 \begin{python}
306 t=0 * day #our start time, usually zero
307 tend=1. * day # - time to end simulation
308 outputs = 200 # number of time steps required.
309 h=(tend-t)/outputs #size of time step
310 #user warning statement
311 print "Expected Number of time outputs is: ", (tend-t)/h
312 i=0 #loop counter
313 \end{python}
314 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:
315 \begin{python}
316 #generate domain using rectangle
317 blocks = Rectangle(l0=mx,l1=my,n0=ndx, n1=ndy)
318 \end{python}
319 \verb blocks now describes a domain in the manner of Section \ref{ss:domcon}. T
321 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.
322 \begin{python}
323 mypde=LinearPDE(blocks)
324 A=zeros((2,2)))
325 A[0,0]=kappa
326 mypde.setValue(A=A, D=rhocp/h)
327 \end{python}
328 In a many cases it may be possible to decrease the computational time of the solver if the PDE is symmetric.
329 Symmetry of a PDE is defined by;
330 \begin{equation}\label{eqn:symm}
331 A\hackscore{jl}=A\hackscore{lj}
332 \end{equation}
333 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;
334 \begin{python}
335 myPDE.setSymmetryOn()
336 \end{python}
337 Next we need to establish the initial temperature distribution \verb|T|. We need to
338 assign the value \verb|T1| to all sample points left to the contact interface at $x\hackscore{0}=\frac{mx}{2}$
339 and the value \verb|T2| right to the contact interface. \esc
340 provides the \verb|whereNegative| function to construct this. In fact,
341 \verb|whereNegative| returns the value $1$ at those sample points where the argument
342 has a negative value. Otherwise zero is returned. If \verb|x| are the $x\hackscore{0}$
343 coordinates of the sample points used to represent the temperature distribution
344 then \verb|x[0]-boundloc| gives us a negative value for
345 all sample points left to the interface and non-negative value to
346 the right of the interface. So with;
347 \begin{python}
348 # ... set initial temperature ....
349 T= T1*whereNegative(x[0]-boundloc)+T2*(1-whereNegative(x[0]-boundloc))
350 \end{python}
351 we get the desired temperature distribution. To get the actual sample points \verb|x| we use
352 the \verb|getX()| method of the function space \verb|Solution(blocks)|
353 which is used to represent the solution of a PDE;
354 \begin{python}
355 x=Solution(blocks).getX()
356 \end{python}
357 As \verb|x| are the sample points for the function space \verb|Solution(blocks)|
358 the initial temperature \verb|T| is using these sample points for representation.
359 Although \esc is trying to be forgiving with the choice of sample points and to convert
360 where necessary the adjustment of the function space is not always possible. So it is
361 advisable to make a careful choice on the function space used.
363 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.
364 \begin{python}
365 while t < tend:
366 i+=1 #increment the counter
367 t+=h #increment the current time
368 mypde.setValue(Y=qH+rhocp/h*T) # set variable PDE coefficients
369 T=mypde.getSolution() #get the PDE solution
370 totE = integrate(rhocp*T) #get the total heat (energy) in the system
371 \end{python}
372 The last statement in this script calculates the total energy in the system as volume integral
373 of $\rho c\hackscore{p} T$ over the block. As the blocks are insulated no energy should be get lost or added.
374 The total energy should stay constant for the example discussed here.
376 \subsection{Running the Script}
377 The script presented so for is available under
378 \verb|example01a.py|. You can edit this file with your favourite text editor.
379 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
380 to launch {\it escript} scripts. For the example script use;
381 \begin{verbatim}
382 run-escript example01a.py
383 \end{verbatim}
384 The program will print a progress report. Alternatively, you can use
385 the python interpreter directly;
386 \begin{verbatim}
387 python example01a.py
388 \end{verbatim}
389 if the system is configured correctly (Please talk to your system administrator).
391 \begin{figure}
392 \begin{center}
393 \includegraphics[width=4in]{figures/ttblockspyplot150}
394 \caption{Example 1b: Total Energy in the Blocks over Time (in seconds).}
395 \label{fig:onedheatout1}
396 \end{center}
397 \end{figure}
399 \subsection{Plotting the Total Energy}
400 \sslist{example01b.py}
402 \esc does not include its own plotting capabilities. However, it is possible to use a variety of free \pyt packages for visualisation.
403 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.
404 The \mpl package is a component of SciPy\footnote{\url{http://www.scipy.org}} and is good for basic graphs and plots.
405 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/}}
406 which bases on the \verb|VTK| toolkit. We will discuss the usage of \verb|VTK| based
407 visualization in Chapter~\ref{Sec:2DHD} where will discuss a two dimensional PDE.
409 For our simple problem we have two plotting tasks: Firstly we are interested in showing the
410 behaviour of the total energy over time and secondly in how the temperature distribution within the block is
411 developing over time. Lets start with the first task.
413 The trick is to create a record of the time marks and the corresponding total energies observed.
414 \pyt provides the concept of lists for this. Before
415 the time loop is opened we create empty lists for the time marks \verb|t_list| and the total energies \verb|E_list|.
416 After the new temperature as been calculated by solving the PDE we append the new time marker and total energy
417 to the corresponding list using the \verb|append| method. With these modifications the script looks as follows:
418 \begin{python}
419 t_list=[]
420 E_list=[]
421 # ... start iteration:
422 while t<tend:
423 t+=h
424 mypde.setValue(Y=qH+rhocp/h*T) # set variable PDE coefficients
425 T=mypde.getSolution() #get the PDE solution
426 totE=integrate(rhocp*T)
427 t_list.append(t) # add current time mark to record
428 E_list.append(totE) # add current total energy to record
429 \end{python}
430 To plot $t$ over $totE$ we use the \mpl a module contained within \pylab which needs to be loaded before used;
431 \begin{python}
432 import pylab as pl # plotting package.
433 \end{python}
434 Here we are not using the \verb|from pylab import *| in order to avoid name clashes for function names
435 within \esc.
437 The following statements are added to the script after the time loop has been completed;
438 \begin{python}
439 pl.plot(t_list,E_list)
440 pl.title("Total Energy")
441 pl.axis([0,max(t_list),0,max(E_list)*1.1])
442 pl.savefig("totE.png")
443 \end{python}
444 The first statement hands over the time marks and corresponding total energies to the plotter.
445 The second statment is setting the title for the plot. The third statement
446 sets the axis ranges. In most cases these are set appropriately by the plotter.
447 The last statement renders the plot and writes the
448 result into the file \verb|totE.png| which can be displayed by (almost) any image viewer.
449 As expected the total energy is constant over time, see \reffig{fig:onedheatout1}.
451 \subsection{Plotting the Temperature Distribution}
452 \label{sec: plot T}
453 \sslist{example01c.py}
454 For plotting the spatial distribution of the temperature we need to modify the strategy we have used
455 for the total energy. Instead of producing a final plot at the end we will generate a
456 picture at each time step which can be browsed as slide show or composed to a movie.
457 The first problem we encounter is that if we produce an image in each time step we need
458 to make sure that the images previously generated are not overwritten.
460 To develop an incrementing file name we can use the following convention. It is convenient to
461 put all image file showing the same variable - in our case the temperature distribution -
462 into a separate directory. As part of the \verb|os| module\footnote{The \texttt{os} module provides
463 a powerful interface to interact with the operating system, see \url{http://docs.python.org/library/os.html}.} \pyt
464 provides the \verb|os.path.join| command to build file and
465 directory names in a platform independent way. Assuming that
466 \verb|save_path| is name of directory we want to put the results the command is;
467 \begin{python}
468 import os
469 os.path.join(save_path, "tempT%03d.png"%i )
470 \end{python}
471 where \verb|i| is the time step counter.
472 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;
473 \begin{verbatim}
474 save_path = "data"
475 \end{verbatim}
476 while a sub-folder of \verb data called \verb example01 would be defined by;
477 \begin{verbatim}
478 save_path = os.path.join("data","example01")
479 \end{verbatim}
480 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;
481 \begin{itemize}
482 \item \verb 0 becomes the padding number;
483 \item \verb 3 tells us the amount of padding numbers that are required; and
484 \item \verb d indicates the end of the \verb % operator.
485 \end{itemize}
486 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;
487 \begin{verbatim}
488 blockspyplot.png
489 blockspyplot.png
490 blockspyplot.png
491 ...
492 \end{verbatim}
493 and so on.
495 A sub-folder check/constructor is available in \esc. The command;
496 \begin{verbatim}
497 mkDir(save_path)
498 \end{verbatim}
499 will check for the existence of \verb save_path and if missing, make the required directories.
501 We start by modifying our solution script from before.
502 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
503 the temperature as a \pyt list of tuples or a \numpy array as requested by the plotting function.
504 We need to convert thearray \verb|x| previously set as \verb|Solution(blocks).getX()| into a \pyt list
505 and then to a \numpy array. The $x\hackscore{0}$ component is then extracted via an array slice to the variable \verb|plx|;
506 \begin{python}
507 import numpy as np # array package.
508 #convert solution points for plotting
509 plx = x.toListOfTuples()
510 plx = np.array(plx) # convert to tuple to numpy array
511 plx = plx[:,0] # extract x locations
512 \end{python}
514 \begin{figure}
515 \begin{center}
516 \includegraphics[width=4in]{figures/blockspyplot001}
517 \includegraphics[width=4in]{figures/blockspyplot050}
518 \includegraphics[width=4in]{figures/blockspyplot200}
519 \caption{Example 1c: Temperature ($T$) distribution in the blocks at time steps $1$, $50$ and $200$.}
520 \label{fig:onedheatout}
521 \end{center}
522 \end{figure}
524 For each time step we will generate a plot of the temperature distribution and save each to a file. We use the same
525 techniques provided by \mpl as we have used to plot the total energy over time.
526 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.
527 Finally, the figure is saved to a \verb|*.png| file and cleared for the following iteration.
528 \begin{python}
529 # ... start iteration:
530 while t<tend:
531 ....
532 T=mypde.getSolution() #get the PDE solution
533 tempT = T.toListOfTuples() # convert to a tuple
534 pl.plot(plx,tempT) # plot solution
535 # set scale (Temperature should be between Tref and T0)
536 pl.axis([0,mx,Tref*.9,T0*1.1])
537 # add title
538 pl.title("Temperature across the blocks at time %e minutes"%(t/day))
539 #save figure to file
540 pl.savefig(os.path.join(save_path,"tempT","blockspyplot%03d.png") %i)
541 \end{python}
542 Some results are shown in \reffig{fig:onedheatout}.
544 \subsection{Make a video}
545 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.
546 \begin{python}
547 # compile the *.png files to create a *.avi videos that show T change
548 # with time. This operation uses Linux mencoder. For other operating
549 # systems it is possible to use your favourite video compiler to
550 # convert image files to videos.
552 os.system("mencoder mf://"+save_path+"/tempT"+"/*.png -mf type=png:\
553 w=800:h=600:fps=25 -ovc lavc -lavcopts vcodec=mpeg4 -oac copy -o \
554 example01tempT.avi")
555 \end{python}

  ViewVC Help
Powered by ViewVC 1.1.26