# torq.py — llms.txt

Brand: **torq.py**. PyPI project: **torqpy**. Import: **`torq`**.

**Multi-domain strongly timed Python** on one logical clock: audio/synth, MIDI/DMX cues, deterministic sim ticks, and lab protocols. Not an asyncio timing hack; not an scsynth/pyo client. Capability-first — peers are related work only, never the headline.

## Install

```bash
pip install torqpy
# Binary wheels include _vm + _audio when available.
# timing / cues / SimClock / lab need no native code.
# From sdist / git (no matching wheel): compile both extensions:
#   TORQ_NATIVE=1 pip install 'torqpy[native]'
# toolchain: C++17 compiler, Python headers, PortAudio
python3 -m unittest discover -s torq/tests
```

```python
import torq                      # not import torqpy
from torq.audio import AudioEngine
```

## Core imports

```python
from torq import Clock, SimClock, Time, Dur, second, ms, samp, minute, lerp
from torq import Shared, SharedValue, SharedEvent, SharedWait
from torq import spork, now, wait, until, every, at, Pat, p, shred
from torq import Flow, Node, Bound, TickGrid, Quantized, tick
from torq import is_bind_target, as_bind_target, is_tick_grid, as_tick_grid
from torq import Protocol, Session, Stimulus, Window, StubDriver, StubDAQ, StimulusDriver, DAQDevice
from torq import Sensor, Metric, LabEngine, sensor, metric
from torq import dumps_timeline, loads_timeline, dumps_session_csv
from torq.cues import CueSchedule, StubBackend, MidoBackend, CompositeBackend, has_mido
from torq.cues import midi, dmx, ch, u, note  # | lane tags
from torq.lab import Protocol, Session, Stimulus, Window, StubDriver, StubDAQ, dumps_timeline, loads_timeline, dumps_session_csv
from torq.lab import sensor, metric, engine, LabEngine
from torq.audio import AudioEngine, write_wav, has_output_device
```

## Mental model

