ViewVC logotype

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

Parent Directory Parent Directory | Revision Log Revision Log

Revision 2975 - (show annotations)
Thu Mar 4 05:44:12 2010 UTC (10 years, 4 months ago) by ahallam
File MIME type: application/x-tex
File size: 37774 byte(s)
Cookbook modifications Review -> Not quite finished yet.
New figure.
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 signed distance from the the block-block interface $x$.
42 \subsection{PDEs and the General Form}
43 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.
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, 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 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 The user needs to keep in mind that the discretization error introduced by \refEq{eqn:beuler}
80 is sufficiently small, thus a good approximation of the true temperature is computed. It is
81 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.
84 To get the temperature $T^{(n)}$ at time $t^{(n)}$ we need to solve the linear
85 differential equation \refEq{eqn:hddisc} which only includes spatial derivatives. To solve this problem
86 we want to use \esc.
88 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 $-(A\hackscore{jl} u\hackscore{,l})\hackscore{,j}+D u =Y$}
90 is described by;
91 \begin{equation}\label{eqn:commonform nabla}
92 -\nabla\cdot(A\cdot\nabla u) + Du = f
93 \end{equation}
94 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 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 \begin{equation}
97 \nabla = \frac{\partial}{\partial x}
98 \end{equation}
99 and we can write \refEq{eqn:commonform nabla} as;
100 \begin{equation}\label{eqn:commonform}
101 -A\frac{\partial^{2}u}{\partial x^{2}} + Du = f
102 \end{equation}
103 if $A$ is constant. To match this simplified general form to our problem \refEq{eqn:hddisc}
104 we rearrange \refEq{eqn:hddisc};
105 \begin{equation}
106 \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 \label{eqn:hdgenf}
108 \end{equation}
109 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 $t^{(0)}=0$ and $t^{(n)}=t^{(n-1)}+h$ where $h>0$ is the step size and assumed to be constant.
111 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 \begin{equation}\label{ESCRIPT SET}
113 u=T^{(n)};
114 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}
117 \subsection{Boundary Conditions}
119 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 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 We discuss Dirichlet boundary condition in our second example presented in Section~\ref{Sec:1DHDv0}.
123 However, for this example we have made the model assumption that the system is insulated, so we need
124 to add an appropriate boundary condition to prevent
125 any loss or inflow of energy at the boundary of our domain. Mathematically this is expressed by prescribing
126 the heat flux $\kappa \frac{\partial T}{\partial x}$ to zero. In our simplified one dimensional model this is expressed
127 in the form;
128 \begin{equation}
129 \kappa \frac{\partial T}{\partial x} = 0
130 \end{equation}
131 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 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 the temperature $T$. Other notations used here are\footnote{The \esc notation for the normal
138 derivative is $T\hackscore{,i} n\hackscore i$.};
139 \begin{equation}
140 \nabla T \cdot n = \frac{\partial T}{\partial n} \; .
141 \end{equation}
142 A condition of the type \refEq{NEUMAN 1} defines a \textbf{Neuman boundary condition} for the PDE.
144 The PDE \refEq{eqn:hdgenf}
145 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 interior of the domain from information known on the boundary only. In most cases
148 we use the term partial differential equation but in fact it is a boundary value problem.
149 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.
152 Conveniently, \esc makes default assumption on the boundary conditions which the user may modify where appropriate.
153 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 -n\cdot A \cdot\nabla u = 0
157 \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 \begin{equation}\label{NEUMAN 2b}
163 \kappa \frac{\partial T}{\partial x} = 0
164 \end{equation}
165 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 \subsection{Outline of the Implementation}
168 \label{sec:outline}
169 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}
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}
190 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 rather than its actual representation. So we will create a domain object to describe the geometry of the two
192 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.
196 \begin{figure}[t]
197 \centering
198 \includegraphics[width=6in]{figures/functionspace.pdf}
199 \caption{\esc domain construction overview}
200 \label{fig:fs}
201 \end{figure}
203 \subsection{The Domain Constructor in \esc}
204 \label{ss:domcon}
205 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.
207 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 elements or cells to be used along the length and height, see \reffig{fig:fs}. Any spatially distributed value
210 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 The quality of the approximation depends - besides other factors- mainly on the number of elements being used. In fact, the
212 approximation becomes better when more elements are used. However, computational costs and time grow with the number of
213 elements being used. It is therefore important that you find the right balance between the demand in accuracy and acceptable resource usage.
215 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 To represent spatial distributed values the user can use
218 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 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 function spaces we use at the moment are;
222 \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 location of the so-called \textbf{sample points} used to represent values of the particular function space. So the
229 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 \reffig{fig:fs}.
233 This distinction between different representations of spatially distributed values
234 is important in order to be able to vary the degrees of smoothness in a PDE problem.
235 The coefficients of a PDE do not need to be continuous, thus this qualifies as a \verb|Function()| type.
236 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 These transformations, which are called \textbf{interpolation} are invoked automatically by \esc if needed.
242 Later in this introduction we discuss how
243 to define specific areas of geometry with different materials which are represented by different material coefficients such the
244 thermal conductivities $\kappa$. A very powerful technique to define these types of PDE
245 coefficients is tagging. Blocks of materials and boundaries can be named and values can be defined on subregions based on their names.
246 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}.
249 \subsection{A Clarification for the 1D Case}
251 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 \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 Notice that for the higher dimensional case $A$ becomes a matrix. It is also
260 important to notice that the usage of the Nabla operator creates
261 a compact formulation which is also independent from the spatial dimension.
262 To make the general PDE \refEq{eqn:commonform2D} one dimensional as
263 shown in \refEq{eqn:commonform} we need to set
264 \begin{equation}
265 A\hackscore{00}=A; A\hackscore{01}=A\hackscore{10}=A\hackscore{11}=0
266 \end{equation}
269 \subsection{Developing a PDE Solution Script}
270 \label{sec:key}
271 \sslist{example01a.py}
272 We write a simple \pyt script which uses the \modescript, \modfinley and \modmpl modules.
273 By developing a script for \esc, the heat diffusion equation can be solved at successive time steps for a predefined period using our general form \refEq{eqn:hdgenf}. Firstly it is necessary to import all the libraries\footnote{The libraries contain predefined scripts that are required to solve certain problems, these can be simple like sine and cosine functions or more complicated like those from our \esc library.}
274 that we will require.
275 \begin{python}
276 from esys.escript import *
277 # 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 \end{python}
285 It is generally a good idea to import all of the \modescript library, although if the functions and classes required are known they can be specified individually. The function \verb|LinearPDE| has been imported explicitly for ease of use later in the script. \verb|Rectangle| is going to be our type of domain. The module \verb unitsSI provides support for SI unit definitions with our variables.
287 Once our library dependencies have been established, defining the problem specific variables is the next step. In general the number of variables needed will vary between problems. These variables belong to two categories. They are either directly related to the PDE and can be used as inputs into the \esc solver, or they are script variables used to control internal functions and iterations in our problem. For this PDE there are a number of constants which 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.
289 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 \begin{python}
291 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 \end{python}
297 The material constants and the temperature variables must also be defined. For the granite in the model they are defined as:
298 \begin{python}
299 #PDE related
300 rho = 2750. *kg/m**3 #kg/m^{3} density of iron
301 cp = 790.*J/(kg*K) # J/Kg.K thermal capacity
302 rhocp = rho*cp
303 kappa = 2.2*W/m/K # watts/m.Kthermal conductivity
304 qH=0 * J/(sec*m**3) # J/(sec.m^{3}) no heat source
305 T1=20 * Celsius # initial temperature at Block 1
306 T2=2273. * Celsius # base temperature at Block 2
307 \end{python}
308 Finally, to control our script we will have to specify our timing controls and where we would like to save the output from the solver. This is simple enough:
309 \begin{python}
310 t=0 * day #our start time, usually zero
311 tend=1. * day # - time to end simulation
312 outputs = 200 # number of time steps required.
313 h=(tend-t)/outputs #size of time step
314 #user warning statement
315 print "Expected Number of time outputs is: ", (tend-t)/h
316 i=0 #loop counter
317 \end{python}
318 Now that we know our inputs we will build a domain using the \verb Rectangle() function from \verb finley . The four arguments allow us to define our domain \verb model as:
319 \begin{python}
320 #generate domain using rectangle
321 blocks = Rectangle(l0=mx,l1=my,n0=ndx, n1=ndy)
322 \end{python}
323 \verb blocks now describes a domain in the manner of Section \ref{ss:domcon}.
325 With a domain and all our required variables established, it is now possible to set up our PDE so that it can be solved by \esc. The first step is to define the type of PDE that we are trying to solve in each time step. In this example it is a single linear PDE\footnote{in comparison to a system of PDEs which we discuss later.}. We also need to state the values of our general form variables.
326 \begin{python}
327 mypde=LinearPDE(blocks)
328 A=zeros((2,2)))
329 A[0,0]=kappa
330 mypde.setValue(A=A, D=rhocp/h)
331 \end{python}
332 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 \begin{equation}\label{eqn:symm}
335 A\hackscore{jl}=A\hackscore{lj}
336 \end{equation}
337 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 \begin{python}
339 myPDE.setSymmetryOn()
340 \end{python}
341 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 \begin{python}
352 # ... set initial temperature ....
353 T= T1*whereNegative(x[0]-boundloc)+T2*(1-whereNegative(x[0]-boundloc))
354 \end{python}
355 we get the desired temperature distribution. To get the actual sample points \verb|x| we use
356 the \verb|getX()| method of the function space \verb|Solution(blocks)|
357 which is used to represent the solution of a PDE;
358 \begin{python}
359 x=Solution(blocks).getX()
360 \end{python}
361 As \verb|x| are the sample points for the function space \verb|Solution(blocks)|
362 the initial temperature \verb|T| is using these sample points for representation.
363 Although \esc is trying to be forgiving with the choice of sample points and to convert
364 where necessary the adjustment of the function space is not always possible. So it is
365 advisable to make a careful choice on the function space used.
367 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 \begin{python}
369 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 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.
380 \subsection{Running the Script}
381 The script presented so far is available under
382 \verb|example01a.py|. You can edit this file with your favourite text editor.
383 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 to launch {\it escript} scripts. For the example script use;
385 \begin{verbatim}
386 run-escript example01a.py
387 \end{verbatim}
388 The program will print a progress report. Alternatively, you can use
389 the python interpreter directly;
390 \begin{verbatim}
391 python example01a.py
392 \end{verbatim}
393 if the system is configured correctly (Please talk to your system administrator).
395 \begin{figure}
396 \begin{center}
397 \includegraphics[width=4in]{figures/ttblockspyplot150}
398 \caption{Example 1b: Total Energy in the Blocks over Time (in seconds).}
399 \label{fig:onedheatout1}
400 \end{center}
401 \end{figure}
403 \subsection{Plotting the Total Energy}
404 \sslist{example01b.py}
406 \esc does not include its own plotting capabilities. However, it is possible to use a variety of free \pyt packages for visualisation.
407 Two types will be demonstrated in this cookbook; \mpl\footnote{\url{http://matplotlib.sourceforge.net/}} and \verb VTK \footnote{\url{http://www.vtk.org/}} visualisation.
408 The \mpl package is a component of SciPy\footnote{\url{http://www.scipy.org}} and is good for basic graphs and plots.
409 For more complex visualisation tasks in particular, 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.
413 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 developing over time. Lets start with the first task.
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 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 to the corresponding list using the \verb|append| method. With these modifications our script looks as follows:
422 \begin{python}
423 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 \end{python}
434 To plot $t$ over $totE$ we use \mpl a module contained within \pylab which needs to be loaded before used;
435 \begin{python}
436 import pylab as pl # plotting package.
437 \end{python}
438 Here we are not using the \verb|from pylab import *| in order to avoid name clashes for function names
439 within \esc.
441 The following statements are added to the script after the time loop has been completed;
442 \begin{python}
443 pl.plot(t_list,E_list)
444 pl.title("Total Energy")
445 pl.axis([0,max(t_list),0,max(E_list)*1.1])
446 pl.savefig("totE.png")
447 \end{python}
448 The first statement hands over the time marks and corresponding total energies to the plotter.
449 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}.
455 \subsection{Plotting the Temperature Distribution}
456 \label{sec: plot T}
457 \sslist{example01c.py}
458 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 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 to make sure that the images previously generated are not overwritten.
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 \begin{python}
472 import os
473 os.path.join(save_path, "tempT%03d.png"%i )
474 \end{python}
475 where \verb|i| is the time step counter.
476 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 \begin{verbatim}
478 save_path = "data"
479 \end{verbatim}
480 while a sub-folder of \verb data called \verb example01 would be defined by;
481 \begin{verbatim}
482 save_path = os.path.join("data","example01")
483 \end{verbatim}
484 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 \begin{itemize}
486 \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 \end{itemize}
490 To actually substitute the value of \verb|i| into the name write \verb %i after the string.
491 When done correctly, the output files from this command would be place in the directory defined by \verb save_path as;
492 \begin{verbatim}
493 blockspyplot001.png
494 blockspyplot002.png
495 blockspyplot003.png
496 ...
497 \end{verbatim}
498 and so on.
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.
506 We start by modifying our solution script.
507 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 We need to convert the array \verb|x| previously set as \verb|Solution(blocks).getX()| into a \pyt list
510 and then to a \numpy array. The $x\hackscore{0}$ component is then extracted via an array slice to the variable \verb|plx|;
511 \begin{python}
512 import numpy as np # array package.
513 #convert solution points for plotting
514 plx = x.toListOfTuples()
515 plx = np.array(plx) # convert to tuple to numpy array
516 plx = plx[:,0] # extract x locations
517 \end{python}
519 \begin{figure}
520 \begin{center}
521 \includegraphics[width=4in]{figures/blockspyplot001}
522 \includegraphics[width=4in]{figures/blockspyplot050}
523 \includegraphics[width=4in]{figures/blockspyplot200}
524 \caption{Example 1c: Temperature ($T$) distribution in the blocks at time steps $1$, $50$ and $200$.}
525 \label{fig:onedheatout}
526 \end{center}
527 \end{figure}
529 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 The following is appended to the end of the \verb while loop and creates one figure of the temperature distribution. We start by converting the solution to a tuple and then plotting this against our \textit{x coordinates} \verb plx we have generated before. We add a title to the diagram before it is rendered into a file.
532 Finally, the figure is saved to a \verb|*.png| file and cleared for the following iteration.
533 \begin{python}
534 # ... start iteration:
535 while t<tend:
536 ....
537 T=mypde.getSolution() #get the PDE solution
538 tempT = T.toListOfTuples() # convert to a tuple
539 pl.plot(plx,tempT) # plot solution
540 # set scale (Temperature should be between Tref and T0)
541 pl.axis([0,mx,Tref*.9,T0*1.1])
542 # add title
543 pl.title("Temperature across the blocks at time %e minutes"%(t/day))
544 #save figure to file
545 pl.savefig(os.path.join(save_path,"tempT","blockspyplot%03d.png") %i)
546 \end{python}
547 Some results are shown in \reffig{fig:onedheatout}.
549 \subsection{Make a video}
550 Our saved plots from the previous section can be cast into a video using the following command appended to the end of the script. The \verb mencoder command is Linux only, so other platform users need to use an alternative video encoder.
551 \begin{python}
552 # compile the *.png files to create a *.avi videos that show T change
553 # with time. This operation uses Linux mencoder. For other operating
554 # systems it is possible to use your favourite video compiler to
555 # convert image files to videos.
557 os.system("mencoder mf://"+save_path+"/tempT"+"/*.png -mf type=png:\
558 w=800:h=600:fps=25 -ovc lavc -lavcopts vcodec=mpeg4 -oac copy -o \
559 example01tempT.avi")
560 \end{python}

  ViewVC Help
Powered by ViewVC 1.1.26