# Cpp-based Expression

**URL:** <https://fenicsproject.discourse.group/t/cpp-based-expression/929>\
**Category:** Uncategorized\
**Created:** [May 31, 2019, 12:27pm UTC](https://fenicsproject.discourse.group/t/cpp-based-expression/929 "2019-05-31T12:27:38Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![MercuryBench](https://avatars.discourse-cdn.com/v4/letter/m/898d66/32.png) [@MercuryBench](https://fenicsproject.discourse.group/u/MercuryBench)\
**Post date:** [May 31, 2019, 12:27pm UTC](https://fenicsproject.discourse.group/t/cpp-based-expression/929/1 "2019-05-31T12:27:38Z")

</div>

Hi,

I am having some trouble with defining an expression via cpp code. The following minimal working example does not run

```
from fenics import *

mesh = UnitSquareMesh(8, 8)
V0 = FunctionSpace(mesh, 'DG', 0)

funcstring = '''
#include <dolfin/function/Expression.h>

class Function : public dolfin::Expression
{
	void eval(Array<double>& values, constArray <double>& x) const
	{
		if (x[0] >= 0.25 && x[0] < 0.5)
		{
			if (x[1] >= 0.5 && x[1] < 0.625)
			{
				values[0] = 1.0
			}
			else if (x[1] >= 0.625 && x[1] < 0.75)
			{
				values[0] = -1.0
			}
			else
			{
				values[0] = 0.0
			}
		}
		else 
		{
			values[0] = 0.0
		}
	}'''

function = project(Expression(funcstring, degree=0), V0)

```

This returns

------------------- Start compiler output ------------------------  
/tmp/tmpsg02dhul/dolfin\_expression\_48aa633c4be2d56887d6fc2cebc19a1f.cpp: In member function ‘virtual void dolfin::dolfin\_expression\_48aa633c4be2d56887d6fc2cebc19a1f::eval(Eigen::Ref\<Eigen::Matrix\<double, -1, 1\> \>, Eigen::Ref\<const Eigen::Matrix\<double, -1, 1\> \>) const’:  
/tmp/tmpsg02dhul/dolfin\_expression\_48aa633c4be2d56887d6fc2cebc19a1f.cpp:64:1: error: expected primary-expression before ‘class’  
class Function : public dolfin::Expression  
^ ~~~~  
/tmp/tmpsg02dhul/dolfin\_expression\_48aa633c4be2d56887d6fc2cebc19a1f.cpp:92:8: error: a function-definition is not allowed here before ‘{’ token  
{  
^  
/tmp/tmpsg02dhul/dolfin\_expression\_48aa633c4be2d56887d6fc2cebc19a1f.cpp:98:8: error: a function-definition is not allowed here before ‘{’ token  
{  
^  
/tmp/tmpsg02dhul/dolfin\_expression\_48aa633c4be2d56887d6fc2cebc19a1f.cpp:105:8: error: a function-definition is not allowed here before ‘{’ token  
{  
^  
/tmp/tmpsg02dhul/dolfin\_expression\_48aa633c4be2d56887d6fc2cebc19a1f.cpp:111:8: error: a function-definition is not allowed here before ‘{’ token  
{  
^  
/tmp/tmpsg02dhul/dolfin\_expression\_48aa633c4be2d56887d6fc2cebc19a1f.cpp: At global scope:  
/tmp/tmpsg02dhul/dolfin\_expression\_48aa633c4be2d56887d6fc2cebc19a1f.cpp:119:8: error: expected unqualified-id before string constant  
extern “C” DLL\_EXPORT dolfin::Expression \* create\_dolfin\_expression\_48aa633c4be2d56887d6fc2cebc19a1f()  
^~~  
/tmp/tmpsg02dhul/dolfin\_expression\_48aa633c4be2d56887d6fc2cebc19a1f.cpp:122:1: error: expected ‘}’ at end of input  
}  
^

------------------- End compiler output ------------------------  
Compilation failed! Sources, command, and errors have been written to: /home/jitfailure-dolfin\_expression\_48aa633c4be2d56887d6fc2cebc19a1f  
Traceback (most recent call last):  
File “/usr/lib/python3/dist-packages/dolfin/jit/jit.py”, line 167, in compile\_class  
mpi\_comm=mpi\_comm)  
File “/usr/lib/python3/dist-packages/dolfin/jit/jit.py”, line 47, in mpi\_jit  
return local\_jit(\*args, \*\*kwargs)  
File “/usr/lib/python3/dist-packages/dolfin/jit/jit.py”, line 103, in dijitso\_jit  
return dijitso.jit(\*args, \*\*kwargs)  
File “/home/philipp/.local/lib/python3.6/site-packages/dijitso/jit.py”, line 217, in jit  
% err\_info[‘fail\_dir’], err\_info)  
dijitso.jit.DijitsoError: Dijitso JIT compilation failed, see ‘/home/jitfailure-dolfin\_expression\_48aa633c4be2d56887d6fc2cebc19a1f’ for details

During handling of the above exception, another exception occurred:

Traceback (most recent call last):  
File “cppfunction.py”, line 35, in   
function = project(Expression(funcstring, degree=0), V0)  
File “/usr/lib/python3/dist-packages/dolfin/function/expression.py”, line 400, in **init**  
self.\_cpp\_object = jit.compile\_expression(cpp\_code, params)  
File “/usr/lib/python3/dist-packages/dolfin/function/jit.py”, line 158, in compile\_expression  
expression = compile\_class(cpp\_data, mpi\_comm=mpi\_comm)  
File “/usr/lib/python3/dist-packages/dolfin/jit/jit.py”, line 170, in compile\_class  
raise RuntimeError(“Unable to compile C++ code with dijitso”)  
RuntimeError: Unable to compile C++ code with dijitso

---

<div class="post-metadata">

**Author:** ![kamensky](https://avatars.discourse-cdn.com/v4/letter/k/e95f7d/32.png) [@kamensky](https://fenicsproject.discourse.group/u/kamensky)\
**Post date:** [May 31, 2019, 2:20pm UTC](https://fenicsproject.discourse.group/t/cpp-based-expression/929/2 "2019-05-31T14:20:10Z")

</div>

The difficulty is that the string expected by the Python `Expression` constructor is something that you should be able to paste in as an R-value to complete `values[0] = ...` , not a full definition of a C++ `Expression` subclass. For the conditional logic you have in your class’s `eval` method, you can compress it all into one line of C++ with the ternary operator, as follows:

```python
from fenics import *

mesh = UnitSquareMesh(8, 8)
V0 = FunctionSpace(mesh, 'DG', 0)

funcstring = """((x[0] >= 0.25 && x[0] < 0.5))?
                 ((x[1] >= 0.5 && x[1] < 0.625)?
                   1.0 : ((x[1] >= 0.625 && x[1] < 0.75)? 
                          -1.0 : 0.0)) : 0.0;"""
function = project(Expression(funcstring, degree=0), V0)

from matplotlib import pyplot as plt
plot(function)
plt.show()

```

If you really do need to define a C++ `Expression` subclass, I think the way to go would be something more like what @miguel did with `SubDomain` here, using pybind11 and `compile_cpp_code`:

> [@CompiledSubdomain using C++ class](https://fenicsproject.discourse.group/t/compiledsubdomain-using-c-class/918):
>
> My goal is to speed up the evaluation of the SubDomain Gamma from dolfin import \* mesh = UnitSquareMesh(50,50, 'left/right') PHI = FunctionSpace(mesh, 'CG', 1) phi\_expr = Expression('2.0\*(1.0 - x[0])\*x[0] + 0.2 - x[1]', degree=2) phi = interpolate(phi\_expr , PHI) File("phi\_initial.pvd") \<\< phi class Gamma(SubDomain): def inside(self, x, on\_boundary): return phi(x) \> 0.5 with a C++ expression as follows omega\_out\_code = """ #include \<pybin…
