# 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 spork, now, wait, until, every, at, Pat, p, shred
from torq import Protocol, Session, Stimulus, Window, StubDriver, StubDAQ, StimulusDriver, DAQDevice
from torq import dumps_timeline, loads_timeline
from torq.cues import CueSchedule, StubBackend, MidoBackend, CompositeBackend, has_mido
from torq.lab import Protocol, Session, Stimulus, Window, StubDriver, StubDAQ, dumps_timeline, loads_timeline
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.
- **Audio:** graph with `>>`, drive params from shreds, `render_while(clock, until=...)` offline or `play_while` if a device exists. STK instruments/effects (Clarinet…Saxofony 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/dmx; `channel_pressure` aliases aftertouch); `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 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`; `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 unchanged); `clear_hooks` / `off_step`|`off_update` / `off_render` drop registrations (silent no-op if missing); `lerp(a, b)` uses `alpha` when `t` omitted; 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; arm once; stub `reset` between trials. JSON-safe export: `Timeline.as_dict` / `dumps_timeline` / `loads_timeline`; `Session.to_jsonable()` / `.to_json()` (rational `Time`/`Dur` strings; non-JSON payloads raise `TypeError`).


## 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
- `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()`
- `await ~d` without parentheses — must be `await (~d)`

## Few-shot: domains

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 >> env >> engine.Gain(0.3) >> engine.dac
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

clock = Clock()
cues = CueSchedule(clock)

def junnu_phrase():
    cues.program_change(0, 12)
    cues.pitch_bend(0, 8192)  # center
    cues.note_on(0, 60, 100)
    yield 250 * ms
    cues.pitch_bend(0, 9000)
    cues.aftertouch(0, 72)  # channel pressure
    yield 250 * ms
    cues.note_off(0, 60)
    cues.dmx(1, {1: 255})
    yield second

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

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: “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_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: “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

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))
# session.trials[i].fired matches plan(origin=...); session.to_json() is stable
# dumps_timeline(proto.plan()) → loads_timeline(...) equals the plan Timeline (inject included)
```

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
- docs/api.md — public API
- docs/strongly-timed-python.md — semantics
- docs/torq-examples.md — snippets
- docs/torq-sim.md — SimClock step / frame / pause / timescale / reset / clear hooks / lerp
- 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
- docs/compare.md — peers (related systems; never the headline)
- docs/torq-ugen-roadmap.md — coverage plan
