I'd like to flag when a function has exceeded a threshold, equivalent to truncating a function.
For instance I can apply Max(f,Constant(0)), which does the job of setting all negative values to 0.
The problem is that the precision of that operation is not necessarily high (unless the mesh is particularly fine). I illustrate the problem in the script below, truncating the negative values of cos(x). The result of the Max operation is quite noisy, and even returns some negative values. Ideally I want it to simply pass the value of the function of the original function where it is positive, and strictly zero otherwise.
Increasing the number of points in the mesh does help, but I guess it's not always convenient to do that in production runs. Is there a better, cleaner method of truncating function values?
from dolfin import *
mesh = IntervalMesh(20,0,10)
V = FunctionSpace(mesh, "CG", 1)
fe = Expression("cos(x[0])")
ff = interpolate(fe,V)
truncated_f = project(Max(ff,Constant(0)),V)
print("original: ", ff.vector().array())
print("truncated: ", truncated_f.vector().array())
plot(ff,title="Original")
plot(truncated_f,interactive=True,title="Truncated")