utils
tit.sim.utils ¶
Shared utilities for TI/mTI simulations.
This module provides all non-class helpers consumed by the simulation package:
- Montage file I/O -- CRUD operations on
montage_list.json. - Montage loading -- resolve EEG-cap and flex/freehand montages.
- Directory setup -- create the BIDS output directory tree.
- Montage visualisation -- render 2-D montage diagrams.
- Post-processing helpers -- field extraction, NIfTI conversion, T1-to-MNI transform, file moves.
- Simulation orchestration -- sequential montage execution.
Public API¶
run_simulation
Execute simulations for every montage in a configuration.
load_montages
Load named montages from montage_list.json.
list_montage_names
List montage names defined under an EEG net.
load_montage_data
Load the full montage_list.json as a dict.
save_montage_data
Write a montage dict to montage_list.json.
ensure_montage_file
Return (and optionally create) the montage_list.json path.
upsert_montage
Insert or update a montage definition.
See Also¶
tit.sim.config : Dataclasses consumed by the functions here. tit.sim.base : Base class that calls directory-setup and viz helpers. tit.sim.TI : 2-pair TI post-processing that uses extract/transform helpers. tit.sim.mTI : N-pair mTI post-processing that uses extract/transform helpers.
ensure_montage_file ¶
ensure_montage_file() -> str
Return the path to montage_list.json, creating it if absent.
If the file does not exist, creates it with the default schema
{"nets": {}}.
Returns¶
str
Absolute path to the montage_list.json file.
See Also¶
load_montage_data : Read the file returned by this function. save_montage_data : Write data to the file returned by this function.
Source code in tit/sim/utils.py
load_montage_data ¶
load_montage_data() -> dict
Load the full montage_list.json as a dict.
Returns¶
dict
Parsed JSON with top-level key "nets" mapping EEG net
names to their uni/multi polar montage definitions.
See Also¶
save_montage_data : Write the dict back to disk. ensure_montage_file : Guarantees the file exists before reading.
Source code in tit/sim/utils.py
save_montage_data ¶
save_montage_data(data: dict) -> None
Write data to montage_list.json, overwriting the file.
Parameters¶
data : dict
Full montage dict (must contain a "nets" key).
See Also¶
load_montage_data : Read the data back after saving.
Source code in tit/sim/utils.py
ensure_eeg_net_entry ¶
ensure_eeg_net_entry(eeg_net: str) -> None
Ensure an entry for eeg_net exists in montage_list.json.
If the net is not yet present, creates it with empty
uni_polar_montages and multi_polar_montages dicts.
Parameters¶
eeg_net : str
EEG net identifier (e.g. "GSN-HydroCel-185.csv").
See Also¶
upsert_montage : Add a specific montage under an EEG net.
Source code in tit/sim/utils.py
upsert_montage ¶
upsert_montage(*, eeg_net: str, montage_name: str, electrode_pairs: list[list[str]], mode: str) -> None
Insert or update a montage definition in montage_list.json.
Creates the EEG net entry if it does not already exist.
Parameters¶
eeg_net : str
EEG net identifier (e.g. "GSN-HydroCel-185.csv").
montage_name : str
Human-readable montage name.
electrode_pairs : list[list[str]]
List of electrode pairs, each a two-element list of electrode
labels (e.g. [["E1", "E2"], ["E3", "E4"]]).
mode : str
"U" for uni-polar montages (2-pair TI) or "M" for
multi-polar montages (4-pair mTI).
See Also¶
list_montage_names : List montage names after upserting.
load_montages : Load upserted montages as Montage objects.
Source code in tit/sim/utils.py
list_montage_names ¶
List all montage names defined under an EEG net.
Parameters¶
eeg_net : str
EEG net identifier (e.g. "GSN-HydroCel-185.csv").
mode : str
"U" for uni-polar montage names or "M" for
multi-polar montage names.
Returns¶
list[str] Sorted montage names. Returns an empty list if the net or mode key does not exist.
See Also¶
upsert_montage : Add montage names to the list.
load_montages : Load the named montages as Montage objects.
Source code in tit/sim/utils.py
load_flex_montages ¶
Load flex/freehand montage definitions from a JSON file.
Parameters¶
flex_file : str or None, optional
Path to the flex montages JSON file. Falls back to the
FLEX_MONTAGES_FILE environment variable if not provided.
Returns¶
list[dict] List of raw flex montage dicts. Returns an empty list if no file is found.
See Also¶
parse_flex_montage : Convert each returned dict into a Montage.
load_montages : Calls this function when include_flex=True.
Source code in tit/sim/utils.py
parse_flex_montage ¶
Convert a raw flex montage dict into a Montage dataclass.
Parameters¶
flex : dict
Dict with keys "name", "type", and either "pairs"
(for flex_mapped) or "electrode_positions" (for
flex_optimized / freehand_xyz).
Returns¶
Montage
Populated Montage instance.
Raises¶
ValueError
If flex["type"] is not a recognised montage type.
See Also¶
load_flex_montages : Produces the dicts consumed by this function. Montage : The returned dataclass.
Source code in tit/sim/utils.py
load_montages ¶
Load named montages from the project's montage_list.json.
Reads the montage_list.json file (managed by
:func:ensure_montage_file), looks up each name under the given
EEG net's uni- and multi-polar sections, and returns them as
:class:Montage instances. When include_flex is True, any
flex/freehand montages found via :func:load_flex_montages are
appended.
The eeg_net value determines the montage mode:
"freehand"setsMontage.Mode.FREEHAND"flex_mode"setsMontage.Mode.FLEX_FREE- Any other value (e.g.
"GSN-HydroCel-185.csv") setsMontage.Mode.NET
Parameters¶
montage_names : list[str]
Names to look up in the montage file.
eeg_net : str
EEG net identifier that selects the sub-dict inside
montage_list.json["nets"].
include_flex : bool, optional
If True (default), append flex/freehand montages loaded
from the FLEX_MONTAGES_FILE environment variable.
Returns¶
list[Montage] Resolved montage objects ready for simulation.
See Also¶
list_montage_names : Discover available names before loading. upsert_montage : Add montages that can then be loaded. Montage : The returned dataclass type.
Source code in tit/sim/utils.py
setup_montage_directories ¶
setup_montage_directories(montage_dir: str, mode: SimulationMode) -> dict[str, str]
Create the BIDS-compliant output directory tree for one montage.
Creates sub-directories for high-frequency fields, TI fields,
meshes, NIfTIs, surface overlays, montage images, and
documentation. For mTI mode, additional mTI/ sub-directories
are created.
Parameters¶
montage_dir : str
Root output directory for this montage.
mode : SimulationMode
SimulationMode.TI or SimulationMode.MTI.
Returns¶
dict[str, str]
Mapping of logical names (e.g. "ti_mesh", "hf_niftis")
to their absolute paths.
See Also¶
SimulationMode : Enum controlling which directories are created. BaseSimulation.run : Calls this at the start of each montage pipeline.
Source code in tit/sim/utils.py
run_montage_visualization ¶
run_montage_visualization(montage_name: str, simulation_mode: SimulationMode, eeg_net: str, output_dir: str, logger, electrode_pairs: list | None = None) -> None
Render a 2-D montage diagram for an EEG-cap montage.
Skips rendering for "freehand" and "flex_mode" montages
(no cap layout available).
Parameters¶
montage_name : str
Name of the montage to visualize.
simulation_mode : SimulationMode
SimulationMode.TI or SimulationMode.MTI.
eeg_net : str
EEG net identifier. Visualization is skipped when this is
"freehand" or "flex_mode".
output_dir : str
Directory where the image file is saved.
logger : logging.Logger
Logger instance for status messages.
electrode_pairs : list or None, optional
Electrode pair list to annotate on the diagram. Defaults to
an empty list.
See Also¶
tit.tools.montage_visualizer.visualize_montage : Underlying rendering function.
Source code in tit/sim/utils.py
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 | |
create_simulation_config_file ¶
create_simulation_config_file(config: SimulationConfig, montage: Montage, documentation_dir: str, logger) -> None
Write a JSON snapshot of the simulation configuration to disk.
Serialises subject ID, montage details, electrode geometry, mapping
options, and a timestamp into config.json inside
documentation_dir.
Parameters¶
config : SimulationConfig
The full simulation configuration.
montage : Montage
The specific montage being simulated.
documentation_dir : str
Directory to write config.json into.
logger : logging.Logger
Logger instance for status messages.
See Also¶
SimulationConfig : The serialised configuration type.
Source code in tit/sim/utils.py
extract_fields ¶
extract_fields(input_mesh: str, output_dir: str, base_name: str, m2m_dir: str, subject_id: str, logger) -> None
Extract grey-matter and white-matter meshes from a full-head mesh.
Crops the input mesh by SimNIBS tissue tags (tag 2 = GM, tag 1 = WM)
and writes the results as separate .msh files.
Parameters¶
input_mesh : str
Path to the full-head .msh file.
output_dir : str
Directory to write the cropped meshes into.
base_name : str
Stem used for output filenames (e.g.
"grey_{base_name}.msh").
m2m_dir : str
Path to the subject's m2m directory (unused but kept for
interface consistency).
subject_id : str
Subject identifier (unused but kept for interface consistency).
logger : logging.Logger
Logger instance for status messages.
See Also¶
transform_to_nifti : Convert the extracted meshes to NIfTI.
Source code in tit/sim/utils.py
transform_to_nifti ¶
transform_to_nifti(mesh_dir: str, output_dir: str, subject_id: str, m2m_dir: str, logger, fields: list[str] | None = None, skip_patterns: list[str] | None = None) -> None
Convert mesh files in a directory to NIfTI volumes.
Delegates to tit.tools.mesh2nii.convert_mesh_dir which
transforms each .msh file into subject-space (and optionally
MNI-space) NIfTI images.
Parameters¶
mesh_dir : str
Directory containing .msh files to convert.
output_dir : str
Directory to write the resulting NIfTI files.
subject_id : str
Subject identifier (unused but kept for interface consistency).
m2m_dir : str
Path to the subject's m2m directory, used for coordinate
transforms.
logger : logging.Logger
Logger instance for status messages.
fields : list[str] or None, optional
Mesh field names to convert. Converts all fields if None.
skip_patterns : list[str] or None, optional
Filename patterns to skip during conversion.
See Also¶
extract_fields : Produces meshes consumed by this function. convert_t1_to_mni : Companion T1-to-MNI transform.
Source code in tit/sim/utils.py
convert_t1_to_mni ¶
Convert the subject's T1 image to MNI space via subject2mni.
Calls the SimNIBS subject2mni CLI tool. Logs a warning (but
does not raise) if the conversion fails.
Parameters¶
m2m_dir : str
Path to the subject's m2m directory containing T1.nii.gz.
subject_id : str
Subject identifier, used for the output filename.
logger : logging.Logger
Logger instance for status/warning messages.
See Also¶
transform_to_nifti : Companion mesh-to-NIfTI transform.
Source code in tit/sim/utils.py
safe_move ¶
run_simulation ¶
run_simulation(config: SimulationConfig, logger=None, progress_callback: Callable[[int, int, str], None] | None = None) -> list[dict]
Run TI or mTI simulations for every montage in config.
For each montage in config.montages, this function:
- Auto-detects TI (2 pairs) vs mTI (4+ pairs) from the montage.
- Builds a SimNIBS SESSION with electrode geometry and conductivity settings from config.
- Runs the FEM solver to compute electric-field distributions.
- Computes temporal-interference envelope fields (
TI_max,TI_normal) and, for mTI, the multi-channel superposition. - Writes output meshes, surface overlays, and NIfTIs to the BIDS-compliant simulation directory.
Montages are processed sequentially. If no logger is provided, a file logger is created under the subject's log directory.
Parameters¶
config : SimulationConfig
Full simulation configuration including subject ID, montage
list, electrode geometry, and conductivity model.
logger : logging.Logger or None, optional
Logger instance. If None, a file logger is created
automatically in the subject's BIDS logs directory.
progress_callback : callable or None, optional
Optional callback invoked before each montage as
callback(current_index, total, montage_name) and once more
with (total, total, "Complete") when finished.
Returns¶
list[dict]
One result dict per montage with keys montage_name,
montage_type, status, and output_mesh.
See Also¶
SimulationConfig : The configuration consumed by this function. BaseSimulation.run : Per-montage pipeline called internally. TISimulation : Concrete class for 2-pair simulations. mTISimulation : Concrete class for N-pair simulations.