- One logical `now` (`Time`) shared across domains. Advancing happens via `yield dur`, `await (~dur)`, `advance`, `run`, or `SimClock.step` / `frame`.
- Never use `time.sleep` / `asyncio.sleep` for timed waits inside shreds.
- **Shared values/events:** `Shared(clock)` / `clock.shared()` — typed latest-wins `set`/`get`/`wait`/`changed` and `emit`/`once` stamped at `now`. Cross-domain (audio/MIDI/sim/lab). **Not** a PySim/SimPy capacity `Store`/`Resource`. `yield from bus.wait(key)` / `await bus.once(topic)`; cancel unregisters waiters.
- **Shared patching:** `>>` flow; `x @ clock_or_engine` / `x.on(...)` bind → `Bound`; `x.to(y)` one-hop handoff; `x.send(y, z)` fan-out (≥1 target). `Flow` / `Node` / `Bound` / `is_bind_target` / `as_bind_target` in `torq.ops` (re-exported). Bind targets: `Clock` / `SimClock` / `NativeClock` / `AudioEngine` / `LabEngine`. Style: bind first, then route; parenthesize mixes `(x @ c) >> y`. Keep `with` / `while` / `yield ~d` / `await (~d)` / unary `+`.
- **Audio:** graph with `>>` / `.to` / `.send` / `@` / `.on`; sugar `(node * g) >> dac` (AudioNode × number → `Gain`) and `dac << src` / `blackhole << src` (`AudioSink` only; ≡ `src >> sink`). `~` wait unchanged. Drive params from shreds; `render_while(clock, until=...)` offline or `play_while` if a device exists. STK instruments/effects (Clarinet…Saxofony, Rhodey/BeeThree FM, ModalBar with `controlChange`/`control_change` values in `[0, 128]`, NRev, JCRev, PRCRev, Chorus) are torq.py UGens on the sample clock.
- **Cues:** `CueSchedule` stamps MIDI/DMX at logical `now` (note/cc/program_change/pitch_bend/aftertouch/poly_aftertouch/sysex/dmx; `channel_pressure` aliases aftertouch; `polyphonic_aftertouch` aliases poly_aftertouch; sysex is non-empty payload bytes without F0/F7); **lane sugar** `(midi.note(60) | midi.ch(1)) >> cues` / `(dmx.cue({1:255}) | dmx.u(2)) >> cues` — `|` is channel/universe tag only, not general handoff; parenthesize with `>>`; `events()` is deterministic offline; `to_midi`/`save_midi` export SMF when optional `mido` is installed (DMX skipped; default 480 TPB / 500000 µs/beat); live sinks: `StubBackend` (DMX frames + note/program/bend/aftertouch/poly_aftertouch/sysex tracking), `MidoBackend`, `CompositeBackend`.
- **Sim:** `SimClock(dt)` fixed `step(n)` / `on_step`|`on_update`; `frame(elapsed)` banks `elapsed * timescale`, drains updates then `on_render` with `alpha`; optional `priority` on `on_step`/`on_update`/`on_render` (default `0`; ascending, then registration order); `set_dt(dur)` / writable `.dt` retunes the fixed quantum (keeps accumulator residual; reject non-positive; same shred/re-entry guards as `reset`); `pause`/`resume`/`paused` freeze `step`/`frame`/`run_ticks`; `timescale` (`>= 0`, default `1.0`) scales `frame` only (`0` freezes `frame`; `paused` wins); `reset()` for replay (hooks stay, shreds clear; pause/timescale/`dt` unchanged); `clear_hooks` / `off_step`|`off_update` / `off_render` drop registrations (silent no-op if missing); `lerp(a, b)` uses `alpha` when `t` omitted. Sim sugar: `event % tick(n)` / `event % sim.grid(n)` → `Quantized` (`.due(sim)` every nth positive tick; `.snap_tick` / `.snap_time`; `.fire`); RHS must be `TickGrid` — not `int`/`Dur`/lab windows. Parenthesize `(event @ sim) % tick(4)`. See `docs/torq-sim.md`.
- **Lab:** `Protocol.plan()` → deterministic offline `Timeline` (stimuli, windows, marks, `inject`); `.run(clock)` fires `StimulusDriver` / `DAQDevice` (stubs or hardware) on the same clock, applying planned `Protocol.inject` via `daq.inject`. `Session` runs N sequential trials with optional ISI, deterministic `shuffle` / `isi_jitter` (`seed` defaults to `0` when RNG needed); arm once; stub `reset` between trials. JSON-safe export: `Timeline.as_dict` / `dumps_timeline` / `loads_timeline`; `Session.to_jsonable()` / `.to_json()` includes `order` / `planned_index` / effective `isi` (rational `Time`/`Dur` strings; non-JSON payloads raise `TypeError`). Wide trial CSV: `Session.to_csv` / `dumps_session_csv` (same snapshot fields; one row per trial). Lab handles: `sensor(name)` / `metric(name)` with `.probe()` / `.mark(...)`; bind via `@` / `.on` to `Clock` or `LabEngine` / `torq.lab.engine(...)`. No `%` for lab windows.


## Anti-patterns

- Framing torq.py as audio-only (it is multi-domain timing first)
- Leading with a peer language instead of torq.py’s capabilities
- Treating `Shared` as a SimPy `Store`/`Resource` (it is a thin value/event bus, not capacity)
- `asyncio.run` / event-loop sleeps as a substitute for shreds
- Driving logical time from wall clock or audio callback into Python
- Assuming live PortAudio works on headless VMs — check `has_output_device()`
- Connecting into source UGens (oscillators / STK instruments have no audio inputs; STK effects do)
- Peer-language `=>` connect — in torq.py use `>>` / `.to()` / `.send(...)`
- `await ~d` without parentheses — must be `await (~d)`
- Using `*` for fan-out, or `<<` on non-sink UGens
- Using `|` as general typed handoff (MIDI/DMX only: channel/universe lanes; handoff stays `.to`)
- Using `%` with bare `int`/`Dur`, or `%` for lab sample windows — use `Window(..., rate=)` / clock bind / `.probe().on(clock)`
- Mixing `@` / `*` / `%` / `>>` / `<<` / `|` without parentheses
- Writing `note | ch(1) >> cues` without parentheses — must be `(note | ch(1)) >> cues`

## Few-shot: domains

