# Access variables of another subsystem in a callback

**URL:** https://discourse.julialang.org/t/access-variables-of-another-subsystem-in-a-callback/108248
**Category:** Modelling & Simulations
**Created:** [January 2, 2024, 7:19am UTC](https://discourse.julialang.org/t/access-variables-of-another-subsystem-in-a-callback/108248 "2024-01-02T07:19:28Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![HKruenaegel](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/hkruenaegel/32/205865_2.png) [@HKruenaegel](https://discourse.julialang.org/u/HKruenaegel)
#### Post date: [January 2, 2024, 7:19am UTC](https://discourse.julialang.org/t/access-variables-of-another-subsystem-in-a-callback/108248/1 "2024-01-02T07:19:29Z")

</div>

Is it possible to read a variable of another subsystem in a callback? For example if I want tu use decay2.u in a callback defined in decay1 in the following example code:

```julia
using ModelingToolkit
function affect!(integ,u,p,ctx)
    println(integ.u[u.decay2.u])
end
function decay_1(; name)
    @parameters t a
    @variables x(t) f(t)
    D = Differential(t)
    control = 10 => (affect!, [x,decay2.u], [], nothing) 

    ODESystem([
            D(x) ~ -a * x + f,
        ];
        name = name,discrete_events=[control])
end

function decay_2(; name)
    @parameters t a
    @variables u(t) f(t)
    D = Differential(t)

    ODESystem([
            D(u) ~ -a * u + f,
        ];
        name = name)
end

@named decay1 = decay_1()
@named decay2 = decay_2()

@parameters t
D = Differential(t)
connected = compose(ODESystem([decay2.f ~ decay1.x
            D(decay1.f) ~ 0], t; name = :connected), decay1, decay2)

equations(connected)

simplified_sys = structural_simplify(connected)

equations(simplified_sys)

x0 = [decay1.x => 1.0
    decay1.f => 0.0
    decay2.u => 1.0]
p = [decay1.a => 0.1
    decay2.a => 0.2]

using DifferentialEquations
prob = ODEProblem(simplified_sys, x0, (0.0, 100.0), p)
sol = solve(prob, Tsit5())
sol[decay2.f]

```

---

<div class="post-metadata">

### Author: ![baggepinnen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/baggepinnen/32/693_2.png) [@baggepinnen](https://discourse.julialang.org/u/baggepinnen)
#### Post date: [January 2, 2024, 8:23am UTC](https://discourse.julialang.org/t/access-variables-of-another-subsystem-in-a-callback/108248/2 "2024-01-02T08:23:13Z")

</div>

This is not possible. Indeed, if you need access to the properties of another subsystem, you could argue that you shouldn’t be using subsystems in the first place.

The workaround is that you define the callback in terms of a “connection variable” inside `decay1`, and connect this variable similar to `decay2.f ~ decay1.x` when you assemble the subsystems.
