Invalid coefficient type for derivative

Hi,
I try to define my energy as the amount of discrepancy between two tensors. One of the tensors is known, and the other is made out of the derivatives as the unknown vector function u. Here is a minimal working example:

import dolfinx
from dolfinx import fem
from dolfinx import mesh
from mpi4py import MPI
import numpy as np
from petsc4py.PETSc import ScalarType
import ufl
from ufl import *

domain = dolfinx.mesh.create_unit_square(MPI.COMM_WORLD, 10, 10)

#define the function space
VFS = fem.VectorFunctionSpace(domain, ("CG", 1))
x = ufl.SpatialCoordinate(domain)
u = ufl.TrialFunction(VFS)
v = ufl.TestFunction(VFS)

#define gbar
gbar=as_tensor(2*fem.Constant(domain, ScalarType((((1,0)), (0,1)))))

#define g as derivatives of u
gradu=ufl.grad(u)
t1=gradu[:,0]
t2=gradu[:,1]
g=as_tensor([[ufl.dot(t1,t1),ufl.dot(t1,t2)],[ufl.dot(t1,t2),ufl.dot(t2,t2)]])

#define boundary conditions
def clamped_boundary(x):
    return np.isclose(x[1], 1)
fdim = domain.topology.dim - 1
boundary_facets = mesh.locate_entities_boundary(domain, fdim, clamped_boundary)
u_D = np.array([0,0], dtype=ScalarType)
bc = fem.dirichletbc(u_D, fem.locate_dofs_topological(VFS, fdim, boundary_facets), VFS)

#define the energy as the discrepancy between g and g bar
Energy=inner(g-gbar,g-gbar)*ufl.dx

Res = derivative(Energy, u,v)

Everything works fine until I get to the last line, which calculates the derivatives. I get the following error:

ValueError: Invalid coefficient type for

How can I fix this?

As your energy is non-linear wrt u, you should not use a TrialFunction, but a Function, i.e.

u = dolfinx.fem.Function(VFS)
1 Like