Minimal example: Laplace equation

PyFreeFEM is designed to be intuitive to use. This page explains how to write simple comprehensive code for solving the Laplace equation in FreeFEM, and then how to retrieve and to plot the solution in Python.

Example script

Let us consider the following .edp script from the examples folder for solving the following Laplace equation on the unit square \(\Omega\):

\[\begin{split}\left\{\begin{aligned} -\Delta u & = 1 \text{ in } \Omega,\\ u &= 0 \text{ on }\partial \Omega. \end{aligned}\right.\end{split}\]
examples/edp/ex15.edp
IMPORT "io.edp"

DEFAULT (N,10)
mesh Th = square($N,$N);
fespace Fh1(Th,P1);

Fh1 u, v;

func f=1;
solve laplace(u,v) = int2d(Th)(dx(u)*dx(v)+dy(u)*dy(v))      
                    -int2d(Th)(f*v) 
                    +on(1,2,3,4,u=0);

exportMesh(Th);
exportArray(u[]);

The following python script runs this .edp file and plot the solution with matplotlib:

examples/ex15_laplace.py
from pyfreefem import FreeFemRunner
from pymedit import P1Function

exports = FreeFemRunner("edp/ex15.edp").execute({'N':40})
u = P1Function(exports['Th'],exports['u[]'])

u.plot(title="u")

Running

console
python ex15_laplace.py

yields the following figure:

solution to laplace equation plotted with pymedit
A matplotlib plot of the solution to the Laplace equation computed with FreeFEM

Detailed comments

The edp/ex15.edp script includes the following special preprocessing directives for communicating with Python:

  • IMPORT:

    freefem
    IMPORT "io.edp"
    

    This imports the FreeFEM macro pyfreefem/edp/io.edp file that define the macros exportMesh and exportArray.

  • Magic variable $N:

    freefem
    DEFAULT (N,10)
    mesh Th = square($N,$N);
    

    This variable is automatically assigned when executing the .edp script from Python with the method execute(). Thanks to the DEFAULT instruction, $N will be set to 10 if not specified during the execution. The dollar $ symbol is used in the .edp script whenever the magic variable needs to be textually substituted with its value.

The python script ex15_laplace.py executes ex15_laplace.py by setting $N to 40. The output variables are contained in the dictionary exports which captures the data that have been passed in the .edp script with exportMesh and exportArray. exports['Th'] is an instance of the Mesh class implemented in the pymedit module.

More details about PyFreeFEM special instructions, imports and exports are given in the following sections: