⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 quickstart.tex

📁 Dolfin provide a high-performance linear algebra library
💻 TEX
字号:
\chapter{Quickstart}\label{chap:quickstart}\index{quickstart}This chapter demonstrates how to get started with \dolfin{}, includingdownloading and installing the latest version of \dolfin{}, and solvingPoisson's equation. These topics are discussed in more detailelsewhere in this manual. In particular, seeAppendix~\ref{app:installation} for detailed installation instructionsand Chapter~\ref{sec:pde} for a detailed discussion of how to solvepartial differential equations with \dolfin{}.%------------------------------------------------------------------------------\section{Downloading and installing \dolfin{}}\index{downloading}\index{installation}The latest version of \dolfin{} can be found on the \fenics{} web page:\begin{code}http://www.fenics.org/\end{code}The following commands illustrate the installation process, assumingthat you have downloaded release x.y.z of \dolfin{}:\begin{code}# tar zxfv dolfin-x.y.z.tar.gz# cd dolfin-x.y.z# ./configure# make# sudo make install\end{code}Since \dolfin{} depends on a number of other packages, you may alsoneed to download and install those packages before you can compile\dolfin{}.  (See Appendix~\ref{app:installation} for detailedinstructions.)%------------------------------------------------------------------------------\section{Solving Poisson's equation with \dolfin{}}\index{Poisson's equation}Let's say that we want to solve Poisson's equation on the unit square$\Omega = (0,1) \times (0,1)$ with homogeneous Dirichlet boundaryconditions on the boundary $\Gamma_0 = \{(x, y) \in \partial \Omega : x = 0\}$,the Neumann boundary condition $\partial_n u = g$ with $g(x, y) = 25 \sin(5\pi y)$on the boundary $\Gamma_1 = \{(x, y) \in \partial \Omega : x = 1\}$,homogeneous Neumann boundary conditions on the remaining part of the boundaryand right-hand side given by $f(x, y) = 500 \exp(-((x-0.5)^2 +(y-0.5)^2)/0.02)$:\begin{eqnarray} \label{eq:poisson,quickstart}  - \Delta u(x, y) &=& f(x, y), \quad  x \in \Omega = (0,1) \times (0,1), \\  u(x, y) &=& 0, \quad  (x, y) \in \Gamma_0 = \{(x, y) \in \partial \Omega : x = 0\}, \\  \partial_n u(x, y) &=& 1, \quad  (x, y) \in \Gamma_1 = \{(x, y) \in \partial \Omega : x = 1\}, \\  \partial_n u(x, y) &=& 0, \quad  (x, y) \in \partial \Omega \setminus (\Gamma_0 \cup \Gamma_1).\end{eqnarray}% FIXME: Explain this betterTo solve a partial differential equation with \dolfin{}, it must firstbe rewritten in \emph{variational form}.  The (discrete) variationalformulation of Poisson's equation reads: Find $u_h \in V_h$ such that\begin{equation} \label{eq:varform}  a(v, u_h) = L(v) \quad \forall v\in \hat{V}_h, \end{equation}with $(\hat{V}_h, V_h)$ a pair of suitable discrete function spaces(the test and trial spaces). The bilinear form $a : \hat{V}_h \times V_h\rightarrow \R$ is given by\begin{equation}  a(v, u_h) = \int_{\Omega} \nabla v \cdot \nabla u_h \dx\end{equation}and the linear form $L : \hat{V}_h \rightarrow \R$ is given by\begin{equation}  L(v) = \int_{\Omega} v f \dx + \int_{\partial \Omega} v g \ds,\end{equation}where $g = \partial_n u$ is the Neumann boundary condition.\subsection{Setting up the variational formulation}\index{ffc}The variational formulation (\ref{eq:varform}) must be given to\dolfin{} as a pair of bilinear and linear forms $(a, L)$ using theform compiler \ffc{}. This is done by entering the definition ofthe forms in a text file with extension \texttt{.form},e.g. \texttt{Poisson.form}, as follows:\begin{code}element = FiniteElement("Lagrange", "triangle", 1)v = TestFunction(element)u = TrialFunction(element)f = Function(element)g = Function(element)a = dot(grad(v), grad(u))*dxL = v*f*dx + v*g*ds\end{code}The example is given here for piecewise linear finite elements in twodimensions, but other choices are available, including arbitrary orderLagrange elements in two and three dimensions.To compile the pair of forms $(a, L)$, now call the form compiler onthe command-line as follows:\begin{code}# ffc -l dolfin Poisson.form\end{code}This generates the file \texttt{Poisson.h} which implements the formsin C++ for inclusion in your \dolfin{} program.\subsection{Writing the solver}Having compiled the variational formulation (\ref{eq:varform})with \ffc{}, it is now easy to implement a solver for Poisson'sequation. We first discuss the implementation line by line and thenpresent the complete program. The source code for this example isavailable in the directory \texttt{src/demo/pde/poisson/} of the \dolfin{}source tree.At the beginning of our C++ program, which we write in a text filenamed \texttt{main.cpp}, we must first include the header file\texttt{dolfin.h}, which gives our program access to the \dolfin{}class library. In addition, we include the header file\texttt{Poisson.h} generated by the form compiler. Since all classesin the \dolfin{} class library are defined within the namespace\texttt{dolfin}, we also specify that we want to work within thisnamespace:\begin{code}#include <dolfin.h>#include "Poisson.h"  using namespace dolfin;\end{code}Since we are writing a C++ program, we need to create a \texttt{main}function.  You are free to organize your program any way you like, butin this simple example we just write our program inside the\texttt{main} function:\begin{code}int main(){  // Write your program here  return 0;}\end{code}We now proceed to specify the right-hand side $f$ of(\ref{eq:poisson,quickstart}). This is done by defining a new subclassof \texttt{Function} (which we here name \texttt{Source}) andoverloading the \texttt{eval()} function to return the value $f(x, y)= 500 \exp(-((x-0.5)^2 + (y-0.5)^2)/0.02)$:\begin{code}class Source : public Function{public:      Source(Mesh& mesh) : Function(mesh) {}  real eval(const real* x) const  {    real dx = x[0] - 0.5;    real dy = x[1] - 0.5;    return 500.0*exp(-(dx*dx + dy*dy)/0.02);  }};\end{code}The function $g$ for the Neumann boundary condition is specifiedsimilarly:\begin{code}class Flux : public Function{public:  Flux(Mesh& mesh) : Function(mesh) {}  real eval(const real* x) const  {    if (x[0] > DOLFIN_EPS)      return 25.0*sin(5.0*DOLFIN_PI*x[1]);    else      return 0.0;  }};\end{code}Note that we here extend $g$ to the entire boundary by setting $g = 0$on $\Omega \setminus \Gamma_1$. It is also possible to define $g$ onlyon $\Gamma_1$ and specify an integral over the boundary subset$\Gamma_1$ in the form file.To define the Dirichlet boundary condition, we define a\texttt{SubDomain} for the Dirichlet boundary:\begin{code}class DirichletBoundary : public SubDomain{  bool inside(const real* x, bool on_boundary) const  {    return x[0] < DOLFIN_EPS && on_boundary;  }};\end{code}Next, we need to create a mesh. \dolfin{} relies on external programsfor mesh generation, and imports meshes in \dolfin{} XMLformat. Meshes in other formats can be converted to the \dolfin{} XMLformat using the script \texttt{dolfin-convert}. However, for simpledomains like the unit square or unit cube, \dolfin{} provides abuilt-in mesh generator. To generate a uniform mesh of the unit squarewith mesh size $1/32$ (with a total of $2\cdot 32^2 = 2048$triangles), we can just type\begin{code}UnitSquare mesh(32, 32);\end{code}We may now instantiate the right-hand side function \texttt{f} and theNeumann boundary condition \texttt{g} as follows:\begin{code}Source f(mesh);Flux g(mesh);\end{code}Next, we define the Dirichlet boundary condition by specifying thevalue that the solution should take and the subset of the boundarywhere it should be applied:\begin{code}Function u0(mesh, 0.0);DirichletBoundary boundary;DirichletBC bc(u0, mesh, boundary);\end{code}Note the difference in how Dirichlet and Neumann boundary conditionsare applied. The Dirichlet condition is applied here strongly (but itcan also be applied weakly) using the \texttt{DirichletBC} class,while the Neumann boundary condition is defined as part of thevariational problem. (It is a \emph{natural} boundary condition forthis variational formulation of Poisson's equation.)Next, we initialize the pair of bilinear and linear forms that we havepreviously compiled with \ffc{} and define a \texttt{LinearPDE} as thevariational problem defined by the two forms and the Dirichletboundary condition:\begin{code}PoissonBilinearForm a;PoissonLinearForm L(f, g);LinearPDE pde(a, L, mesh, bc);\end{code}Note that the right-hand side~\texttt{f} and the Neumann boundarycondition~\texttt{g} need to be given as arguments to the constructorof the linear form, since the linear form depends on these twofunctions.We may now solve the PDE and obtain the solution as a \texttt{Function}:\begin{code}Function u;pde.solve(u);\end{code}To plot the solution, one may simply type\begin{code}plot(u);\end{code}This requires the installation of PyDOLFIN and Viper. (A warning willbe issued if plotting is not available.)Finally, we export the solution \texttt{u} to a file forvisualization. Here, we choose to save the solution in VTK format forvisualization in ParaView or MayaVi, which we do by specifying a filename with extension \texttt{.pvd}:\begin{code}File file("poisson.pvd");file << u;\end{code}The complete program for Poisson's equation now looks as follows:\small\begin{code}#include <dolfin.h>#include "Poisson.h"  using namespace dolfin;int main(){  // Source term  class Source : public Function  {  public:        Source(Mesh& mesh) : Function(mesh) {}    real eval(const real* x) const    {      real dx = x[0] - 0.5;      real dy = x[1] - 0.5;      return 500.0*exp(-(dx*dx + dy*dy)/0.02);    }  };  // Neumann boundary condition  class Flux : public Function  {  public:    Flux(Mesh& mesh) : Function(mesh) {}    real eval(const real* x) const    {      if (x[0] > DOLFIN_EPS)        return 25.0*sin(5.0*DOLFIN_PI*x[1]);      else        return 0.0;    }  };  // Sub domain for Dirichlet boundary condition  class DirichletBoundary : public SubDomain  {    bool inside(const real* x, bool on_boundary) const    {      return x[0] < DOLFIN_EPS && on_boundary;    }  };  // Create mesh  UnitSquare mesh(32, 32);  // Create functions  Source f(mesh);  Flux g(mesh);  // Create boundary condition  Function u0(mesh, 0.0);  DirichletBoundary boundary;  DirichletBC bc(u0, mesh, boundary);    // Define PDE  PoissonBilinearForm a;  PoissonLinearForm L(f, g);  LinearPDE pde(a, L, mesh, bc);  // Solve PDE  Function u;  pde.solve(u);  // Plot solution  plot(u);  // Save solution to file  File file("poisson.pvd");  file << u;  return 0;}\end{code}\normalsize\subsection{Compiling the program}The easiest way to compile the program is to create a\texttt{Makefile} that tells the standard Unix command \texttt{make}how to build the program. The following example shows how to write a\texttt{Makefile} for the above example:\footnotesize\begin{code}CFLAGS  = `pkg-config --cflags dolfin`LIBS    = `pkg-config --libs dolfin`CXX     = `pkg-config --variable=compiler dolfin`DEST    = demoOBJECTS = main.oall: $(DEST)install:clean:	-rm -f *.o core *.core $(OBJECTS) $(DEST)$(DEST): $(OBJECTS)	 $(CXX) -o $@ $(OBJECTS) $(CFLAGS) $(LIBS).cpp.o:	$(CXX) $(CFLAGS) -c $<\end{code}\normalsizeWith the \texttt{Makefile} in place, we just need to type\texttt{make} to compile the program, generating the executable as thefile \texttt{demo}. Note that this requires \texttt{pkg-config} to beable to find the file \texttt{dolfin.pc}. (That file is generated bythe \texttt{configure} script, during the configuration of\dolfin{}. If \texttt{pkg-config} fails to find it, you need to addthe directory containing it to the environment variable\texttt{PKG\_CONFIG\_PATH}.)\subsection{Running the program}To run the program, simply type the name of the executable:\begin{code}# ./demo\end{code}\subsection{Visualizing the solution}The solution may be visualized either by the built-in \texttt{plot()}command or by calling an external application. The built-in plottingrequires the installation of both PyDOLFIN and Viper. In thisexample, we chose to save the solution in VTK format, which can beimported into for example ParaView or MayaVi. The solution may also bevisualized by running the script \texttt{plot.py} available in thePoisson demo directory:\begin{code}python plot.py\end{code}This script also requires the installation of PyDOLFIN and Viper.\begin{figure}[htbp]  \begin{center}    \includegraphics[width=10cm]{eps/poisson.eps}    \caption{The solution of Poisson's equation (\ref{eq:poisson,quickstart})      visualized in MayaVi.}  \end{center}\end{figure}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -