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

Subclassing Expression

+1 vote

How to subclass Expression? The degree needs to be specified, but

from dolfin import Expression


class MyExpr(Expression):
    def __init__(self):
        super(MyExpr, self).__init__(degree=0)
        return

    def eval(self, value, x):
        value[0] = 1.0
        return


MyExpr()

doesn't do the trick.

TypeError: Expression needs an integer argument 'degree' if no 'element' is provided.
asked May 11, 2017 by nschloe FEniCS User (7,120 points)

2 Answers

0 votes

Why don't you pass degree straight to a cpp generated expression?

from dolfin import Expression


class MyExpr(Expression):
    def eval(self, value, x):
        value[0] = 1.0
        return


MyExpr(degree=0)
answered May 11, 2017 by mhabera FEniCS User (1,890 points)
0 votes

Hi, consider the following

from dolfin import Expression, plot, UnitIntervalMesh
from ufl.algorithms import estimate_total_polynomial_degree as get_degree

class MyExpr(Expression):
    def __init__(self, a, **kwargs):
        self.a = a

    def eval(self, value, x):
        value[0] = x[0] + self.a

f = MyExpr(10, degree=10)
assert get_degree(f) == 10

mesh = UnitIntervalMesh(100)
plot(f, mesh=mesh, interactive=True)

Calling the parent initializer is not way to go because of some metaclass related issues. See here for more.

answered May 12, 2017 by MiroK FEniCS Expert (80,920 points)

Thanks Miro.

Problem occurs iff you define own __init__() in subclassed expression.

...