Using ufl for manifactured solutions

Dear fenics experts,
my question is somehow related to Convert sympy expressions to fenicsx expressions but extends on that. I want to use ufl to construct all of the required problem data from a single expression automatically. For that I want to do something like

import dolfinx as df
import ufl
from mpi4py import MPI

mesh = df.mesh.create_unit_interval(MPI.COMM_WORLD,100)
V = df.fem.FunctionSpace(mesh,("Lagrange",1))

t = ufl.Coefficient(V) # Time variable
x = ufl.SpatialCoordinate(V.mesh)[0]

c = 1.0
expr = ufl.sin(0.5 * np.pi *x) * ufl.cos(2 * np.pi * t)
expr_t = ufl.derivative(expr, t)
expr_f = (ufl.derivative(expr, t, t) - ufl.inner( c**2 * ufl.grad(expr), ufl.grad(expr)))
u_exakt = lambda t_eval: ufl.replace(expr, {t:t_eval})
u_bc = u_exakt
v_exakt = lambda t_eval: ufl.replace(expr_t, {t:t_eval})
f = lambda t_eval: ufl.replace(expr_f, {t:t_eval})
u0 = u_exakt(0.0)
v0 = v_exakt(0.0)

However when trying to intepolate a function with for example u0 by

u = df.fem.Function(V)
u.interpolate(u0)

I get errors from the ufl evaluations.

Traceback (most recent call last):
  File "/home/user/Workspace/domainsplitting/src/ProblemDataUFL.py", line 41, in <module>
    u.interpolate(u0)
...
File "/usr/lib/python3/dist-packages/ufl/mathfunctions.py", line 59, in evaluate
    a = self.ufl_operands[0].evaluate(x, mapping, component, index_values)
  File "/usr/lib/python3/dist-packages/ufl/algebra.py", line 193, in evaluate
    tmp *= o.evaluate(x, mapping, (), index_values)
  File "/usr/lib/python3/dist-packages/ufl/indexed.py", line 107, in evaluate
    return A.evaluate(x, mapping, component, index_values)
  File "/usr/lib/python3/dist-packages/ufl/geometry.py", line 170, in evaluate
    return float(x[component[0]])
TypeError: only size-1 arrays can be converted to Python scalars

what am I doing wrong here? Im running dolfinx in version 0.5.2 on Ubuntu22 installed via apt and with ufl version 2022.2.0. Thanks in advance :slight_smile:

The interface to interpolate ufl-expressions is not quite as you tried to use it.

You need to use dolfinx.fem.Expression as a wrapper around the ufl-expression.

This is shown of in various places:
https://jsdokken.com/dolfinx-tutorial/chapter1/membrane_code.html?highlight=fem+expression#interpolation-of-a-ufl-expression
https://jsdokken.com/dolfinx-tutorial/chapter4/convergence.html?highlight=fem+expression#reliable-error-norm-computation
https://jsdokken.com/fenics22-tutorial/heat_eq.html#post-processing-without-projections

1 Like

Thanks a lot, I completely missed that.