Error using the cofac() function of UFL

Hi everyone,

FEniCS generates an error while using the cofac() function from UFL. Its a simple code where I generate a mesh, create a vector function space, create a function in the vector function space, calculate the identity tensor using the geometric dimension, create a deformation gradient tensor, and then calculate the cofactor of the deformation gradient tensor.

Here is the MWE:

from dolfin import *     
from ufl import cofac

mesh = UnitCubeMesh(24, 16, 16)  # Defining cubic mesh

V = VectorFunctionSpace(mesh, "Lagrange", 1) # Defining order 1 Lagrange Vector Function Space

u = Function(V) # Creating element from V

d = u.geometric_dimension() # Calculating dimension of geometry
I = Identity(d)             # Identity tensor with order of geometric dimension
F = I + grad(u)             # Calculating deformation gradient tensor

cofac_F = cofac(F)          # Calculating cofactor of F

This generates the error:

cofac_F = cofac(F)
  File "/usr/lib/python3/dist-packages/ufl/operators.py", line 218, in cofac
    A = as_ufl(A)
  File "/usr/lib/python3/dist-packages/ufl/constantvalue.py", line 501, in as_ufl
    raise ValueError(
ValueError: Invalid type conversion: I + (grad(f_5)) can not be converted to any UFL type.

What am I doing wrong here?

Please advise.

Thanks in advance!

What version of ufl are you using? I cannot reproduce this with the last release of ufl for legacy dolfin (i.e. ufl_legacy) using: docker run -ti -v $(pwd):/root/shared -w /root/shared --rm ghcr.io/scientificcomputing/fenics:2024-02-19

I am using Ubuntu. How do I check the version of ufl?

python3 -c "import ufl; print(ufl.__version__)"

Here is the response:

2023.2.0

Any suggestions on how to resolve this issue?

It is unclear to me how you have gotten that version of ufl for the Legacy release of Dolfin.
For legacy dolfin you should now use ufl_legacy: Announcement: ufl_legacy and legacy dolfin

@dokken Thanks for the explanation. How do I update the version from 2023.2.0 to the one you are referring to in Ubuntu? I am sorry if this is a trivial question. I am not so familiar with ubuntu commands.

Please advise.

Thank you.

It’s a separate package. If your dolfin installation is up to date then you’d already have it installed. Check with dpkg -l python3-ufl-legacy

What you need to do is use it,
i.e. replace

from ufl import cofac

with

from ufl_legacy import cofac

That would be current ufl (python3-ufl not python3-ufl-legacy). Steppenwolf’s system would have it alongside ufl_legacy if they also installed dolfinx (fenicsx) alongside dolfin.

1 Like