Skip to content

Defaults for your lab or study

AlmKanal lets you choose shared defaults for your whole lab or for a particular study. Values you supply in individual function calls still take precedence.

Use a lab profile

To use the built-in Salzburg settings, add this near the beginning of your script:

import almkanal as ak

ak.set_defaults("salzburg")

Then build your pipeline as usual:

pipeline = ak.AlmKanal(
    steps=[
        ak.Filter(),
        ak.Resample(sfreq=200),
    ]
)

The steps use the selected defaults for any optional arguments you leave out. Once you have loaded your MNE recording as raw, run the pipeline with processed_raw, report = pipeline.run(raw).

If you do not select a profile, AlmKanal uses general defaults automatically. Calling ak.set_defaults() resets the active settings to those general defaults.

Adjust settings for a study

You can start from a lab profile and change just the settings needed for a study:

ak.set_defaults("salzburg", filter={"lowpass": 30.0})

step = ak.Filter()              # Uses the study's 30 Hz low-pass setting.
custom = ak.Filter(lowpass=20)  # Uses 20 Hz for this step only.

Options are grouped into sections such as filter, ica, stimuli, and vpixx. Unspecified options retain their values from the selected profile. The complete list of sections, types, and general defaults is at the end of this guide.

Create and save your own lab profile

Another lab can define a reusable profile using Defaults.generic() as a starting point. Save the following in a file called lab_defaults.py, alongside your analysis scripts:

# lab_defaults.py
from almkanal import Defaults

LAB_DEFAULTS = Defaults.generic().with_overrides(
    name="our-lab",
    version="1",
    filter={"highpass": 0.5, "lowpass": 40.0},
    events={"stim_channel": "TRIGGER"},
)

Replace these example values with your lab's settings. with_overrides() creates a new profile and leaves the original unchanged. Defining a profile does not activate it.

Load and use the saved profile

Import the profile in any analysis script and activate it with set_defaults():

import almkanal as ak
from lab_defaults import LAB_DEFAULTS

ak.set_defaults(LAB_DEFAULTS)

pipeline = ak.AlmKanal(
    steps=[
        ak.Filter(),
        ak.Resample(sfreq=200),
    ]
)

Importing lab_defaults.py recreates the profile from the saved values. To share it across projects, put the module in a shared Python package that your scripts can import. Keeping this file under version control also records changes to your lab's settings. Update its version when changing an agreed configuration.

The profile's name is a label for processing records; it does not register a new string shortcut. Use ak.set_defaults(LAB_DEFAULTS) to load your own profile. The built-in string shortcuts are "generic" and "salzburg".

Profiles are saved here as ordinary Python files. Built-in loaders for JSON, YAML, or TOML profile files are not currently available.

Derive a study profile from your lab profile

A study can reuse the lab settings while overriding a few values:

# study_defaults.py
from lab_defaults import LAB_DEFAULTS

STUDY_DEFAULTS = LAB_DEFAULTS.with_overrides(
    name="auditory-study",
    version="1",
    filter={"lowpass": 30.0},
)

The lab profile stays unchanged. Save this definition in study_defaults.py, then load it in your analysis script:

import almkanal as ak
from study_defaults import STUDY_DEFAULTS

ak.set_defaults(STUDY_DEFAULTS)

General and Salzburg settings

The Salzburg profile starts from the general defaults and changes these values:

Setting General profile Salzburg profile
ica.train False True
stimuli.hw_delay_s 0.0 seconds 0.0165 seconds
stimuli.fallback_drift_us_per_s 0.0 µs/s 499.0 µs/s
stimuli.audio_channels None ("MISC007", "MISC008")
vpixx.meg_stim_channel None (MNE detection) "STI101"
vpixx.meg_min_duration 0.0 seconds 0.002 seconds
vpixx.meg_max_trigger None (keep all codes) 4096 (exclude this code and above)
vpixx.screen_distance Must be configured for radians 0.82 m
vpixx.screen_size Must be configured for radians (0.61, 0.34) m
vpixx.screen_resolution Must be configured for radians (1920, 1080) pixels
ica_eog.left_eog_chs Must be configured when using the helper ["MEG0121", "MEG0311"]
ica_eog.right_eog_chs Must be configured when using the helper ["MEG1211", "MEG1411"]

For another setup, supply its measured geometry, timing values, and channel names. Selecting a profile does not check whether its hardware settings match your recording.

