Dolfinx matrix-valued Expression

Hi all,

I found in this post

https://fenicsproject.discourse.group/t/equivalent-for-expression-in-dolfinx/2641

how to efficiently define an expression in dolfinx. The expression there is scalar-valued, and the x variable is treated as an array with all coordinates to which the scalar expression is applied. When trying to define an Expression which is matrix-valued (for every interpolation point), the approach in that post becomes difficult to handle, at least with my knowledge. So my question is, how to define an Expression in dolfinx to define a space-dependent, matrix-valued coefficient?

Thank you in advance for any help.

Laura.

Consider the following minimal working example:

import dolfinx.mesh as msh
from dolfinx import fem
from mpi4py import MPI
import ufl
import numpy as np
mesh = msh.create_unit_square(MPI.COMM_WORLD, 10, 10)

el = ufl.TensorElement("Lagrange", mesh.ufl_cell(), 2, shape=(2, 2))

V = fem.FunctionSpace(mesh, el)


def tensor_expr(x):
    values = np.zeros((4, x.shape[1]))
    values[0] = 1  # location [0,0]
    values[1] = 3*x[0]  # location [0,1]
    values[2] = 3  # location [1,0]
    values[3] = 4*x[1]**2  # location [1, 1]
    return values


u = fem.Function(V)
u.interpolate(tensor_expr)

dx = ufl.Measure("dx", domain=mesh)
print(f"Computed: {fem.assemble_scalar(fem.form(u[0, 0]*dx))} Expected {1}")
print(f"Computed: {fem.assemble_scalar(fem.form(u[0, 1]*dx))} Expected {3/2}")
print(f"Computed: {fem.assemble_scalar(fem.form(u[1, 0]*dx))} Expected {3}")
print(f"Computed: {fem.assemble_scalar(fem.form(u[1, 1]*dx))} Expected {4/3}")

This returns:

Computed: 1.0000000000000095 Expected 1
Computed: 1.5000000000000033 Expected 1.5
Computed: 2.9999999999999627 Expected 3
Computed: 1.333333333333334 Expected 1.3333333333333333

For a three dimensional tensor, you would therefore define the shape (9, x.shape[1]) where the 0th entry corresponds to [0,0] the 1st entry to [0,1], 2nd [0,2] 3rd to [1,0] etc.

1 Like

Thank you now I understand the format in which to put the values!