PyMFEM icon indicating copy to clipboard operation
PyMFEM copied to clipboard

Defining non-homogeneous dirichlet boundary conditions

Open BBBBBbruce opened this issue 8 months ago • 2 comments

Hi,

I am currently building a simple poisson equation, as in example 1. I am using a unit-square mesh, I want to define all boundary as essential(dirichlet) but the right edge(x=1) to be 0.5. How can I do that? thanks for the help.

the only non-homogeneous example I found is example 17, but I dont understand the syntax. is there a tutorial on how to define the boundary condition?

BBBBBbruce avatar Mar 18 '25 20:03 BBBBBbruce

Take a look at Example 27/27p -- it illustrates the usage of various (non-homogeneous, in general) boundary conditions for the Laplace equation.

Let us know if you need additional clarifications about that.

v-dobrev avatar Mar 21 '25 23:03 v-dobrev

Thanks, I have read the example 27, so the logic to define the boundary condition is first to define the boundary attribute in the mesh. However, I am loading mesh from a predefined gmsh file, where I didnt defined the boundary attributes in advance.

The current solution I am using is to adopted the analytical function definition similar in example 7. The rendered results showed it is all as expected, but I am not sure if I got it correctly or a lucky coincident.

    #g_func is a input function 

    dbc_marker = mfem.intArray(mesh.bdr_attributes.Max())
    dbc_marker.Assign(0)  # Initialize to 0 (no Dirichlet by default)

    # Mark boundaries where Dirichlet BC should apply
    dbc_marker[0] = 1  # Adjust based on actual boundary attributes
    dbc_marker[1] = 1

    # 2️⃣ Define Dirichlet BC function
    if g_func is None:
        g_func = lambda x: 0.0  # Default: u = 0 on the boundary

    class DirichletBC(mfem.PyCoefficient):
        def EvalValue(self, x):
            return g_func(x)

    g_coef = DirichletBC()

    # 3️⃣ Apply Dirichlet BC to the grid function
    x = mfem.GridFunction(fespace)
    x.Assign(0.0)  # Initialize
    x.ProjectBdrCoefficient(g_coef, dbc_marker)  # Enforce BC

    # 4️⃣ Determine essential DOFs for BC enforcement
    ess_tdof_list = mfem.intArray()
    fespace.GetEssentialTrueDofs(dbc_marker, ess_tdof_list)

BBBBBbruce avatar Mar 22 '25 11:03 BBBBBbruce