diff --git a/Project.toml b/Project.toml index 87f8e9e7c..6545e9104 100644 --- a/Project.toml +++ b/Project.toml @@ -20,6 +20,7 @@ Primes = "27ebfcd6-29c5-5fa9-bf4b-fb8fc14df3ae" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" RationalFunctionFields = "73480bc8-48a2-41cc-880f-208b490ccf65" TimerOutputs = "a759f4b9-e2f1-59dc-863e-4aeb61b1ea8f" +Unicode = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" [weakdeps] ModelingToolkitBase = "7771a370-6774-4173-bd38-47e70ca0b839" @@ -57,6 +58,7 @@ Symbolics = "7" Test = "1.10, 1.11" TestSetExtensions = "4" TimerOutputs = "0.5.10, 1.0" +Unicode = "1.10, 1.11" julia = "1.10.4, 1.11.2" [extras] diff --git a/src/ODE.jl b/src/ODE.jl index 26478da5f..9e9f97d23 100644 --- a/src/ODE.jl +++ b/src/ODE.jl @@ -258,8 +258,8 @@ function rename_variables( for (i, old_name) in enumerate(new_varnames) if old_name in keys(transform) new_varnames[i] = transform[old_name] - elseif endswith(old_name, "(t)") && old_name[1:(end - 3)] in keys(transform) - new_varnames[i] = transform[old_name[1:(end - 3)]] * "(t)" + elseif endswith(old_name, "(t)") && chopsuffix(old_name, "(t)") in keys(transform) + new_varnames[i] = transform[chopsuffix(old_name, "(t)")] * "(t)" end end diff --git a/src/StructuralIdentifiability.jl b/src/StructuralIdentifiability.jl index c5e1f9635..3de950203 100644 --- a/src/StructuralIdentifiability.jl +++ b/src/StructuralIdentifiability.jl @@ -15,6 +15,7 @@ import Primes import Random import TimerOutputs using TimerOutputs: @timeit, disable_timer!, enable_timer! +import Unicode # Algebra packages import AbstractAlgebra diff --git a/src/identifiable_functions.jl b/src/identifiable_functions.jl index 2ab537100..be4e82b7a 100644 --- a/src/identifiable_functions.jl +++ b/src/identifiable_functions.jl @@ -40,7 +40,7 @@ julia> ode = @ODEmodel( y(t) = x0(t) ); -julia> identifiable_functions = find_identifiable_functions(ode; loglevel = Logging.Error); +julia> identifiable_functions = find_identifiable_functions(ode); julia> length(identifiable_functions) 2 diff --git a/src/parametrizations.jl b/src/parametrizations.jl index b16208efc..161dd2ba9 100644 --- a/src/parametrizations.jl +++ b/src/parametrizations.jl @@ -16,6 +16,76 @@ function vector_field_along(derivation::Dict{T, U}, directions::AbstractVector) return new_vector_field end +function suggest_names(ode, new_states, new_params) + unorm(s) = Unicode.normalize(s; chartransform = Unicode.julia_chartransform) + original_names = unorm.(string.(gens(parent(ode)))) + + @assert allunique(original_names) + names = String[] + tildify(c::Char) = string(c, '\u0303') + tildify(s) = tildify(first(s)) * s[nextind(s, firstindex(s)):end] + + for (i, def) in enumerate(new_states) + num, den = unpack_fraction(def) + name = nothing + + # x --> x + if def in ode.x_vars + name == nothing && (name = var_to_str(num)) + end + + # a*x+b --> x̃ + states = intersect(vars(def), ode.x_vars) + if length(states) == 1 + name_orig = var_to_str(states[1]) + name == nothing && (name = tildify(name_orig)) + end + + # f(x1,...,xn) --> X_i + name == nothing && (name = "X$i(t)") + + push!(names, name) + end + + for (i, def) in enumerate(new_params) + num, den = unpack_fraction(def) + name = nothing + + # x --> x + if def in ode.parameters + name == nothing && (name = var_to_str(num)) + end + + # f(k) --> k̃ + params = intersect(vars(def), ode.parameters) + if length(params) == 1 + name == nothing && (name = tildify(var_to_str(params[1]))) + end + + # f(x) --> ai + name == nothing && (name = "a$i") + + push!(names, name) + end + + append!(names, string.(ode.u_vars), string.(ode.y_vars)) + + # Resolve collisions + reserved, used = Set(original_names), Set{String}() + for (i, def) in enumerate(vcat(new_states, new_params, ode.u_vars, ode.y_vars)) + base = names[i] + suffix = endswith(base, "(t)") ? "(t)" : "" + j = 2 + while unorm(names[i]) in used || (names[i] != string(def) && unorm(names[i]) in reserved) + names[i] = string(chopsuffix(base, suffix), "_", j, suffix) + j += 1 + end + push!(used, unorm(names[i])) + end + + names +end + """ reparametrize_with_respect_to(ode, new_vars) @@ -30,16 +100,17 @@ function reparametrize_with_respect_to(ode, new_vars) contains_states(poly::MPolyRingElem) = any(x -> degree(poly, x) > 0, ode.x_vars) contains_states(func) = contains_states(numerator(func)) || contains_states(denominator(func)) new_vars_contains_states = filter(contains_states, new_vars) - @info """ - Original states: $(ode.x_vars) - Original params: $(ode.parameters) - New variables that contain states: $(new_vars_contains_states)""" + @info "Original variables: $(length(ode.x_vars)) states and $(length(ode.parameters)) parameters" + @debug """Original variables + States: $(join(map(string, ode.x_vars), ", ")) + Params: $(join(map(string, ode.parameters), ", "))""" new_states = new_vars_contains_states new_params = setdiff(new_vars, new_vars_contains_states) - @info """ + @info "New macro variables: $(length(new_states)) states and $(length(new_params)) parameters" + @debug """ Reparametrizing with respect to: - New states: $new_states - New params: $new_params""" + New states: $(join(map(string, new_states), ", ")) + New params: $(join(map(string, new_params), ", "))""" return reparametrize_with_respect_to(ode, new_states, new_params) end @@ -57,6 +128,9 @@ function reparametrize_with_respect_to(ode, new_states, new_params) new_vector_field = vector_field_along(ode.x_equations, new_states) @debug "New vector field:\n$new_vector_field" new_states = collect(keys(new_vector_field)) + # Order by the first original state occurring in each new state. + # TODO: might be too invasive if we do this here instead of the outer function + sort!(new_states, by = f -> something(findfirst(in(vars(f)), ode.x_vars), length(ode.x_vars) + 1)) new_dynamics = [new_vector_field[new_state] for new_state in new_states] # Express the new dynamics in terms of new states and new parameters. outputs = [ode.y_equations[output] for output in ode.y_vars] @@ -74,7 +148,7 @@ function reparametrize_with_respect_to(ode, new_states, new_params) gen_tag_names(length(ode.u_vars), "Input"), gen_tag_names(length(ode.y_vars), "Output"), ) - @info """ + @debug """ Tag names: $tag_names Generating functions: @@ -82,12 +156,14 @@ function reparametrize_with_respect_to(ode, new_states, new_params) Functions to be reduced: $to_be_reduced_funcs """ - membership, new_dynamics_all, implicit_relations, new_vars = + @info "Constructing equations of new ODE" + mem_time = @elapsed membership, new_dynamics_all, implicit_relations, new_vars = check_constructive_field_membership( RationalFunctionField(generating_funcs), to_be_reduced_funcs; tag_names = tag_names, ) + @info "Constructed equations of new ODE in $mem_time seconds" @assert all(membership) ring_of_tags = parent(first(keys(new_vars))) tags = gens(ring_of_tags) @@ -103,7 +179,7 @@ function reparametrize_with_respect_to(ode, new_states, new_params) if !isempty(ode.u_vars) new_inputs = tag_inputs end - @info """ + @debug """ New state dynamics: $new_dynamics_states New output dynamics: @@ -117,19 +193,11 @@ function reparametrize_with_respect_to(ode, new_states, new_params) new_vars_vector_field[state] = new_dynamics_states[i] end @info "Converting variable names to human-readable ones" - internal_variable_names = map(i -> "X$i(t)", 1:length(new_states)) - parameter_variable_names = map(i -> "a$i", 1:length(new_params)) - input_variable_names = map(i -> "u$i(t)", 1:length(tag_inputs)) - output_variable_names = map(i -> "y$i(t)", 1:length(tag_outputs)) - all_variable_names = vcat( - internal_variable_names, - parameter_variable_names, - input_variable_names, - output_variable_names, - ) + new_names = suggest_names(ode, new_states, new_params) + @assert allunique(new_names) ring_output, _ = polynomial_ring( base_ring(ring_of_tags), - all_variable_names, + new_names, internal_ordering = Nemo.internal_ordering(ring_of_tags), ) new_vars_vector_field = Dict( @@ -146,9 +214,9 @@ function reparametrize_with_respect_to(ode, new_states, new_params) parent_ring_change(var_expr, ring_output, matching = :byindex) for (var_old, var_expr) in new_outputs ) - new_vars = Dict( - parent_ring_change(var_old, ring_output, matching = :byindex) => var_expr for - (var_old, var_expr) in new_vars + new_vars = OrderedDict( + parent_ring_change(var_old, ring_output, matching = :byindex) => new_vars[var_old] for + var_old in gens(ring_of_tags) ) implicit_relations = map( var_old -> parent_ring_change(var_old, ring_output, matching = :byindex), @@ -163,6 +231,34 @@ function reparametrize_with_respect_to(ode, new_states, new_params) return new_vars_vector_field, new_inputs, new_outputs, new_vars, implicit_relations end +function show_reparametrization(out, reparam) + # eval(ode_repr(ode)) ≈ ode + ode_repr(ode) = begin + s = sprint(show, reparam.new_ode) + s = join(map(line -> string(" "^2, line), split(rstrip(s, '\n'), "\n")), ",\n") + string("ode = @ODEmodel(\n", s, "\n)") + end + + println(out, "\n", "• Reparametrized ODE:\n") + println(out, ode_repr(reparam.new_ode), "\n") + + is_new = [string(v) != string(f) for (v, f) in reparam.new_vars] + println(out, "• Variable definitions ($(count(is_new)) new):\n") + for ((v, f), new) in zip(reparam.new_vars, is_new) + print(out, " ", v, " := ", f) + new && printstyled(out, " (new)"; color = :green) + println(out) + end + println(out) + + if !isempty(reparam.implicit_relations) + participants = mapreduce(vars, union, reparam.implicit_relations) + println(out, "• These variables are not independent:\n $(join(map(string, participants), ", "))", "\n") + end + + println(out, "• For more info, run\n\njulia> @doc reparametrize_global\n") +end + """ reparametrize_global(ode, options...) @@ -187,42 +283,34 @@ The function accepts the following optional arguments. ## Example -```jldoctest +```jldoctest; setup = :(using Logging; Logging.disable_logging(Logging.Info);) julia> using StructuralIdentifiability -julia> using Logging - -julia> Logging.disable_logging(Logging.Info); - julia> ode = @ODEmodel( x1'(t) = a * x1(t) - b*x1(t)*x2(t), x2'(t) = -c * x2(t) + d*x1(t)*x2(t), y(t) = x1(t) ); -julia> Logging.disable_logging(Logging.BelowMinLevel); - -julia> new_ode, new_vars, relations = reparametrize_global( - ode; loglevel = Logging.Error - ); +julia> new_ode, new_vars, relations = reparametrize_global(ode); ``` Then, we have the following: ``` # new_ode -X2'(t) = X1(t)*X2(t)*a2 - X2(t)*a1 -X1'(t) = -X1(t)*X2(t) + X1(t)*a3 -y1(t) = X1(t) +x1'(t) = a*x1(t) - x1(t)*x̃2(t) +x̃2'(t) = d*x1(t)*x̃2(t) - c*x̃2(t) +y(t) = x1(t) # new_vars Dict{Nemo.QQMPolyRingElem, AbstractAlgebra.Generic.FracFieldElem{Nemo.QQMPolyRingElem}} with 6 entries: - X2 => b*x2 - y1 => y - X1 => x1 - a2 => d - a3 => a - a1 => c + x1(t) => x1(t) + x̃2(t) => b*x2(t) + y(t) => y(t) + d => d + a => a + c => c ``` Notice that the `new_ode` is fully identifiabile, and has `1` less parameter @@ -256,6 +344,11 @@ function _reparametrize_global(ode::ODE{P}; prob_threshold = 0.99, seed = 42, cm new_vector_field, new_inputs, new_outputs, new_vars, implicit_relations = reparametrize_with_respect_to(ode, id_funcs) new_ring = parent(first(keys(new_vector_field))) - new_ode = ODE{P}(new_vector_field, new_outputs, new_inputs) - return (new_ode = new_ode, new_vars = new_vars, implicit_relations = implicit_relations) + # Fix the order of variables in the new ODE + new_x_vars = filter(v -> haskey(new_vector_field, v), gens(new_ring)) + new_y_vars = filter(v -> haskey(new_outputs, v), gens(new_ring)) + new_ode = ODE{P}(new_x_vars, new_y_vars, new_vector_field, new_outputs, new_inputs) + reparam = (new_ode = new_ode, new_vars = new_vars, implicit_relations = implicit_relations) + @info (show_reparametrization(stdout, reparam); "Done!") + reparam end diff --git a/test/bodies/ode.jl b/test/bodies/ode.jl index 51b3a9ae9..d70cfea28 100644 --- a/test/bodies/ode.jl +++ b/test/bodies/ode.jl @@ -29,6 +29,72 @@ include(joinpath(@__DIR__, "..", "shared", "test_setup.jl")) ) end +# Some nasty corner cases +@testset "Reparametrization names" begin + suggest_names = StructuralIdentifiability.suggest_names + ode = @ODEmodel( + x10'(t) = a1 * x10(t) + b * z(t) + x̃10(t), + z'(t) = 0, + X3(t) = x10(t), + ) + @test suggest_names(ode, ode.x_vars, ode.parameters) == + string.(vcat(ode.x_vars, ode.parameters, ode.u_vars, ode.y_vars)) + + # Preserve indices and reserve names of parameters, inputs, and outputs. + @test suggest_names( + ode, [a1 * x10, b * x10, x10 + z, x10] .// one(parent(ode)), + [a1 + b, a1] .// one(parent(ode)), + ) == ["x̃10_2(t)", "x̃10_3(t)", "X3_2(t)", "x10(t)", "a1_2", "a1", "x̃10(t)", "X3(t)"] + @test suggest_names(ode, [x10], [a1, a1]) == + ["x10(t)", "a1", "a1_2", "x̃10(t)", "X3(t)"] + + # An unchanged name always wins. + ode = @ODEmodel(n'(t) = a * n(t), ñ'(t) = 0, y(t) = n(t)) + for states in ([a * n, ñ], [ñ, a * n]) + names = suggest_names(ode, states, [a]) + @test Dict(names[1:2] .=> states) == Dict("ñ(t)" => ñ, "ñ_2(t)" => a * n) + end + + R, (x0, a, y) = polynomial_ring(QQ, ["x0", "a", "y"]) + ode = ODE{typeof(x0)}(Dict(x0 => a * x0), Dict(y => x0), typeof(x0)[]) + @test suggest_names(ode, [a * x0, 2 * a * x0], [a]) == ["x̃0", "x̃0_2", "a", "y"] + + ode = @ODEmodel(x'(t) = (k8 + k9 + k10) * x(t), y(t) = x(t)) + @test suggest_names(ode, [x], [k9^2]) == ["x(t)", "k̃9", "y(t)"] + @test suggest_names(ode, [x], [k9^2, 1 // k9, k9]) == ["x(t)", "k̃9", "k̃9_2", "k9", "y(t)"] + @test suggest_names(ode, [x], [k10 + 2 * k8, k10 * k9]) == ["x(t)", "a1", "a2", "y(t)"] + @test suggest_names(ode, empty(ode.x_vars), [k9^2]) == ["k̃9", "y(t)"] +end + +@testset "Rename variables" begin + ode = @ODEmodel( + x'(t) = (a * x(t) + u(t)) // (b + x(t)), + z'(t) = x(t) - z(t), + y(t) = x(t) + z(t), + ) + original = sprint(show, ode) + @test sprint(show, rename_variables(ode, Dict{String, String}())) == original + for transform in ( + Dict("x" => "χ", "a" => "α", "u" => "signal", "y" => "output"), + Dict("x" => "ignored", "x(t)" => "χ(t)", "a" => "α", "u(t)" => "signal(t)", "y(t)" => "output(t)"), + ) + renamed = rename_variables(ode, transform) + χ, z, α, b, signal, output = str_to_var.( + ["χ(t)", "z(t)", "α", "b", "signal(t)", "output(t)"], Ref(parent(renamed)), + ) + @test renamed.x_vars == [χ, z] + @test renamed.u_vars == [signal] + @test renamed.y_vars == [output] + @test Set(string.(renamed.parameters)) == Set(["α", "b"]) + @test renamed.x_equations[χ] == (α * χ + signal) // (b + χ) + @test renamed.x_equations[z] == χ - z + @test renamed.y_equations[output] == χ + z + restored = rename_variables(renamed, Dict("χ" => "x", "α" => "a", "signal" => "u", "output" => "y")) + @test sprint(show, restored) == original + @test sprint(show, ode) == original + end +end + @testset "ODE/DDE unicode" begin ode = StructuralIdentifiability.@ODEmodel( 🐁'(t) = a * 🐁 - b * 🐁 * 🦉, diff --git a/test/bodies/paradigm_shift.jl b/test/bodies/paradigm_shift.jl index a8a686556..0d74eacf2 100644 --- a/test/bodies/paradigm_shift.jl +++ b/test/bodies/paradigm_shift.jl @@ -3,9 +3,8 @@ include(joinpath(@__DIR__, "..", "shared", "test_setup.jl")) ≡(A, B) = A ⊆ B && B ⊆ A function test_reparametrization(old_ode, new_ode, var_mapping, implicit_relations) - # NOTE: should this be strengthened to == ? - # @test map(string, old_ode.u_vars) ≡ map(string, new_ode.u_vars) - # @test map(string, old_ode.y_vars) ≡ map(string, new_ode.y_vars) + @test map(var_to_str, old_ode.u_vars) ≡ map(var_to_str, new_ode.u_vars) + @test map(var_to_str, old_ode.y_vars) ≡ map(var_to_str, new_ode.y_vars) @test length(old_ode.y_vars) == length(new_ode.y_vars) @test length(old_ode.u_vars) == length(new_ode.u_vars) @test base_ring(parent(first(values(var_mapping)))) == parent(old_ode)