|
| 1 | +function swap_id_name(k, v; prop = :name) |
| 2 | + new_prop = getproperty(v, prop) |
| 3 | + @set! v.$prop = k |
| 4 | + new_prop, v |
| 5 | +end |
| 6 | + |
| 7 | +function replace_math_ident(id_name_dict, node) |
| 8 | + if typeof(node) == SBML.MathIdent |
| 9 | + return SBML.MathIdent(id_name_dict[node.id]) |
| 10 | + elseif typeof(node) == SBML.MathApply |
| 11 | + return SBML.MathApply(node.fn, replace_math_ident(id_name_dict, node.args)) |
| 12 | + elseif isa(node, AbstractArray) |
| 13 | + return map(x -> replace_math_ident(id_name_dict, x), node) |
| 14 | + else |
| 15 | + return node |
| 16 | + end |
| 17 | +end |
| 18 | + |
| 19 | +"SimBiology makes the names of everything a hashed ID, but keeps the ID in the name" |
| 20 | +function fix_simbio_names(m::SBML.Model) |
| 21 | + cid_name_d = Dict(keys(m.compartments) .=> getproperty.(values(m.compartments), :name)) |
| 22 | + pid_name_d = Dict(keys(m.parameters) .=> getproperty.(values(m.parameters), :name)) |
| 23 | + rid_name_d = Dict(keys(m.reactions) .=> getproperty.(values(m.reactions), :name)) |
| 24 | + |
| 25 | + for prop in [:compartments, :parameters, :reactions] |
| 26 | + xs = getproperty(m, prop) |
| 27 | + new_xs = Dict() |
| 28 | + for (k, v) in xs |
| 29 | + nk, nv = swap_id_name(k, v) |
| 30 | + new_xs[nk] = nv |
| 31 | + end |
| 32 | + @set! m.$prop = new_xs |
| 33 | + end |
| 34 | + |
| 35 | + new_ss = Dict() |
| 36 | + for (k, v) in m.species |
| 37 | + nk, nv = swap_id_name(k, v) |
| 38 | + cname = cid_name_d[v.compartment] |
| 39 | + # for species, we want to concat the name and compartment name like in simbiology and MTK |
| 40 | + sname = string(cname, "₊", nk) |
| 41 | + @set! nv.compartment = cname |
| 42 | + new_ss[sname] = nv |
| 43 | + end |
| 44 | + @set! m.species = new_ss |
| 45 | + |
| 46 | + sid_name_d = Dict(reverse.(keys(new_ss) .=> getproperty.(values(new_ss), :name))) |
| 47 | + |
| 48 | + ds = [cid_name_d, pid_name_d, rid_name_d, sid_name_d] |
| 49 | + slen = sum(length.(ds)) |
| 50 | + id_name_dict = merge(ds...) |
| 51 | + @assert slen == length(id_name_dict) |
| 52 | + |
| 53 | + for (k, v) in m.reactions |
| 54 | + for (i, sr) in enumerate(v.reactants) |
| 55 | + @set! sr.species = id_name_dict[sr.species] |
| 56 | + m.reactions[k].reactants[i] = sr |
| 57 | + end |
| 58 | + for (i, sr) in enumerate(v.products) |
| 59 | + @set! sr.species = id_name_dict[sr.species] |
| 60 | + m.reactions[k].products[i] = sr |
| 61 | + end |
| 62 | + @set! m.reactions[k].kinetic_math = replace_math_ident(id_name_dict, v.kinetic_math) |
| 63 | + end |
| 64 | + |
| 65 | + for (i, r) in enumerate(m.rules) |
| 66 | + @set! m.rules[i].variable = id_name_dict[r.variable] |
| 67 | + new_tree = replace_math_ident(id_name_dict, r.math) |
| 68 | + @set! m.rules[i].math = new_tree |
| 69 | + end |
| 70 | + |
| 71 | + m |
| 72 | +end |
0 commit comments