User: “Bind a patch node to a clock, then fan out.”

```python
from torq import Clock, Node, ms, second, spork

clock = Clock()
kick = Node("kick")
midi_note = Node("midi.note36")
lab_mark = Node("lab.kick")

(kick @ clock).send(midi_note, lab_mark)   # or kick.on(clock).send(...)
# kick.outs == (midi_note, lab_mark); parenthesize mixes: (kick @ clock) >> midi_note

def junnu_pulse():
    while True:
        yield ~(second / 4)

with clock:
    spork(junnu_pulse)
```

User: “Sim pose drives a synth cutoff sketch; collision fans out.”

```python
from torq import Node, SimClock, second

sim = SimClock(second / 60)
pose = Node("bot.pose")
(pose @ sim).to(Node("synth.cutoff"))

hit = Node("collision")
hit.on(sim).send(Node("click"), Node("midi60"), Node("hits"))
```

User: “Two concurrent pulses, then a beep.”

```python
from torq import Clock, Time, ms, spork
from torq.audio import AudioEngine, write_wav

engine = AudioEngine(48_000)
osc = engine.SinOsc(440)
env = engine.ADSR(0.005, 0.05, 0.2, 0.1)
(osc @ engine) >> env >> engine.Gain(0.3) >> engine.dac
env.send(engine.blackhole)   # metering tap via fan-out
clock = Clock(sample_rate=48_000)

def pulse(period_ms, who):
    for _ in range(4):
        env.keyOn()
        yield period_ms * ms
        env.keyOff()
        yield period_ms * ms

with clock:
    spork(lambda: pulse(100, "junnu"))
    spork(lambda: pulse(150, "Laddu"))
buf = engine.render_while(clock, until=Time(0) + 1200 * ms)
write_wav("pulses.wav", buf, engine.sample_rate)
```

User: “MIDI notes + program/bend + a DMX bump on logical time.”

```python
from torq import Clock, ms, second
from torq.cues import CueSchedule, midi, dmx

clock = Clock()
cues = CueSchedule(clock)

def junnu_phrase():
    cues.program_change(0, 12)
    cues.pitch_bend(0, 8192)  # center
    (midi.note(60, velocity=100) | midi.ch(0)) >> cues
    yield 250 * ms
    cues.pitch_bend(0, 9000)
    cues.aftertouch(0, 72)  # channel pressure
    cues.poly_aftertouch(0, 60, 88)  # per-note pressure
    cues.sysex(bytes([0x43, 0x12, 0x00]))  # payload without F0/F7
    yield 250 * ms
    (midi.note_off(60) | midi.ch(0)) >> cues
    (dmx.cue({1: 255}) | dmx.u(1)) >> cues
    yield second

clock.spork(junnu_phrase())
clock.run()
events = cues.events()
# if has_mido(): cues.save_midi("junnu.mid")  # SMF; DMX omitted
```

User: “Tag a MIDI note onto channel 2 with | then stamp.”

```python
from torq import Clock, ms, spork
from torq.cues import CueSchedule, midi

clock = Clock()
cues = CueSchedule(clock)

def junnu():
    (midi.note(48, velocity=96) | midi.ch(2)) >> cues
    yield 100 * ms
    (midi.note_off(48) | midi.ch(2)) >> cues

with clock:
    spork(junnu)
clock.run()
```

User: “60 Hz sim ticks with a shred.”

```python
from torq import SimClock, second, spork, now

sim = SimClock(second / 60)
log = []

def junnu():
    while True:
        log.append(sim.now)
        yield sim.dt

@sim.on_step
def laddu_hook():
    log.append(("Laddu", now(), sim.tick))

with sim:
    spork(junnu)
sim.step(3)
```

User: “Only fire a sim impulse every 4th tick.”

```python
from torq import Node, SimClock, second, tick

sim = SimClock(second / 60)
throttled = Node("bot.impulse") % tick(4)  # or % sim.grid(4)
hits = []

@sim.on_step
def laddu():
    if throttled.due(sim):
        hits.append(sim.tick)

sim.step(12)  # hits == [4, 8, 12]
```

User: “Game-style accumulator frame with update and render.”

