SciML / ModelingToolkit.jl

An acausal modeling framework for automatically parallelized scientific machine learning (SciML) in Julia. A computer algebra system for integrated symbolics for physics-informed machine learning and automated transformations of differential equations
https://mtk.sciml.ai/dev/
Other
1.38k stars 196 forks source link

conditionally chosen array variable #2812

Open baggepinnen opened 1 week ago

baggepinnen commented 1 week ago

I've found it hard to use if statements to control how equations involving arrays behave. This pattern is very common in modelica multibody models, but in MTK I frequently have to degrade parameters to be structural parameters to make it work. The following are two failed attempts

using ModelingToolkit
using ModelingToolkit: t_nounits as t, D_nounits as D
@mtkmodel ArrayIf begin
    @parameters begin
        stable = true
    end
    @variables begin
        x(t)[1:2]
    end
    @equations begin
        if stable
            D(x) ~ -x
        else
            D(x) ~ x
        end
    end
end

@mtkbuild arrayif = ArrayIf()
julia> @mtkbuild arrayif = ArrayIf()
ERROR: TypeError: non-boolean (Num) used in boolean context
@mtkmodel ArrayIf begin
    @parameters begin
        stable = true
    end
    @variables begin
        x(t)[1:2]
    end
    @equations begin
        D(x) ~ ifelse(stable, -x, x)
    end
end

@mtkbuild arrayif = ArrayIf()
ERROR: MethodError: no method matching ifelse(::SymbolicUtils.BasicSymbolic{…}, ::Symbolics.ArrayOp{…}, ::SymbolicUtils.BasicSymbolic{…})