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\):
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:
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
python ex15_laplace.py
yields the following figure:
Detailed comments¶
The edp/ex15.edp script includes
the following special preprocessing directives for communicating with Python:
IMPORT:
freefemIMPORT "io.edp"This imports the FreeFEM macro pyfreefem/edp/io.edp file that define the macros
exportMeshandexportArray.Magic variable
$N:freefemDEFAULT (N,10) mesh Th = square($N,$N);This variable is automatically assigned when executing the
.edpscript from Python with the methodexecute(). Thanks to theDEFAULTinstruction,$Nwill be set to10if not specified during the execution. The dollar$symbol is used in the.edpscript 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: