Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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]
Expand Down
4 changes: 2 additions & 2 deletions src/ODE.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions src/StructuralIdentifiability.jl
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import Primes
import Random
import TimerOutputs
using TimerOutputs: @timeit, disable_timer!, enable_timer!
import Unicode

# Algebra packages
import AbstractAlgebra
Expand Down
2 changes: 1 addition & 1 deletion src/identifiable_functions.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
183 changes: 138 additions & 45 deletions src/parametrizations.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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))))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Runic] reported by reviewdog 🐶

Suggested change

@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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Runic] reported by reviewdog 🐶

Suggested change

# 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Runic] reported by reviewdog 🐶

Suggested change
names
return names

end

"""
reparametrize_with_respect_to(ode, new_vars)

Expand All @@ -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

Expand All @@ -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]
Expand All @@ -74,20 +148,22 @@ 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:
$generating_funcs
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)
Expand All @@ -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:
Expand All @@ -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(
Expand All @@ -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),
Expand All @@ -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")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Runic] reported by reviewdog 🐶

Suggested change
println(out, "• For more info, run\n\njulia> @doc reparametrize_global\n")
return println(out, "• For more info, run\n\njulia> @doc reparametrize_global\n")

end

"""
reparametrize_global(ode, options...)

Expand All @@ -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
Expand Down Expand Up @@ -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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Runic] reported by reviewdog 🐶

Suggested change
reparam
return reparam

end
Loading
Loading