Problem of C++ compilation with Expression()

Hello,

I am a beginner in fenics and I am trying to resolve Poisson equation with a boundary condition which is a Perlin noise generated by opensimplex (Python library).

However, when trying to define f the boundary condition by Expression (). (I tried Expression('function(x[0],x[1],x[2])') where function (x,y,z)=opensimplex.tmp.noise3d(x,y,z)). However, as this opensimplex function is not managed by C++, I got a compilation error. Is there any solution to overcome this compilation error ?

Thank you for your answer,

If you want to execute arbitrary Python code in a variational form, you need to create a subclass of UserExpression, e.g.,

from dolfin import *

class MyExpression(UserExpression):
    def __init__(self,a,**kwargs):

        # Call superclass constructor with keyword arguments to properly
        # set up the instance:
        super().__init__(**kwargs)
        
        # Custom setup for the subclass:
        self.a = a
        
    def eval(self, values, x):
        # Some more complicated Python code could go here.
        values[0] = self.a**2

    def value_shape(self):
        return ()

# Create an instance to verify:
f = MyExpression(2.0)
print(assemble(f*dx(domain=UnitIntervalMesh(1))))
1 Like