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

How best to take elementwise min() and assign to function?

0 votes

Given a function phi defined on a mesh, I could assign its values to another function phi_k defined on the same mesh like

phi_k.vector()[:] = phi.vector()

But now I need to assign the element-wise minimum of phi and G to phi_k. How do I do this correctly?

i.e. something like:

phi_k.vector()[:] = min_elementwise(phi.vector(), G.vector())

Thanks in advance!

asked Sep 22, 2015 by npmitchell FEniCS Novice (600 points)

2 Answers

+1 vote
 
Best answer

Elementwise minimum is implemented in PETSc.
If you have petsc4py, you can use the following:

def pwmin(x, y):
    z = as_backend_type(x).vec().duplicate()
    z.pointwiseMin(as_backend_type(x).vec(),
                   as_backend_type(y).vec())
    return PETScVector(z)

Alternatively you can implement pointwise minimum as follows:

def pwmin(x, y):
    z = x - y
    z.abs()
    z -= x
    z -= y
    z /= -2.0
    return z

This is not as fast as the PETSc implementation but faster than numpy.

answered Sep 22, 2015 by Magne Nordaas FEniCS Expert (13,820 points)
selected Sep 22, 2015 by npmitchell

Thanks for the insight. The assigning follows trivially:

phi_min = pwmin(phi.vector(),G.vector())
phi_k.vector()[:] = phi_min
0 votes
import numpy as np
phi_k.vector()[:] = np.minimum(phi.vector().array(), G.vector().array())

Does it work?

answered Sep 22, 2015 by Chao Zhang FEniCS User (1,180 points)
...