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

Call finite element function from Expression

0 votes

Dear Community,

I have a finite element function F given by interpolate function and a custom class

class MyExpression(Expression):
    def eval(self, val, x):
        val[0] = ...
        val[1] = ...
    def value_shape(self):
        return (2,)

Is it possible (and how) to use F in eval function to calculate values of val variable?

asked Aug 25, 2016 by engraver FEniCS Novice (150 points)
edited Aug 27, 2016 by engraver

1 Answer

+1 vote

Does something like this fit your needs? This is not a particularly efficient method if you have a large problem.

from dolfin import *

class MyExpression(Expression):
  def __init__(self, F):
    self.F = F

  def eval(self, val, x):
    f_val = F(x)
    val[0] = 10.0 if f_val > 0.5 else 1.0
    val[1] = 10.0 if f_val > 0.5 else 1.0

  def value_shape(self):
    return (2,)

mesh = UnitSquareMesh(64, 64)


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

F = interpolate(Expression('x[0]'), V)
my_exp = MyExpression(F)

a = dot(grad(u), grad(v))*dx
L = dot(my_exp, my_exp)*v*dx

soln = Function(V)
bc = DirichletBC(V, Constant(0.0), 'on_boundary')
solve(a == L, soln, bcs=[bc])
plot(soln, interactive=True)
answered Aug 31, 2016 by nate FEniCS Expert (17,050 points)

Thank you, it's really I want to do.

...