Metadata-Version: 2.4
Name: torqpy
Version: 0.3.0
Summary: torq.py — strongly timed concurrent Python with an optional embedded audio graph
Author-email: Dote <10195318+valid22@users.noreply.github.com>
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/valid22/torq.py
Project-URL: Repository, https://github.com/valid22/torq.py
Project-URL: Documentation, https://github.com/valid22/torq.py#readme
Project-URL: Issues, https://github.com/valid22/torq.py/issues
Project-URL: Release notes, https://github.com/valid22/torq.py/releases
Keywords: timing,music,audio,shreds,logical-clock,strongly-timed
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: C++
Classifier: Topic :: Multimedia :: Sound/Audio
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: numpy; extra == "dev"
Requires-Dist: build; extra == "dev"
Requires-Dist: pytest; extra == "dev"
Provides-Extra: midi
Requires-Dist: mido; extra == "midi"
Provides-Extra: native
Dynamic: license-file

# torq.py

[![PyPI version](https://img.shields.io/pypi/v/torqpy.svg)](https://pypi.org/project/torqpy/)
[![Python versions](https://img.shields.io/pypi/pyversions/torqpy.svg)](https://pypi.org/project/torqpy/)
[![License](https://img.shields.io/pypi/l/torqpy.svg)](https://github.com/valid22/torq.py/blob/main/LICENSE)

**Strongly timed concurrent Python on one logical clock** — audio/synth, MIDI/DMX cues, deterministic sim ticks, and lab protocols share the same rational `Time` / `Dur` timeline.

`now` advances only when shreds yield a duration (or you `advance` / `run` / `SimClock.step` / `frame`). No wall-clock sleep for logical waits. Timing, cues, sim, and lab are pure-Python; optional native `_vm` / `_audio` ship as binary wheels when available.

> **Status:** research / alpha (`0.2.x`). APIs may evolve. PyPI project **`torqpy`**; import **`torq`**; brand **torq.py**.

## Install

```bash
pip install torqpy
```

On platforms with a matching binary wheel (manylinux, macOS, Windows release builds), that install already includes `torq._vm` and `torq._audio`. Timing / shreds / cues / `SimClock` / lab need no native code either way.

```python
import torq   # package name on PyPI is torqpy; import is torq
```

Editable checkout:

```bash
git clone https://github.com/valid22/torq.py.git
cd torq.py
pip install -e ".[dev]"
python3 -m unittest discover -s torq/tests
```

### Optional native extensions (`[native]`)

`torq.audio` and `torq.native_clock` need the compiled extensions. Prefer a binary wheel from PyPI. When no matching wheel is available (or you are on a git checkout), build both `_vm` and `_audio` from the included sources with setuptools:

```bash
# toolchain: C++17 compiler, Python headers, PortAudio (e.g. portaudio19-dev / brew install portaudio)
TORQ_NATIVE=1 pip install 'torqpy[native]'
# from a git checkout:
TORQ_NATIVE=1 pip install -e '.[native]'
```

`TORQ_NATIVE=1` tells the setuptools `Extension` build to compile; the `[native]` extra documents that you want the native feature set. In-place helpers remain as `bash torq/native/build_vm.sh` / `build_audio.sh` if you prefer not to reinstall.

## Quickstart

junnu’s four-hit metronome — deterministic, no wall sleep:

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

clock = Clock()
hits = []

def junnu_metro():
    for _ in range(4):
        hits.append(clock.now)
        yield 500 * ms

clock.spork(junnu_metro())
clock.run()
# hits at 0, 0.5s, 1s, 1.5s
```

Laddu’s polite meow on the same clock (needs `_audio` from a wheel or `torqpy[native]`):

```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.01, 0.1, 0.3, 0.2)
osc >> env >> engine.Gain(0.35) >> engine.dac

clock = Clock(sample_rate=48_000)

def laddu_meow():
    env.keyOn()
    yield 300 * ms
    env.keyOff()
    yield 300 * ms

with clock:
    spork(laddu_meow)
buf = engine.render_while(clock, until=Time(0) + 600 * ms)
write_wav("beep.wav", buf, engine.sample_rate)
```

## Features by domain

| Domain | Entry points | Highlights |
| --- | --- | --- |
| **Core clock / shreds** | `Clock`, `Time`, `Dur`, `spork`, `yield` / `await (~d)` | Exact rational time; concurrent shreds in ordinary Python |
| **Ergonomics** | `with clock:`, `now`, `wait`, `~d`, `t ^ d`, `Pat` / `p["x-x-"]`, `@shred` | Context-local clock; patterns; unary `+` spork |
| **Audio / synth** | `torq.audio.AudioEngine` | In-process UGens + embedded STK (Clarinet…Saxofony with `controlChange`, NRev, JCRev, PRCRev, Chorus) on torq.py’s sample clock; offline WAV; optional PortAudio |
| **MIDI / DMX cues** | `torq.cues.CueSchedule` | Note/CC/program/bend/aftertouch/DMX stamps; deterministic `events()`; SMF/`MidiFile` export via `to_midi`/`save_midi` (optional `mido`; DMX skipped); stub frames / `mido` / composite live sinks |
| **Sim ticks** | `SimClock(dt)` | Fixed-timestep `step` / accumulator `frame` + `pause` / `timescale` / `reset` / `clear_hooks` / `lerp`; replay-stable |
| **Lab protocols** | `torq.lab.Protocol` / `Session` | Stimuli, DAQ windows, planned `inject` steps, multi-trial sessions; JSON-safe Timeline/session export; stubs |


### MIDI / DMX cues

```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 (0–16383)
    cues.note_on(0, 60, 100)
    yield 250 * ms
    cues.pitch_bend(0, 9000)
    cues.aftertouch(0, 72)  # channel pressure (alias: channel_pressure)
    yield 250 * ms
    cues.note_off(0, 60)
    cues.cc(0, 1, 64)
    yield 250 * ms
    cues.dmx(1, {1: 255, 2: 128})
    yield second

clock.spork(junnu_phrase())
clock.run()
events = cues.events()  # deterministic offline list
# optional: cues.save_midi("junnu.mid")  # needs mido; DMX omitted from SMF
```

### Sim ticks

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

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

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

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

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

# Accumulator frame: fixed updates + render alpha
@sim.on_update
def junnu_physics():
    pass

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

sim.frame(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; step ignores timescale
sim.reset()             # replay from origin; hooks stay, shreds clear
sim.off_render(laddu_draw)  # Laddu unsubscribes draw before a second scene
sim.clear_hooks()       # drop remaining update/render hooks
```

### Lab protocol

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

proto = (
    Protocol("meow-trial")
    .mark("ready")
    .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.75}, at=30 * ms, window="adc")  # planned stub sample
    .wait(100 * ms)
    .mark("done")
)

timeline = proto.plan()  # offline, no hardware (includes inject edges)
clock = Clock()
driver, daq = StubDriver(lines=("ttl0",)), StubDAQ(sample_rate=1000)
timeline, fired = proto.run(clock, driver=driver, daq=daq)
# daq.records[0].by_channel["mic"][30] == 0.75

# Multi-trial session: N runs on one clock, stubs reset between trials
session = Session(proto, isi=50 * ms)
session.run(Clock(), trials=3, driver=StubDriver(lines=("ttl0",)), daq=StubDAQ())
# session.to_json() — JSON-safe snapshot (rational Time/Dur strings)
```

## Documentation

| Doc | Contents |
| --- | --- |
| [docs/api.md](docs/api.md) | Public API surface |
| [docs/strongly-timed-python.md](docs/strongly-timed-python.md) | Timing model & type rules |
| [docs/torq-examples.md](docs/torq-examples.md) | Copy-paste timing snippets |
| [docs/torq-sim.md](docs/torq-sim.md) | SimClock step / frame / pause / timescale / reset / clear hooks / lerp |
| [docs/torq-cues.md](docs/torq-cues.md) | MIDI / DMX cue schedules |
| [docs/torq-lab.md](docs/torq-lab.md) | Stimuli, DAQ windows, protocols, multi-trial sessions |
| [docs/torq-audio.md](docs/torq-audio.md) | UGens, stereo, live, STK |
| [docs/torq-ugen-roadmap.md](docs/torq-ugen-roadmap.md) | Audio coverage roadmap |
| [docs/compare.md](docs/compare.md) | Related systems (peers, not the headline) |
| [llms.txt](llms.txt) | Agent-oriented install & patterns |

## Contributing

Issues and PRs welcome at [github.com/valid22/torq.py](https://github.com/valid22/torq.py).

```bash
pip install -e ".[dev]"
python3 -m unittest discover -s torq/tests
```

Optional native extensions (used by audio + some tests): `TORQ_NATIVE=1 pip install -e '.[native]'` (or the `torq/native/build_*.sh` helpers).

## License

Apache-2.0. Vendored STK under `torq/native/stk/` carries its own MIT-style license (Cook & Scavone).
