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

revision 2681 by ahallam, Thu Sep 24 03:04:04 2009 UTC revision 2775 by ahallam, Wed Nov 25 05:01:43 2009 UTC
# Line 14  Line 14
14  \section{One Dimensional Heat Diffusion in an Iron Rod}  \section{One Dimensional Heat Diffusion in an Iron Rod}
15  \sslist{onedheatdiff001.py and cblib.py}  \sslist{onedheatdiff001.py and cblib.py}
16  %\label{Sec:1DHDv0}  %\label{Sec:1DHDv0}
17  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 \ESCRIPT and 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 \ESCRIPT and implementation should become a clearer as we develop our understanding further into the cookbook.}  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 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.}
18
19  \begin{figure}[h!]  \begin{figure}[h!]
20  \centerline{\includegraphics[width=4.in]{figures/onedheatdiff}}  \centerline{\includegraphics[width=4.in]{figures/onedheatdiff}}
# Line 34  where $\rho$ is the material density, $c Line 34 where$\rho$is the material density,$c
34  The heat source is defined by the right hand side of \ref{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} = Te^{-\gamma t}$ where we have the output of our heat source decaying with time. There are also two partial derivatives in \ref{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$.  The heat source is defined by the right hand side of \ref{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} = Te^{-\gamma t}$ where we have the output of our heat source decaying with time. There are also two partial derivatives in \ref{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$.
35
36  \subsection{Escript, PDEs and The General Form}  \subsection{Escript, PDEs and The General Form}
37  Potentially, it is now possible to solve \ref{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 when a large number of sums or a more complex visualisation is required. To do this, a numerical approach is required - \ESCRIPT can help us here -  and it becomes necessary to discretize the equation so that 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 modeller.  Potentially, it is now possible to solve \ref{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 when a large number of sums or a more complex visualisation is required. To do this, a numerical approach is required - \esc can help us here -  and it becomes necessary to discretize the equation so that 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 modeller.
38
39  \ESCRIPT interfaces with any given PDE via a general form. In this example we will illustrate a simpler version of the full linear PDE general form which is available in the \ESCRIPT user's guide. A simplified form that suits our heat diffusion problem\footnote{In the form of the \ESCRIPT users guide which using the Einstein convention is written as  \esc interfaces with any given PDE via a general form. In this example 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
40  $-(A\hackscore{jl} u\hackscore{,l})\hackscore{,j}+D u =Y$}  $-(A\hackscore{jl} u\hackscore{,l})\hackscore{,j}+D u =Y$}
41  is described by;  is described by;
42  \label{eqn:commonform nabla}  \label{eqn:commonform nabla}
# Line 81  To fit our simplified general form we ca Line 81  To fit our simplified general form we ca
81  \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)}  \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)}
82  \label{eqn:hdgenf}  \label{eqn:hdgenf}
83
84  The PDE is now in a form that satisfies \refEq{eqn:commonform nabla} which is required for \ESCRIPT to solve our PDE. This can be done by generating a solution for successive increments in the time nodes $t^{(n)}$ where  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
85  $t^{(0)}=0$ and  $t^{(n)}=t^{(n-1)}+h$ where $h>0$ is the step size and assumed to be constant.  $t^{(0)}=0$ and  $t^{(n)}=t^{(n-1)}+h$ where $h>0$ is the step size and assumed to be constant.
86  In the following the upper index ${(n)}$ refers to a value at time $t^{(n)}$. Finally, by comparing \ref{eqn:hdgenf} with \ref{eqn:commonform} it can be seen that;  In the following the upper index ${(n)}$ refers to a value at time $t^{(n)}$. Finally, by comparing \ref{eqn:hdgenf} with \ref{eqn:commonform} it can be seen that;
87
88  A = \kappa; D = \frac{\rho c \hackscore{p}}{h}; f = q \hackscore{H} + \frac{\rho c\hackscore p}{h} T^{(n-1)}  A = \kappa; D = \frac{\rho c \hackscore{p}}{h}; f = q \hackscore{H} + \frac{\rho c\hackscore p}{h} T^{(n-1)}
89
90
91  Now that the general form has been established, it can be submitted to \ESCRIPT. 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 \ref{eqn:Tbeuler}. Our model stipulates a starting temperature in the iron bar of 0\textcelsius. Thus the temperature distribution is simply;  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 \ref{eqn:Tbeuler}. Our model stipulates a starting temperature in the iron bar of 0\textcelsius. Thus the temperature distribution is simply;
92
93  T(x,0) = T\hackscore{ref} = 0  T(x,0) = T\hackscore{ref} = 0
94
# Line 110  and simplified to our one dimensional mo Line 110  and simplified to our one dimensional mo
110  where $\eta$ is a given material coefficient depending on the material of the block and the surrounding medium and $\hat{n}\hackscore i$ is the $i$-th component of the outer normal field \index{outer normal field} at the surface of the domain. These two conditions form a boundary value problem that has to be solved for each time step. Due to the perfect insulation in our model we can set $\eta = 0$ which results in zero flux - no energy in or out - we do not need to worry about the Neumann terms of the general form for this example.  where $\eta$ is a given material coefficient depending on the material of the block and the surrounding medium and $\hat{n}\hackscore i$ is the $i$-th component of the outer normal field \index{outer normal field} at the surface of the domain. These two conditions form a boundary value problem that has to be solved for each time step. Due to the perfect insulation in our model we can set $\eta = 0$ which results in zero flux - no energy in or out - we do not need to worry about the Neumann terms of the general form for this example.
111
112  \subsection{A \textit{1D} Clarification}  \subsection{A \textit{1D} Clarification}
113  It is necessary for clarification that we revisit the general PDE from \refeq{eqn:commonform nabla} under the light of a two dimensional domain. \ESCRIPT is inherently designed to solve problems that are greater than one dimension and so \ref{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, \ref{eqn:commonform nabla} assuming a constant coefficient $A$, takes the form;  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 \ref{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, \ref{eqn:commonform nabla} assuming a constant coefficient $A$, takes the form;
114  \label{eqn:commonform2D}  \label{eqn:commonform2D}
115  -A\hackscore{00}\frac{\partial^{2}u}{\partial x^{2}}  -A\hackscore{00}\frac{\partial^{2}u}{\partial x^{2}}
116  -A\hackscore{01}\frac{\partial^{2}u}{\partial x\partial y}  -A\hackscore{01}\frac{\partial^{2}u}{\partial x\partial y}
# Line 130  A\hackscore{00}=A; A\hackscore{01}=A\hac Line 130  A\hackscore{00}=A; A\hackscore{01}=A\hac
130  \subsection{Developing a PDE Solution Script}  \subsection{Developing a PDE Solution Script}
131  To solve \ref{eqn:hd} we will write a simple python script which uses the \modescript, \modfinley and \modmpl modules. At this point we assume that you have some basic understanding of the python programming language. If not there are some pointers and links available in Section \ref{sec:escpybas} .  To solve \ref{eqn:hd} we will write a simple python script which uses the \modescript, \modfinley and \modmpl modules. At this point we assume that you have some basic understanding of the python programming language. If not there are some pointers and links available in Section \ref{sec:escpybas} .
132
133  Our goal here is to develop a script for \ESCRIPT that will solve the heat equation at successive time steps for a predefined period using our general form \ref{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 sin and cos functions or more complicated like those from our \ESCRIPT library.}  Our goal here is to develop a script for \esc that will solve the heat equation at successive time steps for a predefined period using our general form \ref{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 sin and cos functions or more complicated like those from our \esc library.}
134  that we will require.  that we will require.
135  \begin{verbatim}  \begin{python}
136  from esys.escript import *  from esys.escript import *
137  # This defines the LinearPDE module as LinearPDE  # This defines the LinearPDE module as LinearPDE
138  from esys.escript.linearPDEs import LinearPDE  from esys.escript.linearPDEs import LinearPDE
# Line 144  from esys.escript.unitsSI import * Line 144  from esys.escript.unitsSI import *
144  import pylab as pl #Plotting package.  import pylab as pl #Plotting package.
145  import numpy as np #Array package.  import numpy as np #Array package.
146  import os #This package is necessary to handle saving our data.  import os #This package is necessary to handle saving our data.
147  \end{verbatim}  \end{python}
148  It is generally a good idea to import all of the \modescript library, although if you know the packages you need you can specify them individually. The function \verb|LinearPDE| has been imported for ease of use later in the script. \verb|Rectangle| is going to be our type of domain. The package \verb unitsSI  is a module of \esc that provides support for units definitions with our variables; and the \verb|os| package is needed to handle file outputs once our PDE has been solved. \verb pylab  and \verb numpy  are modules developed independently of \esc. They are used because they have efficient plotting and array handling capabilities.  It is generally a good idea to import all of the \modescript library, although if you know the packages you need you can specify them individually. The function \verb|LinearPDE| has been imported for ease of use later in the script. \verb|Rectangle| is going to be our type of domain. The package \verb unitsSI  is a module of \esc that provides support for units definitions with our variables; and the \verb|os| package is needed to handle file outputs once our PDE has been solved. \verb pylab  and \verb numpy  are modules developed independently of \esc. They are used because they have efficient plotting and array handling capabilities.
149
150  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 \ESCRIPT 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 domain upon which we wish to solve our problem needs to be defined. There are many different types of domains in \modescript which we will demonstrate in later tutorials but for our iron rod, we will simply use a rectangular domain.  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 domain upon which we wish to solve our problem needs to be defined. There are many different types of domains in \modescript which we will demonstrate in later tutorials but for our iron rod, we will simply use a rectangular domain.
151
152  Using a rectangular domain 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 domain, 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 domain 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 our \textit{1D} problem we will define our bar as being 1 metre long. An appropriate \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 so the temperature does not vary with $y$. Thus the domain 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.  Using a rectangular domain 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 domain, 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 domain 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 our \textit{1D} problem we will define our bar as being 1 metre long. An appropriate \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 so the temperature does not vary with $y$. Thus the domain 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.
153  \begin{verbatim}  \begin{python}
154  #Domain related.  #Domain related.
155  mx = 1*m #meters - model length  mx = 1*m #meters - model length
156  my = .1*m #meters - model width  my = .1*m #meters - model width
157  ndx = 100 # mesh steps in x direction  ndx = 100 # mesh steps in x direction
158  ndy = 1 # mesh steps in y direction - one dimension means one element  ndy = 1 # mesh steps in y direction - one dimension means one element
159  \end{verbatim}  \end{python}
160  The material constants and the temperature variables must also be defined. For the iron rod in the model they are defined as:  The material constants and the temperature variables must also be defined. For the iron rod in the model they are defined as:
161  \begin{verbatim}  \begin{python}
162  #PDE related  #PDE related
163  q=200. * Celsius #Kelvin - our heat source temperature  q=200. * Celsius #Kelvin - our heat source temperature
164  Tref = 0. * Celsius #Kelvin - starting temp of iron bar  Tref = 0. * Celsius #Kelvin - starting temp of iron bar
# Line 166  rho = 7874. *kg/m**3 #kg/m^{3} density o Line 166  rho = 7874. *kg/m**3 #kg/m^{3} density o
166  cp = 449.*J/(kg*K) #j/Kg.K thermal capacity  cp = 449.*J/(kg*K) #j/Kg.K thermal capacity
167  rhocp = rho*cp  rhocp = rho*cp
168  kappa = 80.*W/m/K #watts/m.Kthermal conductivity  kappa = 80.*W/m/K #watts/m.Kthermal conductivity
169  \end{verbatim}  \end{python}
170  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:  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:
171  \begin{verbatim}  \begin{python}
172  t=0 #our start time, usually zero  t=0 #our start time, usually zero
173  tend=5.*minute #seconds - time to end simulation  tend=5.*minute #seconds - time to end simulation
174  outputs = 200 # number of time steps required.  outputs = 200 # number of time steps required.
# Line 178  print "Expected Number of time outputs i Line 178  print "Expected Number of time outputs i
178  i=0 #loop counter  i=0 #loop counter
179  #the folder to put our outputs in, leave blank "" for script path  #the folder to put our outputs in, leave blank "" for script path
180  save_path="data/onedheatdiff001"  save_path="data/onedheatdiff001"
181  \end{verbatim}  \end{python}
182  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:  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:
183  \begin{verbatim}  \begin{python}
184  #generate domain using rectangle  #generate domain using rectangle
185  rod = Rectangle(l0=mx,l1=my,n0=ndx, n1=ndy)  rod = Rectangle(l0=mx,l1=my,n0=ndx, n1=ndy)
186  \end{verbatim}  \end{python}
187  \verb rod  now describes a domain in the manner of Section \ref{ss:domcon}. As we define our variables, various function spaces will be created to accomodate them. There is an easy way to extract finite points from the domain \verb|rod| using the 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;  \verb rod  now describes a domain in the manner of Section \ref{ss:domcon}. As we define our variables, various function spaces will be created to accomodate them. There is an easy way to extract finite points from the domain \verb|rod| using the 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;
188  \begin{verbatim}  \begin{python}
189  #extract finite points - the solution points  #extract finite points - the solution points
190  x=rod.getX()  x=rod.getX()
191  \end{verbatim}  \end{python}
192  The data locations of specific function spaces can be returned in a similar manner by extracting the relevent function space from the domain followed by the \verb .getX()  operator.  The data locations of specific function spaces can be returned in a similar manner by extracting the relevent function space from the domain followed by the \verb .getX()  operator.
193
194  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 \ESCRIPT. 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.  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.
195  \begin{verbatim}  \begin{python}
196  mypde=LinearSinglePDE(rod)  mypde=LinearSinglePDE(rod)
197  mypde.setValue(A=kappa*kronecker(rod),D=rhocp/h)  mypde.setValue(A=kappa*kronecker(rod),D=rhocp/h)
198  \end{verbatim}  \end{python}
199
200  In a few special cases it may be possible to decrease the computational time of the solver if our PDE is symmetric. Symmetry of a PDE is defined by;  In a few special cases it may be possible to decrease the computational time of the solver if our PDE is symmetric. Symmetry of a PDE is defined by;
201  \label{eqn:symm}  \label{eqn:symm}
202  A\hackscore{jl}=A\hackscore{lj}  A\hackscore{jl}=A\hackscore{lj}
203
204  Symmetry is only dependent on the $A$ coefficient in the general form and the others $D$ and $d$ as well as the RHS coefficients $Y$ and $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;  Symmetry is only dependent on the $A$ coefficient in the general form and the others $D$ and $d$ as well as the RHS coefficients $Y$ and $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;
205  \begin{verbatim}  \begin{python}
206   myPDE.setSymmetryOn()   myPDE.setSymmetryOn()
207  \end{verbatim}  \end{python}
208
209  We now need to specify our boundary conditions and initial values. The initial values required to solve this PDE are temperatures for each discrete point in our domain. We will set our bar to:  We now need to specify our boundary conditions and initial values. The initial values required to solve this PDE are temperatures for each discrete point in our domain. We will set our bar to:
210  \begin{verbatim}  \begin{python}
211   T = Tref   T = Tref
212  \end{verbatim}  \end{python}
213  Boundary conditions are a little more difficult. Fortunately the escript solver will handle our insulated boundary conditions by default with a zero flux operator. However, we will need to apply our heat source $q_{H}$ to the end of the bar at $x=0$ . \ESCRIPT makes this easy by letting us define areas in our domain. The finite points in the domain were previously defined as \verb x  and it is possible to set all of points that satisfy $x=0$ to \verb q  via the \verb whereZero()  function. There are a few \verb where  functions available in \ESCRIPT. They will return a value \verb 1  where they are satisfied and \verb 0  where they are not. In this case our \verb qH  is only applied to the far LHS of our model as required.  Boundary conditions are a little more difficult. Fortunately the escript solver will handle our insulated boundary conditions by default with a zero flux operator. However, we will need to apply our heat source $q_{H}$ to the end of the bar at $x=0$ . \esc makes this easy by letting us define areas in our domain. The finite points in the domain were previously defined as \verb x  and it is possible to set all of points that satisfy $x=0$ to \verb q  via the \verb whereZero()  function. There are a few \verb where  functions available in \esc. They will return a value \verb 1  where they are satisfied and \verb 0  where they are not. In this case our \verb qH  is only applied to the far LHS of our model as required.
214  \begin{verbatim}  \begin{python}
215  # ... set heat source: ....  # ... set heat source: ....
216  qH=q*whereZero(x[0])  qH=q*whereZero(x[0])
217  \end{verbatim}  \end{python}
218
219  Finally we will initialise an iteration loop to solve our PDE for all the time steps we specified in the variable section. As the RHS 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 timestep is \verb T  the heat distribution and \verb totT  the total heat in the system.  Finally we will initialise an iteration loop to solve our PDE for all the time steps we specified in the variable section. As the RHS 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 timestep is \verb T  the heat distribution and \verb totT  the total heat in the system.
220  \begin{verbatim}  \begin{python}
221  while t<=tend:  while t<=tend:
222      i+=1 #increment the counter      i+=1 #increment the counter
223      t+=h #increment the current time      t+=h #increment the current time
224      mypde.setValue(Y=qH+rhocp/h*T) #set variable PDE coefficients      mypde.setValue(Y=qH+rhocp/h*T) #set variable PDE coefficients
225      T=mypde.getSolution() #get the PDE solution      T=mypde.getSolution() #get the PDE solution
226      totT = rhocp*T #get the total heat solution in the system      totT = rhocp*T #get the total heat solution in the system
227  \end{verbatim}  \end{python}
228
229  \subsection{Plotting the heat solutions}  \subsection{Plotting the heat solutions}
230  Visualisation of the solution can be achieved using \mpl a module contained with \pylab. We start by modifying our solution script from before. 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 it is necessary to convert \verb x  to a list of tuples. These are then converted to a \numpy array and the $x$ locations extracted via an array slice to the variable \verb plx  .  Visualisation of the solution can be achieved using \mpl a module contained with \pylab. We start by modifying our solution script from before. 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 it is necessary to convert \verb x  to a list of tuples. These are then converted to a \numpy array and the $x$ locations extracted via an array slice to the variable \verb plx  .
231  \begin{verbatim}  \begin{python}
232  #convert solution points for plotting  #convert solution points for plotting
233  plx = x.toListOfTuples()  plx = x.toListOfTuples()
234  plx = np.array(plx) #convert to tuple to numpy array  plx = np.array(plx) #convert to tuple to numpy array
235  plx = plx[:,0] #extract x locations  plx = plx[:,0] #extract x locations
236  \end{verbatim}  \end{python}
237  As there are two solution outputs, we will generate two plots and save each to a file for every time step in the solution. The following is appended to the end of the \verb while  loop and creates two figures. The first figure is for the temperature distribution, and the second the total temperature in the bar. Both cases are similar with a few minor changes for scale and labelling. We start by converting the solution to a tuple and then plotting this against our \textit{x coordinates} \verb plx  from before. The axis is then standardised and a title applied. The figure is then saved to a *.png file and cleared for the following iteration.  As there are two solution outputs, we will generate two plots and save each to a file for every time step in the solution. The following is appended to the end of the \verb while  loop and creates two figures. The first figure is for the temperature distribution, and the second the total temperature in the bar. Both cases are similar with a few minor changes for scale and labelling. We start by converting the solution to a tuple and then plotting this against our \textit{x coordinates} \verb plx  from before. The axis is then standardised and a title applied. The figure is then saved to a *.png file and cleared for the following iteration.
238  \begin{verbatim}  \begin{python}
239      #establish figure 1 for temperature vs x plots      #establish figure 1 for temperature vs x plots
240      tempT = T.toListOfTuples(scalarastuple=False)      tempT = T.toListOfTuples(scalarastuple=False)
241      pl.figure(1) #current figure      pl.figure(1) #current figure
# Line 255  As there are two solution outputs, we wi Line 255  As there are two solution outputs, we wi
255      pl.title("Total temperature accross Rod")      pl.title("Total temperature accross Rod")
256      pl.savefig(os.path.join(save_path+"/totT","ttrodpyplot%03d.png")%i)      pl.savefig(os.path.join(save_path+"/totT","ttrodpyplot%03d.png")%i)
257      pl.clf()      pl.clf()
258  \end{verbatim}  \end{python}
259  \begin{figure}  \begin{figure}
260  \begin{center}  \begin{center}
261  \includegraphics[width=4in]{figures/ttrodpyplot150}  \includegraphics[width=4in]{figures/ttrodpyplot150}
# Line 267  As there are two solution outputs, we wi Line 267  As there are two solution outputs, we wi
267  \subsubsection{Parallel scripts (MPI)}  \subsubsection{Parallel scripts (MPI)}
268  In some of the example files for this cookbook the plot part of the script looks a little different.  In some of the example files for this cookbook the plot part of the script looks a little different.
269  For example,  For example,
270  \begin{verbatim}  \begin{python}
271      pl.title("Total temperature accross Rod")      pl.title("Total temperature accross Rod")
272      if getMPIRankWorld() == 0:      if getMPIRankWorld() == 0:
273          pl.savefig(os.path.join(save_path+"/totT","ttrodpyplot%03d.png")%i)          pl.savefig(os.path.join(save_path+"/totT","ttrodpyplot%03d.png")%i)
274      pl.clf()          pl.clf()
275  \end{verbatim}  \end{python}
276
277  The additional \verb if  statement is not necessary for normal desktop use.  The additional \verb if  statement is not necessary for normal desktop use.
278  It becomes important for scripts run on parallel computers.  It becomes important for scripts run on parallel computers.
# Line 281  For more details on writing scripts for Line 281  For more details on writing scripts for
281
282  \subsection{Make a video}  \subsection{Make a video}
283  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.  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.
284  \begin{verbatim}  \begin{python}
285  # compile the *.png files to create two *.avi videos that show T change  # compile the *.png files to create two *.avi videos that show T change
286  # with time. This operation uses linux mencoder. For other operating  # with time. This operation uses linux mencoder. For other operating
287  # systems it is possible to use your favourite video compiler to  # systems it is possible to use your favourite video compiler to
# Line 294  onedheatdiff001tempT.avi") Line 294  onedheatdiff001tempT.avi")
294  os.system("mencoder mf://"+save_path+"/totT"+"/*.png -mf type=png:\  os.system("mencoder mf://"+save_path+"/totT"+"/*.png -mf type=png:\
295  w=800:h=600:fps=25 -ovc lavc -lavcopts vcodec=mpeg4 -oac copy -o \  w=800:h=600:fps=25 -ovc lavc -lavcopts vcodec=mpeg4 -oac copy -o \
296  onedheatdiff001totT.avi")  onedheatdiff001totT.avi")
297  \end{verbatim}  \end{python}
298

Legend:
 Removed from v.2681 changed lines Added in v.2775