How does numpy.float64 extract values from ufl functions?

Hi everyone,
I would have a curiosity about numpy.float64. Along my code I need to check the value of some constant quantities, i.e.:

if R > 0:
   c -= 16 * t**3 / (1 + 2 * t)**4

R can be either a “simple” number or let’s say a fem.Constant(), so I can’t use directly this condition or something like if R.values.item():. In order to overcome this problem I edit my code as follow:

from dolifinx import default_scalar_type as scalar


if scalar(R) > 0:
   c -= 16 * t**3 / (1 + 2 * t)**4

Now I known that default_scalar_type is just numpy.float64 and I’m curious to understand how numpy.float64 can extract the value of my fem.Constant(). Surprisingly I could see that this also works in other cases, for example I can pass as argument ufl.conditional(gt(1, 0), 2, 4) to numpy.float64() and then I get 2. But really I don’t understand how it’s possible, some of you could kindly give me some explanation?

thanks in advance :slight_smile:

The code you have presented here doesn’t really make sense.

is a statement that always evals to True.
Calling np.float64 on a ufl expression will cause ufl to try to convert all values in the ufl-expression to floats. In your case this will work, as there are no function or trial/test-functions in the condition, only scalar constants.

1 Like

Hi Jorgen, thank you for your prompt reply. Yes, you are right this condition doesn’t make sense, I made it up just to say that if I pass it as a numpy.float argument I will obtain the numerical value (in this case since it’s always True I get 2.0).
My question was about the relationship between numpy and ufl, maybe I misexplained myself when I asked the question. What I would like to understand is how does numpy.float64 extract values from ufl functions?

It calls float recursively on each operand in the ufl expression.

If the float conversion function is implemented for all operands, then you will be able to display it as a float

Okay, now I understand. I went to look at the source code and found what I was looking for. Specifically by inspecting the class Constant(), in fem module, I found the __float__() method. I guess it’s just through this method that values can be extracted.
https://docs.fenicsproject.org/dolfinx/v0.7.1/python/_modules/dolfinx/fem/function.html#Constant

I hope I got it right, thanks for your help :slight_smile: