API Reference

Core

rigconductor — drive a Motif rig from recording to results on a USB disk.

exception rigconductor.ConductorError[source]

An error the operator can act on; the message is shown verbatim.

Shared constants for Rig Conductor.

Conductor configuration: ~/.config/rigconductor/rig.yaml (or $RIGCONDUCTOR_RIG).

Machine paths, the camera serial and cluster names live here, never in code.

class rigconductor.config.MotifConfig(host: 'str' = '127.0.0.1', port: 'int' = 6083, serial: 'str | None' = None, codec: 'str' = 'mq-fast', api_key_cmd: 'str' = 'recnode-apikey', camera: 'dict' = <factory>)[source]
Parameters:
class rigconductor.config.ClusterConfig(ssh_host: 'str' = 'aoraki', lab_root: 'str' = '/projects/sciences/zoology/geurten_lab', poll_interval_s: 'int' = 60)[source]
Parameters:
  • ssh_host (str)

  • lab_root (str)

  • poll_interval_s (int)

class rigconductor.config.ExportConfig(clips: 'str' = 'plain', unmount: 'bool' = False, blind: 'bool' = False)[source]
Parameters:
class rigconductor.config.ReduceConfig(enabled: 'bool' = True, padding_px: 'int' = 40, crf: 'int' = 18, keep_full: 'bool' = False)[source]
Parameters:
class rigconductor.config.ConductorConfig(data_root: 'Path', sessions_dir: 'Path', motif: 'MotifConfig' = <factory>, cluster: 'ClusterConfig' = <factory>, profiles: 'dict[str, dict]' = <factory>, export: 'ExportConfig' = <factory>, reduce: 'ReduceConfig' = <factory>, path: 'Path | None' = None)[source]
Parameters:

One experiment session, as idempotent stages with on-disk state.

State lives in <sessions_dir>/<session_id>.json (and a copy inside the recording folder once it exists), so every stage can be re-run after a crash, a lost VPN or a cancelled job. Finished stages are skipped.

class rigconductor.session.ConductorSpec(profile: 'str', session_id: 'str', title: 'str', duration_s: 'float', codec: 'str | None' = None, operator: 'str | None' = None, metadata: 'dict' = <factory>, recording_dir: 'str | None' = None, model_id: 'str | None' = None, export_device: 'str | None' = None, export_dir: 'str | None' = None, blind: 'bool' = False, clips: 'str' = 'plain', unmount: 'bool' = False, force_model: 'bool' = False, reduce: 'bool | None' = None, reduce_padding_px: 'int | None' = None, preset: 'str | None' = None, gray: 'bool | None' = None)[source]
Parameters:
  • profile (str)

  • session_id (str)

  • title (str)

  • duration_s (float)

  • codec (str | None)

  • operator (str | None)

  • metadata (dict)

  • recording_dir (str | None)

  • model_id (str | None)

  • export_device (str | None)

  • export_dir (str | None)

  • blind (bool)

  • clips (str)

  • unmount (bool)

  • force_model (bool)

  • reduce (bool | None)

  • reduce_padding_px (int | None)

  • preset (str | None)

  • gray (bool | None)

rigconductor.session.saved_state_for(cfg, rec_dir)[source]

The session state belonging to a recording: the rig’s copy in sessions_dir if it exists (newest), else the copy next to the video.

Parameters:
Return type:

dict | None

rigconductor.session.adopt_saved_state(cfg, state)[source]

Resume a session from a saved state (copied to sessions_dir if missing).

Parameters:
Return type:

ConductorSession

rigconductor — the command line twin of the wizard.

rigconductor init-config rigconductor doctor [–profile P] [–no-ssh] rigconductor motif status | motif record TITLE SECONDS [–codec C] rigconductor models [–profile P] [–refresh] rigconductor disks rigconductor run SESSION.json [–from STAGE] [–to STAGE] [–disk /dev/sdX1] rigconductor status SESSION_ID rigconductor gui rigconductor label-default [NAME] | label-sync [–set S] [–install-cron | –remove-cron]

Readiness checks shown on the wizard’s first screen and by rigconductor doctor.

class rigconductor.doctor.Check(name: 'str', ok: 'bool', detail: 'str', hint: 'str' = '', blocking: 'bool' = True)[source]
Parameters:

Model-vs-data check: does the chosen AI model expect the kind of video we are sending?

Run before every cluster submission. Each registry entry may carry an expects block describing the data the model was trained on:

expects:
  channels: 1            # 1 = grayscale, 3 = colour
  polarity: bright       # animals bright on dark ("bright") or dark on light ("dark")
  invert: true           # the pipeline inverts our clips before inference
  min_side_px: 224       # clips smaller than this cannot hold one instance crop
  fps: [25, 30]          # frame rates the model was trained at (tolerance 20 %)
  input_size: 1024       # model resizes every frame to this (resize_and_pad_to_target);
                         # clips more than 10 % off change the animals' apparent size

Missing keys are not checked. Problems found on 2026-11-05/11 that motivated this: flies13 was trained on bright flies on dark (ours are dark on white, so every prediction failed), and fine-tuning crashed because our frames were 3-channel and the base weights 1-channel. Then the fine-tune learned nothing because the inherited config resized our 512 px clips to flies13’s 1024 px, doubling the flies.

class rigconductor.compat.ClipInfo(path: 'Path', width: 'int', height: 'int', fps: 'float', pix_fmt: 'str', mean_intensity: 'float | None')[source]
Parameters:
property polarity: str | None

‘dark’ animals on a light background when the frame is mostly bright.

rigconductor.compat.check_model_vs_clips(model, clips, invert=None)[source]

Compare the model’s expects block with the probed clips.

invert is what the pipeline will do to the clips before inference (None = take the model’s expects.invert).

Parameters:
Return type:

list[Check]

class rigconductor.compat.CameraInfo(pixel_format: 'str | None', fps: 'float | None', model_name: 'str | None' = None)[source]
Parameters:
  • pixel_format (str | None)

  • fps (float | None)

  • model_name (str | None)

rigconductor.compat.camera_info(client)[source]

Read what matters from a MotifClient (missing settings → None).

Return type:

CameraInfo

rigconductor.compat.check_model_vs_camera(model, cam, preset)[source]

Checks to run on the first page, before anything is recorded.

Check.name ends in CHANNELS or CAMERA_FPS for the two problems the GUI offers a fix for (convert to grayscale / set the camera frame rate).

Parameters:
Return type:

list[Check]

Experiment presets: one choice on the first page that fixes how the video is recorded and processed (colour, frame rate, crop to arenas, default pose model).

Built-in presets live here per profile; rig.yaml can override or add some:

profiles:
  drosophila_triad:
    presets:
      heat: {gray: true, reduce: true, padding_px: 60, model: lab_oct2025_v2}
      courtship25: {label: "Courtship, fixed 25 fps", fps: 25}
class rigconductor.presets.Preset(key: 'str', label: 'str', gray: 'bool' = True, fps: 'float | None' = None, reduce: 'bool' = True, padding_px: 'int' = 40, model: 'str | None' = None, notes: 'str' = '', extra: 'dict' = <factory>)[source]
Parameters:

Check for and install updates of the rig’s own code (git).

class rigconductor.updates.RepoStatus(name, path=None, branch='', upstream='', behind=0, ahead=0, changed=<factory>, error='', new_commits=<factory>)[source]

State of one package’s git checkout.

Parameters:
name

Package name.

Type:

str

path

Repository root, None when the package is not a git checkout.

Type:

pathlib.Path | None

branch

Current branch.

Type:

str

upstream

Tracked remote branch, e.g. origin/main.

Type:

str

behind

Commits on the remote not here yet.

Type:

int

ahead

Local commits not on the remote.

Type:

int

changed

Tracked files with uncommitted changes.

Type:

list[str]

error

Why the check could not be done.

Type:

str

new_commits

One-line summaries of the commits an update would bring.

Type:

list[str]

rigconductor.updates.repo_of(package)[source]

Git root of an installed package (editable installs point into the checkout).

Parameters:

package (str)

Return type:

Path | None

rigconductor.updates.update_repo(st, run=<function run>)[source]

Fast-forward one checkout; reinstall when its pyproject changed.

Parameters:

st (RepoStatus)

Return type:

str

Desktop launchers (freedesktop .desktop files) for the wizards.

rigconductor.desktop.conductor_exe()[source]

The rigconductor script of the running environment.

Return type:

Path

rigconductor.desktop.install(home=None, exe=None, run=<function run>)[source]

Write both launchers to the app menu and (when it exists) the desktop.

Parameters:
Return type:

list[Path]

User-manual helpers that need no Qt.

The manual is written in the Markdown that Qt’s QTextDocument.setMarkdown understands (CommonMark and GitHub tables): no admonitions, attribute lists or tabs. Slugs follow Python-Markdown’s toc so #links also work on a docs site.

class rigconductor.manual.Section(level: 'int', title: 'str', slug: 'str', line: 'int')[source]
Parameters:
rigconductor.manual.load_manual(path=PosixPath('/home/runner/work/RigConductor/RigConductor/docs/manual/user_manual.md'))[source]

