24
$\begingroup$

Laplace's Equation is an equation on a scalar in which, given the value of the scalar on the boundaries (the boundary conditions), one can determine the value of the scalar at any point in the region within the boundaries.

Initially, I considered using NDSolve, but I realized that I did not know how to specify the boundary conditions properly. In the example below, my boundary is a square with value 0 along the top, left and right boundary and 1 along the bottom boundary.

Alternatively, the solutions to the equation can be approximated via the Method of Relaxation. In the method, the region is divided into a grid, with the grid squares along the boundary being assigned (fixed) boundary conditions, and the value for the grid squares within the boundary being iteratively calculated by assigning the average values (in the previous time-step) of four grid squares adjacent to it.

My current code is as follows

localmeaner = 
  Mean@{#1[[#2 - 1, #3]], #1[[#2 + 1, #3]], #1[[#2, #3 - 1]], #1[[#2, #3 + 1]]} &;

relaxer = ({#[[1]]}~Join~
     Table[
      {#[[j, 1]]}~Join~
       Table[localmeaner[#, j, i], {i, 2, Dimensions[#][[2]] - 1} ]~
       Join~{#[[j, Dimensions[#][[2]]]]}, {j, 2, 
       Dimensions[#][[1]] - 1}]~Join~{#[[Dimensions[#][[1]]]]}) &;

matrixold = Append[ConstantArray[0, {41, 40}], ConstantArray[1, 40]]; (*test matrix fixing the boundary conditions as 0 on the top, left and right boundaries and 1 on the bottom boundary*)

tempmatrix = Nest[relaxer, matrixold, 300]; (*matrix after 300 relaxations*)

localmeaner is a function that takes the average of the four grid squares adjacent to a square.

relaxer is a function that preserves the boundary values but otherwise applies localmeaner onto each of the grid cells to produce their new values based on the average of the four grid cells adjacent to it.

Is there a quicker way to find a numerical solution to the Laplace's Equation given specific boundary conditions?

As a point of interest, one can plot the solution as ArrayPlot[tempmatrix*1., ColorFunction -> "Rainbow"], resulting in the following image, which helps one to visualize the results.

enter image description here

NB: I'm planning to extend this solution to approximations that can work in polar coordinates, Cartesian coordinates in three dimensions and spherical coordinates, so I'm hoping that the answers could be equally general.

$\endgroup$
9
  • $\begingroup$ Take a look here. $\endgroup$
    – swish
    Apr 19, 2013 at 10:54
  • $\begingroup$ Too bad! So since the documentation states that "This rules out purely elliptic equations such as Laplace's equation, but leaves a large class of evolution equations that can be solved quite efficiently.", I'd have to continue to work using my method? $\endgroup$ Apr 19, 2013 at 11:01
  • $\begingroup$ I posted a pretty flexible relaxation solver for the Poisson equation here. The Laplace equation is a special case of that. Maybe you can use it for your problem. $\endgroup$
    – Jens
    Apr 19, 2013 at 17:00
  • $\begingroup$ @Jens thank you! have you ever tried to write code that works for the Poisson equation in three dimensions, in particular in spherical coordinates? I was hoping that I could modify your code to do so, but haven't figured out a way yet. $\endgroup$ Apr 20, 2013 at 4:20
  • $\begingroup$ I haven't extended it to three dimensions. The first thing one might try is to do a cylindrically symmetric 3D problem in cylinder coordinates, where the radial derivative is modified to $\frac{1}{r}\frac{\partial}{\partial r}\left(r\,\frac{\partial f}{\partial r}\right)$ but can still be discretized. But fully 3D calculations aren't just tricky, they may quickly become impractical for Mathematica. It depends on the application, I guess, but I'd go straight to FORTRAN. $\endgroup$
    – Jens
    Apr 20, 2013 at 19:06

2 Answers 2

29
$\begingroup$

Here is a code that is about 2 orders of magnitude faster. We will use a finite element method to solve the issue at hand. Before we start, note however, that the transition between the Dirichlet values should be smooth.

We use the finite element method because that works for general domains and some meshing utilities exist here and in the links there in. For 3D you can use the build in TetGenLink.

For your rectangular domain, we just create the coordinates and incidences by hand:

<< Developer`
nx = ny = 4;
coordinates = 
  Flatten[Table[{i, j}, {i, 0., 1., 1/(ny - 1)}, {j, 0., 1., 
     1/(nx - 1)}], 1];
incidents = 
  Flatten[Table[{j*nx + i, 
     j*nx + i + 1, (j - 1)*nx + i + 1, (j - 1)*nx + i}, {i, 1, 
     nx - 1}, {j, 1, ny - 1}], 1];

(* triangulate the quad incidences *)
incidents = 
  ToPackedArray[
   incidents /. {i1_?NumericQ, i2_, i3_, i4_} :> 
     Sequence[{i1, i2, i3}, {i3, i4, i1}]];

Graphics[GraphicsComplex[
  coordinates, {EdgeForm[Gray], FaceForm[], Polygon[incidents]}]]

enter image description here

Now, we create the finite element symbolically and compile that:

tmp = Join[ {{1, 1, 1}}, 
   Transpose[Quiet[Array[Part[var, ##] &, {3, 2}]]]];
me = {{0, 0}, {1, 0}, {0, 1}};
p = Inverse[tmp].me;
help = Transpose[ (p.Transpose[p])*Abs[Det[tmp]]/2];

diffusion2D = 
  With[{code = help}, 
   Compile[{{coords, _Real, 2}, {incidents, _Integer, 1}}, Block[{var},
     var = coords[[incidents]];
     code
     ]
    , RuntimeAttributes -> Listable
    (*,CompilationTarget\[Rule]"C"*)]];

AbsoluteTiming[allElements = diffusion2D[coordinates, incidents];]

You can not do this in FORTRAN! For this specific problem the element contributions are all the same, so that could be utilized, but since you wanted a somewhat more general approach I am leaving it as it is.

To assemble the elements into a system matrix:

matrixAssembly[ values_, pos_, dim_] := Block[{matrix, p},
  System`SetSystemOptions[ 
   "SparseArrayOptions" -> {"TreatRepeatedEntries" -> 1}];
  matrix = SparseArray[ pos -> Flatten[ values], dim];
  System`SetSystemOptions[ 
   "SparseArrayOptions" -> {"TreatRepeatedEntries" -> 0}];
  Return[ matrix]]

pos = Compile[{{inci, _Integer, 2}}, 
    Flatten[Map[Outer[List, #, #] &, inci], 2]][incidents];

dofs = Max[pos];

AbsoluteTiming[
 stiffness = matrixAssembly[ allElements, pos, dofs] ]

The last part that is missing are the Dirichlet conditions. We modify the system matrix in place for that:

SetAttributes[dirichletBoundary, HoldFirst]
dirichletBoundary[ {load_, matrix_}, fPos_List, fValue_List] := 
 Block[{},
  load -= matrix[[All, fPos]].fValue;
  load[[fPos]] = fValue;
  matrix[[All, fPos]] = matrix[[fPos, All]] = 0.;
  matrix += SparseArray[ 
    Transpose[ {fPos, fPos}] -> Table[ 1., {Length[fPos]}], 
    Dimensions[matrix], 0];
  ]

load = Table[ 0., {dofs}];
diriPos1 = Position[coordinates, {_, 0.}];
diriVals1 = Table[1., {Length[diriPos1]}];
diriPos2 = 
  Position[coordinates, ({_, 
      1.} | {1., _?(# > 0 &)} | {0., _?(# > 0 &)})];
diriVals2 = Table[0., {Length[diriPos2]}];
diriPos = Flatten[Join[diriPos1, diriPos2]];
diriVals = Join[diriVals1, diriVals2];
dirichletBoundary[{load, stiffness}, diriPos, diriVals]
AbsoluteTiming[ 
 solution = LinearSolve[ stiffness, load(*, Method\[Rule]"Krylov"*)]; ]

When I use your code on my laptop it has about 1600 quads and takes about 6 seconds. When I run this code with nx = ny = 90; (which gives about 16000 triangles) it runs in about 0.05 seconds. Note that the element computation and matrix assembly take less time than the LinearSolve. That's the way things should be. The result can be visualized:

Graphics[GraphicsComplex[coordinates, Polygon[incidents], 
  VertexColors -> 
   ToPackedArray@(List @@@ (ColorData["Rainbow"][#] & /@ 
        solution))]]

enter image description here

For the 3D case have a look here.

Hope this helps.

$\endgroup$
9
  • $\begingroup$ There are so many nice tricks in here... (+1). To make this code easier to study, I think it will be good to add a link to this page: What are some useful, undocumented Mathematica functions? $\endgroup$
    – Jens
    Apr 23, 2013 at 23:42
  • $\begingroup$ @Jens, I am glad you like it. $\endgroup$
    – user21
    Apr 24, 2013 at 5:41
  • $\begingroup$ @ruebenko this is great! I was looking through some of the documentation for other Laplace / Poisson equation solvers on the Mathematica site but was having trouble understanding them. Thank you for taking the time to explain your solution in detail. $\endgroup$ Apr 25, 2013 at 1:33
  • 1
    $\begingroup$ By the way, just out of curiosity, did you already have a solution to this problem before or did you code this from scratch? $\endgroup$ Apr 25, 2013 at 1:34
  • $\begingroup$ @VincentTjeng, well I had the 3D version from a talk I gave and then had some other notebooks with experiments. Also, I worked a lot with FEM during my thesis. You may also want to read this. $\endgroup$
    – user21
    Apr 25, 2013 at 6:14
5
$\begingroup$

We all know FEM has been implemented in NDSolve since v10 and solving Laplace equation with Mathematica is no longer a problem. Still, I'd like to post this answer solving Laplace equation with FDM, as an illustration for the usage of pdetoae (a function that discretizes differential equations to algebraic equations, its definition can be found here).

xpoints = 90;
ypoints = 90;
{xl, xr} = xdomain = {0, 1};
{yl, yr} = ydomain = {0, 1};
xgrid = Array[# &, xpoints, xdomain];
ygrid = Array[# &, ypoints, ydomain];
difforder = 2;

eqn = D[u[x, y], {x, 2}] + D[u[x, y], {y, 2}] == 0;
bc = {u[xl, y] == 0, u[xr, y] == 0, u[x, yl] == 1, u[x, yr] == 0};

var = Flatten@Outer[u, xgrid, ygrid];

(* Definition of pdetoae isn't included in this code piece,
   please find it in the link above *)
ptoa = pdetoae[u[x, y], {xgrid, ygrid}, difforder];
del = Delete[#, {{1}, {-1}}] &;

ae = del /@ del@ptoa@eqn; // AbsoluteTiming
bcae = MapAt[del, ptoa@bc, {{1}, {2}}];

{b, mat} = CoefficientArrays[{ae, bcae} // Flatten, var]; // AbsoluteTiming
sollst = LinearSolve[N@mat, -b]; // AbsoluteTiming

sol = ListInterpolation[ArrayReshape[sollst, {xpoints, ypoints}], {xgrid, ygrid}];

Plot3D[sol[x, y], {x, xl, xr}, {y, yl, yr}, ColorFunction -> "Rainbow"]

(* {0.331821, Null} *)
(* {0.100300, Null} *)
(* {0.081133, Null} *)

Mathematica graphics

This method is no more than half as fast as user21's method above, but easier to extend to "polar coordinates, Cartesian coordinates in three dimensions and spherical coordinates". We can also easily obtain a solution with higher accuracy by raising the difference order i.e. difforder. Of course all these self-implementations aren't necessary nowadays :) .

$\endgroup$
2
  • $\begingroup$ @ xzczd : Sorry, it cannot be reproduced on my comp dropbox.com/s/vz15ubuam6nkaeu/Dirichlet.pdf?dl=0 $\endgroup$
    – user64494
    Oct 23, 2016 at 11:29
  • $\begingroup$ @user64494 As mentioned in the answer, this solution uses the function pdetoae, its definition can be found in the link above. $\endgroup$
    – xzczd
    Oct 23, 2016 at 11:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.