treble_tsdk.collections.scene_collection

Classes

RenderPathsEntry

Shape of one entry in the render_paths column, matching _render_paths_dtype.

RenderResultEntry

Shape of one entry in the renders column, matching render_result_struct.

SceneCollection

class treble_tsdk.collections.scene_collection.RenderPathsEntry

Shape of one entry in the render_paths column, matching _render_paths_dtype.

total=False because render_to_disk() builds this incrementally — clean_path/separated_tracks_paths/snr are only present when the corresponding option (target_selection/output_separated_tracks/ calculate_snr) was requested.

__init__(*args, **kwargs)
clean_path: str
noisy_path: str
normalization_coefficient: float
output_path: str
render_mode: str
sampling_rate: float
separated_tracks_paths: list[str]
snr: list[float]
target_render_mode: str
target_selection: str | None
class treble_tsdk.collections.scene_collection.RenderResultEntry

Shape of one entry in the renders column, matching render_result_struct.

__init__(*args, **kwargs)
clean: bytes | None
noisy: bytes
render_mode: str
sampling_rate: float
separated_tracks: list[bytes] | None
snr: list[float] | None
target_render_mode: str
target_selection: str | None
class treble_tsdk.collections.scene_collection.SceneCollection
__init__(client: TSDKClient | None = None, data_loader: IRDataLoader = None, description: str = '')

Create a collection of AudioScene objects that can be rendered together.

Parameters:
  • client – TSDKClient used to resolve simulations/devices and to drive remote optimization.

  • data_loader – IRDataLoader used to load and cache IR data.

  • description – Free-text description stored in the collection metadata.

add_column(name: str, mapper: Callable[[T], Any], dtype: polars.DataType | None = None)

Add a column to the collection using a mapper function.

Parameters:
  • name (str) – Name of the column.

  • mapper (Callable[[T], Any]) – Mapper function to get a value. Called for each row in the collection with the item (e.g. Simulation or IRInfo) as a parameter.

  • dtype (pl.DataType) – Data type of the column. If not provided the mapper function will be used to determine the data type.

add_scene(scene: AudioScene)

Append a scene to the collection.

Parameters:

scene – The AudioScene to add.

add_scenes(scenes: list[AudioScene])

Append multiple scenes to the collection in a single batch.

Prefer this over repeated add_scene() calls when adding many scenes (e.g. during generation).

Parameters:

scenes – The AudioScene objects to add.

apply(func: Callable[[polars.DataFrame], polars.DataFrame]) → _Self

Apply a DataFrame transformation and return a new collection of the same type.

The returned collection shares cached objects with the original but has an independent DataFrame. The transformation must preserve the required columns.

Parameters:

func (Callable[[pl.DataFrame], pl.DataFrame]) – A function that receives the underlying Polars DataFrame and returns a transformed DataFrame.

Returns:

A new collection of the same type with the transformed DataFrame.

Example:

filtered = coll.apply(lambda df: df.filter(pl.col("x") > 5).sort("y"))
as_remote_optimization_live_progress()

Display a live, auto-refreshing progress view for the remote optimization job.

cancel_remote_optimization()
copy_custom_columns(other_collection: CollectionBase, key_columns: list[str] | None = None, columns_to_copy: list[str] | None = None)
enrich_with_predicted_snr(target_selection: TargetSelection)

Predict the SNR of each scene for a given target and append the result as a new entry in the predicted_snr column.

Each struct in predicted_snr is keyed by target_selection and holds the predicted SNR (in dB) for that target. Calling this again with the same target_selection skips the matching entry; a different target_selection accumulates as an additional list entry.

SNR prediction requires the IRs to carry per-band spl values (added via IRCollection.enrich_with_acoustic_parameters()) and the audio sources to carry SPL metadata (added via AudioDataset.enrich_with_spl()).

Parameters:

target_selection – The target track(s), as a TargetSelection or any raw value it accepts.

filter_by_predicted_snr(min_db: float | None = None, max_db: float | None = None, target_selection: TargetSelection | None = None) → SceneCollection

Return a new collection keeping only scenes whose predicted SNR falls within [min_db, max_db].

Parameters:
  • min_db – Lower bound on predicted SNR in dB. If None, no lower bound is applied.

  • max_db – Upper bound on predicted SNR in dB. If None, no upper bound is applied.

  • target_selection – The target used during enrich_with_predicted_snr(). Required when scenes carry more than one predicted-SNR entry; may be omitted when each scene has a single entry, in which case that entry is used.

Returns:

A new SceneCollection with the matching scenes.

filter_collection(*args, **kwargs) → _Self

Filter the collection and return a new collection with matching rows.

Accepts the same arguments as polars.DataFrame.filter().

Returns:

A new collection of the same type containing only the matching rows.

Example:

nearby = coll.filter_collection(pl.col("source_receiver_dist") < 5.0)
get_predicted_snr(scene_id: str, target_selection: TargetSelection | None = None) → float | None

Retrieve a predicted SNR value for the scene with id scene_id.

When the scene has only one predicted-SNR entry, target_selection may be omitted. When multiple entries exist, supply target_selection to select the matching one.

Parameters:
  • scene_id – The id of the scene in the collection.

  • target_selection – The target selection used during enrich_with_predicted_snr(). Required when the scene has more than one predicted-SNR entry.

Returns:

The predicted SNR in dB, or None when it could not be estimated.

get_remote_optimization_progress() → OneOffTaskBundleProgress | None

Fetch a point-in-time progress snapshot for the remote optimization job.

Returns:

The OneOffTaskBundleProgress, or None when no eligible remote render has been started.

get_remote_optimization_token_cost() → Decimal

Estimate the token cost of running the remote optimization for this collection.

get_render(scene_id: str, sampling_rate: float | None = None, render_mode: RenderMode | None = None, target_selection: TargetSelection | None = None, target_render_mode: TargetRenderMode | WetMonoWindowed | WetDeviceWindowed | None = None) → dict

Retrieve a rendered audio entry for the scene with id scene_id.

When the scene has only one render entry, no recipe arguments are needed. When multiple entries exist, narrow the result by supplying one or more recipe arguments.

Parameters:
  • scene_id – The id of the scene in the collection.

  • sampling_rate – Filter by output sampling rate in Hz.

  • render_mode – Filter by render mode.

  • target_selection – Filter by target selection. Required when the scene has more than one render entry.

  • target_render_mode – Filter by target render mode.

Returns:

A dict with keys noisy (AudioSignal), clean (AudioSignal or None), separated_tracks (list of AudioSignal or None), and snr (float or None).

get_renders_from_disk(scene_id: str, output_path: str | Path | None = None) → dict

Retrieve a render_to_disk() result for the scene with id scene_id, loaded back from disk as audio tracks.

Each output_path holds at most one render_paths entry (see render_to_disk()), so output_path alone always disambiguates. When the scene has only one render_paths entry, output_path may be omitted.

Parameters:
  • scene_id – The id of the scene in the collection.

  • output_path – The output_path used in the render_to_disk() call. Required when the scene has more than one render_paths entry.

Returns:

A dict with keys noisy (ConvolvedAudioSignal), clean (ConvolvedAudioSignal or None), separated_tracks (list of ConvolvedAudioSignal or None), and snr (list of float or None), read back from the .wav files on disk and un-normalized using the entry’s normalization_coefficient.

head(n: int = 5) → _Self

Return a new collection with the first n rows.

Parameters:

n (int) – Number of rows, defaults to 5.

Returns:

A new collection of the same type.

plot()

Plot the collection using an interactive widget.

Extends CollectionBase.plot() so the SNR columns become plottable:

  • predicted_snr — one numeric column per distinct target_selection (e.g. predicted_snr ["target"]).

  • renders — one per-channel snr column per distinct render recipe (e.g. renders snr [mono, 0, wet_mono]).

  • render_paths — one per-channel snr column per distinct render recipe across every render_to_disk() call (e.g. SNR [mono, 0, wet_mono]), regardless of how many different output_path values were used. If renders already has a column for that same recipe (from a matching render() call), render_paths reuses it instead of adding a duplicate.

preload_rendered_irs()

Preload the rendered IR data into the data loader.

print_remote_optimization_token_cost()

Print the token cost of running the remote optimization for this collection.

remove_column(name: str)

Remove a column from the collection.

render(sampling_rate: float = 32000, render_mode: RenderMode = RenderMode.AUTO, target_selection: TargetSelection | None = None, target_render_mode: TargetRenderMode | WetMonoWindowed | WetDeviceWindowed = TargetRenderMode.WET_MONO, calculate_snr: bool = False, output_separated_tracks: bool = False, show_progress: bool = True, minutes_to_wait: int = 720, max_workers: int | None = None)

