Repository navigation
Add ContinuousState and Threshold for event-driven continuous-time dynamics - #3766
Conversation
ContinuousState, Threshold, and ContinuousScheduler
|
I am also open to integrate |
|
Performance benchmarks:
|
|
Example Run of Tram Model |
|
I would appreciate some guidance @quaquel |
|
@codebreaker32, I had a quick first pass but need some time to look at it in detail. I'll try to respond tomorrow the latest. |
|
|
|
Would appreciate what @quaquel think about APIs now? Following our discussion, |
|
I have fixed the ruff checks, Now the next thing is to decide upon tram_model example
|
jackiekazil
left a comment
There was a problem hiding this comment.
LGTM.... everything discussed was covered. All related tests are passing. There are tests unrelated to this that are failing due to upstream dependencies, but that shouldn't hold this up.
^^ I missed this comment. RE: tram_model -- yes or no? RE: tram_model PR |
We have changes to the PR coming... removing for now, so no mistaken merges are mage.
Done. |
|
Was new PR for the example posted? Can you link it? |
|
Tests and Description updated! Good to go from my end 👍 |
ContinuousState and ThresholdContinuousState and Threshold for event-driven continuous-time dynamics
Summary
Adds
mesa/experimental/states/—ContinuousStateandThreshold, giving Mesa agents exact, event-driven continuous-time kinematics instead of step-by-step polling.Motive
Agents with continuously-changing quantities — speed, position, energy, inventory drain, anything with a rate — have had two bad options in Mesa: poll every tick (cost scales with step count, accuracy scales with step size), or hand-roll time-projection math per model. Neither generalizes.
This module gives a declarative alternative: state a quantity's rate of change once, and get its exact value at any future time plus a callback the instant it crosses a threshold — computed once analytically, not approximated by sampling. A transit agent whose speed and position must be queryable at arbitrary times, without the model stepping every second just to check "have we reached the brake point yet," is the motivating case; a tram example exercising it end-to-end follows in a separate PR.
Implementation
ContinuousState(aBaseObservabledescriptor): tracksbase_value/last_time/current_rateand extrapolatesvalue(t) = base + rate·dt.rateis either a constant float or a callablef(agent) -> floatevaluated reactively through themesa_signalsComputedStatediffing engine, so a rate change snapshots the current value as the new baseline and the trajectory stays mathematically continuous across the switch.ContinuousState—position's rate isspeed, which is itself changing under acceleration —_find_chained_ratedetects it from the recorded dependencies and adds the next-order term,0.5·second_order_rate·dt², so position integrates exactly through an acceleration phase instead of drifting between reads.{name}_rateObservable, with a__set_name__guard that raises on namespace collisions (checked against both__dict__and__slots__).Agent.__init__) is narrowly detected and treated as "at rest," while genuine typos in the rate lambda still raise.Threshold: fires a named agent callback when aContinuousStatecrosses a value, with the crossing time solved analytically rather than polled. The solver branches on whether the state is chained — plain linear solve for a constant-rate state, exact quadratic root solve (0.5·a·t² + v·t + (x₀−limit) = 0) for one chained off anotherContinuousState.direction("rising"/"falling"/"crossing") is enforced against the velocity at the root, so tangent touches bounce rather than fire, and a zero-time root while already sitting on the limit (the mid-callback case, wherebrake()sets acceleration whileposition == limit) is rejected instead of immediately re-firing.limitis a fixed float or anObservableon the agent. When it's an Observable,bind()subscribes to the limit'sCHANGEDsignal alongside the state's, so a per-instance runtime target — a tram's brake point depends on its own route, not a class-wide constant — is set by plain assignment and recalculates itself. No imperativeset_limit()/rearm()calls, and re-arming across repeated cycles falls out of the same mechanism.model.schedule_event, cancelling and re-scheduling as the trajectory shifts; a "never crosses" result cancels and parks the projected time atinf.ContinuousStateaccess on an instance walks the MRO for_continuous_thresholdsand wires them up, so no scheduler or registration step is required.Usage
Additional Notes
A future direction worth flagging now:
_find_chained_ratelooks one link deep and adds a single quadratic term. It works because the chain is exactly twoContinuousStates long (position → speed → acceleration, a discreteObservable). A natural generalization is anODEState: instead of a single scalar rate, it would hold a rate functionf(t, y) -> dy/dt(or a small system of them) stepped forward with a proper numerical integrator (RK4 or an adaptive method) rather than a closed-form polynomial per order. That would let arbitrary chains, or genuinely nonlinear dynamics such as drag proportional tospeed², be expressed directly — at the cost ofThresholdlosing its exact analytical crossing time and needing bisection/interpolation on the integrator's output instead of a polynomial root. Worth keeping in mind as a separate, later addition.