How to implement function with condition?

Hi, I’m my variational equation has a conditional function like below

H\left(u\right)=\left\{\begin{align}&f\left(u\right),~ if~u<0\\&g\left(u\right),~if~u\ge0\end{align}\right.

I tried

def H(u):
    val = u.vector().vec().array
    tmp = np.zeros_like(val)
    tmp[val < 0] = ...
    tmp[val >= 0] = ...
    v = Function(u.function_space())
    v.vector()[:] = tmp
    return v

and

u_ = TrialFunction(V)
v_ = TestFunction(V)
a = inner(some_function(H(u_)), another_function(v_))*dx
l = the_other_function(v_)*dx
u = Function(V)
solve(a == l, u, dbc)

But the error message says

AttributeError: 'Indexed' object has no attribute 'vector'

which means the trial function does not have the attribute vector.
Then, how can I implement a function has conditions?

Check the UFL documentation.

1 Like

You can use a ufl conditional, see: Using Conditional function inside a Project function - #4 by dokken
and Form language — Unified Form Language (UFL) 2021.1.0 documentation

2 Likes