Render the Scene Collection, adding an entry with the audio (and optional separated_tracks/snr) to the renders column.

Entries are keyed by sampling_rate, render_mode, target_selection and target_render_mode. Re-rendering with the same key updates that entry (e.g. to add snr), or skips it if nothing new is requested.

Scenes with a target SNR (see SceneRules.target_snr) are rendered at that SNR when target_selection is set, by splitting the missing dB equally between target and noise.

Starts and waits for remote optimization first, if needed.

Parameters:
  • sampling_rate – Output sampling rate in Hz.

  • render_mode – Rendering mode for the mixed audio.

  • target_selection – The track(s) to isolate as the clean target, as a TargetSelection or any raw value it accepts. If None, no target/clean output is produced.

  • target_render_mode – How the isolated target is rendered; also used to measure the SNR for a target SNR.

  • calculate_snr – If True, compute the per-device channel SNR between the rendered target and the noise.

  • output_separated_tracks – If True, also store each separated track.

  • show_progress – If True, show progress bars/live views during remote rendering and scene rendering.

  • minutes_to_wait – Number of minutes to wait for remote optimization to finish. By default this allows for up to 12 hours of waiting before giving up.

  • max_workers – Number of scenes to render concurrently, using a thread pool. Defaults to os.cpu_count().

render_to_disk(output_path: str | Path, sampling_rate: float = 32000, render_mode: RenderMode = RenderMode.AUTO, target_selection: TargetSelection | None = None, target_render_mode: TargetRenderMode | WetMonoWindowed | WetDeviceWindowed = TargetRenderMode.WET_MONO, calculate_snr: bool = False, output_separated_tracks: bool = False, collate_fn: Callable[..., None] | None = None, collate_fn_kwargs: dict = {}, show_progress: bool = True, minutes_to_wait: int = 720, max_workers: int | None = None)

Render the Scene Collection to .wav files, adding an entry with the file paths to the render_paths column.

Files are written as {scene.id}.wav under output_path/noisy, clean and separated (suffixed with the track index). Noisy and clean audio of a scene are normalized together by their shared peak.

Entries are keyed by output_path alone: rendering to the same output_path again overwrites its entry and files, even with different settings.

Scenes with a target SNR (see SceneRules.target_snr) are rendered at that SNR when target_selection is set, by splitting the missing dB equally between target and noise.

Starts and waits for remote optimization first, if needed.

Parameters:
  • output_path – Directory under which noisy/clean/separated subdirectories are created and populated with .wav files. Also part of the identity of the render_paths entry — reusing the same output_path overwrites the matching entry and its files.

  • sampling_rate – Output sampling rate in Hz.

  • render_mode – Rendering mode for the mixed audio.

  • target_selection – The track(s) to isolate as the clean target, as a TargetSelection or any raw value it accepts. If None, no target/clean output is produced.

  • target_render_mode – How the isolated target is rendered; also used to measure the SNR for a target SNR.

  • calculate_snr – If True, compute the per-device channel SNR between the rendered target and the noise.

  • output_separated_tracks – If True, also write each separated track to disk.

  • collate_fn – Optional callable invoked once per scene, after that scene’s audio has been written to disk. Called as collate_fn(row, output_path, entry, scene, **collate_fn_kwargs), where row is the scene’s dataframe row, output_path is the render output directory, entry is the render metadata computed for this scene (e.g. normalization_coefficient, noisy_path, clean_path, snr), and scene is the rendered AudioScene itself. Use this to write out anything else derived from the collection, such as transcripts, alongside the rendered audio.

  • collate_fn_kwargs – Optional dict of extra keyword arguments forwarded to every collate_fn call, for passing in custom context (e.g. a model, config, or logger) that isn’t derivable from the row/entry/scene alone.

  • show_progress – If True, show progress bars/live views during remote rendering and scene rendering.

  • minutes_to_wait – Number of minutes to wait for remote optimization to finish. By default this allows for up to 12 hours of waiting before giving up.

  • max_workers – Number of scenes to render concurrently, using a thread pool. Defaults to os.cpu_count(). collate_fn is always called sequentially, once per scene in completion order, on the main thread.

Usage:

def write_transcripts_and_store_irs(row, output_path, entry, scene):
    path = output_path / "transcripts" / f"{row['id']}.txt"
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(str(row["track_transcripts"]))

