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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2878 - (hide annotations)
Thu Jan 28 00:59:30 2010 UTC (9 years, 7 months ago) by gross
File MIME type: application/x-tex
File size: 38452 byte(s)
more work on cookbook review
1 ahallam 2401
2     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3     %
4     % Copyright (c) 2003-2009 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 ahallam 2801 We will start by examining a simple one dimensional heat diffusion example. This problem will provide a good launch pad to build our knowledge of \esc and demonstrate how to solve simple partial differential equations (PDEs)\footnote{Wikipedia provides an excellent and comprehensive introduction to \textit{Partial Differential Equations} \url{http://en.wikipedia.org/wiki/Partial_differential_equation}, however their relevance to \esc and implementation should become a clearer as we develop our understanding further into the cookbook.}
15    
16 ahallam 2401 \section{One Dimensional Heat Diffusion in an Iron Rod}
17 gross 2878
18 ahallam 2401 %\label{Sec:1DHDv0}
19 ahallam 2801 The first model consists of a simple cold iron bar at a constant temperature of zero \reffig{fig:onedhdmodel}. The bar is perfectly insulated on all sides with a heating element at one end. Intuition tells us that as heat is applied; energy will disperse along the bar via conduction. With time the bar will reach a constant temperature equivalent to that of the heat source.
20 ahallam 2494 \begin{figure}[h!]
21     \centerline{\includegraphics[width=4.in]{figures/onedheatdiff}}
22     \caption{One dimensional model of an Iron bar.}
23     \label{fig:onedhdmodel}
24     \end{figure}
25 ahallam 2495 \subsection{1D Heat Diffusion Equation}
26     We can model the heat distribution of this problem over time using the one dimensional heat diffusion equation\footnote{A detailed discussion on how the heat diffusion equation is derived can be found at \url{http://online.redwoods.edu/instruct/darnold/DEProj/sp02/AbeRichards/paper.pdf}};
27 ahallam 2494 which is defined as:
28 ahallam 2401 \begin{equation}
29     \rho c\hackscore p \frac{\partial T}{\partial t} - \kappa \frac{\partial^{2} T}{\partial x^{2}} = q\hackscore H
30     \label{eqn:hd}
31     \end{equation}
32 gross 2861 where $\rho$ is the material density, $c\hackscore p$ is the specific heat and $\kappa$ is the thermal
33     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
34     parameters are \textbf{constant}.
35     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$.
36 ahallam 2401
37 gross 2861 \subsection{PDEs and the General Form}
38     Potentially, it is now possible to solve PDE \refEq{eqn:hd} analytically and this would produce an exact solution to our problem. However, it is not always possible or practical to solve a problem this way. Alternatively, computers can be used to solve these kinds of problems. To do this, a numerical approach is required to discretised
39     the PDE \refEq{eqn:hd} in time and space so finally we are left with a finite number of equations for a finite number of spatial and time steps in the model. While discretization introduces approximations and a degree of error, we find that a sufficiently sampled model is generally accurate enough for the requirements of the modeler.
40 gross 2477
41 gross 2861 Firstly, we will discretise the PDE \refEq{eqn:hd} in the time direction which will
42     leave as with a steady linear PDE which is involving spatial derivatives only and needs to be solved in each time
43     step to progress in time - \esc can help us here.
44    
45     For the discretization in time we will use is the Backwards Euler approximation scheme\footnote{see \url{http://en.wikipedia.org/wiki/Euler_method}}. It bases on the
46     approximation
47     \begin{equation}
48     \frac{\partial T(t)}{\partial t} \approx \frac{T(t)-T(t-h)}{h}
49     \label{eqn:beuler}
50     \end{equation}
51     for $\frac{\partial T}{\partial t}$ at time $t$
52     where $h$ is the time step size. This can also be written as;
53     \begin{equation}
54     \frac{\partial T}{\partial t}(t^{(n)}) \approx \frac{T^{(n)} - T^{(n-1)}}{h}
55     \label{eqn:Tbeuler}
56     \end{equation}
57     where the upper index $n$ denotes the n\textsuperscript{th} time step. So one has
58     \begin{equation}
59     \begin{array}{rcl}
60     t^{(n)} & = & t^{(n-1)}+h \\
61     T^{(n)} & = & T(t^{(n-1)}) \\
62     \end{array}
63     \label{eqn:Neuler}
64     \end{equation}
65     Substituting \refEq{eqn:Tbeuler} into \refEq{eqn:hd} we get;
66     \begin{equation}
67     \frac{\rho c\hackscore p}{h} (T^{(n)} - T^{(n-1)}) - \kappa \frac{\partial^{2} T^{(n)}}{\partial x^{2}} = q\hackscore H
68     \label{eqn:hddisc}
69     \end{equation}
70     Notice that we evaluate the spatial derivative term at current time $t^{(n)}$ - therefore the name \textbf{backward Euler} scheme. Alternatively, one can use evaluate the spatial derivative term at the previous time $t^{(n-1)}$. This
71     approach is called the \textbf{forward Euler} scheme. This scheme can provide some computational advantages which
72     we are not discussed here but has the major disadvantage that depending on the
73     material parameter as well as the discretiztion of the spatial derivative term the time step size $h$ needs to be chosen sufficiently small to achieve a stable temperature when progressing in time. The term \textit{stable} means
74     that the approximation of the temperature will not grow beyond its initial bounds and becomes unphysical.
75     The backward Euler which we use here is unconditionally stable meaning that under the assumption of
76     physically correct problem set-up the temperature approximation remains physical for all times.
77     The user needs to keep in mind that the discretization error introduced by \refEq{eqn:beuler}
78     is sufficiently small so a good approximation of the true temperature is calculated. It is
79     therefore crucial that the user remains critical about his/her results and for instance compares
80     the results for different time and spatial step sizes.
81    
82     To get the temperature $T^{(n)}$ at time $t^{(n)}$ we need to solve the linear
83     differential equation \refEq{eqn:hddisc} which is only including spatial derivatives. To solve this problem
84     we want to to use \esc.
85    
86     \esc interfaces with any given PDE via a general form. For the purpose of this introduction we will illustrate a simpler version of the full linear PDE general form which is available in the \esc user's guide. A simplified form that suits our heat diffusion problem\footnote{In the form of the \esc users guide which using the Einstein convention is written as
87 gross 2477 $-(A\hackscore{jl} u\hackscore{,l})\hackscore{,j}+D u =Y$}
88 ahallam 2606 is described by;
89 gross 2477 \begin{equation}\label{eqn:commonform nabla}
90 jfenwick 2657 -\nabla\cdot(A\cdot\nabla u) + Du = f
91 ahallam 2411 \end{equation}
92 gross 2861 where $A$, $D$ and $f$ are known values and $u$ is the unknown solution. The symbol $\nabla$ which is called the \textit{Nabla operator} or \textit{del operator} represents
93 ahallam 2495 the spatial derivative of its subject - in this case $u$. Lets assume for a moment that we deal with a one-dimensional problem then ;
94 gross 2477 \begin{equation}
95     \nabla = \frac{\partial}{\partial x}
96     \end{equation}
97 gross 2861 and we can write \refEq{eqn:commonform nabla} as;
98 ahallam 2411 \begin{equation}\label{eqn:commonform}
99 gross 2477 -A\frac{\partial^{2}u}{\partial x^{2}} + Du = f
100 ahallam 2411 \end{equation}
101 gross 2861 if $A$ is constant. To match this simplified general form to our problem \refEq{eqn:hddisc}
102     we rearrange \refEq{eqn:hddisc};
103 ahallam 2411 \begin{equation}
104 ahallam 2645 \frac{\rho c\hackscore p}{h} T^{(n)} - \kappa \frac{\partial^2 T^{(n)}}{\partial x^2} = q\hackscore H + \frac{\rho c\hackscore p}{h} T^{(n-1)}
105 ahallam 2494 \label{eqn:hdgenf}
106     \end{equation}
107 ahallam 2775 The PDE is now in a form that satisfies \refEq{eqn:commonform nabla} which is required for \esc to solve our PDE. This can be done by generating a solution for successive increments in the time nodes $t^{(n)}$ where
108 ahallam 2495 $t^{(0)}=0$ and $t^{(n)}=t^{(n-1)}+h$ where $h>0$ is the step size and assumed to be constant.
109 gross 2861 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} it can be seen that;
110 gross 2862 \begin{equation}\label{ESCRIPT SET}
111 gross 2861 u=T^{(n)};
112 ahallam 2494 A = \kappa; D = \frac{\rho c \hackscore{p}}{h}; f = q \hackscore{H} + \frac{\rho c\hackscore p}{h} T^{(n-1)}
113     \end{equation}
114    
115 gross 2870 % Now that the general form has been established, it can be submitted to \esc. Note that it is necessary to establish the state of our system at time zero or $T^{(n=0)}$. This is due to the time derivative approximation we have used from \refEq{eqn:Tbeuler}. Our model stipulates a starting temperature in the iron bar of 0\textcelsius. Thus the temperature distribution is simply;
116     % \begin{equation}
117     % T(x,0) = \left
118     % \end{equation}
119     % for all $x$ in the domain.
120 ahallam 2494
121 ahallam 2495 \subsection{Boundary Conditions}
122 gross 2878 \label{SEC BOUNDARY COND}
123 gross 2862 With the PDE sufficiently modified, consideration must now be given to the boundary conditions of our model. Typically there are two main types of boundary conditions known as \textbf{Neumann} and \textbf{Dirichlet} boundary conditions\footnote{More information on Boundary Conditions is available at Wikipedia \url{http://en.wikipedia.org/wiki/Boundary_conditions}}, respectively.
124     A \textbf{Dirichlet boundary condition} is conceptually simpler and is used to prescribe a known value to the unknown - in our example the temperature - on parts of or the entire boundary of the region of interest.
125     For our model problem we want to keep the initial temperature setting on the left side of the
126     iron bar over time. This defines a Dirichlet boundary condition for the PDE \refEq{eqn:hddisc} to be solved at each time step.
127 ahallam 2495
128 gross 2878 On the other end of the iron rod we want to add an appropriate boundary condition to define insulation to prevent
129 gross 2862 any loss or inflow of energy at the right end of the rod. Mathematically this is expressed by prescribing
130     the heat flux $\kappa \frac{\partial T}{\partial x}$ to zero on the right end of the rod
131     In our simplified one dimensional model this is expressed
132     in the form;
133 ahallam 2494 \begin{equation}
134 gross 2862 \kappa \frac{\partial T}{\partial x} = 0
135 ahallam 2494 \end{equation}
136 gross 2862 or in a more general case as
137     \begin{equation}\label{NEUMAN 1}
138     \kappa \nabla T \cdot n = 0
139     \end{equation}
140     where $n$ is the outer normal field \index{outer normal field} at the surface of the domain.
141     For the iron rod the outer normal field on the right hand side is the vector $(1,0)$. The $\cdot$ (dot) refers to the
142     dot product of the vectors $\nabla T$ and $n$. In fact, the term $\nabla T \cdot n$ is the normal derivative of
143     the temperature $T$. Other notations which are used are\footnote{The \esc notation for the normal
144     derivative is $T\hackscore{,i} n\hackscore i$.};
145 ahallam 2645 \begin{equation}
146 gross 2862 \nabla T \cdot n = \frac{\partial T}{\partial n} \; .
147 ahallam 2645 \end{equation}
148 gross 2862 A condition of the type \refEq{NEUMAN 1} defines a \textbf{Neuman boundary condition} for the PDE.
149 ahallam 2494
150 gross 2862 The PDE \refEq{eqn:hdgenf} together with the Dirichlet boundary condition set on the left face of the rod
151     and the Neuman boundary condition~\ref{eqn:hdgenf} define a \textbf{boundary value problem}.
152     It is a nature of a boundary value problem that it allows to make statements on the solution in the
153     interior of the domain from information known on the boundary only. In most cases
154     we use the term partial differential equation but in fact mean a boundary value problem.
155     It is important to keep in mind that boundary conditions need to be complete and consistent in the sense that
156     at any point on the boundary either a Dirichlet or a Neuman boundary condition must be set.
157    
158 gross 2878 Conveniently, \esc makes default assumption on the boundary conditions which the user may modify where appropriate.
159 gross 2862 For a problem of the form in~\refEq{eqn:commonform nabla} the default condition\footnote{In the form of the \esc users guide which is using the Einstein convention is written as
160     $n\hackscore{j}A\hackscore{jl} u\hackscore{,l}=0$.} is;
161     \begin{equation}\label{NEUMAN 2}
162     n\cdot A \cdot\nabla u = 0
163     \end{equation}
164     which is used everywhere on the boundary. Again $n$ denotes the outer normal field.
165     Notice that the coefficient $A$ is the same as in the \esc PDE~\ref{eqn:commonform nabla}.
166     With the settings for the coefficients we have already identified in \refEq{ESCRIPT SET} this
167     condition translates into
168 gross 2867 \begin{equation}\label{NEUMAN 2b}
169 gross 2862 \kappa \frac{\partial T}{\partial x} = 0
170     \end{equation}
171     for the right hand side of the rod. This is identical to the Neuman boundary condition we want to set. \esc will take care of this condition for us. We will discuss the Dirichlet boundary condition later.
172    
173 gross 2870 \subsection{Outline of the Implementation}
174     \label{sec:outline}
175     To solve the heat diffusion equation (equation \refEq{eqn:hd}) we will write a simple \pyt script. At this point we assume that you have some basic understanding of the \pyt programming language. If not there are some pointers and links available in Section \ref{sec:escpybas}. The script we will discuss later in details will have four major steps. Firstly we need to define the domain where we want to
176     calculate the temperature. For our problem this is the iron rod which has a rectangular shape. Secondly we need to define the PDE
177 gross 2878 we need to solve in each time step to get the updated temperature. Thirdly we need to define the the coefficients of the PDE and finally we need to solve the PDE. The last two steps need to be repeated until the final time marker has been reached. As a work flow this takes the form;
178     \begin{enumerate}
179     \item create domain
180     \item create PDE
181     \item while end time not reached:
182     \begin{enumerate}
183     \item set PDE coefficients
184     \item solve PDE
185     \item update time marker
186     \end{enumerate}
187     \item end of calculation
188     \end{enumerate}
189 gross 2870 In the terminology of \pyt the domain and PDE are represented by \textbf{objects}. The nice feature of an object is that it defined by it usage and features
190 gross 2878 rather than its actual representation. So we will create a domain object to describe the geometry of our iron rod. The main feature
191 gross 2870 of the object we will use is the fact that we can define PDEs and spatially distributed values such as the temperature
192     on a domain. In fact the domain object has many more features - most of them you will
193     never use and do not need to understand. Similar a PDE object is defined by the fact that we can define the coefficients of the PDE and solve the PDE. At a
194 gross 2878 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.
195 gross 2870
196    
197     \begin{figure}[t]
198     \centering
199     \includegraphics[width=6in]{figures/functionspace.pdf}
200     \label{fig:fs}
201     \caption{\esc domain construction overview}
202     \end{figure}
203    
204     \subsection{The Domain Constructor in \esc}
205     \label{ss:domcon}
206     It is helpful to have a better understanding how spatially distributed value such as the temperature or PDE coefficients are interpreted in \esc. Again
207     from the user's point of view the representation of these spatially distributed values is not relevant.
208    
209     There are various ways to construct domain objects. The simplest form is as rectangular shaped region with a length and height. There is
210     a ready to use function call for this. Besides the spatial dimensions the function call will require you to specify the number
211 gross 2878 elements or cells to be used along the length and height, see Figure~\ref{fig:fs}. Any specially distributed value
212 gross 2870 and the PDE is represented in discrete form using this element representation\footnote{We will use the finite element method (FEM), see \url{http://en.wikipedia.org/wiki/Finite_element_method}i for details.}. Therefore we will have access to an approximation of the true PDE solution only.
213     The quality of the approximation depends - besides other factors- mainly on the number of elements being used. In fact, the
214     approximation becomes better the more elements are used. However, computational costs and compute time grow with the number of
215 gross 2878 elements being used. It therefore important that you find the right balance between the demand in accuracy and acceptable resource usage.
216 gross 2870
217     In general, one can thinks about a domain object as a composition of nodes and elements.
218     As shown in Figure~\ref{fig:fs}, an element is defined by the nodes used to describe its vertices.
219     To represent spatial distributed values the user can use
220     the values at the nodes, at the elements in the interior of the domain or at elements located at the surface of the domain.
221     The different approach used to represent values is called \textbf{function space} and is attached to all objects
222     in \esc representing a spatial distributed value such as the solution of a PDE. The three
223     function spaces we will use at the moment are;
224     \begin{enumerate}
225     \item the nodes, called by \verb|ContinuousFunction(domain)| ;
226     \item the elements/cells, called by \verb|Function(domain)| ; and
227     \item the boundary, called by \verb|FunctionOnBoundary(domain)| .
228     \end{enumerate}
229     A function space object such as \verb|ContinuousFunction(domain)| has the method \verb|getX| attached to it. This method returns the
230     location of the so-called \textbf{sample points} used to represent values with the particular function space attached to it. So the
231     call \verb|ContinuousFunction(domain).getX()| will return the coordinates of the nodes used to describe the domain while
232     the \verb|Function(domain).getX()| returns the coordinates of numerical integration points within elements, see
233     Figure~\ref{fig:fs}.
234    
235 gross 2878 This distinction between different representations of spatial distributed values
236 gross 2870 is important in order to be able to vary the degrees of smoothness in a PDE problem.
237     The coefficients of a PDE need not be continuous thus this qualifies as a \verb|Function()| type.
238     On the other hand a temperature distribution must be continuous and needs to be represented with a \verb|ContinuousFunction()| function space.
239     An influx may only be defined at the boundary and is therefore a \verb FunctionOnBoundary() object.
240     \esc allows certain transformations of the function spaces. A \verb ContinuousFunction() can be transformed into a \verb|FunctionOnBoundary()|
241     or \verb|Function()|. On the other hand there is not enough information in a \verb FunctionOnBoundary() to transform it to a \verb ContinuousFunction() .
242 gross 2878 These transformations, which are called \textbf{interpolation} are invoked automatically by \esc if needed.
243 gross 2870
244     Later in this introduction we will discuss how
245     to define specific areas of geometry with different materials which are represented by different material coefficients such the
246 gross 2878 thermal conductivities $kappa$. A very powerful technique to define these types of PDE
247 gross 2870 coefficients is tagging. Blocks of materials and boundaries can be named and values can be defined on subregions based on their names.
248 gross 2878 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}.
249 gross 2870
250    
251     \subsection{A Clarification for the 1D Case}
252 gross 2861 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;
253 gross 2477 \begin{equation}\label{eqn:commonform2D}
254     -A\hackscore{00}\frac{\partial^{2}u}{\partial x^{2}}
255     -A\hackscore{01}\frac{\partial^{2}u}{\partial x\partial y}
256     -A\hackscore{10}\frac{\partial^{2}u}{\partial y\partial x}
257     -A\hackscore{11}\frac{\partial^{2}u}{\partial y^{2}}
258     + Du = f
259     \end{equation}
260 ahallam 2606 Notice that for the higher dimensional case $A$ becomes a matrix. It is also
261 ahallam 2495 important to notice that the usage of the Nabla operator creates
262     a compact formulation which is also independent from the spatial dimension.
263 gross 2861 So to make the general PDE \refEq{eqn:commonform2D} one dimensional as
264     shown in \refEq{eqn:commonform} we need to set
265 ahallam 2606 \begin{equation}
266 ahallam 2494 A\hackscore{00}=A; A\hackscore{01}=A\hackscore{10}=A\hackscore{11}=0
267 gross 2477 \end{equation}
268    
269 gross 2867
270 ahallam 2495 \subsection{Developing a PDE Solution Script}
271 ahallam 2801 \label{sec:key}
272 gross 2878 \sslist{onedheatdiffbase.py}
273 gross 2870 We will write a simple \pyt script which uses the \modescript, \modfinley and \modmpl modules.
274 gross 2861 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.}
275 ahallam 2495 that we will require.
276 ahallam 2775 \begin{python}
277 ahallam 2495 from esys.escript import *
278 ahallam 2606 # This defines the LinearPDE module as LinearPDE
279     from esys.escript.linearPDEs import LinearPDE
280     # This imports the rectangle domain function from finley.
281     from esys.finley import Rectangle
282     # A useful unit handling package which will make sure all our units
283     # match up in the equations under SI.
284     from esys.escript.unitsSI import *
285 ahallam 2775 \end{python}
286 gross 2878 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.
287 gross 2477
288 ahallam 2801 Once our library dependencies have been established, defining the problem specific variables is the next step. In general the number of variables needed will vary between problems. These variables belong to two categories. They are either directly related to the PDE and can be used as inputs into the \esc solver, or they are script variables used to control internal functions and iterations in our problem. For this PDE there are a number of constants which will need values. Firstly, the model upon which we wish to solve our problem needs to be defined. There are many different types of models in \modescript which we will demonstrate in later tutorials but for our iron rod, we will simply use a rectangular model.
289 ahallam 2401
290 ahallam 2801 Using a rectangular model simplifies our rod which would be a \textit{3D} object, into a single dimension. The iron rod will have a lengthways cross section that looks like a rectangle. As a result we do not need to model the volume of the rod because a cylinder is symmetrical about its centre. There are four arguments we must consider when we decide to create a rectangular model, the model \textit{length}, \textit{width} and \textit{step size} in each direction. When defining the size of our problem it will help us determine appropriate values for our model arguments. If we make our dimensions large but our step sizes very small we will to a point, increase the accuracy of our solution. Unfortunately we also increase the number of calculations that must be solved per time step. This means more computational time is required to produce a solution. In this \textit{1D} problem, the bar is defined as being 1 metre long. An appropriate step size \verb|ndx| would be 1 to 10\% of the length. Our \verb|ndy| need only be 1, this is because our problem stipulates no partial derivatives in the $y$ direction. Thus the temperature does not vary with $y$. Hence, the model parameters can be defined as follows; note we have used the \verb unitsSI convention to make sure all our input units are converted to SI.
291 ahallam 2775 \begin{python}
292 ahallam 2495 #Domain related.
293 ahallam 2606 mx = 1*m #meters - model length
294 ahallam 2495 my = .1*m #meters - model width
295 ahallam 2606 ndx = 100 # mesh steps in x direction
296     ndy = 1 # mesh steps in y direction - one dimension means one element
297 ahallam 2775 \end{python}
298 ahallam 2495 The material constants and the temperature variables must also be defined. For the iron rod in the model they are defined as:
299 ahallam 2775 \begin{python}
300 ahallam 2495 #PDE related
301     rho = 7874. *kg/m**3 #kg/m^{3} density of iron
302 gross 2878 cp = 449.*J/(kg*K) # J/Kg.K thermal capacity
303     rhocp = rho*cp
304     kappa = 80.*W/m/K # watts/m.Kthermal conductivity
305     qH=0 * J/(sec*m**3) # J/(sec.m^{3}) no heat source
306     T0=100 * Celsius # initial temperature at left end of rod
307     Tref=20 * Celsius # base temperature
308 ahallam 2775 \end{python}
309 ahallam 2495 Finally, to control our script we will have to specify our timing controls and where we would like to save the output from the solver. This is simple enough:
310 ahallam 2775 \begin{python}
311 gross 2878 t=0 * day #our start time, usually zero
312     tend=1. * day # - time to end simulation
313 ahallam 2495 outputs = 200 # number of time steps required.
314     h=(tend-t)/outputs #size of time step
315 ahallam 2606 #user warning statement
316     print "Expected Number of time outputs is: ", (tend-t)/h
317     i=0 #loop counter
318 ahallam 2775 \end{python}
319 ahallam 2606 Now that we know our inputs we will build a domain using the \verb Rectangle() function from \verb finley . The four arguments allow us to define our domain \verb rod as:
320 ahallam 2775 \begin{python}
321 ahallam 2606 #generate domain using rectangle
322     rod = Rectangle(l0=mx,l1=my,n0=ndx, n1=ndy)
323 ahallam 2775 \end{python}
324 gross 2878 \verb rod now describes a domain in the manner of Section \ref{ss:domcon}. There is an easy way to extract
325     the coordinates of the nodes used to describe the domain \verb|rod| using the
326     domain property function \verb|getX()| . This function sets the vertices of each cell as finite points to solve in the solution. If we let \verb|x| be these finite points, then;
327 ahallam 2775 \begin{python}
328 gross 2878 #extract data points - the solution points
329 ahallam 2606 x=rod.getX()
330 ahallam 2775 \end{python}
331 gross 2878 The data locations of specific function spaces can be returned in a similar manner by extracting the relevant function space from the domain followed by the \verb|.getX()| method.
332 ahallam 2658
333 ahallam 2775 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.
334     \begin{python}
335 ahallam 2495 mypde=LinearSinglePDE(rod)
336 gross 2878 A=zeros((2,2)))
337     A[0,0]=kappa
338     q=whereZero(x[0])
339     mypde.setValue(A=A, D=rhocp/h, q=q, r=T0)
340 ahallam 2775 \end{python}
341 gross 2878 The argument \verb|q| has not been discussed yet: In fact the arguments \verb|q| and \verb|r| are used to define
342     Dirichlet boundary condition as discussed in Section~\ref{SEC BOUNDARY COND}. In the \esc
343     PDE from the argument \verb|q| indicates by a positive value for which nodes we want to apply a
344     Dirichlet boundary condition, ie. where we want to prescribe the value of the PDE solution
345     rather then using the PDE. The actually value for the solution to be taken is set by the argument \verb|r|.
346     In our case we want to keep the initial temperature $T0$ on the left face of the rode for all times. Notice,
347     that as set to a constant value \verb|r| is assumed to have the same value
348     at all nodes, however only the value at those nodes marked by a positive value by \verb|q| are actually used.
349 ahallam 2401
350 gross 2878 In order to set \verb|q| we use
351     \verb|whereZero| function. The function returns the value (positive) one for those data points (=nodes) where the argument is equal to zero and otherwise returns (non-positive) value zero.
352     As \verb|x[0]| given the $x$-coordinates of the nodes for the domain,
353     \verb|whereZero(x[0])| gives the value $1$ for the nodes at the left end of the rod $x=x_0=0$ and
354     zero elsewhere which is exactly what we need.
355    
356     In a many cases it may be possible to decrease the computational time of the solver if the PDE is symmetric.
357     Symmetry of a PDE is defined by;
358 ahallam 2495 \begin{equation}\label{eqn:symm}
359     A\hackscore{jl}=A\hackscore{lj}
360     \end{equation}
361 gross 2878 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;
362 ahallam 2775 \begin{python}
363 ahallam 2495 myPDE.setSymmetryOn()
364 ahallam 2775 \end{python}
365 gross 2878 Next we need to establish the initial temperature distribution \verb|T|. We want to have this initial
366     value to be \verb|Tref| except at the left end of the rod $x=0$ where we have the temperature \verb|T0|. We use;
367     \begin{python}
368     # ... set initial temperature ....
369     T = T0*whereZero(x[0])+Tref*(1-whereZero(x[0]))
370     \end{python}
371     Finally we will initialize an iteration loop to solve our PDE for all the time steps we specified in the variable section. As the right hand side of the general form is dependent on the previous values for temperature \verb T across the bar this must be updated in the loop. Our output at each time step is \verb T the heat distribution and \verb totT the total heat in the system.
372     \begin{python}
373     while t < tend:
374     i+=1 #increment the counter
375     t+=h #increment the current time
376     mypde.setValue(Y=qH+rhocp/h*T) # set variable PDE coefficients
377     T=mypde.getSolution() #get the PDE solution
378     totE = integrate(rhocp*T) #get the total heat (energy) in the system
379     \end{python}
380     The last statement in this script calculates the total energy in the system as volume integral
381     of $\rho \c_p T$ over the rod.
382 ahallam 2401
383 gross 2878 \subsection{Plotting the Total Energy}
384     \sslist{onedheatdiff001.py}
385    
386     \esc does not include its own plotting capabilities. However, it is possible to use a variety of free \pyt packages for visualization.
387     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.
388     The \mpl package is a component of SciPy\footnote{\url{http://www.scipy.org}} and is good for basic graphs and plots.
389     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/}}
390     which bases the \verb|VTK| toolkit. We will discuss the usage of \verb|VTK| based
391     visualization in Chapter~\ref{Sec:2DHD} where will discuss a two dimensional PDE.
392    
393     For our simple problem we have two plotting tasks: Firstly we are interested in showing the
394     behavior of the total energy over time and secondly in how the temperature distribution within the rod is
395     developing over time. Lets start with the first task.
396    
397     \begin{figure}
398     \begin{center}
399     \includegraphics[width=4in]{figures/ttrodpyplot150}
400     \caption{Total Energy in Rod over Time (in seconds).}
401     \label{fig:onedheatout1}
402     \end{center}
403     \end{figure}
404    
405     The trick is to create a record of the time marks and the corresponding total energies observed.
406     \pyt provides the concept of lists for this. Before
407     the time loop is opened we create empty lists for the time marks \verb|t_list| and the total energies \verb|E_list|.
408     After the new temperature as been calculated by solving the PDE we append the new time marker and total energy
409     to the corresponding list using the \verb|append| method. With these modifications the script looks as follows:
410 ahallam 2775 \begin{python}
411 gross 2878 t_list=[]
412     E_list=[]
413     # ... start iteration:
414     while t<tend:
415     t+=h
416     mypde.setValue(Y=qH+rhocp/h*T) # set variable PDE coefficients
417     T=mypde.getSolution() #get the PDE solution
418     totE=integrate(rhocp*T)
419     t_list.append(t) # add current time mark to record
420     E_list.append(totE) # add current total energy to record
421 ahallam 2775 \end{python}
422 gross 2878 To plot $t$ over $totE$ we use the \mpl a module contained within \pylab which needs to be loaded before used;
423 ahallam 2775 \begin{python}
424 gross 2878 import pylab as pl # plotting package.
425 ahallam 2775 \end{python}
426 gross 2878 Here we are not using the \verb|from pylab import *| in order to name clashes for function names
427     with \esc.
428 ahallam 2401
429 gross 2878 The following statements are added to the script after the time loop has been completed;
430 ahallam 2775 \begin{python}
431 gross 2878 pl.plot(t_list,E_list)
432     pl.title("Total Energy")
433     pl.savefig("totE.png")
434 ahallam 2775 \end{python}
435 gross 2878 The first statement hands over the time marks and corresponding total energies to the plotter.
436     The second statement is setting the title for the plot. The last statement renders the plot and writes the
437     result into the file \verb|totE.png| which can be displayed by (almost) any image viewer. Your result should look
438     similar to Figure~\ref{fig:onedheatout1}.
439 ahallam 2401
440 gross 2878 \subsection{Plotting the Temperature Distribution}
441     \sslist{onedheatdiff001b.py}
442     For plotting the spatial distribution of the temperature we need to modify the strategy we have used
443     for the total energy. Instead of producing a final plot at the end we will generate a
444     picture at each time step which can be browsed as slide show or composed to a movie.
445     The first problem we encounter is that if we produce an image in each time step we need
446     to make sure that the images previously generated are not overwritten.
447    
448     To develop an incrementing file name we can use the following convention. It is convenient to
449     put all image file showing the same variable - in our case the temperature distribution -
450     into a separate directory. As part of the \verb|os| module\footnote{The \texttt{os} module provides
451     a powerful interface to interact with the operating system, see \url{http://docs.python.org/library/os.html}.} \pyt
452     provides the \verb|os.path.join| command to build file and
453     directory names in a platform independent way. Assuming that
454     \verb|save_path| is name of directory we want to put the results the command is;
455 ahallam 2775 \begin{python}
456 gross 2878 import os
457     os.path.join(save_path, "tempT%03d.png"%i )
458 ahallam 2775 \end{python}
459 gross 2878 where \verb|i| is the time step counter.
460     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;
461     \begin{verbatim}
462     save_path = "data"
463     \end{verbatim}
464     while a sub-folder of \verb data called \verb onedheatdiff001 would be defined by;
465     \begin{verbatim}
466     save_path = os.path.join("data","onedheatdiff001")
467     \end{verbatim}
468     The second argument of \verb join \xspace contains a string which is the filename or subdirectory name. We can use the operator \verb|%| to increment our file names with the value \verb|i| denoting a incrementing counter. The substring \verb %03d does this by defining the following parameters;
469     \begin{itemize}
470     \item \verb 0 becomes the padding number;
471     \item \verb 3 tells us the amount of padding numbers that are required; and
472     \item \verb d indicates the end of the \verb % operator.
473     \end{itemize}
474     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;
475     \begin{verbatim}
476     rodpyplot.png
477     rodpyplot.png
478     rodpyplot.png
479     ...
480     \end{verbatim}
481     and so on.
482    
483     A sub-folder check/constructor is available in \esc. The command;
484     \begin{verbatim}
485     mkDir(save_path)
486     \end{verbatim}
487     will check for the existence of \verb save_path and if missing, make the required directories.
488    
489     We start by modifying our solution script from before.
490     Prior to the \verb|while| loop we will need to extract our finite solution points to a data object that is compatible with \mpl. First we create the node coordinates of the data points used to represent
491     the temperature as a \pyt list of tuples. As a solution of a PDE
492     the temperature has the \verb|Solution(rod)| function space attribute. We use
493     the \verb|getX()| method to get the coordinates of the data points as an \esc object
494     which is then converted to a \numpy array. The $x$ component is then extracted via an array slice to the variable \verb|plx|;
495 ahallam 2775 \begin{python}
496 gross 2878 import numpy as np # array package.
497     #convert solution points for plotting
498     plx = Solution(rod).getX().toListOfTuples()
499     plx = np.array(plx) # convert to tuple to numpy array
500     plx = plx[:,0] # extract x locations
501 ahallam 2775 \end{python}
502 gross 2878
503 ahallam 2645 \begin{figure}
504     \begin{center}
505 gross 2878 \includegraphics[width=4in]{figures/rodpyplot001}
506     \includegraphics[width=4in]{figures/rodpyplot050}
507     \includegraphics[width=4in]{figures/rodpyplot200}
508     \caption{Temperature ($T$) distribution in rod at time steps $1$, $50$ and $200$.}
509 ahallam 2645 \label{fig:onedheatout}
510     \end{center}
511     \end{figure}
512    
513 gross 2878 For each time step we will generate a plot of the temperature distribution and save each to a file. We use the same
514     techniques provided by \mpl as we have used to plot the total energy over time.
515     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.
516     Finally, the figure is saved to a \verb|*.png| file and cleared for the following iteration.
517 ahallam 2775 \begin{python}
518 gross 2878 # ... start iteration:
519     while t<tend:
520     ....
521     T=mypde.getSolution() #get the PDE solution
522     tempT = T.toListOfTuples() # convert to a tuple
523     pl.plot(plx,tempT) # plot solution
524     # set scale (Temperature should be between Tref and T0)
525     pl.axis([0,mx,Tref*.9,T0*1.1])
526     # add title
527     pl.title("Temperature across rod at time %e minutes"%(t/minutes))
528     #save figure to file
529     pl.savefig(os.path.join(save_path,"tempT","rodpyplot%03d.png") %i)
530 ahallam 2775 \end{python}
531 gross 2878 Some results are shown in Figure~\ref{fig:onedheatout}.
532 jfenwick 2657
533 ahallam 2606 \subsection{Make a video}
534 gross 2878 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.
535 ahallam 2775 \begin{python}
536 gross 2878 # compile the *.png files to create a *.avi videos that show T change
537     # with time. This operation uses Linux mencoder. For other operating
538     # systems it is possible to use your favorite video compiler to
539 ahallam 2606 # convert image files to videos.
540 gross 2477
541 ahallam 2606 os.system("mencoder mf://"+save_path+"/tempT"+"/*.png -mf type=png:\
542 gross 2878 w=800:h=600:fps=25 -ovc lavc -lavcopts vcodec=mpeg4 -oac copy -o \
543     onedheatdiff001tempT.avi")
544 ahallam 2775 \end{python}
545 gross 2477

  ViewVC Help
Powered by ViewVC 1.1.26