ModelingToolkit -- if statements?

Silly question… I need to create a function that I call within an MTK model (computing friction force), and the friction depends on the direction of the velocity… two very different expressions if v> 0, or whether v <= 0.

So I tried to do (qualitatively):

function friction(v)
    if v < 0
        Ff1 = ...
        Ff = Ff1
    else 
        Ff2 = ...
        Ff = Ff2
    end
    return Ff
end

When I run the code, I get an error message:

TypeError: non-boolean (Num) used in boolean context
A symbolic expression appeared in a Boolean context.
...

So – I assume this implies that I cannot do boolean tests on MTK variables (such as v).

Is the best way to handle this to do the following:

function friction(v)
    Ff1 = ...
    Ff2 = ...
    Ff = (1-sign(v))*Ff1/2 + (1+sign(v))*Ff2/2
    return Ff
end

[Possible problem if v=0?]

Have you tried @register_symbolic friction(v::Real)?

1 Like

I didn’t try this.

Will the syntax friction(v::Real) force the MTK variable (v is a function of time) to be converted to a real number within the function friction?

[Note: my trick with (1-sign(v))/2*... + (1+sign(v))/2*... seems to work for this case, but it is, of course, not a general solution to the problem.]

No, it will rather prevent the symbols from going inside the function and instead treat the function call friction(v) as a symbolic “atom”.

1 Like