Salzburg's audio channels enable recorded-audio alignment during stimulus processing. If a recording has no audio channels, use ak.set_defaults("salzburg", stimuli={"audio_channels": None}) or pass audio_channels=None to the individual EpochStimuls step.

When settings take effect

Set defaults before constructing your steps. Existing steps keep the values and profile they captured when they were created:

ak.set_defaults("generic", filter={"lowpass": 30.0})
first = ak.Filter()

ak.set_defaults("generic", filter={"lowpass": 40.0})
second = ak.Filter()

print(first.lowpass)   # 30.0
print(second.lowpass)  # 40.0

Built-in steps also run their internal helpers and callbacks under their captured profile. Standalone functions resolve omitted arguments when called.

Explicit arguments always win, including None, False, and 0 where those values are supported:

ak.set_defaults("salzburg")

unfiltered_lowpass = ak.Filter(lowpass=None)
without_train_removal = ak.ICA(train=False)

Required inputs remain required. For example, Resample still needs sfreq, ForwardModel needs subject_id and subjects_dir, and EpochStimuls needs its span callback and audio path. Profiles do not replace the pipeline's step ordering requirements.

Repeated calls and validation

Each set_defaults() call starts from the selected profile, which is "generic" when omitted. It does not accumulate earlier customizations. To extend your active settings explicitly, pass get_defaults():

ak.set_defaults("salzburg", filter={"lowpass": 30.0})
ak.set_defaults(ak.get_defaults(), ica={"random_state": 123})

This keeps the 30 Hz low-pass setting and changes the ICA random seed. set_defaults() returns the activated profile if you want to keep it in a variable.

Unknown sections or options and incompatible value types raise an error before the active defaults change. Processing functions still check scientific constraints, such as whether a cutoff suits the recording's sampling rate.

A dictionary supplied as an option replaces that whole option; dictionaries are not recursively merged. For example, supply a complete IIR configuration:

ak.set_defaults(
    LAB_DEFAULTS,
    filter={"method": "iir", "iir_params": {"order": 4, "ftype": "butter"}},
)

The lower-level configure(profile) activates an already-built Defaults object. For most scripts, set_defaults() is sufficient.

VPixx eye tracking

VPixxCleaner and the standalone eye-tracking helpers share the vpixx section. Sampling rate comes from the recording's timestamps. Screen size and viewing distance are in metres; resolution is in pixels:

ak.set_defaults(
    LAB_DEFAULTS,
    vpixx={
        "screen_resolution": (1920, 1080),
        "screen_size": (0.53, 0.30),
        "screen_distance": 0.65,
        "meg_stim_channel": "TRIGGER",
    },
)

step = ak.VPixxCleaner(eye_path="eye.mat", interpolate_blinks=False)

Replace the example geometry with your equipment's values. The general profile requires these three geometry settings for conversion to radians. Pixel-only processing with convert_to_radians=False does not require geometry.

eye_path remains required. Set concatenate_raws=True to combine a list of recording blocks after cleaning; a single recording returns a single Raw object. The align option controls only the standalone add_eye_tracking_data() helper; VPixxCleaner always aligns eye tracking to its input recordings.

VPixxConfig() captures its omitted values at construction. The standalone load_eyetracking_data(), add_eye_tracking_data(), and align_eye_to_meg() resolve omitted options at call time. An omitted or None config builds a fresh VPixxConfig from the active profile. An explicit config supplies its own geometry and calibration settings; other loading and alignment arguments still use the active profile unless explicitly supplied.

vpixx.blink_buffer_vpixx supplies VPixxConfig.blink_buffer. vpixx.blink_buffer overrides that buffer during loading; None uses the config's buffer and (0.0, 0.0) uses no padding. Explicit None also overrides a profile's non-None loading buffer.

meg_max_trigger=None retains all trigger codes. meg_stim_channel=None uses MNE's stimulus-channel detection.

Temporary settings

For a temporary comparison, use_defaults() accepts the same profile and section overrides as set_defaults():

ak.set_defaults("salzburg")

with ak.use_defaults("generic", filter={"lowpass": 25.0}):
    comparison_filter = ak.Filter()

# Salzburg is active again; comparison_filter keeps its 25 Hz setting.

Blocks can be nested. The previous profile is restored even if an exception leaves the block. Steps created inside can be run afterward.

Inspect and record settings

profile = ak.get_defaults()

print(profile.name)
print(profile.filter.lowpass)
filter_settings = profile.section("filter")
all_settings = profile.to_dict()

Profiles protect their values from accidental changes. Section objects and returned dictionaries are independent copies; editing them does not change the active profile. Use with_overrides() or set_defaults() to customize it.

After a pipeline runs, each built-in step records its profile name, version, and resolved configurable parameters, including explicit overrides. Save the processing history with:

pipeline.generate_json("preprocessing.json")

The JSON contains an ordered processing_history list, with separate settings for each occurrence of a step. It is a processing record, not a loadable lab profile. Keep your profile's Python file alongside the analysis, particularly when callbacks also use helper defaults.

Concurrent execution

Active settings are local to the current execution context. Async tasks inherit the context in which they are created; later changes remain local to each task. Configure worker threads and processes explicitly, or pass an appropriate context or already-constructed steps. Setting a profile in one process does not configure every worker.

Complete settings reference

Use these section names as keyword arguments to set_defaults(), use_defaults(), or with_overrides(). Every configurable option is listed below with its accepted type and general-profile default. The Salzburg differences are listed earlier in this guide.

None is an explicit value, not an instruction to fall back to another profile. Literal[...] lists allowed choices; Sequence accepts lists or tuples and Mapping accepts dictionaries. Any means that the profile does not restrict the value's type; the processing function determines which inputs it supports.

Related helpers share settings where appropriate. Trial span inference uses stimuli.fallback_drift_us_per_s, and find_train_ica uses ica.train_thresh for its peak_threshold argument. An explicit EpochStimuls(fallback_drift_us_per_s=...) also supplies the default inside its span callback; an explicit callback argument still takes precedence.

filter

Used by Filter.

Option Type General default
highpass float | None 0.1
lowpass float | None 40.0
picks Any None
filter_length str | int 'auto'
l_trans_bandwidth float | Literal['auto'] 'auto'
h_trans_bandwidth float | Literal['auto'] 'auto'
n_jobs int | str | None None
method str 'fir'
iir_params dict[str, Any] | None None
phase str 'zero'
fir_window str 'hamming'
fir_design str 'firwin'
skip_by_annotation str | tuple[str, ...] | list[str] ('edge', 'bad_acq_skip')
pad str 'reflect_limited'

resample

Used by Resample (the target sfreq is required separately).

Option Type General default
npad str 'auto'
window str | tuple[str, float] 'auto'
n_jobs int | None None
pad str 'auto'
method Literal['fft', 'polyphase'] 'fft'

ica

Used by ICA and run_ica.

Option Type General default
fit_only bool False
n_components None | int | float None
method str 'picard'
random_state None | int 42
fit_params dict | None None
ica_hp_freq None | float 1.0
ica_lp_freq None | float None
resample_freq int | None 200
eog bool True
surrogate_eog_chs None | dict None
eog_corr_thresh float 0.5
ecg bool True
ecg_corr_thresh float 0.5
emg bool False
emg_thresh float 0.5
train bool False
train_freq float 16.666
train_thresh float 6.0
img_path None | str None
fname None | str None

events

Used by Events and trigger selection in trial helpers.

Option Type General default
stim_channel str | list[str] | None None
output str 'onset'
consecutive bool | str 'increasing'
min_duration float 0.0
shortest_event int 2
mask int | None None
uint_cast bool False
mask_type str 'and'
initial_event bool False
verbose bool | str | int | None None

physio

Used by PhysioCleaner and run_bio_preproc.

Option Type General default
ecg None | str | list None
resp None | str | list None
eog None | str | list None
emg None | str | list None

maxwell

Used by Maxwell, MultiBlockMaxwell, and run_maxwell.

Option Type General default
mw_coord_frame str 'head'
mw_destination Any None
mw_calibration_file str | bool | None None
mw_cross_talk_file str | bool | None None
mw_st_duration float | None None
mw_st_correlation float 0.98

ransac

Used by EEGRANSAC.

Option Type General default
ransac_epoch_duration int | float 4
n_resample int 50
min_channels float 0.25
min_corr float 0.75
unbroken_time float 0.4
n_jobs int 1
verbose bool False
random_state int | None 435656

rereference

Used by ReReference.

Option Type General default
ref_channels str | list[str] | dict 'average'
projection bool False
ch_type str | list[str] 'auto'
forward Any None
joint bool False
verbose bool | str | int | None False

epochs

Used by Epochs.

Option Type General default
tmin float -0.15
tmax float 0.5
events Any None
event_id None | dict None
baseline None | tuple None
preload bool True
picks Any None
reject dict | None None
flat dict | None None
proj bool | str True
reject_tmin float | None None
reject_tmax float | None None
detrend int | None None
on_missing str 'raise'
reject_by_annotation bool True
metadata Any None
event_repeated str 'error'
verbose bool | str | int | None None

forward_model

Used by ForwardModel and optional arguments of make_fwd.

Option Type General default
pick_dict dict | None None
source str 'surface'
redo_hdm bool True
spacing str 'oct6'
source_ico int 4
bem_conductivity float | Sequence[float] (0.3,)
volume_pos float 5.0
use_template_mri bool True
min_dist_src float 5.0
meg bool True
eeg bool False
redo_bem bool False

spatial_filter

Used by SpatialFilter and optional arguments of comp_spatial_filters.

Option Type General default
fwd Any None
pick_dict dict | None None
data_cov Any None
noise_cov Any None
empty_room Any None
nearest_empty_room bool False
chans2keep list[str] | None None
lcmv_reg float 0.05
lcmv_pick_ori str | None 'max-power'
lcmv_weight_norm str | None 'nai'
lcmv_reduce_rank bool False

source_reconstruction

Used by SourceReconstruction and parcellation helpers.

Option Type General default
filters Any None
return_parc bool False
label_mode str 'pca_flip'
atlas str 'glasser'
morph2fsaverage bool True

stimuli

Used by EpochStimuls, build_stimulus_epochs, and fallback drift in trial helpers. Configure these settings through Defaults.stimuli and with_overrides(stimuli={...}).

Option Type General default
feature str | Sequence[str] 'envelope'
resample_sfreq float | None None
audio_cutoff_hz float 80.0
hw_delay_s float 0.0
epoch_len_s float 5.0
audio_channels Sequence[str] | None None
alignment_kwargs Mapping[str, Any] | None None
preserve_annotations bool True
on_alignment_error Literal['raise', 'skip'] 'raise'
verbose bool True
realign_without_audio bool False
fallback_drift_us_per_s float 0.0

pipeline

Used by AlmKanal.

Option Type General default
pick_params dict | None None

vpixx

Used by VPixxCleaner, VPixxConfig, and eye loading/alignment helpers.

Option Type General default
screen_resolution tuple[int, int] | None None
screen_size tuple[float, float] | None None
screen_distance float | None None
calibration_model str 'HV5'
calibration_eye Literal['left', 'right'] 'right'
blink_buffer_vpixx tuple[float, float] (0.05, 0.2)
digital_output_threshold float 256.0
missing_value float 9999.0
interpolate_blinks bool True
blink_buffer tuple[float, float] | None None
convert_to_radians bool True
include_raw_vpixx_channels bool False
meg_stim_channel str | None None
eye_stim_channel str 'Digital Output'
meg_min_duration float 0.0
meg_max_trigger int | None None
concatenate_raws bool False
align bool True

ica_eog

Used by eog_ica_from_meg.

Option Type General default
left_eog_chs list[str] | None None
right_eog_chs list[str] | None None
threshold float 0.5
tol float 0.2

ica_train

Used by find_train_ica.

Option Type General default
duration int 8
overlap float 0.5
hmax float 2.0

trials

Used by find_audio_trials and StimulusSpanSpec.from_events.

Option Type General default
end_triggers int | Sequence[int] | None None
infer_missing_ends bool False
base_audio_path Any None

alignment

Used by estimate_raw_wav_alignment.

Option Type General default
sync_sfreq float 500.0
audio_band tuple[float, float] (80.0, 400.0)
envelope_lowpass float 30.0
window_s float 10.0
step_s float 5.0
max_lag_s float 0.25
min_corr float 0.3
min_anchors int 5
reject_outliers bool True
warn_residual_rms_ms float 10.0
verbose bool True

audio

Used by prepare_audio.

Option Type General default
feature str | Sequence[str] 'envelope'
resample_sfreq float | None None
target_fs float 100.0
cutoff_hz float 80.0
n_mels int 32
fmin float 50.0
fmax float 8000.0