The manual’s Markdown source.

Parameters:

path (Path)

Return type:

str

rigconductor.manual.slugify(title)[source]

Python-Markdown’s default toc slug.

Parameters:

title (str)

Return type:

str

rigconductor.manual.parse_sections(markdown)[source]

ATX headings in document order, skipping fenced code blocks.

Parameters:

markdown (str)

Return type:

list[Section]

rigconductor.manual.image_targets(markdown)[source]

Relative paths of every ![alt](path) picture.

Parameters:

markdown (str)

Return type:

list[str]

rigconductor.manual.anchor_targets(markdown)[source]

Slugs of every in-page [text](#slug) link.

Parameters:

markdown (str)

Return type:

list[str]

Rig, recording and export

Motif (loopbio) recorder control over its REST API, plus an in-memory fake.

Only the handful of endpoints Conductor needs are wrapped; the wire format is the same as the vendor’s motifapi package (X-Api-Key header, JSON body, HTTPS with the recnode’s self-signed certificate).

exception rigconductor.motif.MotifError[source]
class rigconductor.motif.CameraStatus(serial: 'str', status: 'str', filename: 'str | None', raw: 'dict')[source]
Parameters:
class rigconductor.motif.Recorder(*args, **kwargs)[source]

What the session needs from a recorder (real Motif or the fake).

rigconductor.motif.motif_dir_name(title, when)[source]

Motif names the store <title lowercased>_<YYYYMMDD>_<HHMMSS>.

Parameters:
Return type:

str

rigconductor.motif.find_new_recording(data_root, started_after, title=None)[source]

The newest recording folder created after started_after (epoch seconds) whose name starts with title (lower-cased), if given. Motif writes <data_root>/<camera serial>/<title>_<stamp>, so one level of sub-directories is searched as well.

Parameters:
Return type:

Path | None

rigconductor.motif.recording_is_closed(rec_dir, quiet_s=5.0, now=None)[source]

True when no file in the store changed for quiet_s seconds (now = epoch s).

Parameters:
Return type:

bool

class rigconductor.motif.FakeMotif(data_root, serial='FAKE0001', camera_status='ready')[source]

Behaves like Motif from the outside: a recording lasts duration seconds of fake clock time, writes metadata.yaml and one chunk file into data_root/<title>_<stamp>. Advance time with tick() or pass a real clock for timing tests.

Parameters:
  • data_root (Path)

  • serial (str)

  • camera_status (str)

Motif’s live preview: an MJPEG stream (multipart JPEG over HTTP) whose URL the recnode publishes in camera_info.stream.preview.url. Qt-free so it can be tested; the widget lives in gui/preview.py.

rigconductor.preview.iter_jpegs(stream, chunk=16384, max_buffer=8388608)[source]

Yield complete JPEG images from a multipart MJPEG byte stream.

Parameters:
  • chunk (int)

  • max_buffer (int)

Return type:

Iterator[bytes]

rigconductor.preview.follow(url, on_frame, should_stop, on_error=<function <lambda>>, timeout_s=10.0)[source]

Read the stream until should_stop(); reconnect with back-off on errors.

Parameters:
Return type:

None

rigconductor.preview.load_arena_overlay(path)[source]

Arena circles (cx, cy, r) in full-frame px and the full frame width, from a ThermoKourt arenas JSON; None when there is no file yet.

Parameters:

path (Path | None)

Return type:

tuple[list[tuple[float, float, float]], int] | None

rigconductor.preview.crop_box(circles, pad, width, height)[source]

Bounding box (x, y, w, h) of all circles plus pad px on each side, clamped to the image; None without circles.

Parameters:
Return type:

tuple[int, int, int, int] | None

Arena layout helpers (ThermoKourt arenas JSON, full camera coordinates).

class rigconductor.arenas.Layout(circles, frame_width, frame_height, meta=<factory>)[source]

Arena circles plus the file metadata ThermoKourt expects.

Parameters:
circles

(cx, cy, r) in full camera pixels, row-major order.

Type:

list[tuple[float, float, float]]

frame_width

Full camera frame width.

Type:

int

frame_height

Full camera frame height.

Type:

int

meta

Other keys of the JSON file (recording, padding, …), kept on save.

Type:

dict

rigconductor.arenas.sort_row_major(circles)[source]

Order top→bottom, left→right exactly like ThermoKourt numbers its arenas.

Parameters:

circles (list[tuple[float, float, float]])

Return type:

list[tuple[float, float, float]]

rigconductor.arenas.uniform_radii(circles)[source]

Give every arena the median radius (the arenas on one plate are identical).

Parameters:

circles (list[tuple[float, float, float]])

Return type:

list[tuple[float, float, float]]

rigconductor.arenas.radius_outliers(circles, tol=0.1)[source]

Indices of arenas whose radius differs from the median by more than tol.

Parameters:
Return type:

list[int]

rigconductor.arenas.save_layout(path, layout)[source]

Write layout as a ThermoKourt arenas JSON (circles renumbered row-major).

Parameters:
Return type:

Path

rigconductor.arenas.video_offset(rec_dir)[source]

Where the recording’s video sits in the full camera frame ((0, 0) unless Rig Conductor cropped it).

Parameters:

rec_dir (Path)

Return type:

tuple[int, int]

rigconductor.arenas.grab_frame(rec_dir, out_png, at_fraction=0.5)[source]

Save one frame of the recording’s first chunk as PNG (ffmpeg, no OpenCV).

Parameters:
Return type:

Path

Crop a Motif recording to the arenas (‘reduce’) to save disk space.

Runs after the cut: every chunk NNNNNN.mp4 of the Motif image store is re-encoded to the bounding box of all arenas plus a padding, frame for frame (-fps_mode passthrough), so the NNNNNN.npz frame timestamps stay valid. A chunk is replaced only after its cropped copy decodes to the same number of frames. With gray the colour is dropped too (format=gray, still stored as yuv420p: on a mono camera that changes nothing; a gray pix_fmt file came out 38 % larger in the 2026-11-11 test). metadata.yaml gets the new imgshape (the original is kept as metadata.full.yaml) and reduced.json records the crop offset, so full-frame coordinates map to the reduced video as (x - x0, y - y0).

rigconductor.reduce.reduce_box(circles, pad, width, height, align=16)[source]

(x, y, w, h) covering every circle + pad px, grown to multiples of align and clamped to the frame.

Parameters:
Return type:

tuple[int, int, int, int]

rigconductor.reduce.recorded_fps(rec_dir)[source]

Real camera rate: Motif frame timestamps, snapped to the set acquisitionframerate when within 1 % (jitter like 69.001 gives time bases MPEG-4 cannot store); else the timestamp rate to 2 decimals, else metadata. Same rule as ThermoKourt’s recorded_fps.

Parameters:

rec_dir (Path)

Return type:

float | None

rigconductor.reduce.reduce_recording(rec_dir, circles, padding_px=40, crf=18, keep_full=False, gray=False, log=<built-in function print>)[source]

Crop every chunk of the Motif store in rec_dir; returns the reduced.json dict.

Parameters:
Return type:

dict

Deliver results to a removable disk: detect, mount, copy, manifest, verify, unmount.

class rigconductor.export.Disk(device: 'str', size: 'str', fstype: 'str | None', label: 'str | None', mountpoint: 'str | None')[source]
Parameters:
  • device (str)

  • size (str)

  • fstype (str | None)

  • label (str | None)

  • mountpoint (str | None)

rigconductor.export.removable_disks(run=<function run>)[source]

Partitions on removable block devices (USB sticks, USB disks) that carry a filesystem.

Return type:

list[Disk]

rigconductor.export.write_bundle(files, dest, log=None)[source]

Copy {relative name: source} into dest and write a sha256 manifest. Returns the manifest path. Refuses to overwrite a non-empty dest.

Parameters:
Return type:

Path

rigconductor.export.verify_bundle(dest)[source]

Re-read every file against the manifest; returns the names that differ or are missing.

Parameters:

dest (Path)

Return type:

list[str]

DrosoDB snapshot by USB stick, for rigs without a network.

The tablet writes <stick>/drosodb/ddb.latest.sqlite3 plus snapshot.json (deploy/tablet/ddb_to_usb.py); the rig imports it here. The snapshot is checked (SHA-256, SQLite integrity, DrosoDB tables present) and must be newer than the one the rig already has, then replaces it atomically; the previous copy is kept as *.prev.

class rigconductor.ddbsync.SnapshotInfo(path: 'Path', created: 'str', sha256: 'str', n_active_vials: 'int', source_host: 'str' = '')[source]
Parameters:
rigconductor.ddbsync.validate_snapshot(path)[source]

Raise unless path is a sound DrosoDB file; return the active-vial count.

Parameters:

path (Path)

Return type:

int

Offline hand-over: a rig without network packs a session, a relay (any Conductor install that can reach the cluster) runs the cluster stages, and the results travel back on the same USB stick:

rig    : pack_job(session, dest)            → <session>.job.zip
relay  : import_job(cfg, zip) → session ; run upload → fetch
         pack_results(session, dest)        → <session>.results.zip
rig    : import_results(session, zip)       ; then score → export

Packages are plain ZIP files (videos stored, not re-compressed) with a manifest.json holding the SHA-256 of every member; both ends verify.

rigconductor.relay.find_packages(root)[source]

Conductor packages on a mounted stick (top level and one folder down).

Parameters:

root (Path)

Return type:

list[Path]

Cluster and models

SLURM array job status from sacct.

class rigconductor.cluster_status.TaskState(task, state, node='', elapsed='', exit_code='')[source]

One array task.

Parameters:
task

Array index (= arena / unit index for Conductor jobs).

Type:

int

state

SLURM state, e.g. RUNNING, CANCELLED by 123 → CANCELLED.

Type:

str

node

Node it runs or ran on (’’ while pending).

Type:

str

elapsed

HH:MM:SS as sacct prints it.

Type:

str

exit_code

0:0 etc.

Type:

str

property category: str

pending · running · done · failed.

rigconductor.cluster_status.expand_array_spec(spec)[source]

[3-5,8%2] → [3, 4, 5, 8].

Parameters:

spec (str)

Return type:

list[int]

rigconductor.cluster_status.parse_sacct(text, job_id)[source]

Parse sacct -X -n -P -o SACCT_FIELDS output for one array job.

Parameters:
Return type:

list[TaskState]

rigconductor.cluster_status.summarise(tasks)[source]

Counts per category and running tasks per node.

Parameters:

tasks (list[TaskState])

Return type:

dict

rigconductor.cluster_status.fetch_tasks(ssh_host, job_id, ssh_cmd='ssh -o BatchMode=yes', run=<function run>)[source]

Ask the cluster for every task of job_id (one ssh round trip).

Parameters:
Return type:

list[TaskState]

class rigconductor.cluster_status.WorkerState(job_id, state, partition='', node='', elapsed='', reason='')[source]

One GPU worker job.

Parameters:
job_id

SLURM job id.

Type:

str

state

SLURM state.

Type:

str

partition

GPU partition it was sent to.

Type:

str

node

Node it runs or ran on.

Type:

str

elapsed

HH:MM:SS.

Type:

str

reason

Why a pending job waits (squeue %r, e.g. Resources).

Type:

str

property card: str

aoraki_gpu_L4_24GB → L4.

rigconductor.cluster_status.queue_listing_command(pose_dir)[source]

Shell snippet that lists a trial’s outputs and queue state in one go.

Parameters:

pose_dir (str)

Return type:

str

rigconductor.cluster_status.parse_queue(text, trial, indices, workers_done, stale_after_s=300)[source]

Per-arena state from queue_listing_command() output.

workers_done: no worker is pending or running any more, so a clip that is neither finished nor parked will not be picked up again (shown as failed). A claim whose heartbeat is older than stale_after_s is reported with exit_code “stale …”: its worker died or hangs; another worker (or a rerun) takes it over.

Parameters:
Return type:

list[TaskState]

class rigconductor.cluster_status.JobStatus(workers: 'list[WorkerState]', arenas: 'list[TaskState]')[source]
Parameters:
rigconductor.cluster_status.fetch_queue_status(ssh_host, job_ids, pose_dir, trial, indices, ssh_cmd='ssh -o BatchMode=yes', run=<function run>)[source]

Workers (sacct) and arenas (queue files) in one ssh round trip.

Parameters:
Return type:

JobStatus

rigconductor.cluster_status.stop_run(ssh_host, job_ids, pose_dir, ssh_cmd='ssh -o BatchMode=yes', run=<function run>)[source]

Cancel every job of a run and release its claimed arenas, so a rerun can take them at once. Finished arenas (.h5 / .empty) are kept.

Parameters:
  • ssh_host (str)

  • job_ids (str)

  • pose_dir (str | None)

  • ssh_cmd (str)

Return type:

str

rigconductor.cluster_status.arena_log(ssh_host, pose_dir, index, lines=80, ssh_cmd='ssh -o BatchMode=yes', run=<function run>)[source]

Last lines of one arena’s SLEAP log on the cluster.

Parameters:
Return type:

str

Model registry: one YAML per organism on the cluster, cached locally.

Entry example:

- id: flies13_lab_v1
  organism: drosophila
  kind: sleap-topdown          # sleap-topdown | dlc | tadpose-assign
  run: flies13_lab_v1          # what the SLURM script takes (models/<run>.centroid …)
  env: sleap
  trained: 2026-11-20
  validation: {frames: 150, mAP: 0.82}
  notes: fine-tuned from flies13 on 150 October frames
class rigconductor.models.Model(id: 'str', organism: 'str', kind: 'str', run: 'str', env: 'str' = 'sleap', trained: 'str | None' = None, validation: 'dict' = <factory>, notes: 'str' = '', deprecated: 'bool' = False, expects: 'dict' = <factory>, grayscale_input: 'bool' = False, default: 'bool' = False)[source]
Parameters:
property label: str

id, date and the headline validation number.

Type:

Dropdown text

rigconductor.models.default_for(models, organism)[source]

Id of the promoted model for organism (the last one marked default).

Parameters:
Return type:

str | None

The SLEAP 1.6 environment used for labelling and pre-filling.

Installed per user with uv tool install "sleap[nn]" (CPU wheels, no sudo, no GPU). Everything that needs sleap-io runs as <env>/bin/python -I labels/worker.py <task> <args.json>.

class rigconductor.sleapenv.SleapEnv(python: 'Path', version: 'str' = '')[source]
Parameters:
rigconductor.sleapenv.probe(python, run=<function run>)[source]

SLEAP version of an env, or None when it is not a working SLEAP 1.6 env.

Parameters:

python (Path)

Return type:

str | None

rigconductor.sleapenv.parse_line(line)[source]

Classify one worker output line: (‘progress’, (frac, text)), (‘result’, dict), (‘log’, s).

Parameters:

line (str)

Return type:

tuple[str, object]

rigconductor.sleapenv.run_task(env, task, args, log=None, progress=None, timeout_s=3600)[source]

Run one worker task in the SLEAP env and return its result.

Parameters:
Return type:

dict

rigconductor.sleapenv.open_labelling(env, slp)[source]

Start the SLEAP labelling GUI on slp (does not wait).

Parameters:
Return type:

Popen

rigconductor.sleapenv.installer_text(name)[source]

An installer file with this Conductor’s pinned versions filled in.

Parameters:

name (str)

Return type:

str

rigconductor.sleapenv.write_installer(dest_dir)[source]

Copy the installer and the launcher script into dest_dir.

Parameters:

dest_dir (Path)

Return type:

list[Path]

rigconductor.sleapenv.install(log=None, reinstall=False)[source]

Install SLEAP (CPU) for this user with the bundled script; returns the env.

Parameters:
Return type:

SleapEnv

Organism profiles

Organism profiles: everything that differs between Drosophila arenas and tadpole plates.

class rigconductor.profiles.Profile[source]
abstract validate_metadata(meta, cfg)[source]

Human-readable problems; empty list means go.

Parameters:
Return type:

list[str]

motif_metadata(meta)[source]

What is written into Motif’s metadata.yaml at recording start (JSON-safe).

Parameters:

meta (dict)

Return type:

dict

abstract register(ctx)[source]

Register a virtual subclass of an ABC.

Returns the subclass, to allow usage as a class decorator.

Parameters:

ctx (SessionContext)

Return type:

None

abstract submit(ctx, model)[source]

Submit the cluster job; return the job id.

Parameters:
Return type:

str

abstract poll(ctx, interval_s)[source]

Block until the job finished; True if every task completed.

Parameters:
Return type:

bool

abstract export_files(ctx, blind, clips)[source]

{relative name in the bundle: source path}.

Parameters:
Return type:

dict[str, Path]

clips_for_check(ctx)[source]

Clips the model will see (for the model-vs-data check).

Parameters:

ctx (SessionContext)

Return type:

list[Path]

inverts_for(ctx, model)[source]

Whether the cluster step inverts the clips for this model (None = model default).

Parameters:
Return type:

bool | None

cluster_queue(ctx)[source]

Remote pose dir, trial name and unit indices of a pull-queue run.

Parameters:

ctx (SessionContext)

Return type:

tuple[str, str, list[int]] | None

unit_label(index)[source]

How a cluster task (= one arena / well) is named to the operator.

Parameters:

index (int)

Return type:

str

archive_analysis(ctx, label)[source]

Move the results of the last cluster run aside before a rerun with another model; returns a description of where they went.

Parameters:
Return type:

str | None

reset_analysis(ctx)[source]

Clear profile-side state of a cluster run (job id, …).

Parameters:

ctx (SessionContext)

Return type:

None

arena_layout_path(ctx)[source]

The arena layout the cut used (editable in ‘Fix arenas’); None → no editor.

Parameters:

ctx (SessionContext)

Return type:

Path | None

save_arena_layout(ctx, layout)[source]

Store an edited layout where the next cut will use it.

Parameters:

ctx (SessionContext)

Return type:

list[Path]

reset_cut(ctx)[source]

Move the clips aside so the next cut starts fresh; returns where to.

Parameters:

ctx (SessionContext)

Return type:

Path | None

arena_circles(ctx)[source]

Arena circles (cx, cy, r) in full-frame px after the cut, for ‘reduce’; None → this profile does not crop recordings.

Parameters:

ctx (SessionContext)

Return type:

list[tuple[float, float, float]] | None

relay_files(ctx)[source]

Files a relay needs to run upload → fetch, relative to the recording dir.

Parameters:

ctx (SessionContext)

Return type:

dict[str, Path]

result_files(ctx)[source]

Files the relay sends back, relative to the recording dir.

Parameters:

ctx (SessionContext)

Return type:

dict[str, Path]

adopt_relay_state(ctx, relay_profile_state)[source]

Merge what the relay learned (job id, …) into the rig’s profile state.

Parameters:
Return type:

None

class rigconductor.profiles.SessionContext(cfg: 'ConductorConfig', session_id: 'str', metadata: 'dict', recording_dir: 'Path', log: 'Log', state: 'dict' = <factory>)[source]
Parameters:

The Profile interface and the context a session hands to it.

class rigconductor.profiles.base.SessionContext(cfg: 'ConductorConfig', session_id: 'str', metadata: 'dict', recording_dir: 'Path', log: 'Log', state: 'dict' = <factory>)[source]
Parameters:
class rigconductor.profiles.base.Profile[source]
abstract validate_metadata(meta, cfg)[source]

Human-readable problems; empty list means go.

Parameters:
Return type:

list[str]

motif_metadata(meta)[source]

What is written into Motif’s metadata.yaml at recording start (JSON-safe).

Parameters:

meta (dict)

Return type:

dict

abstract register(ctx)[source]

Register a virtual subclass of an ABC.

Returns the subclass, to allow usage as a class decorator.

Parameters:

ctx (SessionContext)

Return type:

None

abstract submit(ctx, model)[source]

Submit the cluster job; return the job id.

Parameters:
Return type:

str

abstract poll(ctx, interval_s)[source]

Block until the job finished; True if every task completed.

Parameters:
Return type:

bool

abstract export_files(ctx, blind, clips)[source]

{relative name in the bundle: source path}.

Parameters:
Return type:

dict[str, Path]

clips_for_check(ctx)[source]

Clips the model will see (for the model-vs-data check).

Parameters:

ctx (SessionContext)

Return type:

list[Path]

inverts_for(ctx, model)[source]

Whether the cluster step inverts the clips for this model (None = model default).

Parameters:
Return type:

bool | None

cluster_queue(ctx)[source]

Remote pose dir, trial name and unit indices of a pull-queue run.

Parameters:

ctx (SessionContext)

Return type:

tuple[str, str, list[int]] | None

unit_label(index)[source]

How a cluster task (= one arena / well) is named to the operator.

Parameters:

index (int)

Return type:

str

archive_analysis(ctx, label)[source]

Move the results of the last cluster run aside before a rerun with another model; returns a description of where they went.

Parameters:
Return type:

str | None

reset_analysis(ctx)[source]

Clear profile-side state of a cluster run (job id, …).

Parameters:

ctx (SessionContext)

Return type:

None

arena_layout_path(ctx)[source]

The arena layout the cut used (editable in ‘Fix arenas’); None → no editor.

Parameters:

ctx (SessionContext)

Return type:

Path | None

save_arena_layout(ctx, layout)[source]

Store an edited layout where the next cut will use it.

Parameters:

ctx (SessionContext)

Return type:

list[Path]

reset_cut(ctx)[source]

Move the clips aside so the next cut starts fresh; returns where to.

Parameters:

ctx (SessionContext)

Return type:

Path | None

arena_circles(ctx)[source]

Arena circles (cx, cy, r) in full-frame px after the cut, for ‘reduce’; None → this profile does not crop recordings.

Parameters:

ctx (SessionContext)

Return type:

list[tuple[float, float, float]] | None

relay_files(ctx)[source]

Files a relay needs to run upload → fetch, relative to the recording dir.

Parameters:

ctx (SessionContext)

Return type:

dict[str, Path]

result_files(ctx)[source]

Files the relay sends back, relative to the recording dir.

Parameters:

ctx (SessionContext)

Return type:

dict[str, Path]

adopt_relay_state(ctx, relay_profile_state)[source]

Merge what the relay learned (job id, …) into the rig’s profile state.

Parameters:
Return type:

None

Drosophila triad arenas: everything delegates to ThermoKourt’s session runner, so a session started here can also be resumed with thermokourt-trial.

rigconductor.profiles.drosophila.experiment_label(exp_id)[source]

Speaking name for pickers, e.g. E1 – Thermal performance curve.

Parameters:

exp_id (str)

Return type:

str

class rigconductor.profiles.drosophila.DrosophilaTriad[source]
active_vials(cfg)[source]

print code -> genotype name from the synced DrosoDB snapshot.

Parameters:

cfg (ConductorConfig)

Return type:

dict[str, str]

vial_catalogue(cfg)[source]

Active vials with what the shelf shows: code, genotype, location, generation, owner, created. Empty list when no snapshot is available.

Parameters:

cfg (ConductorConfig)

Return type:

list[dict]

validate_metadata(meta, cfg)[source]

Human-readable problems; empty list means go.

Parameters:
Return type:

list[str]

motif_metadata(meta)[source]

What is written into Motif’s metadata.yaml at recording start (JSON-safe).

Parameters:

meta (dict)

Return type:

dict

inverts_for(ctx, model)[source]

Whether the cluster step inverts the clips for this model (None = model default).

Parameters:
Return type:

bool | None

cluster_queue(ctx)[source]

Remote pose dir, trial name and unit indices of a pull-queue run.

Parameters:

ctx (SessionContext)

Return type:

tuple[str, str, list[int]] | None

unit_label(index)[source]

How a cluster task (= one arena / well) is named to the operator.

Parameters:

index (int)

Return type:

str

arena_layout_path(ctx)[source]

The arena layout the cut used (editable in ‘Fix arenas’); None → no editor.

Parameters:

ctx (SessionContext)

Return type:

Path | None

save_arena_layout(ctx, layout)[source]

Save for this recording and as the rig default (the next cut reads that).

Parameters:

ctx (SessionContext)

Return type:

list[Path]

archive_analysis(ctx, label)[source]

Poses (local and on Aoraki) and clips drawn from them go to archive/<model>_<time>/ next to the recording and pose/_archive/<trial>.<model>_<time> on the cluster.

Parameters:
Return type:

str | None

reset_analysis(ctx)[source]

Clear profile-side state of a cluster run (job id, …).

Parameters:

ctx (SessionContext)

Return type:

None

reset_cut(ctx)[source]

Move the clips aside so the next cut starts fresh; returns where to.

Parameters:

ctx (SessionContext)

Return type:

Path | None

arena_circles(ctx)[source]

Arenas grown to what the clips will cover (ThermoKourt padding and its minimum clip size), so cropping the recording never cuts into a clip.

Parameters:

ctx (SessionContext)

Return type:

list[tuple[float, float, float]] | None

register(ctx)[source]

Register a virtual subclass of an ABC.

Returns the subclass, to allow usage as a class decorator.

Parameters:

ctx (SessionContext)

Return type:

None

submit(ctx, model)[source]

Submit the cluster job; return the job id.

Parameters:
Return type:

str

poll(ctx, interval_s)[source]

Block until the job finished; True if every task completed.

Parameters:
Return type:

bool

relay_files(ctx)[source]

Files a relay needs to run upload → fetch, relative to the recording dir.

Parameters:

ctx (SessionContext)

Return type:

dict[str, Path]

result_files(ctx)[source]

Files the relay sends back, relative to the recording dir.

Parameters:

ctx (SessionContext)

Return type:

dict[str, Path]

adopt_relay_state(ctx, relay_profile_state)[source]

The relay’s ThermoKourt state knows the job and the finished cluster stages; keep the rig’s own spec and trials, take the rest.

Parameters:
Return type:

None

export_files(ctx, blind, clips)[source]

{relative name in the bundle: source path}.

Parameters:
Return type:

dict[str, Path]

render_clips(ctx, mode)[source]

Annotated arena clips (thermokourt-overlay), drawn in parallel in child processes (OpenCV and Qt cannot share the GUI process). Reuses clips already drawn in the same mode.

Parameters:
Return type:

list[Path]

Xenopus tadpoles in a 24-well plate (TadPose backend).

Metadata: one row per occupied well — well (A1…D6), clutch, genotype, drug, dose, stage, notes — matching TadPose’s tadpole_group / well_type vocabulary. The cluster side runs scripts/slurm/tadpose_track_assign.sh (track → ingest → features → assign to the canonical k = 36 prototypes).

Status: the metadata, upload, submit, poll, fetch and export paths are complete; cut (plate → 24 well crops) requires tadpose installed on this PC and is pending the recording-rig decision (Rig Conductor dev plan §4).

rigconductor.profiles.tadpole.parse_plate_csv(text)[source]

Plate map CSV with a header containing at least well; unknown columns are kept in notes.

Parameters:

text (str)

Return type:

list[dict]

class rigconductor.profiles.tadpole.Tadpole24Well[source]
validate_metadata(meta, cfg)[source]

Human-readable problems; empty list means go.

Parameters:
Return type:

list[str]

motif_metadata(meta)[source]

What is written into Motif’s metadata.yaml at recording start (JSON-safe).

Parameters:

meta (dict)

Return type:

dict

register(ctx)[source]

Write the plate map next to the recording; TadPose builds its DB on the cluster.

Parameters:

ctx (SessionContext)

Return type:

None

submit(ctx, model)[source]

Submit the cluster job; return the job id.

Parameters:
Return type:

str

poll(ctx, interval_s)[source]

Block until the job finished; True if every task completed.

Parameters:
Return type:

bool

score(ctx, model)[source]

Per-well prototype proportions from the assigned labels CSV(s).

Parameters:
Return type:

None

export_files(ctx, blind, clips)[source]

{relative name in the bundle: source path}.

Parameters:
Return type:

dict[str, Path]

Labels and training

Training data for SLEAP: label sets, frame selection, packages, merging, training.

Label sets on disk.

Layout:

<sets_dir>/DEFAULT            name of the default set
<sets_dir>/<name>/
    registry.yaml        versions, validation recordings, packages, models
    v1.pkg.slp           frames embedded, only hand-placed instances
    v2.pkg.slp
    packages/<id>/       outgoing labelling packages (and what came back)
    train/vN/            train / validation split written before training
rigconductor.labels.store.scale_name(arena_diameter_px)[source]

Camera-scale label of an arena, e.g. 500px.

Parameters:

arena_diameter_px (float)

Return type:

str

rigconductor.labels.store.default_set(root=None)[source]

Name of the default label set (wizard pre-selects it, label-sync sends it).

Parameters:

root (str | Path | None)

Return type:

str | None

class rigconductor.labels.store.LabelSet(path: 'Path', data: 'dict')[source]
Parameters:
add_version(stats, note='', parent=None)[source]

Record a new version file (already written as v<N>.pkg.slp).

Parameters:
Return type:

dict

set_validation(scale, recordings)[source]

Recordings whose frames are only ever used to test models at scale.

Parameters:
Return type:

None

set_training_roles(shown, roles)[source]

Roles chosen for the recordings of one version.

Parameters:
  • shown (dict[str, str]) – Recording → its scale, for every recording on the page.

  • roles (dict[str, str]) – Recording → train, all (split by frame), val or out.

Return type:

None

Validation and shared recordings not shown (no frames in that version yet) are kept.

shared()[source]

Recordings split by frame into training and validation (recording → scale).

Return type:

dict[str, str]

add_project(path, note='')[source]

A SLEAP project (.slp) whose new hand labels can be taken into the set.

Parameters:
Return type:

dict

remove_project(path)[source]

Take a project off the list (its file is not touched).

Parameters:

path (str | Path)

Return type:

None

labelled_frames()[source]

(recording, arena, frame) of everything in the set or out for labelling.

Return type:

set[tuple[str, int, int]]

Find cut (and ideally analysed) recordings under the data root.

A recording qualifies when it has arena clips; pose files make the frame choice smarter (unsure and contact frames) but are not required.

class rigconductor.labels.recordings.Recording(name: 'str', path: 'Path', clips: 'dict[int, Path]' = <factory>, poses: 'dict[int, Path]' = <factory>, diameter_px: 'float | None' = None, fps: 'float' = 25.0)[source]
Parameters:
clip_entries()[source]

Arguments for the worker’s select task, one per arena clip.

Return type:

list[dict]

rigconductor.labels.recordings.find_recordings(data_root)[source]

Recordings with clips under data_root (two levels: camera / recording), newest first.

Parameters:

data_root (Path)

Return type:

list[Recording]

Frame selection for new labels.

Scores come from the SLEAP analysis export of an arena (tracks, point_scores, track_occupancy). Three kinds of frames are picked:

  • unsure: the model found fewer flies than expected or placed points with low confidence;

  • contact: two thoraxes are closer than LABEL_CONTACT_BL body lengths (identity swaps and leg mix-ups happen here);

  • uniform: spread evenly over the clip, so ordinary frames stay covered.

class rigconductor.labels.select.Pick(frame: 'int', reason: 'str', score: 'float' = 0.0)[source]
Parameters:
rigconductor.labels.select.unsure_scores(point_scores, occupancy, n_expected)[source]

Per-frame doubt: missing flies plus low point confidence, 0 (sure) … 2.

Parameters:
  • point_scores (ndarray) – (n_tracks, n_nodes, n_frames), NaN where no point.

  • occupancy (ndarray) – (n_frames, n_tracks), 1 where a track has an instance.

  • n_expected (int) – Flies that should be in every frame.

Return type:

ndarray

rigconductor.labels.select.body_length_px(tracks, node_names)[source]

Median head-to-abdomen distance, a body-length estimate in px.

Parameters:
Return type:

float

rigconductor.labels.select.contact_scores(tracks, node_names)[source]

Per-frame closeness of the two nearest flies, 0 (apart) … 1 (touching).

Parameters:
  • tracks (ndarray) – (n_tracks, 2, n_nodes, n_frames) positions, NaN where missing.

  • node_names (list[str]) – Skeleton node names.

Return type:

ndarray

rigconductor.labels.select.quotas(n, mix=None)[source]

Split n frames over the kinds by mix (rounded, sums to n).

Parameters:
Return type:

dict[str, int]

rigconductor.labels.select.pick_frames(n_frames, n, unsure=None, contact=None, mix=None, min_gap=1, exclude=None, seed=0)[source]

Choose n frames of one arena clip.

Parameters:
  • n_frames (int) – Frames in the clip.

  • n (int) – Frames wanted.

  • unsure (ndarray | None) – Doubt per frame (unsure_scores) or None without a pose file.

  • contact (ndarray | None) – Closeness per frame (contact_scores) or None.

  • mix (dict[str, float] | None) – Shares per kind; defaults to LABEL_MIX.

  • min_gap (int) – Picked frames are at least this many frames apart.

  • exclude (set[int] | None) – Frames that must not be picked (already labelled).

  • seed (int) – Seed for breaking ties between equal scores.

Returns:

Picks sorted by frame. Kinds without scores, or without enough distinct frames, are filled up with evenly spread frames.

Return type:

list[Pick]

Build labelling packages and take labelled ones back.

The package folder is self-contained: a labeller needs neither the videos nor the Conductor, only a Linux PC (label.sh installs SLEAP when needed). package.json carries the pixel hash of every frame, so frames that come back are matched without trusting file names.

rigconductor.labels.package.manifest_problems(folder)[source]

Files changed since packing; the labels file is expected to change.

Parameters:

folder (Path)

Return type:

list[str]

rigconductor.labels.package.build_package(lset, frames, env, prefill=None, dest=None, allowed_counts=(3,), log=None, progress=None)[source]

Write a package for frames and register it with the set.

Parameters:
  • lset (LabelSet) – Label set the frames will be merged into.

  • frames (list[dict]) – Picks from the select task (recording, arena, clip, frame, …).

  • env (SleapEnv) – SLEAP environment.

  • prefill (list[str] | None) – Model dirs (centroid, centred instance) to pre-fill with, or None.

  • dest (Path | None) – Copy the finished folder here as well (a USB stick), or None.

  • allowed_counts (tuple[int, ...]) – Valid fly counts per frame.

Returns:

The package folder inside the set (or the copy on dest).

Return type:

Path

rigconductor.labels.package.find_packages(root)[source]

Package folders under root (a stick or a folder), newest first.

Parameters:

root (Path)

Return type:

list[Path]

rigconductor.labels.package.take_back(lset, folder)[source]

Copy a returned labels file into the set’s package folder.

Returns:

The package info and the path of the stored copy.

Parameters:
Return type:

tuple[dict, Path]

rigconductor.labels.package.check_returned(lset, info, returned, env, log=None, progress=None)[source]

Run the frame checks; returns the worker’s report (nothing is merged).

Parameters:
rigconductor.labels.package.merge_returned(lset, info, returned, accepted, labeller, env, report=None, log=None, progress=None)[source]

Merge accepted frames into a new version of the set; returns its registry entry.

Parameters:
Return type:

dict

rigconductor.labels.package.copy_package(lset, source, dest_root, replace=False)[source]

Copy a package folder (with what is labelled so far) to a stick or folder.

Parameters:
  • source (Path) – The package folder to copy (the copy being labelled).

  • dest_root (Path) – Stick mount point or folder; the copy goes into <set>_<id>.

  • replace (bool) – Overwrite an existing copy there (its labels are lost).

  • lset (LabelSet)

Returns:

The new copy.

Return type:

Path

rigconductor.labels.package.package_copies(lset, pkg_id, also=())[source]

Folders holding package pkg_id: this PC’s copy, copies made with copy_package that are reachable now, and any of also.

Parameters:
Return type:

list[Path]

rigconductor.labels.package.delete_package(lset, pkg_id, also=())[source]

Delete every copy of a package that was not merged; its frames can be picked again.

Only folders whose package.json names this package are removed. The registry keeps the entry (status deleted).

Returns:

The folders removed.

Parameters:
Return type:

list[Path]

rigconductor.labels.package.check_project(lset, slp, env, log=None, progress=None)[source]

New hand-labelled frames of a project, checked; the report carries their hashes.

Parameters:
Return type:

dict

rigconductor.labels.package.merge_project(lset, slp, report, accepted, labeller, env, log=None)[source]

Accepted new frames of a project → next version of the set; returns its entry.

Parameters:
Return type:

dict

Checks for labelled frames coming back from a labeller.

A frame is rejected when training on it would teach the model something wrong (half-corrected, wrong fly count, no thorax, points off the image, duplicates). It gets a warning when it breaks a labelling convention that a person should look at (the decapitated female’s hidden head points).

class rigconductor.labels.rules.Inst(xy, user=True)[source]

One instance: xy (n_nodes, 2) with NaN where not visible.

Parameters:
class rigconductor.labels.rules.Verdict(status: 'str', reasons: 'list[str]' = <factory>, warnings: 'list[str]' = <factory>)[source]
Parameters:
rigconductor.labels.rules.same_fly(a, b, tol=2.0)[source]

True when two instances are copies: every point visible in both coincides.

Flies that overlap (courtship, mounting, copulation) share at most some points, so they are not flagged; at least two shared points are needed.

Parameters:
Return type:

bool

rigconductor.labels.rules.check_frame(instances, nodes, shape_hw, allowed_counts=(3,), n_females=1)[source]

Judge one labelled frame.

Parameters:
  • instances (list[Inst]) – All instances on the frame (user and predicted).

  • nodes (list[str]) – Skeleton node names, in order.

  • shape_hw (tuple[int, int]) – Image height and width.

  • allowed_counts (tuple[int, ...]) – Valid numbers of user instances (3 for triads).

  • n_females (int | None) – Instances expected with hidden head points, None to skip.

Return type:

Verdict

rigconductor.labels.rules.skeleton_problem(nodes, expected)[source]

Text describing a skeleton mismatch, or None when identical.

Parameters:
Return type:

str | None

Send a label set (versions, registry, packages) to Aoraki.

Lands in <project>/sleap_labels/sets/<name>/. The train/ folder is left out (it is rebuilt before every training run). Run from cron, the ssh key comes from the desktop keyring’s agent, so the PC must stay logged in.

rigconductor.labels.sync.ssh_env()[source]

Environment for ssh/rsync; under cron, borrow the desktop keyring’s agent.

Return type:

dict

rigconductor.labels.sync.sync(cfg, name=None, run=<function run>)[source]

Copy one label set (default: the default set) to Aoraki; returns a log line.

Parameters:
Return type:

str

rigconductor.labels.sync.sync_locked(cfg, name=None)[source]

sync unless another copy of it is still running.

Parameters:
Return type:

str

rigconductor.labels.sync.with_cron_line(current, line)[source]

Crontab text with our line replaced (or removed when line is None).

Parameters:
  • current (str)

  • line (str | None)

Return type:

str

rigconductor.labels.sync.install_cron(exe, config=None, remove=False, run=<function run>)[source]

Add (or remove) the label-sync line in this user’s crontab; returns the line.

Parameters:

Fine-tune a pose model on a label-set version and decide whether it replaces the current one.

Promotion rule (Decisions 2026-11-11): the new model is offered as the default only if it is not worse than the current model on any validation set and better on at least one; Bart confirms it in the wizard.

class rigconductor.labels.train.TrainPlan(set_name: 'str', version: 'int', run: 'str', base_run: 'str', compare_run: 'str', remote_dir: 'str' = '', val: 'dict[str, str]' = <factory>, job_id: 'str' = '', excluded: 'list[str]' = <factory>, shared: 'list[str]' = <factory>)[source]
Parameters:
classmethod from_entry(entry)[source]

Rebuild a plan from its record in the label set’s models list.

Parameters:

entry (dict)

Return type:

TrainPlan

rigconductor.labels.train.project_root(cfg, profile)[source]

Aoraki project folder (the registry lives in <project>/models/).

Parameters:
Return type:

str

rigconductor.labels.train.run_name(lset, version, today=None)[source]

<set>_v<N>_<date>, with b, c, … added when that run exists already.

Parameters:
Return type:

str

rigconductor.labels.train.summarise(lset, version, env, log=None, progress=None)[source]

Per-recording facts of a version (cached: version files never change).

Parameters:
Return type:

list[dict]

rigconductor.labels.train.prepare(lset, version, env, exclude=(), log=None, progress=None)[source]

Split a version into train / validation files (by recording, or by frame for the recordings set to All).

Parameters:
  • exclude – Recordings left out of training altogether.

  • lset (LabelSet)

  • version (int)

Return type:

dict[str, Path]

rigconductor.labels.train.upload(cfg, profile, lset, plan, files, scripts_root, run=<function run>)[source]

Send the split and the training scripts to Aoraki; fills in remote paths.

Parameters:
Return type:

TrainPlan

rigconductor.labels.train.parse_status(text)[source]

State, done/failed flags, loss curves per head, last epoch seen and a log tail.

curves maps a head to rows (epoch, train loss, val loss, seconds); patience a head to its early-stopping patience (epochs without a better validation loss); trained is how many heads have finished training.

Parameters:

text (str)

Return type:

dict

rigconductor.labels.train.compare(rows, new, old, metric='mAP')[source]

Side-by-side numbers per validation set and the promotion verdict.

Parameters:
Return type:

dict

rigconductor.labels.train.registry_entry(run_id, base, lset, version, verdict, promote, today=None, excluded=None, shared=None)[source]

Registry entry for a trained model (expects inherited from its base).

Parameters:
Return type:

dict

rigconductor.labels.train.append_registry(cfg, profile, entry, run=<function run>)[source]

Append entry to the registry on Aoraki (backup kept next to it).

Parameters:
Return type:

None

rigconductor.labels.train.local_runs(root=None)[source]

Model runs with both halves (centroid + centred instance) on this PC.

Parameters:

root (Path | None)

Return type:

list[str]

rigconductor.labels.train.fetch_model(cfg, profile, run_id, run=<function run>)[source]

Copy a model pair from Aoraki to this PC (only the files inference needs).

Parameters:
Return type:

None

SLEAP-side tasks of the labelling wizard.

The Conductor never imports sleap-io itself (it lives in its own uv env with PyTorch). It writes the arguments to a JSON file and runs this script with the SLEAP env’s Python; see rigconductor.sleapenv.

Tasks: inspect, seed, select, build, check, harvest, merge, summary, split. Every frame in a label set is identified by a hash of its pixels, so provenance survives SLEAP re-saving, merging and splitting.

rigconductor.labels.worker.clip_scale(video)[source]

Camera scale of an arena clip from its width (arena + ThermoKourt padding).

Return type:

str

rigconductor.labels.worker.stats(labels, prov)[source]

Counts for the registry: frames, flies, per recording, scale, labeller.

Parameters:

prov (dict)

Return type:

dict

rigconductor.labels.worker.keep_user_only(labels, frames)[source]

Reduce labels to frames with only hand-placed instances.

Parameters:

frames (list)

Return type:

None

rigconductor.labels.worker.frame_states(labels)[source]

Frames to label (suggestions and labelled frames) by state.

labelled: hand-placed instances; predicted: only model predictions; empty: nothing yet.

Return type:

dict

rigconductor.labels.worker.clip_info(lf, scale, labeller, source)[source]

Provenance of a frame labelled straight on an arena clip (not a package).

Parameters:
  • scale (str | None)

  • labeller (str)

  • source (str)

Return type:

dict

rigconductor.labels.worker.task_seed(a)[source]

First version of a set from an existing SLEAP project (hand labels only).

Parameters:

a (dict)

Return type:

dict

rigconductor.labels.worker.task_select(a)[source]

Pick frames per arena clip.

Parameters:

a (dict)

Return type:

dict

rigconductor.labels.worker.task_build(a)[source]

Write a labelling package: chosen frames embedded, optional pre-fill.

Parameters:

a (dict)

Return type:

dict

rigconductor.labels.worker.task_check(a)[source]

Judge every frame of a returned package; nothing is merged here.

Parameters:

a (dict)

Return type:

dict

rigconductor.labels.worker.task_harvest(a)[source]

Frames hand-labelled in a SLEAP project since they were last taken into the set.

Frames already in the set (by pixel hash) are skipped; the rest get provenance from their clip names and the usual rule check.

Parameters:

a (dict)

Return type:

dict

rigconductor.labels.worker.task_merge(a)[source]

New version = base set + accepted frames of a returned package.

Parameters:

a (dict)

Return type:

dict

rigconductor.labels.worker.task_summary(a)[source]

Per recording: frames, flies per frame, image sizes and one example frame.

Parameters:

a (dict)

Return type:

dict

rigconductor.labels.worker.hash_share(h)[source]

A frame’s fixed place in [0, 1) from its pixel hash (same in every version).

Parameters:

h (str)

Return type:

float

rigconductor.labels.worker.task_split(a)[source]

Train file + one validation (test) file per scale.

Validation recordings are held out whole. Recordings in shared (recording → scale) are split by frame: a test_share of their frames, chosen by pixel hash so a frame stays on its side in later versions, joins the validation file of their scale; the rest is trained on.

Parameters:

a (dict)

Return type:

dict

Windows (PyQt6)

The operator wizard: Setup → Animals → Record → Cut → Analyse → Deliver.

Every button goes through rigconductor.session.ConductorSession, so a session started here can be resumed from the command line and vice versa.

class rigconductor.gui.wizard.Worker(fn)[source]
run(self, /)[source]
class rigconductor.gui.wizard.Wizard(cfg)[source]
Parameters:

cfg (ConductorConfig)

arena_genotypes()[source]

Genotypes per arena from the vial board, if the animals page has one.

Return type:

dict[int, list[str]]

set_reduce_padding(v)[source]

One padding for every preview and for cropping the recording.

Parameters:

v (int)

class rigconductor.gui.wizard.SetupPage(wiz)[source]
Parameters:

wiz (Wizard)

cleanupPage(self, /)[source]
validatePage(self, /) → bool[source]
Return type:

bool

preferred_model()[source]

A model promoted in the registry beats the preset’s built-in choice.

Return type:

str | None

check_camera(interactive=True)[source]

Model + preset vs the live camera. Non-interactive: only report.

Parameters:

interactive (bool)

Return type:

bool

load_recording(rec)[source]

Choose an existing recording; if the Conductor made it, resume its session (animals, vials, model, stages already done). Returns True then.

Parameters:

rec (Path)

Return type:

bool

isComplete(self, /) → bool[source]
Return type:

bool

class rigconductor.gui.wizard.AnimalsPage(wiz)[source]
Parameters:

wiz (Wizard)

validatePage(self, /) → bool[source]
Return type:

bool

class rigconductor.gui.wizard.StagePage(wiz, title, subtitle)[source]

A page that runs one or more stages in the worker and shows the log.

Parameters:
initializePage(self, /)[source]
isComplete(self, /) → bool[source]
Return type:

bool

class rigconductor.gui.wizard.RecordPage(wiz)[source]
initializePage(self, /)[source]
cleanupPage(self, /)[source]
validatePage(self, /) → bool[source]
Return type:

bool

class rigconductor.gui.wizard.CutPage(wiz)[source]
class rigconductor.gui.wizard.AnalysePage(wiz)[source]
cleanupPage(self, /)[source]
initializePage(self, /)[source]
class rigconductor.gui.wizard.DeliverPage(wiz)[source]
initializePage(self, /)[source]

The training-data wizard (second wizard of Rig Conductor).

All SLEAP work runs in the SLEAP 1.6 env as child processes (rigconductor.sleapenv); this window only shows progress and choices.

class rigconductor.gui.labelling_wizard.TaskPage(wiz, title, subtitle)[source]

A page with a log, a progress bar and one background task at a time.

Parameters:
run(fn, done)[source]

Run fn(emit) in the worker; done(ok, msg) afterwards.

class rigconductor.gui.labelling_wizard.StartPage(wiz)[source]
initializePage(self, /)[source]
isComplete(self, /) → bool[source]
nextId(self, /) → int[source]
class rigconductor.gui.labelling_wizard.RecordingsPage(wiz)[source]
initializePage(self, /)[source]
isComplete(self, /) → bool[source]
validatePage(self, /) → bool[source]
class rigconductor.gui.labelling_wizard.FramesPage(wiz)[source]
initializePage(self, /)[source]
isComplete(self, /) → bool[source]
validatePage(self, /) → bool[source]
class rigconductor.gui.labelling_wizard.PackagePage(wiz)[source]
initializePage(self, /)[source]
isComplete(self, /) → bool[source]
nextId(self, /) → int[source]
rigconductor.gui.labelling_wizard.open_packages(lset, extra_roots=())[source]

Unmerged packages of lset: (folder, where, info), sticks before this PC.

A package written to a stick has a copy on this PC too; the stick copy is the one that gets labelled, so it wins when both are there.

Parameters:
Return type:

list[tuple[Path, str, dict]]

class rigconductor.gui.labelling_wizard.LabelBar(states=None)[source]

Green / yellow / red bar of a project’s frames.

Parameters:

states (dict | None)

paintEvent(self, a0: QPaintEvent | None, /)[source]
rigconductor.gui.labelling_wizard.labelling_items(lset, extra_roots=())[source]

Everything that can be labelled further: wizard packages and SLEAP projects.

Parameters:
Return type:

list[dict]

class rigconductor.gui.labelling_wizard.ContinuePage(wiz)[source]
initializePage(self, /)[source]
count_states()[source]

Labelled / predicted / empty frames of every item (read in the SLEAP env).

isComplete(self, /) → bool[source]
nextId(self, /) → int[source]
class rigconductor.gui.labelling_wizard.BackPage(wiz)[source]
initializePage(self, /)[source]
isComplete(self, /) → bool[source]
nextId(self, /) → int[source]
rigconductor.gui.labelling_wizard.flies_text(flies)[source]

{"3": 28, "2": 3} → 3 flies: 28 · 2 flies: 3 (most first).

Parameters:

flies (dict)

Return type:

str

class rigconductor.gui.labelling_wizard.ExampleDialog(parent, path, title)[source]
Parameters:
class rigconductor.gui.labelling_wizard.DataPage(wiz)[source]
initializePage(self, /)[source]
counts()[source]

Frames per use; for All recordings the test share is an estimate.

Return type:

dict[str, int]

isComplete(self, /) → bool[source]
validatePage(self, /) → bool[source]
class rigconductor.gui.labelling_wizard.TrainPage(wiz)[source]
initializePage(self, /)[source]
resume()[source]

Pick up a training run that is still going (wizard reopened).

nextId(self, /) → int[source]
class rigconductor.gui.labelling_wizard.LabellingWizard(cfg)[source]
Parameters:

cfg (ConductorConfig)

Training progress for the Train on Aoraki page.

Fed with rigconductor.labels.train.parse_status() results. Training stops early when the validation loss stops improving, so the time left is an upper bound.

rigconductor.gui.train_progress.epochs_done(rows)[source]

Finished epochs: rows with a training loss (row 0 is the check before training).

Parameters:

rows (list[tuple])

Return type:

int

rigconductor.gui.train_progress.best_epoch(rows)[source]

Epoch with the lowest validation loss (the checkpoint sleap-nn keeps).

Parameters:

rows (list[tuple])

Return type:

tuple[int, float] | None

rigconductor.gui.train_progress.stop_epoch(rows, patience, max_epochs)[source]

Last epoch training can reach: early stopping ends it patience epochs after the best one unless the validation loss improves again.

Parameters:
Return type:

int

rigconductor.gui.train_progress.current_step(st)[source]

0 centroid, 1 instance, 2 scoring, 3 done.

Parameters:

st (dict)

Return type:

int

class rigconductor.gui.train_progress.LossPlot(title, parent=None)[source]

Training and validation loss per epoch, log scale.

Parameters:
  • title (str)

  • parent (QWidget | None)

set_rows(rows, x_epochs)[source]

x_epochs: how far the x axis reaches (the expected last epoch).

Parameters:
Return type:

None

paintEvent(self, a0: QPaintEvent | None, /)[source]
Return type:

None

class rigconductor.gui.train_progress.TrainingProgress(parent=None)[source]

Steps, epoch bar and loss curves of one training run.

Parameters:

parent (QWidget | None)

show_status(st, max_epochs=None)[source]

Draw a parsed status (empty dict: nothing started yet).

Parameters:
  • st (dict)

  • max_epochs (int | None)

Return type:

None

In-app user manual.

It renders the same Markdown the PDF is printed from, so editing docs/manual/user_manual.md updates both. The window is not modal: keep it open beside the wizard while you work.

class rigconductor.gui.help_window.ManualBrowser(base_dir, parent=None)[source]

QTextBrowser that finds pictures next to the manual and fits them.

Parameters:
  • base_dir (Path)

  • parent (QWidget | None)

loadResource(self, type: int, name: QUrl, /) → Any[source]
Parameters:
  • kind (int)

  • url (QUrl)

Return type:

object

class rigconductor.gui.help_window.HelpWindow(manual_path=PosixPath('/home/runner/work/RigConductor/RigConductor/docs/manual/user_manual.md'))[source]

The user manual with a contents tree and a search bar.

Parameters:

manual_path (Path)

reload()[source]

Read the manual from disk again (picks up edits without a restart).

Return type:

None

show_section(title_or_slug)[source]

Scroll to a heading; False when the manual has no such heading.

Parameters:

title_or_slug (str)

Return type:

bool

find(*, backward=False, from_start=False)[source]

Select the next (or previous) match, wrapping around.

Parameters:
Return type:

bool

showEvent(self, a0: QShowEvent | None, /)[source]
Return type:

None

rigconductor.gui.help_window.show_help(section=None)[source]

Open (or raise) the manual, optionally at section.

Parameters:

section (str | None)

Return type:

HelpWindow

rigconductor.gui.help_window.add_help_button(wizard)[source]

Help button (and F1) on a QWizard: opens the manual at the page’s section.

A page names its section in manual_section, otherwise its title is used.

Return type:

None

rigconductor.gui.help_window.page_section(page)[source]

The manual heading for a wizard page: manual_section, else its title.

Return type:

str | None

Progress bar for the stage pages.

class rigconductor.gui.progress.ProgressLine(stage: 'str', fraction: 'float', detail: 'str')[source]
Parameters:
rigconductor.gui.progress.parse_progress(line)[source]

@progress cut 0.4200 3/10 arenas → ProgressLine, else None.

Parameters:

line (str)

Return type:

ProgressLine | None

class rigconductor.gui.progress.Eta(clock=<built-in function monotonic>)[source]

Elapsed time and time left from a growing fraction (tqdm’s estimate).

Parameters:

clock (Callable[[], float])

class rigconductor.gui.progress.ProgressPanel[source]

Message boxes sized to their text.

Qt’s static message boxes keep a narrow fixed width, so long paths and log lines get cut or wrap into a tall sliver. These versions widen the box to the longest line (up to a share of the screen), make the text selectable, and move very long messages behind Show Details….

rigconductor.gui.dialogs.split_long(text, max_lines=24)[source]

Shown text and details: long plain messages keep their head in the box.

Parameters:
Return type:

tuple[str, str | None]

rigconductor.gui.dialogs.screen_side(parent)[source]

Largest square that fits the share of the screen (for pictures).

Parameters:

parent (QWidget | None)

Return type:

int

rigconductor.gui.dialogs.text_width(parent, widget, *texts)[source]

Width that fits the longest line of texts, within the screen share.

Parameters:
  • parent (QWidget | None)

  • widget (QWidget)

  • texts (str)

Return type:

int

rigconductor.gui.dialogs.fit(box, parent=None)[source]

Widen a hand-built message box to its text and informative text.

Parameters:
  • box (QMessageBox)

  • parent (QWidget | None)

Return type:

QMessageBox

rigconductor.gui.dialogs.get_text(parent, title, label, text='')[source]

Like QInputDialog.getText, wide enough for the label and the default.

Parameters:
Return type:

tuple[str, bool]

rigconductor.gui.dialogs.get_item(parent, title, label, items, current=0)[source]

Like QInputDialog.getItem (not editable), wide enough for the longest choice.

Parameters:
Return type:

tuple[str, bool]

class rigconductor.gui.dialogs.TextDialog(parent, title, heading, text)[source]

A heading and a read-only monospace text, sized to the text.

Parameters:
rigconductor.gui.dialogs.show_text(parent, title, heading, text)[source]

Show a log or other long text in a window that fits it.

Parameters:
Return type:

None

Live camera preview with arena overlay and a ‘find arenas in this image’ check.

class rigconductor.gui.preview.PreviewThread(url)[source]
Parameters:

url (str)

run(self, /)[source]
class rigconductor.gui.preview.PreviewView[source]

Shows the stream, optionally cropped, with toggleable overlays drawn in screen pixels so lines and text stay readable at any zoom.

resizeEvent(self, a0: QResizeEvent | None, /)[source]
class rigconductor.gui.preview.PreviewPanel(url_provider, arenas_json=None, n_arenas=10, genotype_provider=None, padding=40, on_padding=None)[source]

Start/stop the stream, show it, overlay the rig’s arenas, test detection, and zoom the view to the arenas (‘Reduce view’). Nothing here touches the camera.

Parameters:
  • n_arenas (int)

  • padding (int)

showEvent(self, a0: QShowEvent | None, /)[source]
reduce_view(on=True)[source]

Crop the display to all arenas + padding (after a fresh detection).

Parameters:

on (bool)

Return type:

bool

find_arenas()[source]

Run ThermoKourt’s arena detector on the current frame; returns arenas found.

Return type:

int

Interactive arena circle editor.

class rigconductor.gui.arena_editor.ArenaCanvas(image, circles, offset=(0, 0))[source]

The frame with editable circles. Circles are kept in full camera px; the image may be a crop of the camera frame starting at offset.

Parameters:
hit(p)[source]

Arena under the screen point and whether it is the centre or the rim.

Parameters:

p (QPointF)

Return type:

tuple[int | None, str]

mousePressEvent(self, a0: QMouseEvent | None, /)[source]
mouseMoveEvent(self, a0: QMouseEvent | None, /)[source]
mouseReleaseEvent(self, a0: QMouseEvent | None, /)[source]
wheelEvent(self, a0: QWheelEvent | None, /)[source]
keyPressEvent(self, a0: QKeyEvent | None, /)[source]
paintEvent(self, a0: QPaintEvent | None, /)[source]
class rigconductor.gui.arena_editor.ArenaEditorDialog(image, circles, offset=(0, 0), n_expected=10, detect=None, parent=None)[source]

Edit a layout; circles() returns the result in full camera px.

Parameters:
  • image (QImage)

  • circles (list[Circle])

Drag-and-drop arena assignment straight from the DrosoDB snapshot.

Left: the vial shelf (active vials grouped by genotype, searchable, filtered by location; Sickbay hidden by default). Right: one card per arena with three slots (male 1, male 2, decapitated female). Drag vials onto slots; drop on a card’s title to fill its empty slots (a single vial fills both male slots); drop several selected vials to fill slots in order. Every genotype has its own colour.

rigconductor.gui.vialboard.genotype_colour(name)[source]

Stable, readable pastel per genotype.

Parameters:

name (str)

Return type:

QColor

class rigconductor.gui.vialboard.VialTree[source]
startDrag(self, supportedActions: Qt.DropAction, /)[source]
class rigconductor.gui.vialboard.VialShelf(catalogue)[source]
Parameters:

catalogue (list[dict])

class rigconductor.gui.vialboard.VialSlot(role, shelf)[source]
Parameters:
dragEnterEvent(self, a0: QDragEnterEvent | None, /)[source]
dropEvent(self, a0: QDropEvent | None, /)[source]
mouseDoubleClickEvent(self, a0: QMouseEvent | None, /)[source]
class rigconductor.gui.vialboard.ArenaCard(index, shelf)[source]
Parameters:
drop_codes(codes, n_roles=3)[source]

Fill empty slots in order; a single vial fills both male slots.

Parameters:
dragEnterEvent(self, a0: QDragEnterEvent | None, /)[source]
dropEvent(self, a0: QDropEvent | None, /)[source]
class rigconductor.gui.vialboard.VialBoard(catalogue, n_arenas=10)[source]

Shelf + ten arena cards. values(n_roles) returns the arenas dict the Drosophila profile expects.

Parameters:
fill_from_selection()[source]

Selected vials go round-robin into the male slots of the ticked arenas.

genotypes_by_arena()[source]

Distinct genotypes per ticked arena, in slot order (for the preview overlay).

Return type:

dict[int, list[str]]

Rig Relay: a small window for a networked PC that runs the cluster part of a session packed by an offline rig.

Load the .job.zip from the stick → Send to Aoraki and wait → Write results to the stick. Everything goes through rigconductor.relay.

class rigconductor.gui.relay.RelayWindow(cfg)[source]
Parameters:

cfg (ConductorConfig)

Graphical SLURM job monitor.

class rigconductor.gui.cluster_monitor.MonitorThread(fetch, interval_s=5)[source]

Polls fetch every interval_s and emits the task list (or an error).

Parameters:
run(self, /)[source]
class rigconductor.gui.cluster_monitor.TaskTile(label, task=0)[source]
Parameters:
mousePressEvent(self, a0: QMouseEvent | None, /)[source]
class rigconductor.gui.cluster_monitor.ClusterMonitor(ssh_host, ssh_cmd='ssh -o BatchMode=yes', label=<class 'str'>, fetch=None, queue=None)[source]
Parameters:
arena_clicked

One tile per arena plus a line per GPU worker. start(job_ids) begins polling; stop() ends it.

With a queue lookup (pose dir, trial, arena indices) the arenas come from the pull-queue files and the jobs are workers; without one, job_ids is a single array job whose task index is the arena.

Recording-duration field.

rigconductor.gui.duration.format_duration(seconds)[source]

1800 → "30 min", 90 → "1 min 30 s", 3725 → "1 h 2 min 5 s".

Parameters:

seconds (float)

Return type:

str

class rigconductor.gui.duration.DurationEdit(seconds=600)[source]

value() / setValue() in seconds, with the duration in words beside it.

Parameters:

seconds (int)

Per-profile metadata forms for the wizard’s Animals page.

class rigconductor.gui.forms.MetadataForm[source]

Base: values() returns the profile metadata dict; set_values restores it.

class rigconductor.gui.forms.DrosophilaForm(cfg, parent=None)[source]
Parameters:

cfg (ConductorConfig)

class rigconductor.gui.forms.TadpoleForm(cfg, parent=None)[source]
Parameters:

cfg (ConductorConfig)