Operation on the solutions?

Hello,

I am working on a code that is similar to the Cahn-Hillard tutorial. At each time iteration when the solution is obtain:

while (t < T):
t += dt
u0.vector()[:] = u.vector()
solver.solve(problem, u.vector())
file << (u.split()[0], t)

So u is a solution of two coupled equations, instead of exporting u, I wanted to do some operation on the solution and output that result. For example, if I want to do result = u12 + u22, where u1 and u2 are the the part of u (solution the the two couple equations respectively), and “result” is the output I want to send to .pvd file to use in Paraview, how should I make this work?

I tried this:

a, b =u.split()
result = a2 + b2
file << (posit)

And the error was on the last line mentioning that ‘Sum’ object has no attribute ‘_cpp_object’

It the two functions are from the same function space, you can sum the vectors,

result = Function(SubSpace)
Result.vector()[:] =  a.vector()+b.vector()

If the solutions are in different function spaces, you would have to project them

result = project (a+b, AppropriateFunctionSpace)

Thank you for your response! Both are from the same function space. So I tried the following two ways and they both gave me errors:

one is:
a, b = u.split()
result = ( a.vector() )**2 + ( b.vector() )**2
file << (result, t)

error says unsupported operand type for ** or pow(). ‘DOLFIN.cpp.la.PETScVector’ and ‘Int’

the other one is:

a, b = u.split()
result = ( a2 ).vector() + ( b2 ).vector()
file << (result, t)

error says ‘Power’ object has no attribute ‘vector’

There was a “typo” on my second attempt,
result = ( a 2 ).vector() + ( b 2 ).vector() somehow the stars for powers didn’t show, should be result = ( a star star 2 ).vector() + ( b star star 2 ).vector()

I also made a couple more attempts like, using dot() and inner() to replace power of 2, didn’t work. I also tried to project the operation to the same function space, it says something like finite element object has no attribute mesh

Result.vector()[:] =  a.vector() * a.vector() + b.vector() * b.vector()

do the trick, I don’t know if there is another workaround.

If you want to post code blocks as you did, write triple back ticks ``` before and after the code. Inline code works with single back ticks, `.

Anyways, you want to assign the result of your computation to a new Function. Your result (if **2 worked) would only be a vector, without function space information etc.
See what @dokken wrote. You have to define that result function.

For instance, if u is a function of FunctionSpace V, you could do so with

a, b = u.split(deepcopy=True)      # note deepcopy
result = Function(a.function_space())
c = a.vector()*a.vector() + b.vector()*b.vector()
result.vector()[:] = c
```