How to avoid recompilation problem when the parameter's value being changed in for loop

I have a problem with large number of loop, the parameter’s value will be changed for every time, so huge cache files are produced and the compute speed is slowed.

For example, the Possion problem,

from mpi4py import MPI
from petsc4py.PETSc import ScalarType  # type: ignore
import numpy as np
import ufl
from dolfinx import fem, io, mesh, plot
from dolfinx.fem.petsc import LinearProblem
from ufl import ds, dx, grad, inner
msh = mesh.create_rectangle(
    comm=MPI.COMM_WORLD,
    points=((0.0, 0.0), (2.0, 1.0)),
    n=(32, 16),
    cell_type=mesh.CellType.triangle,
)
V = fem.functionspace(msh, ("Lagrange", 1))


facets = mesh.locate_entities_boundary(
    msh,
    dim=(msh.topology.dim - 1),
    marker=lambda x: np.isclose(x[0], 0.0) | np.isclose(x[0], 2.0),
)

dofs = fem.locate_dofs_topological(V=V, entity_dim=1, entities=facets)
bc = fem.dirichletbc(value=ScalarType(0), dofs=dofs, V=V)

u = ufl.TrialFunction(V)
v = ufl.TestFunction(V)
x = ufl.SpatialCoordinate(msh)

g = ufl.sin(5 * x[0])
a = inner(grad(u), grad(v)) * dx
#######################################################################
for lamd in [10,11]:
    f = lamd * ufl.exp(-((x[0] - 0.5) ** 2 + (x[1] - 0.5) ** 2) / 0.02)

    L = inner(f, v) * dx + inner(g, v) * ds

    problem = LinearProblem(a, L, bcs=[bc], petsc_options={"ksp_type": "preonly", "pc_type": "lu"})
    uh = problem.solve()
    print('lamd = ', lamd)

When the values number of parameter lamd is two that will produce 16 cache files, but as the number is one that will only produce 4 cache files. And for a problem with large number of loop the speed of computing is slowed.

I suspect that this is caused by repeated compilation of the problem.

So my question is whether there is a way to prevent the problem from being recompiled when the parameters are changed.

This has been asked several times in this forum, a search would have given you the answer.

Wrap the value of lamd in a dolfinx.fem.Constant(mesh, lamd).

1 Like

Dear francesco-ballarin,

Thank you very much!

That’s really what I want.