Error when using the derivative method

from fenics import *

# Define the constants (You should replace these with appropriate values)
K = Constant(1.0)  # Elastic constant
epsilon = Constant(1.0)  # Material constant
gamma = Constant(1.0)  # Material constant

# Create the mesh and define function space
mesh = RectangleMesh(Point(0, 0), Point(1, 1), 32, 32)  # Adjust the mesh resolution as needed
V = FunctionSpace(mesh, "CG", 1)

# Define the trial and test functions
n = TrialFunction(V)
v = TestFunction(V)

# Define the free energy functional
F = 0.5 * K * inner(grad(n), grad(n)) * dx + 0.25 * (epsilon + gamma * inner(grad(n), grad(n))) * n**2 * dx

# Compute the first variation (derivative) of the functional
dFdn = derivative(F, n, v)

I am trying to minimize the free-energy functional given by the formulation and I encounter this error while taking the derivative. Please help me with this error.
Invalid coefficient type for
Traceback (most recent call last):

File ~/opt/anaconda3/envs/fenicsproject/lib/python3.11/site-packages/spyder_kernels/py3compat.py:356 in compat_exec
exec(code, globals, locals)

File ~/Desktop/LIQUID CRYSTALS/untitled3.py:28
dFdn = derivative(F, n, v)

File ~/opt/anaconda3/envs/fenicsproject/lib/python3.11/site-packages/dolfin/fem/formmanipulations.py:82 in derivative
return ufl.derivative(form, u, du, coefficient_derivatives)

File ~/opt/anaconda3/envs/fenicsproject/lib/python3.11/site-packages/ufl/formoperators.py:280 in derivative
coefficients, arguments = _handle_derivative_arguments(form, coefficient,

File ~/opt/anaconda3/envs/fenicsproject/lib/python3.11/site-packages/ufl/formoperators.py:230 in _handle_derivative_arguments
error(“Invalid coefficient type for %s” % ufl_err_str(c))

File ~/opt/anaconda3/envs/fenicsproject/lib/python3.11/site-packages/ufl/log.py:172 in error
raise self._exception_type(self._format_raw(*message))
UFLException: Invalid coefficient type for

Try

n = Function(V)
v = TestFunction(V)

# Define the free energy functional
F = 0.5 * K * inner(grad(n), grad(n)) * dx + 0.25 * (epsilon + gamma * inner(grad(n), grad(n))) * n**2 * dx

# Compute the first variation (derivative) of the functional
dFdn = derivative(F, n, v)

A bilinear form can never be non linear wrt the TrialFunction.

1 Like