Update Expression for DirichletBC

This is because the class of this two objects differs, and is handled differently by the DirichletBC.
You can see this with the following code:

import ufl
print(isinstance(Coeff(T), ufl.Coefficient))
print(isinstance(2*Coeff(T), ufl.Coefficient))

which returns

True
False

This means that the latter input is treated as something that has to be projected internally in the DirichletBC, and is thus not prone to updates. What you should do here is to add a scaling parameter to your UserExpression:

from fenics import *

mesh = UnitSquareMesh(5, 5)
V = FunctionSpace(mesh, "P", 1)
u = Function(V)
v = TestFunction(V)
T = Constant(1)


class Coeff(UserExpression):
    def __init__(self, T, **kwargs):
        super().__init__(kwargs)
        self._T = T
        self.alpha = 1

    def eval_cell(self, value, x, ufc_cell):
        value[0] = self.alpha*2*self._T(x)*x[0]

    def value_shape(self):
        return ()

coeff = Coeff(T)
sm = MeshFunction("size_t", mesh, 1, 0)
right = CompiledSubDomain('x[0] > 0.75')
right.mark(sm, 2)
bc1 = DirichletBC(V, coeff, sm, 2)

bc2 = DirichletBC(V, coeff, sm, 2)

F = dot(grad(u), grad(v))*dx

set_log_level(30)
for i in range(1, 10):
    coeff.alpha = 1
    coeff._T.assign(i)
    solve(F == 0, u, bc1)
    a = u(0.5, 0.5)
    coeff.alpha = 2
    solve(F == 0, u, bc2)
    b = u(0.5, 0.5)

    print(a, b)
1 Like