Skip to content

chore: add change_tunables #3886

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Aug 12, 2025
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/parameters.jl
Original file line number Diff line number Diff line change
Expand Up @@ -147,3 +147,27 @@ function split_parameters_by_type(ps)
end
end
end

"""
$(TYPEDSIGNATURES)

Change the tunable parameters of a system to a new set of tunables.

The new tunable parameters must be a subset of the current tunables as discovered by [`tunable_parameters`](@ref).
The remaining parameters will be set as constants in the system.
"""
function change_tunables(sys, new_tunables)
cur_tunables = tunable_parameters(sys, parameters(sys))
diff_params = setdiff(cur_tunables, new_tunables)

if !isempty(setdiff(new_tunables, cur_tunables))
throw(ArgumentError("New tunables must be a subset of the current tunables. Found tunable parameters not in the system: $(setdiff(new_tunables, cur_tunables))"))
end
cur_ps = get_ps(sys)
const_ps = toconstant.(diff_params)

new_ps = replace(cur_ps, (diff_params .=> const_ps)...)
new_ps = replace(new_ps, (Initial.(diff_params) .=> Initial.(const_ps))...)
@set! sys.ps = new_ps
complete(sys)
end
18 changes: 18 additions & 0 deletions test/parameter_dependencies.jl
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,24 @@ end
@test SciMLBase.successful_retcode(sol)
end

@testset "Change Tunables" begin
@variables θ(t)=π/6 ω(t)=0.
@parameters g=9.81 L=1.0 b=0.1 errp=1
eqs = [
D(θ) ~ ω,
D(ω) ~ -(g/L)*sin(θ) - b*ω
]
@named pendulum_sys = System(eqs, t, [θ, ω], [g, L, b])
sys = mtkcompile(pendulum_sys)

new_tunables = [L, b]
sys2 = ModelingToolkit.change_tunables(sys, new_tunables)
sys2_tunables = ModelingToolkit.tunable_parameters(sys2, ModelingToolkit.parameters(sys2))
@test length(sys2_tunables) == 2
@test isempty(setdiff(sys2_tunables, new_tunables))
@test_throws ArgumentError ModelingToolkit.change_tunables(sys, [errp])
end

struct CallableFoo
p::Any
end
Expand Down
Loading