Skip to content

Add ContinuousState and Threshold for event-driven continuous-time dynamics - #3766

Merged
jackiekazil merged 26 commits into
mesa:mainfrom
codebreaker32:experimental/states_v2
Aug 9, 2026
Merged

jackiekazil merged 26 commits into
mesa:mainfrom
codebreaker32:experimental/states_v2

Conversation

@codebreaker32

@codebreaker32 codebreaker32 commented Jun 29, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds mesa/experimental/states/ — ContinuousState and Threshold, 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 (a BaseObservable descriptor): tracks base_value/last_time/current_rate and extrapolates value(t) = base + rate·dt. rate is either a constant float or a callable f(agent) -> float evaluated reactively through the mesa_signals ComputedState diffing engine, so a rate change snapshots the current value as the new baseline and the trajectory stays mathematically continuous across the switch.

    • Chained states: when a state's rate is itself another ContinuousState — position's rate is speed, which is itself changing under acceleration — _find_chained_rate detects 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.
    • Declaring the state auto-generates a shadow {name}_rate Observable, with a __set_name__ guard that raises on namespace collisions (checked against both __dict__ and __slots__).
    • Assigning inside a computed context raises on cyclical dependencies, and an init-ordering race (a rate lambda reading an Observable whose backing store doesn't exist yet, mid-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 a ContinuousState crosses 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 another ContinuousState. 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, where brake() sets acceleration while position == limit) is rejected instead of immediately re-firing.

    • Limits are declarative. limit is a fixed float or an Observable on the agent. When it's an Observable, bind() subscribes to the limit's CHANGED signal 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 imperative set_limit()/rearm() calls, and re-arming across repeated cycles falls out of the same mechanism.
    • Each threshold owns exactly one live entry on Mesa's native event queue via model.schedule_event, cancelling and re-scheduling as the trajectory shifts; a "never crosses" result cancels and parks the projected time at inf.
    • Thresholds bind lazily — the first ContinuousState access on an instance walks the MRO for _continuous_thresholds and wires them up, so no scheduler or registration step is required.

Usage

from mesa.experimental.mesa_signals import HasEmitters, Observable
from mesa.experimental.states import ContinuousState, Threshold


class Tram(Agent, HasEmitters):
    acceleration = Observable(fallback_value=0.0)
    speed = ContinuousState(fallback_value=0.0, rate=lambda a: a.acceleration)
    position = ContinuousState(fallback_value=0.0, rate=lambda a: a.speed)  # chained: position' = speed
    brake_point = Observable(fallback_value=float("inf"))

    # fixed limit -- same cruise speed for every tram
    _cruise = Threshold(state=speed, limit=15.0, callback="start_coasting", direction="rising")

    # Observable limit -- per-instance, recalculates whenever brake_point is assigned
    _brake_point = Threshold(state=position, limit=brake_point, callback="brake", direction="rising")

    _stop = Threshold(state=speed, limit=0.0, callback="arrive_at_station", direction="falling")

    def depart(self):
        self.brake_point = self.next_station - self.braking_distance()  # re-arms automatically
        self.acceleration = 2.0

    def brake(self):
        # fires with an exact crossing time whether the tram is still
        # accelerating, coasting, or already braking when it reaches brake_point
        self.acceleration = -3.0

Additional Notes

A future direction worth flagging now: _find_chained_rate looks one link deep and adds a single quadratic term. It works because the chain is exactly two ContinuousStates long (position → speed → acceleration, a discrete Observable). A natural generalization is an ODEState: instead of a single scalar rate, it would hold a rate function f(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 to speed², be expressed directly — at the cost of Threshold losing 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.

@codebreaker32

Copy link
Copy Markdown
Collaborator Author

I have spent some good time building over @quaquel, @EwoutH and @tpike3 feedbacks(Thanks for it). Hope this implementation aligns with what you all have in mind.
I am currently working on Tram Model as suggested, will push the model by tomorrow to have better understanding

@codebreaker32 codebreaker32 changed the title Introduction of ContinuousState, Threshold, and ContinuousScheduler Introduction of ContinuousState, Threshold, and ContinuousScheduler Jun 29, 2026
@codebreaker32

codebreaker32 commented Jun 29, 2026 •

Copy link
Copy Markdown
Collaborator Author

I am also open to integrate ContinuousScheduler into mesa.time.events

@github-actions

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🟢 -3.8% [-4.4%, -3.3%] 🔵 -0.3% [-0.5%, -0.2%]
BoltzmannWealth large 🔵 -2.4% [-3.2%, -1.5%] 🔵 -0.2% [-3.1%, +3.8%]
Schelling small 🟢 -4.3% [-4.8%, -3.8%] 🔵 -1.7% [-2.6%, -0.8%]
Schelling large 🔵 -2.7% [-3.3%, -2.0%] 🟢 -6.8% [-10.0%, -4.4%]
WolfSheep small 🔵 -1.8% [-2.5%, -1.2%] 🔵 +1.8% [-2.1%, +5.9%]
WolfSheep large 🔵 -0.7% [-2.5%, +0.9%] 🔵 -1.2% [-4.5%, +2.2%]
SugarscapeG1mt small 🟢 -7.2% [-7.8%, -6.6%] 🔵 -3.5% [-5.0%, -2.0%]
SugarscapeG1mt large 🟢 -4.8% [-6.1%, -3.8%] 🟢 -4.5% [-5.8%, -3.1%]
BoidFlockers small 🔵 -2.7% [-3.3%, -2.1%] 🔵 -0.6% [-1.1%, -0.2%]
BoidFlockers large 🔵 -0.3% [-1.0%, +0.4%] 🔵 -0.8% [-1.1%, -0.5%]

@codebreaker32

Copy link
Copy Markdown
Collaborator Author

Example Run of Tram Model

Route: [0, 200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000, 2200, 2400, 2600, 2800, 3000, 3200, 3400, 3600, 3800]
cruise_speed=15.0 m/s, acceleration=2.0 m/s^2, deceleration=3.0 m/s^2, braking_distance=37.50m

[t=0.00] Tram 1 departing (pos=0.00) towards station at 200.00m. Accelerating at 2.0 m/s^2.
[t=7.50] Tram 1 reached cruise speed 15.0 m/s. Coasting.
[t=14.58] Tram 1 at brake point (pos=162.50). Applying brakes at -3.0 m/s^2.
[t=19.58] Tram 1 arrived at station (pos=200.00).
[t=24.58] Tram 1 departing (pos=200.00) towards station at 400.00m. Accelerating at 2.0 m/s^2.
[t=32.08] Tram 1 reached cruise speed 15.0 m/s. Coasting.
[t=39.17] Tram 1 at brake point (pos=362.50). Applying brakes at -3.0 m/s^2.
[t=44.17] Tram 1 arrived at station (pos=400.00).
[t=49.17] Tram 1 departing (pos=400.00) towards station at 600.00m. Accelerating at 2.0 m/s^2.
[t=56.67] Tram 1 reached cruise speed 15.0 m/s. Coasting.
[t=63.75] Tram 1 at brake point (pos=562.50). Applying brakes at -3.0 m/s^2.
[t=68.75] Tram 1 arrived at station (pos=600.00).
[t=73.75] Tram 1 departing (pos=600.00) towards station at 800.00m. Accelerating at 2.0 m/s^2.
[t=81.25] Tram 1 reached cruise speed 15.0 m/s. Coasting.
[t=88.33] Tram 1 at brake point (pos=762.50). Applying brakes at -3.0 m/s^2.
[t=93.33] Tram 1 arrived at station (pos=800.00).
[t=98.33] Tram 1 departing (pos=800.00) towards station at 1000.00m. Accelerating at 2.0 m/s^2.
[t=105.83] Tram 1 reached cruise speed 15.0 m/s. Coasting.
[t=112.92] Tram 1 at brake point (pos=962.50). Applying brakes at -3.0 m/s^2.
[t=117.92] Tram 1 arrived at station (pos=1000.00).
[t=122.92] Tram 1 departing (pos=1000.00) towards station at 1200.00m. Accelerating at 2.0 m/s^2.
[t=130.42] Tram 1 reached cruise speed 15.0 m/s. Coasting.
[t=137.50] Tram 1 at brake point (pos=1162.50). Applying brakes at -3.0 m/s^2.
[t=142.50] Tram 1 arrived at station (pos=1200.00).
[t=147.50] Tram 1 departing (pos=1200.00) towards station at 1400.00m. Accelerating at 2.0 m/s^2.
[t=155.00] Tram 1 reached cruise speed 15.0 m/s. Coasting.
[t=162.08] Tram 1 at brake point (pos=1362.50). Applying brakes at -3.0 m/s^2.
[t=167.08] Tram 1 arrived at station (pos=1400.00).
[t=172.08] Tram 1 departing (pos=1400.00) towards station at 1600.00m. Accelerating at 2.0 m/s^2.
[t=179.58] Tram 1 reached cruise speed 15.0 m/s. Coasting.
[t=186.67] Tram 1 at brake point (pos=1562.50). Applying brakes at -3.0 m/s^2.
[t=191.67] Tram 1 arrived at station (pos=1600.00).
[t=196.67] Tram 1 departing (pos=1600.00) towards station at 1800.00m. Accelerating at 2.0 m/s^2.
[t=204.17] Tram 1 reached cruise speed 15.0 m/s. Coasting.
[t=211.25] Tram 1 at brake point (pos=1762.50). Applying brakes at -3.0 m/s^2.
[t=216.25] Tram 1 arrived at station (pos=1800.00).
[t=221.25] Tram 1 departing (pos=1800.00) towards station at 2000.00m. Accelerating at 2.0 m/s^2.
[t=228.75] Tram 1 reached cruise speed 15.0 m/s. Coasting.
[t=235.83] Tram 1 at brake point (pos=1962.50). Applying brakes at -3.0 m/s^2.
[t=240.83] Tram 1 arrived at station (pos=2000.00).
[t=245.83] Tram 1 departing (pos=2000.00) towards station at 2200.00m. Accelerating at 2.0 m/s^2.
[t=253.33] Tram 1 reached cruise speed 15.0 m/s. Coasting.
[t=260.42] Tram 1 at brake point (pos=2162.50). Applying brakes at -3.0 m/s^2.
[t=265.42] Tram 1 arrived at station (pos=2200.00).
[t=270.42] Tram 1 departing (pos=2200.00) towards station at 2400.00m. Accelerating at 2.0 m/s^2.
[t=277.92] Tram 1 reached cruise speed 15.0 m/s. Coasting.
[t=285.00] Tram 1 at brake point (pos=2362.50). Applying brakes at -3.0 m/s^2.
[t=290.00] Tram 1 arrived at station (pos=2400.00).
[t=295.00] Tram 1 departing (pos=2400.00) towards station at 2600.00m. Accelerating at 2.0 m/s^2.
[t=302.50] Tram 1 reached cruise speed 15.0 m/s. Coasting.
[t=309.58] Tram 1 at brake point (pos=2562.50). Applying brakes at -3.0 m/s^2.
[t=314.58] Tram 1 arrived at station (pos=2600.00).
[t=319.58] Tram 1 departing (pos=2600.00) towards station at 2800.00m. Accelerating at 2.0 m/s^2.
[t=327.08] Tram 1 reached cruise speed 15.0 m/s. Coasting.
[t=334.17] Tram 1 at brake point (pos=2762.50). Applying brakes at -3.0 m/s^2.
[t=339.17] Tram 1 arrived at station (pos=2800.00).
[t=344.17] Tram 1 departing (pos=2800.00) towards station at 3000.00m. Accelerating at 2.0 m/s^2.
[t=351.67] Tram 1 reached cruise speed 15.0 m/s. Coasting.
[t=358.75] Tram 1 at brake point (pos=2962.50). Applying brakes at -3.0 m/s^2.
[t=363.75] Tram 1 arrived at station (pos=3000.00).
[t=368.75] Tram 1 departing (pos=3000.00) towards station at 3200.00m. Accelerating at 2.0 m/s^2.
[t=376.25] Tram 1 reached cruise speed 15.0 m/s. Coasting.
[t=383.33] Tram 1 at brake point (pos=3162.50). Applying brakes at -3.0 m/s^2.
[t=388.33] Tram 1 arrived at station (pos=3200.00).
[t=393.33] Tram 1 departing (pos=3200.00) towards station at 3400.00m. Accelerating at 2.0 m/s^2.
[t=400.83] Tram 1 reached cruise speed 15.0 m/s. Coasting.
[t=407.92] Tram 1 at brake point (pos=3362.50). Applying brakes at -3.0 m/s^2.
[t=412.92] Tram 1 arrived at station (pos=3400.00).
[t=417.92] Tram 1 departing (pos=3400.00) towards station at 3600.00m. Accelerating at 2.0 m/s^2.
[t=425.42] Tram 1 reached cruise speed 15.0 m/s. Coasting.
[t=432.50] Tram 1 at brake point (pos=3562.50). Applying brakes at -3.0 m/s^2.
[t=437.50] Tram 1 arrived at station (pos=3600.00).
[t=442.50] Tram 1 departing (pos=3600.00) towards station at 3800.00m. Accelerating at 2.0 m/s^2.
[t=450.00] Tram 1 reached cruise speed 15.0 m/s. Coasting.
[t=457.08] Tram 1 at brake point (pos=3762.50). Applying brakes at -3.0 m/s^2.
[t=462.08] Tram 1 arrived at station (pos=3800.00).
[t=462.08] Tram 1 has completed its route.

Final time:     2000.00
Final position: 3800.00 m

@codebreaker32

Copy link
Copy Markdown
Collaborator Author

I would appreciate some guidance @quaquel

@quaquel

quaquel commented Jul 6, 2026

Copy link
Copy Markdown
Member

@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.

Comment thread mesa/experimental/states/state.py Resolved
Comment thread mesa/experimental/states/state.py Resolved
Comment thread mesa/experimental/states/state.py Resolved
Comment thread mesa/experimental/states/tram_model.py Resolved
@codebreaker32

Copy link
Copy Markdown
Collaborator Author

Threshold.limit now accepts an Observable in addition to a plain float. When it does, bind() subscribes to the limit's CHANGED signal so the projected crossing time updates automatically whenever the limit changes, the same way it already responds to the watched state changing. This removes the need for rearm(), set_limit(), limit_attr, and fired_attr, which only existed to manually compensate for the limit being static. In tram_model.py, the brake point becomes a plain Observable on the tram; depart() just sets it alongside acceleration, and the threshold does the rest.

@codebreaker32

codebreaker32 commented Jul 13, 2026 •

Copy link
Copy Markdown
Collaborator Author

Would appreciate what @quaquel think about APIs now? Following our discussion, tram_model.py no longer accesses the private descriptor nor method

@codebreaker32

codebreaker32 commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator Author

I have fixed the ruff checks, Now the next thing is to decide upon tram_model example

  1. Should I include it in this PR, if yes? where should I put it?
  2. Or should I open a separate PR for it?

jackiekazil
jackiekazil previously approved these changes Jul 30, 2026

@jackiekazil jackiekazil left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

@jackiekazil jackiekazil self-assigned this Jul 30, 2026
@jackiekazil jackiekazil added the experimental Release notes label label Jul 30, 2026
@jackiekazil

Copy link
Copy Markdown
Member

I have fixed the ruff checks, Now the next thing is to decide upon tram_model example

  1. Should I include it in this PR, if yes? where should I put it?
  2. Or should I open a separate PR for it?

^^ I missed this comment.

RE: tram_model -- yes or no?
Looking at our examples in our examples folder -- I didn't think that we can cleanly extend one of our current examples. It sounds like we are in agreement here (/cc @quaquel, re: #3755 (comment)).

RE: tram_model PR
Let's remove it from this PR and put it into another PR, then we can merge this.

@jackiekazil
jackiekazil self-requested a review July 30, 2026 15:29
@jackiekazil
jackiekazil dismissed their stale review July 30, 2026 15:29

We have changes to the PR coming... removing for now, so no mistaken merges are mage.

@codebreaker32

Copy link
Copy Markdown
Collaborator Author

RE: tram_model PR
Let's remove it from this PR and put it into another PR, then we can merge this.

Done.

@jackiekazil

Copy link
Copy Markdown
Member

Was new PR for the example posted? Can you link it?

@codebreaker32

Copy link
Copy Markdown
Collaborator Author

Tests and Description updated! Good to go from my end 👍

@codebreaker32 codebreaker32 changed the title Introduction of ContinuousState and Threshold Add ContinuousState and Threshold for event-driven continuous-time dynamics Aug 6, 2026

@jackiekazil jackiekazil left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM (Looks good to me)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

experimental Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants