Skip to content

respecialize always promotes Float16 and Float32 to Float64 #3908

@bradcarman

Description

@bradcarman

Using MTK v10.21.0

All Int types are preserved, but Float types are not. Take the following MWE...

using ModelingToolkit
using ModelingToolkit: t_nounits as t
using Test

function ConstantGeneric(;name, k::T) where T

    pars = @parameters begin
        k::T = k
    end

    systems = @named begin
        output = Blocks.RealOutput()
    end
    eqs = [
        output.u ~ k
    ]

    return ODESystem(eqs, t, [], pars; name, systems)
end

function TypeTest(T1::Type, T2::Type; name)
    vars = @variables begin
        output(t)
    end
    systems = @named begin
        c1 = ConstantGeneric(k = T1(1))
        c2 = ConstantGeneric(k = T2(2))
    end
    equations = [
        output ~ ifelse(sin(t) > 0, c1.output.u, c2.output.u)
    ]
    ODESystem(equations, t; name, systems)
end

function run_test(T1, T2)
    @mtkcompile sys = TypeTest(T1, T2)
    sys = respecialize(sys)
    prob = ODEProblem(sys, Any[], (0,1))
    sol = solve(prob)

    @test typeof(sol(0.0; idxs=sys.c1.output.u)) == T1
    @test typeof(sol(0.0; idxs=sys.c2.output.u)) == T2 
    @test typeof(sol(0.0; idxs=sys.output)) == promote_type(T1,T2)
end

run_test(Int16, Int16) # Test Passed
run_test(Int16, Int32) # Test Passed
run_test(Float16, Float16) # ERROR
run_test(Float32, Float32) # ERROR
run_test(Float64, Float64) # Test Passed
run_test(Int16, Float16) # ERROR
#=
Test Failed at c:\Work\Packages\BoeingLLFLibrary\scripts\type_testing.jl:45
  Expression: typeof(sol(0.0; idxs = sys.c2.output.u)) == T2
   Evaluated: Float64 == Float16
=#

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions