UFLValueError: Invalid type conversion error on weak form

I’m trying to use Fenics to solve a replicator equation PDE problem but keep running into the UFLValueError(“Invalid type conversion: %s can not be converted”) error when putting the weak form in for F.

My code is largely based on the nonlinear Poisson example from the Fenics documentation, but I’ve attached code below:

import numpy as np
from fenics import *

def D(u):
    return np.identity(2)

import sympy as sym
x, y = sym.symbols('x[0], x[1]')
u = 1 + x + 2*y
u_old = - sym.diff(D(u)*sym.diff(u, x), x) - sym.diff(D(u)*sym.diff(u, y), y) # right-hand side
u_old = sym.simplify(u_old)

mesh = UnitSquareMesh(8, 8)
V = FunctionSpace(mesh, 'P', 1)

u_D = Expression(u_code, degree=2)

def boundary(x, on_boundary):
    return on_boundary

bc = DirichletBC(V, u_D, boundary)

# Define variational problem
u = Function(V)  # Note: not TrialFunction!
v = TestFunction(V)
u_old = Expression(u_old_code, degree=2)

F = float(dot(grad(v),D(u)*grad(u)))*dx - u_old*v*dx

# Compute solution
solve(F == 0, u, bc)

# Plot solution

u_e = interpolate(u_D, V)
error_max = np.abs(np.array(u_e.vector() - np.array(u.vector()))).max()
print('error_max = ', error_max)

The F weak form is able to compute if I don’t multiply by D(u) but gives the above error if I do, despite D(u) just being the identity matrix. Thanks for your help!

UFL is used for symbolic algebra representation of weak formulations. You’re trying to mix numerics via numpy and symbolic algebra with UFL which doesn’t make sense. Consider ufl.Identity.

1 Like

Thanks! That resolved that error, I switched D(u) to

return Identity(2)

and that resolved that code problem. However, it opened up a new problem with an earlier line in the code, namely

u_old = - sym.diff(D(u)*sym.diff(u, x), x) - sym.diff(D(u)*sym.diff(u, y), y) # right-hand side

now returns:
TypeError: unsupported operand type(s) for *: ‘Identity’ and ‘One’.

I assume that D(u) is now of type Identity in the UFL symbolic algebra, what operation would correspond to the “*” operation in UFL language to modify u_{old}?

Again, sympy and UFL are separate packages. You can use symbolic differentiation in UFL.