Convert Sum to Function

I have a ufl sum object composed of a sum of functions in a space W and a space K which I want to convert to a Function in the space K.

For instance consider the example code below:

import numpy as np
from fenics import *

resolution = 5
mesh = UnitSquareMesh(resolution,resolution)
W = FunctionSpace(mesh,"DG",1)
K = FunctionSpace(mesh,"DG",0)

u = interpolate(Constant(1),W)
au = interpolate(Constant(1),W)
alpha = interpolate(Constant(1),K)

ConvertThis = inner(u,u)*alpha+inner(au,alpha*u)
print(type(ConvertThis))

#conversion ?

How do I get ConvertThis to be a function in K ?

The conversion cannot be exact, because, for arbitrary u and au in W, the expression ConvertThis is not necessarily constant on each element, while K is the space of elementwise-constant functions. Thus, there must be some approximation, the choice of which is not unique. A natural choice when K is a degree-0 DG space might be to approximate ConvertThis by its average on each element, which would be equivalent to the L^2 projection operation implemented by

ConvertThis_K = project(ConvertThis,K)

Note that project involves a linear solve, but, when projecting onto DG spaces, it can be optimized by using independent solves on each element, as demonstrated here.

2 Likes