scene_collection.render_to_disk(
    output_path = "rendered_scenes",
    sampling_rate = 32000,
    render_mode = treble.scene.RenderMode.DEVICE,
    target_selection = treble.scene.TargetSelection.group("speech"),
    target_render_mode = treble.scene.TargetRenderMode.DRY_MONO,
    collate_fn=write_transcripts
)
sample_with_distribution(column: str, n_samples: int, distribution: Gaussian | Uniform | LogNormal | Exponential | Bimodal | Beta | ScaledBeta) → _Self

Sample rows where the specified column follows a target distribution.

Returns a new collection of the same type containing only the sampled rows.

Parameters:
  • column (str) – The column to sample from.

  • n_samples (int) – The number of rows to sample.

  • distribution (Distribution) – Distribution to sample from.

Returns:

A new collection containing the sampled rows.

sample_with_gaussian_distribution(column: str, n_samples: int, target_mean: float, target_std: float, seed: int = 42)

Sample rows where the specified column follows a target Gaussian distribution.

This is a convenience wrapper around sample_with_distribution.

Parameters:
  • column (str) – The column to sample from.

  • n_samples (int) – The number of rows to sample.

  • target_mean (float) – The target mean for the distribution.

  • target_std (float) – The target standard deviation for the distribution.

  • seed (int) – The random seed for reproducibility.

start_remote_optimization(show_progress: bool = True)

Start the remote optimization for this scene collection.

Parameters:

show_progress – If True, display a live progress view for the processing tasks.

swap_device(device: DeviceObj | None, orientation: Rotation | OrientationRange | None = None, device_specs: DeviceSpecs | None = None) → SceneCollection

Generate a copy of this collection that uses another listener device.

The scenes are generated again with the new device, because a device with a different number of microphones consumes a different number of random draws.

For that same reason the result is not this collection with its device replaced: its scenes are new, and their composition can differ. The two collections share the generation settings and the seed, not the scenes themselves. A device with the same number of microphones leaves the draws untouched, so in that case only the device changes.

Parameters:
  • device – The device the listener should use, or None to render the listener in mono.

  • orientation – The listener orientation. The orientation of the original generation is kept when None.

  • device_specs – The microphone noise/filter specs. The specs of the original generation are kept when None.

Returns:

A new SceneCollection generated with the new device.

tail(n: int = 5) → _Self

Return a new collection with the last n rows.

Parameters:

n (int) – Number of rows, defaults to 5.

Returns:

A new collection of the same type.

wait_for_remote_optimization_processing(minutes_to_wait: int = 720) → str | None

Waits until the remote optimization has been completed and then returns the status.

Parameters:

minutes_to_wait – Number of minutes to wait before stopping, defaults to 720 minutes (12 hours).

Returns:

The status of the remote optimization.

with_column(name: str, mapper: Callable[[T], Any], dtype: polars.DataType | None = None) → _Self

Return a copy of the collection with a column added. The current collection is not modified.

See add_column() for parameter details.

Returns:

A new collection with the column added.

write_parquet(path: str | Path, **kwargs)

Write the dataframe to a parquet file.

Parameters:
  • path (str | Path) – Path to the parquet file.

  • kwargs – Additional keyword arguments passed to polars.DataFrame.write_parquet.

property columns: list[str]

List of columns in the DataFrame

property compact_columns: dict[str, int]

Columns to truncate when printing, mapped to their max display length in characters.

property dataframe: polars.DataFrame

Get the collection data as a Polars DataFrame.

Returns pl.DataFrame:

DataFrame containing all collection items and computed columns.

property editable_dataframe: polars.DataFrame

DataFrame with only the user-modifiable (non-locked) columns. The key column is always included in the editable dataframe although it is locked.

property generation_settings: SceneGenerationSettings | None

The settings this collection was generated with, or None when it was not generated.

property lazy_df: polars.LazyFrame

Lazy access to underlying Polars DataFrame

property locked_columns: list[str]

List of locked columns for the collection. Columns in this list are read-only and cannot be modified by the user.

property remote_optimization_status: SolveTaskStatus | None

Return the aggregate status of the remote optimization job.

Returns:

The SolveTaskStatus, or None when no eligible remote render has been started.

property required_columns: list[str]

List of required columns for the collection.

property scenes: list[AudioScene]

The scenes held by this collection, reconstructed from the dataframe.

Returns:

A list of AudioScene, empty when the collection holds no scenes.