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

Linear Combination of solutions

0 votes

Hi,
I need to obtain a solution from linear combination of several solutions. If my linear combination coefficients is stored in numpy vector the desired solution will be the linear combination of obtained solutions.
UU=LinearCombCoef[0]U0+LinearCombCoef[1]U1+LinearCombCoef[2]*U2
The problem is that each solution is dolfin.functions.function.Function but when I add them and multiply them by the coefficient it change to numpy.ndarray and naturally i am not able to evaluate the solution on some points.
any hints on how can I fix this problem ? ( how can I write the linear combination of solutions sets in a way the result stay in the same class as initial solutions)

      u = Function(V)
      solve(a == L, u, bc)
  LinearCombCoef = numpy.array([2,3,1])
 UU=LinearCombCoef[0]*U0+LinearCombCoef[1]*U1+LinearCombCoef[2]*U2
 print type(UU)
 print type(U1)
 cc=[0.1,0.4]


print UU(cc)[1]

Thanks.

asked Jan 22, 2014 by Bahram FEniCS Novice (400 points)
edited Jan 22, 2014 by Bahram

2 Answers

+3 votes
 
Best answer

Wow, this:

print UU

threw a strange exception (at least to me):

UFL conditions cannot be evaluated as bool in a Python context.
Traceback (most recent call last):
  File "foo.py", line 49, in <module>
    print UU
  File "/usr/lib/python2.7/dist-packages/numpy/core/numeric.py", line 1471, in array_str
    return array2string(a, max_line_width, precision, suppress_small, ' ', "", str)
  File "/usr/lib/python2.7/dist-packages/numpy/core/arrayprint.py", line 445, in array2string
    separator, prefix, formatter=formatter)
  File "/usr/lib/python2.7/dist-packages/numpy/core/arrayprint.py", line 248, in _array2string
    'int' : IntegerFormat(data),
  File "/usr/lib/python2.7/dist-packages/numpy/core/arrayprint.py", line 638, in __init__
    max_str_len = max(len(str(maximum.reduce(data))),
  File "/home/oyvinev/Work/FEniCS_1.3/lib/python2.7/site-packages/ufl/conditional.py", line 50, in __nonzero__
    error("UFL conditions cannot be evaluated as bool in a Python context.")
  File "/home/oyvinev/Work/FEniCS_1.3/lib/python2.7/site-packages/ufl/log.py", line 154, in error
    raise self._exception_type(self._format_raw(*message))
ufl.log.UFLException: UFL conditions cannot be evaluated as bool in a Python context.

However, you can make this work by using Constants and Function.assign

UU = Function(V)
UU.assign(Constant(LinearCombCoef[0])*U0+Constant(LinearCombCoef[1])*U1+Constant(LinearCombCoef[2])*U2)
answered Jan 22, 2014 by Øyvind Evju FEniCS Expert (17,700 points)
selected Jan 22, 2014 by Marie E. Rognes

Thank you very much, It solved my problem.

+2 votes
UU = Function(V)
UU.vector()[:]=U0.vector()*LinearCombCoef[0]+U1.vector()*LinearCombCoef[1]+U2.vector()*LinearCombCoef[2]
answered Jan 22, 2014 by mmorandi FEniCS Novice (990 points)
...