Skip to content

About

Rust reinforcement schedule engine. Port of contingency-py with bit-equivalent semantics (via 14 conformance fixtures). Bindings: PyO3, WASM, C FFI, UniFFI (Swift/Kotlin). HIL TCP/JSONL binary included.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

contingency-rs

🇯🇵 日本語版 README

contingency-rs is the Rust version of the OperantKit reinforcement-schedule engine: given a schedule such as FR 5 or a concurrent VI VI, and the responses as they happen, it decides when a reinforcer is delivered. Use it when the program that runs your chamber or task is not written in Python: a Rust or C controller, a browser experiment (WebAssembly, with a jsPsych plugin), a Swift or Kotlin app, or a hardware-in-the-loop (HIL) test rig. It is a port of contingency-py within OperantKit; the executable specification is the Python package's 39 conformance fixtures, which this crate replays.

  • Same outcomes as contingency-py. tests/conformance.rs replays all 39 fixtures, including the 8 seeded ones; the seeded draws match because the crate ports CPython's random.Random.
  • Variable schedules use the Fleshler–Hoffman (1962) progression, and concurrent schedules apply the changeover delay (COD): the time after a switch between operanda (levers, keys) during which no response is reinforced.
  • One engine for several hosts: Rust, C, Python, WebAssembly, and Swift/Kotlin call the same schedule code.

Notes for AI coding agents are in AGENTS.md.

Installation

The crate (named contingency) is not on crates.io. Add it to your Cargo.toml as a git dependency; indexmap is needed to key the components of a concurrent schedule:

[dependencies]
contingency = { git = "https://github.com/OperantKit/contingency-rs" }
indexmap = "2"

Example

A concurrent VI 30-s VI 60-s schedule with a 2-s COD, driven by a simulated subject that responds every 0.5 s and switches operanda every 10 s for 10 minutes:

use contingency::{ResponseEvent, ScheduleBuilder};
use indexmap::IndexMap;

fn main() -> contingency::Result<()> {
    // Conc VI 30-s VI 60-s, COD 2 s; Fleshler-Hoffman intervals (n = 12) with fixed seeds.
    let mut components = IndexMap::new();
    components.insert("left".to_string(), ScheduleBuilder::vi(30.0, 12, Some(42))?);
    components.insert("right".to_string(), ScheduleBuilder::vi(60.0, 12, Some(7))?);
    let mut schedule = ScheduleBuilder::concurrent(components, 2.0, 0)?;

    // Simulated subject: one response every 0.5 s, switching operanda every 10 s, for 10 min.
    let (mut left, mut right) = (0, 0);
    for i in 1..=1200 {
        let now = i as f64 * 0.5;
        let operandum = if (i / 20) % 2 == 0 { "left" } else { "right" };
        let outcome = schedule.step(now, Some(&ResponseEvent::on(operandum, now)))?;
        if outcome.reinforced {
            if operandum == "left" { left += 1 } else { right += 1 }
        }
    }
    println!("left={left} right={right}"); // left=16 right=8 — identical on every run, and to contingency-py with the same seeds
    assert_eq!((left, right), (16, 8));
    Ok(())
}

schedule.step(now, event) advances the clock to now; event is Some(&ResponseEvent) for a response or None for the passage of time, and outcome.reinforced says whether a reinforcer is delivered at now.

What is included

Area Contents
Simple schedules FR, VR, RR, CRF, FI, VI, RI, FT, VT, RT, EXT, limited hold
Compound schedules Concurrent (with COD, fixed-ratio changeover, direction-specific COD), Multiple, Mixed, Chained, Tandem, Alternative, Conjunctive, Interpolate, Overlay, second-order
Differential and progressive DRO (resetting, momentary), DRL, DRH, percentile, progressive ratio (arithmetic, geometric, Richardson–Roberts), adjusting, interlocking
Other procedures Timeout, response cost, Sidman avoidance, discriminated avoidance, escape, matching-to-sample, go/no-go
Value generators Fleshler–Hoffman (Fleshler & Hoffman, 1962) and the Hantula (1991) variant, in helpers::fleshler_hoffman
Hardware abstraction layer (hw) An apparatus interface with a virtual backend and a serial-port backend (serial feature)
HIL bridge The contingency-hil binary: a TCP server that takes responses as newline-delimited JSON, runs a schedule, and sends reinforcers back (contingency-hil --help)
Serial HIL runner The contingency-hil-serial binary (serial feature): runs CRF on a serial device through the serial backend and fetches the device's latency report, for host-side timing runs (contingency-hil-serial --help)
Bindings C (include/contingency.h, generated by cbindgen), Python (python feature, module contingency_core), WebAssembly (wasm32 target), Swift/Kotlin (uniffi feature)
jsPsych plugin jspsych/: runs FR, VI, CRF, or EXT for one trial in the browser

Cargo features: python, uniffi, serial; none is on by default.

The behavior the two engines share (time tolerance 1e-9, when each schedule starts timing, how COD gates reinforcement, and so on) is listed in section 5 of the Python–Rust correspondence. The schedule interface is described in protocol.md.

Limitations

  • Not on crates.io; the API can still change.
  • No parser for contingency-dsl expressions. To run a schedule written as text, compile it with contingency-py, or build it here with ScheduleBuilder.
  • contingency-hil drops stimulus messages, and it ignores reinforcer messages sent by the host.
  • The jsPsych plugin supports FR, VI, CRF, and EXT only.

Development

git clone https://github.com/OperantKit/contingency-rs
git clone https://github.com/OperantKit/contingency-py   # the conformance tests read ../contingency-py/conformance/
cd contingency-rs
cargo test

The Rust code blocks in both READMEs run as doctests (cargo test --doc).

References

  • Fleshler, M., & Hoffman, H. S. (1962). A progression for generating variable-interval schedules. Journal of the Experimental Analysis of Behavior, 5(4), 529-530. https://doi.org/10.1901/jeab.1962.5-529
  • Hantula, D. A. (1991). A simple BASIC program to generate values for variable-interval schedules of reinforcement. Journal of Applied Behavior Analysis, 24(4), 799-801. https://doi.org/10.1901/jaba.1991.24-799

License

MIT. See LICENSE.

About

Rust reinforcement schedule engine. Port of contingency-py with bit-equivalent semantics (via 14 conformance fixtures). Bindings: PyO3, WASM, C FFI, UniFFI (Swift/Kotlin). HIL TCP/JSONL binary included.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages