Stimulus epoching and WAV alignment
StimulusEpochs divides each stimulus trial into non-overlapping, fixed-length
epochs and appends one or more WAV-derived stimulus features. The resulting
epochs can be used for TRFs and other analyses.
Use feature="envelope" for a single feature or
feature=["envelope", "mel_onsets"] to append several features.
All generated feature channels are automatically preserved by a later
SpatialFilter and returned alongside source estimates in
SourceReconstruction's extra_data dictionary. There is no need to repeat
their names in SpatialFilter.chans2keep; that list can specify additional
recording channels to retain.
resample_sfreq=200.0 resamples trial segments after alignment and physical-delay
correction, before computing features at 200 Hz; None retains the input rate.
Changing the sampling rate with a later Resample step emits a warning:
resampling appended features can distort binary (0/1) values, introducing
intermediate values or ringing. Use StimulusEpochs(resample_sfreq=...) to
compute features at the desired output rate instead.
StimulusSpanSpec describes the trial spans and audio files used for this workflow.
almkanal.almkanal_steps.stimulus_utils.StimulusEpochs
Bases: AlmKanalStep
Create fixed-length epochs within stimulus trials and attach WAV features.
Optionally correct the recording clock, apply a fixed neural timing shift,
then split trials into non-overlapping epochs with WAV features as misc
channels. Defaults below describe the general profile; omitted settings use
the active profile captured when the step is constructed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gen_span_spec
|
callable
|
Callback |
required |
base_audio_path
|
str | Path
|
Directory used to resolve relative WAV paths in the generated span spec. |
required |
resample_sfreq
|
float | None
|
Output sampling frequency in Hz. Resample continuous trial segments after alignment and physical-delay correction, before extracting and appending features. None retains the input rate. Uses FFT resampling with a boxcar window, automatic padding, and reflect_limited edge padding; MNE applies anti-aliasing internally. Trial spans always refer to input samples. |
None
|
feature
|
str | sequence of str
|
One or more distinct WAV features, appended in the requested order.
Single-channel features use the requested name; multichannel features
use that name as a prefix followed by component or band identifiers.
Names must not overlap existing recording channels. Available features:
|
'envelope'
|
audio_cutoff_hz
|
float
|
Low-pass cutoff in Hz for WAV features, capped below their Nyquist rate. |
80.0
|
hw_delay_s
|
float
|
Neural timing shift in seconds, applied after clock correction. Positive values advance neural events; negative values add lag and warn. |
0.0
|
epoch_len_s
|
float
|
Duration of each non-overlapping epoch in seconds. Must be positive; incomplete trailing epochs are discarded. |
5.0
|
audio_channels
|
sequence of str | None
|
Recorded audio channel names for estimating offset and drift.
|
None
|
alignment_kwargs
|
mapping | None
|
Overrides for |
None
|
preserve_annotations
|
bool
|
Keep annotations and reject epochs overlapping bad intervals.
|
True
|
on_alignment_error
|
('raise', 'skip')
|
Raise on alignment failure, or warn, record the failure, and skip the trial. Applies to measured and assumed alignment, not quality warnings. |
'raise'
|
verbose
|
bool
|
Emit processing messages. Quality warnings are shown regardless. |
True
|
realign_without_audio
|
bool
|
Resample using assumed drift and WAV duration when |
False
|
fallback_drift_us_per_s
|
float
|
Assumed drift in microseconds per second for |
0.0
|
must_be_before
|
tuple of str
|
Step class names that must follow this step if present in the pipeline. |
()
|
must_be_after
|
tuple of str
|
Step class names that must precede this step if present in the pipeline. |
()
|
Notes
- Recorded audio: takes precedence over assumed drift and needs sufficient
signal bandwidth. Failed fits follow
on_alignment_errorwithout falling back to assumed drift. For long stimuli, increasealignment_kwargs['max_lag_s']to cover offset plus accumulated drift; seeestimate_raw_wav_alignmentfor search limits and quality warnings. - Assumed drift: uses
t_raw = (1 + drift / 1e6) * t_wavrelative to trial onset. Positive drift lengthens raw time. The WAV determines trial duration; the end trigger does not determine drift. No offset is measured. - Physical delay: applied after clock correction, rounded to a sample. WAV features stay unchanged. Use zero if the audio reference already represents sound arrival at the ears. Alignment needs raw coverage for the full WAV plus delay margins; insufficient coverage is an alignment error.
- Salzburg defaults:
hw_delay_s=0.0165compensates the 16.5 ms air-tube delay when the reference precedes the tubes. The profile also setsaudio_channels=('MISC007', 'MISC008')andfallback_drift_us_per_s=499.0. Passaudio_channels=Noneexplicitly to use assumed drift with this profile.
See Also
StimulusSpanSpec : Trial spans, WAV paths, and optional metadata. build_stimulus_epochs : Standalone epoch builder using an existing span spec. estimate_raw_wav_alignment : Alignment options and fit diagnostics. prepare_audio : Available WAV features and their output channels.
reports(data, report, info)
Add stimulus epochs and any alignment diagnostics to the report.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
BaseEpochs
|
Epochs produced by this step. |
required |
report
|
Report
|
Report to update in place. |
required |
info
|
AlmKanalInfo
|
Pipeline history containing this step's |
required |
run(data, info)
Build stimulus epochs and collect processing diagnostics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
BaseRaw
|
Continuous recording passed to |
required |
info
|
AlmKanalInfo
|
Pipeline processing history; not used by this step. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
result |
dict
|
|
almkanal.almkanal_steps.stimulus_utils.StimulusSpanSpec
Describe trial spans, WAV files, and metadata for stimulus epoching.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spans_by_label
|
dict of str to tuple of (int, int | None)
|
Trial label to |
required |
metadata_by_label
|
dict of str to mapping
|
Extra epoch metadata per trial. Scalars are repeated; sequences with one value per retained epoch are assigned elementwise. Defaults to empty. |
required |
wav_by_label
|
mapping of str to str | pathlib.Path
|
WAV paths, absolute or relative to |
required |
Notes
Trials are processed in insertion order. Use distinct labels for repeated
presentations of the same WAV, or construct them with :meth:from_events.
build_stimulus_epochs can override the implicit WAV suffix via wav_ext.
from_events(raw, onset_trigger_to_wav, end_triggers=None, *, stim_channel=None, infer_missing_ends=False, base_audio_path=None, fallback_drift_us_per_s=DEFAULT_FALLBACK_DRIFT_US_PER_S)
classmethod
Build uniquely labelled stimulus trials from onset and end triggers.
Defaults below describe the general profile; omitted settings use the active defaults profile.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw
|
BaseRaw
|
Continuous recording containing the stimulus triggers. |
required |
onset_trigger_to_wav
|
mapping of int to str | pathlib.Path
|
Onset trigger codes mapped to WAV paths. Repeated codes create separate trials referencing the same WAV. |
required |
end_triggers
|
int | sequence of int | None
|
Codes that end a trial. |
None
|
stim_channel
|
str | None
|
Trigger channel name. |
None
|
infer_missing_ends
|
bool
|
Estimate missing endpoints from WAV duration and assumed drift. Recorded end triggers take precedence. |
False
|
base_audio_path
|
str | Path | None
|
WAV directory, required for relative paths when inferring ends. |
None
|
fallback_drift_us_per_s
|
float
|
Assumed drift in microseconds per second for end inference. Positive values lengthen the span; Salzburg defaults to +499. |
0.0
|
Returns:
| Name | Type | Description |
|---|---|---|
spec |
StimulusSpanSpec
|
Trials in trigger order, labelled |
Notes
End inference uses WAV duration * (1 + drift / 1e6) and leaves the
trigger channel unchanged. It only defines spans: to also resample
neural data without recorded audio, set realign_without_audio=True
on :class:EpochStimuls and use the same fallback_drift_us_per_s.
With recorded audio, EpochStimuls estimates the offset and drift instead.
See Also
find_audio_trials : Trigger pairing and missing-end handling.
labels()
Return trial labels in insertion order.
StimulusSpanSpec is a supporting data class, not an AlmKanalStep. See the WAV-alignment guide for workflow details.
almkanal.almkanal_steps.stimulus_utils.build_stimulus_epochs(raw, spec, base_audio_path, *, feature='envelope', resample_sfreq=None, audio_cutoff_hz=80.0, hw_delay_s=0.0, epoch_len_s=5.0, wav_ext='.wav', audio_channels=None, realign_without_audio=False, fallback_drift_us_per_s=DEFAULT_FALLBACK_DRIFT_US_PER_S, alignment_kwargs=None, preserve_annotations=True, on_alignment_error='raise', verbose=True)
Build fixed-length stimulus epochs with stimulus features from WAV files.
Defaults below describe the general profile; omitted configurable settings use the active defaults profile.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw
|
BaseRaw
|
Continuous recording to epoch. The input is not modified. |
required |
spec
|
StimulusSpanSpec
|
Trial spans, WAV paths, and optional per-trial metadata. |
required |
base_audio_path
|
str | Path
|
Directory used to resolve relative WAV paths in |
required |
resample_sfreq
|
float | None
|
Output sampling frequency in Hz. Resample continuous trial segments after alignment and physical-delay correction, before extracting and appending features. None retains the input rate. Uses FFT resampling with a boxcar window, automatic padding, and reflect_limited edge padding; MNE applies anti-aliasing internally. Trial spans always refer to input samples. |
None
|
feature
|
str | sequence of str
|
One or more distinct WAV features, appended in the requested order.
Single-channel features use the requested name; multichannel features
use that name as a prefix followed by component or band identifiers.
Names must not overlap existing recording channels. Available features:
|
'envelope'
|
audio_cutoff_hz
|
float
|
Low-pass cutoff in Hz for WAV features, capped below their Nyquist rate. |
80.0
|
hw_delay_s
|
float
|
Neural timing shift in seconds, applied after clock correction. Positive values advance neural events; negative values add lag and warn. |
0.0
|
epoch_len_s
|
float
|
Duration of each non-overlapping epoch in seconds. Must be positive; incomplete trailing epochs are discarded. |
5.0
|
wav_ext
|
str
|
Suffix used to turn labels without a |
'.wav'
|
audio_channels
|
sequence of str | None
|
Recorded audio channel names for estimating offset and drift.
|
None
|
realign_without_audio
|
bool
|
Resample using assumed drift and WAV duration when |
False
|
fallback_drift_us_per_s
|
float
|
Assumed drift in microseconds per second for |
0.0
|
alignment_kwargs
|
mapping | None
|
Overrides for |
None
|
preserve_annotations
|
bool
|
Keep annotations and reject epochs overlapping bad intervals.
|
True
|
on_alignment_error
|
('raise', 'skip')
|
Raise on alignment failure, or warn and skip the affected trial. Applies to measured and assumed alignment, not fit-quality warnings. |
'raise'
|
verbose
|
bool
|
Emit processing messages. Quality warnings are shown regardless. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
epochs |
Epochs
|
Concatenated epochs with the input channels, WAV features as |
Notes
Recorded audio takes precedence over assumed drift, including when a fit
fails. Clock correction precedes the sample-rounded hw_delay_s shift;
WAV features are not shifted. Alignment requires recording coverage for
the full WAV duration plus any physical-delay margins.
The Salzburg profile uses hw_delay_s=0.0165, audio_channels
('MISC007', 'MISC008'), and fallback_drift_us_per_s=499.0.
See :class:StimulusEpochs for delay conventions and assumed-drift behavior.
See Also
StimulusEpochs : Pipeline step with alignment diagnostics and reporting. estimate_raw_wav_alignment : Alignment options and search-range guidance. prepare_audio : Available WAV features and their output channels.