```python
from torq import SimClock, lerp, second

sim = SimClock(second / 60)

@sim.on_update
def junnu_physics():
    pass

@sim.on_update(priority=10)
def laddu_hud_prep():
    pass  # ascending priority within the update phase

@sim.on_render
def laddu_draw():
    blend = sim.alpha  # Fraction in [0, 1)
    x = lerp(0, 10)    # uses alpha when t omitted

sim.frame(sim.dt / 2)
sim.frame(sim.dt + sim.dt / 2)
sim.pause()            # junnu freezes the chase; Laddu inspects alpha
sim.frame(sim.dt)      # no-op while paused
sim.resume()
sim.timescale = 2.0    # frame banks elapsed * 2
sim.reset()            # replay from origin; hooks stay
sim.off_render(laddu_draw)  # Laddu unsubscribes draw before a second scene
sim.clear_hooks()
```

User: “Probe a lab sensor, mark a baseline, bind to the clock.”

```python
from torq import Clock, ms, sensor
from torq.lab import engine

clock = Clock()
temp = sensor("temp_c").probe().on(clock)   # or temp @ engine("daq-1")
temp.mark("baseline", when=0 * ms)
# temp.marks == (("baseline", Dur(0), None),); no % for lab windows
```

User: “Lab stimulus inside a DAQ window.”

```python
from torq import Clock, ms
from torq.lab import Protocol, StubDAQ, StubDriver

proto = (
    Protocol("meow-trial")
    .window("adc", duration=100 * ms, channels=("mic",), rate=1000, advance=False)
    .stimulus("meow", duration=20 * ms, onset=25 * ms, payload={"who": "Laddu"}, advance=False)
    .inject({"mic": 0.75}, at=30 * ms, window="adc")
    .wait(100 * ms)
)
timeline, fired = proto.run(Clock(), driver=StubDriver(), daq=StubDAQ(sample_rate=1000))
# planned inject lands in daq.records[0].by_channel["mic"][30]
```

User: “Repeat a lab trial three times with ISI.”

```python
from torq import Clock, ms
from torq.lab import Protocol, Session, StubDAQ, StubDriver, dumps_session_csv

proto = (
    Protocol("meow-trial")
    .window("adc", duration=100 * ms, channels=("mic",), rate=1000, advance=False)
    .stimulus("meow", duration=20 * ms, onset=25 * ms, payload={"who": "Laddu", "line": "ttl0"}, advance=False)
    .inject({"mic": 0.8}, at=30 * ms, window="adc")
    .wait(100 * ms)
)
session = Session(proto, isi=50 * ms)
session.run(
    Clock(),
    trials=3,
    driver=StubDriver(lines=("ttl0",)),
    daq=StubDAQ(sample_rate=1000),
    shuffle=True,
    seed=7,
    isi_jitter=(5 * ms, 15 * ms),
)
# session.order / trial.planned_index / trial.isi recoverable from to_json() / dumps_session_csv()
# same seed → same order and jitter; dumps_timeline(proto.plan()) round-trips inject
```

User: “Async-looking code but sample-exact waits.”

```python
from torq import Clock, ms, now, spork

clock = Clock()
hits = []

async def junnu_metro():
    for _ in range(4):
        hits.append(now())
        await (~(500 * ms))   # parentheses required

with clock:
    spork(junnu_metro)
clock.run()
```

## Docs to read

- README.md — multi-domain overview + hello per domain (includes shared patching)
- docs/api.md — public API (`Flow` / `Node` / `Bound` / `@` / `.on` / `.to` / `.send`)
- docs/strongly-timed-python.md — semantics
- docs/torq-examples.md — timing + shared patching snippets
- docs/torq-sim.md — SimClock step / frame / set_dt / pause / timescale / reset / clear hooks / lerp / `%` tick grid
- docs/torq-cues.md — MIDI / DMX cue schedules
- docs/torq-lab.md — stimuli / DAQ windows / protocols / multi-trial Session
- docs/torq-audio.md — UGens / STK / live (UGen `>>` / `.to` / `.send` / `@`)
- docs/compare.md — peers (related systems; never the headline)
- docs/torq-ugen-roadmap.md — coverage plan
- `torq/examples.py` — `run_shared_patching` and domain demos
