How PyFreeFEM works

PyFreeFEM operates through the FreeFemRunner class which is used to

  1. read .edp scripts from source files or code written in python strings:

    python
    from pyfreefem import FreeFemRunner
    
    # Loading the script "foo.edp"
    runner = FreeFemRunner("foo.edp")
    
    # Loading directly FreeFEM code
    script = """mesh Th=square(10,10);"""
    runner = FreeFemRunner(script)
    
  2. execute .edp scripts with the method execute():

python
# Execute the script
runner.execute()

PyFreeFEM offers a flexible interfacing between FreeFEM and Python by supporting special instructions that can be added in .edp scripts. For instance, the following code which defines a function returning a square mesh with an input number N of boundary elements:

python
from pyfreefem import FreeFemRunner

def square(N):
    code = """
    IMPORT "io.edp"

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

    exportMesh(Th);"""
    runner=FreeFemRunner(code,{'N':N})
    return runner.execute()['Th']

Calling the method execute() does the following steps:

  1. A temporary running directory is created (for instance /tmp/pyfreefem_l2zm1dqj/), which is removed once runner is destroyed.

  2. The code is parsed into a valid .edp file

    freefem run.edp
    include("/tmp/pyfreefem_l2zm1dqj/io.edp")
    mesh Th=square(30,30);
    
    exportMesh(Th);
    

    which is saved to the temporary directory. These parsing operations are achieved with the Preprocessor module.

  3. Macro files such as io.edp are also stored in the temporary directory, as well as imported python data structures.

  4. Finally, the .edp script is executed in a Popen subprocess with the command FreeFEM++.