This is a read only copy of the old FEniCS QA forum. Please visit the new QA forum to ask questions

How to create an "empty" UFL form in Python

+2 votes

Is it possible to create an "empty" UFL form in Python and then add terms to it as required?

The code would look something like this:

form = EmptyForm()
for term in terms:
    form += term

I have tried the following which seems to work:

form = 0
for term in terms:
    form += term

Are there any potential issues with this implementation?

asked Jun 15, 2016 by benzwick FEniCS Novice (350 points)
edited Jun 15, 2016 by benzwick

1 Answer

0 votes

The problem with this is that EmptyForm() would not know about rank (and other details) required for consistency checks.

You could mimic this by form = Constant(0.0)*TestFunction(V)*dx. Disadvantage is that actual code is generated (and executed by assembler) for this term.

Alternatively you could maybe take advantage of list/generator comprehension: form = sum(term for term in terms).

answered Jun 17, 2016 by Jan Blechta FEniCS Expert (51,420 points)

Haven't read properly that 0 + term works in your post. If it works it should be fine.

Hi, the constructs below seem equivalent. I agree with Jan that there should be no issues with 0. I you insist on ''type stability'' then perhaps f3 and f4 are the way to go.

from dolfin import *
from ufl import zero

mesh = UnitSquareMesh(10, 10)
V = FunctionSpace(mesh, 'CG', 1)
u = TrialFunction(V)
v = TestFunction(V)

cs = map(Constant, range(4))
forms = [c*inner(u, v)*dx for c in cs]

f0 = sum(forms)
f1 = sum(forms, 0)
f2 = sum(forms, zero())
f3 = sum(forms[1:], forms[0])

iforms = iter(forms)
f4 = sum(iforms, next(iforms))

print len(set([f.signature() for f in (f0, f1, f2, f3, f4)]))
...