# 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
# timing / cues / SimClock / lab need no native build; audio needs a local build:
bash "$(python -c 'import torq, pathlib; print(pathlib.Path(torq.__file__).parent / "native" / "build_audio.sh")')"
# from a git checkout: pip install -e . && bash torq/native/build_audio.sh
# needs: g++, python3-dev, portaudio19-dev
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
from torq import spork, now, wait, until, every, at, Pat, p, shred
from torq import Protocol, Stimulus, Window, StubDriver, StubDAQ, StimulusDriver, DAQDevice
from torq.cues import CueSchedule, StubBackend, MidoBackend, CompositeBackend, has_mido
from torq.lab import Protocol, Stimulus, Window, StubDriver, StubDAQ  # also re-exported
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, NRev, Chorus) are torq.py UGens on the sample clock.
- **Cues:** `CueSchedule` stamps MIDI/DMX at logical `now`; `events()` is deterministic offline; live sinks: `StubBackend` (DMX frames + note tracking), `MidoBackend`, `CompositeBackend`.
- **Sim:** `SimClock(dt)` fixed `step(n)` / `on_step`|`on_update`; `frame(elapsed)` accumulator drains updates then `on_render` with `alpha`; replay-stable.
- **Lab:** `Protocol.plan()` → deterministic offline `Timeline`; `.run(clock)` fires `StimulusDriver` / `DAQDevice` (stubs or hardware) on the same clock.

## 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 + 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.note_on(0, 60, 100)
    yield 250 * ms
    cues.note_off(0, 60)
    cues.dmx(1, {1: 255})
    yield second

clock.spork(junnu_phrase())
clock.run()
events = cues.events()
```

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, 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)

sim.frame(sim.dt / 2)
sim.frame(sim.dt + sim.dt / 2)
```

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)
    .wait(100 * ms)
)
timeline, fired = proto.run(Clock(), driver=StubDriver(), daq=StubDAQ(sample_rate=1000))
```

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-cues.md — MIDI / DMX cue schedules
- docs/torq-lab.md — stimuli / DAQ windows / protocols
- docs/torq-audio.md — UGens / STK / live
- docs/compare.md — peers (related systems; never the headline)
- docs/torq-ugen-roadmap.md — coverage plan
