pynibs.expio package¶
Submodules¶
pynibs.expio.Mep module¶
- class pynibs.expio.Mep.Mep(intensities, mep, intensity_min_threshold=None, mep_min_threshold=None)¶
Bases:
objectMep object.
- fun¶
Kind of function to fit data with (sigmoid / exp / linear)
- Type
function
- fun_sig¶
Best fitting equivalent sigmoidal function (added by add_sigmoidal_bestfit(self))
- Type
function
- popt_sig¶
Best fitting parameters x0, r, and amp of equivalent sigmoidal function
- Type
nparray of float [3]
- fit¶
Gmodel object instance of parameter fit
- Type
object instance
Methods
calc_motor_threshold(threshold)Determine motor threshold of stimulator depending on MEP threshold given in [mV]
eval(x, p)Evaluating fitted function with optimal parameters in points x.
eval_fun_sig(x, p)Evaluating optimally fitted sigmoidal function with optimal parameters in points x.
eval_opt(x)Evaluating fitted function with optimal parameters in points x.
eval_uncertainties(x[, sigma])Evaluating approximated uncertainty interval around fitted distribution.
fit_mep_to_function([p0])Fits MEP data to function.
fit_mep_to_function_multistart([p0, ...])Fits MEP data to function.
plot(label[, sigma, plot_samples, ...])Plotting mep data and fitted curve together with uncertainties.
run_fit_multistart(fun, x, y, p0[, ...])Run multistart approach to fit data to function.
- calc_motor_threshold(threshold)¶
Determine motor threshold of stimulator depending on MEP threshold given in [mV]
- Parameters
threshold (float) – Threshold of MEP amplitude in [mV]
Notes
Add Attributes:
- Mep.mtfloat
Motor threshold for given MEP threshold.
- eval(x, p)¶
Evaluating fitted function with optimal parameters in points x.
- eval_fun_sig(x, p)¶
Evaluating optimally fitted sigmoidal function with optimal parameters in points x.
- eval_opt(x)¶
Evaluating fitted function with optimal parameters in points x.
- eval_uncertainties(x, sigma=1)¶
Evaluating approximated uncertainty interval around fitted distribution.
- Parameters
- Returns
y_min (nparray of float [N_x]) – Lower bounds of y-values
y_max (nparray of float [N_x]) – Upper bounds of y-values
- fit_mep_to_function(p0=None)¶
Fits MEP data to function. The algorithm tries to fit the function first to a sigmoid, then to an exponential and finally to a linear function.
- Parameters
p0 (nparray of float) – Initial guess of parameter values
Notes
Add Attributes:
- Mep.poptnparray of float [N_para]
Fitted optimal function parameters
- Mep.coptnparray of float [N_para x N_para]
Covariance matrix of fitted parameters
- Mep.pstdnparray of float [N_para]
Standard deviation of fitted parameters
- Mep.funfunction
Function mep data was fitted with
- Mep.fitobject instance
Gmodel object instance of parameter fit
- Mep.mtfloat
Motor threshold (MEP > 50 uV).
- fit_mep_to_function_multistart(p0=None, constraints=None, fun=None)¶
Fits MEP data to function.
- Parameters
Notes
Add Attributes:
- Mep.poptnparray of float [N_para]
Best fitted optimal function parameters
- Mep.coptnparray of float [N_para x N_para]
Covariance matrix of best fitted parameters
- Mep.pstdnparray of float [N_para]
Standard deviation of best fitted parameters
- Mep.funfunction
Function of best fit mep data was fitted with
- Mep.fitlist of fit object instances
Gmodel object instances of parameter fits
- Mep.best_fit_idxint
Index of best function fit (fit[best_fit_idx])
- Mep.constraintsdict
Dictionary with parameter names as keys and [min, max] values as constraints
- plot(label, sigma=3, plot_samples=True, show_plot=False, fname_plot='', ylim=None, ylabel=None, fontsize_axis=10, fontsize_legend=10, fontsize_label=10, fontsize_title=10, fun=None)¶
Plotting mep data and fitted curve together with uncertainties. For (fun is None), the optimal function is plotted.
- Parameters
label (str) – Title of plot
sigma (float) – Factor of standard deviations the uncertainty of the fit is plotted with
plot_samples (boolean) – Plot sampling curves of the fit in the uncertainty interval.
show_plot (boolean) – Show or hide plot window (TRUE / FALSE)
fname_plot (str) – Filename of plot showing fitted data (with .png extension!)
fontsize_axis (int) – Fontsize of axis numbers
fontsize_legend (int) – Fontsize of Legend labels
fontsize_label (int) – Fontsize of axis labels
fontsize_title (int) – Fontsize of title
fun (str or None (None, 'sigmoid', 'exp', 'linear')) – Which function to plot
- Returns
<File> – Plot of Mep data and fit (format: png)
- Return type
.png file
- run_fit_multistart(fun, x, y, p0, constraints=None, verbose=False, n_multistart=100)¶
Run multistart approach to fit data to function. n_multistart optimizations are performed based on random variations of the initial guess parameters p0. The fit with the lowest aic (Akaike information criterion), i.e. best fit is returned as gmodel fit instance.
- Parameters
fun (function) – Function mep data has to be fitted with
x (nparray of float [N_data]) – Independent variable the data is fitted on
y (nparray of float [N_data]) – Dependent data the curve is fitted through
p0 (nparray of float) – Initial guess of parameter values
constraints (dict, optional) – Dictionary with parameter names as keys and [min, max] values as constraints
verbose (bool) – Show output messages (True / False (Default))
n_multistart (int) – Number of repeated optimizations with different starting points to perform
- Returns
fit – Gmodel object instance of best parameter fit with lowest parameter variance
- Return type
object instance
- pynibs.expio.Mep.butter_lowpass(cutoff, fs, order=5)¶
Setup Butter low-pass filter and return filter parameters.
- pynibs.expio.Mep.butter_lowpass_filter(data, cutoff, fs, order=5)¶
- pynibs.expio.Mep.calc_p2p(sweep, tms_pulse_time=0.2, start_mep=20, end_mep=35, measurement_start_time=0, sampling_rate=4000, cutoff_freq=500, fn_plot=None)¶
Calc peak-to-peak values of and mep sweep.
- Parameters
sweep (np.array of float [Nx1]) – Input curve
tms_pulse_time (float (Default: .2)) – onset time of TMS pulse trigger in [s]
start_mep (int (Default: 18)) – start of p2p search window after TMS pulse. In [ms].
end_mep (int (Default: 35)) – end of p2p search window after TMS pulse. In [ms].
measurement_start_time (float (Default: 0)) – start time of the EMG measurement. In [ms].
sampling_rate (int (Default: 2000)) – Sampling rate in Hz
cutoff_freq (int (Default: 500)) – Desired cutoff frequency of the filter, Hz
fn_plot (str, optional, default: None) – Filename of sweep to plot (.png). If None, plot is omitted.
- Returns
p2p (float) – Peak-to-peak value of input curve
sweep_filt (np.array of float) – Filtered input curve (Butter lowpass filter with specified cutoff_freq)
onset (float) – MEP onset after tms_pulse_time
- pynibs.expio.Mep.calc_p2p_old_exp0(sweep, start_mep=None, end_mep=None, tms_pulse_time=None, sampling_rate=None)¶
Calc peak-to-peak values of an mep sweep. This version was probably used in the ancient times of experiment 0.
- pynibs.expio.Mep.calc_p2p_old_exp1(sweep, start_mep=18, end_mep=35, tms_pulse_time=None, sampling_rate=2000)¶
Calc peak-to-peak values of an mep sweep. This version was probably used for the first fits of experiment 1.
- Parameters
sweep (np.array of float [Nx1]) –
Input curve
- start_mep: Int or Float (Default: 18)
Starttime in [ms] after TMS for MEP seach window.
- end_mep: Int or Float (Default: 35)
Endtime in [ms] after TMS for MEP seach window.
tms_pulse_time (None) – Not used.
sampling_rate (int (Default: 2000)) – Sampling rate in Hz
- Returns
p2p – Peak-to-peak value of input curve
- Return type
- pynibs.expio.Mep.dummy_fun(x, a)¶
Dummy function for congruence factor calculation.
- pynibs.expio.Mep.exp(x, x0, r, y0)¶
Parametrized exponential function

- pynibs.expio.Mep.exp0(x, x0, r)¶
Parametrized exponential function w/o offset.

- pynibs.expio.Mep.exp0_log(x, x0, r)¶
Parametrized exponential function w/o offset.

- pynibs.expio.Mep.exp_log(x, x0, r, y0)¶
Parametrized exponential function (log)

- pynibs.expio.Mep.get_mep_elements(mep_fn, tms_pulse_time, drop_mep_idx=None, cfs_data_column=0, channels=None, time_format='delta', plot=False)¶
Read EMG data from CED .cfs or .txt file and returns MEP amplitudes.
- Parameters
mep_fn (string) – path to …cfs-file or .txt file (Signal export)
tms_pulse_time (float) – Time in [s] of TMS pulse as specified in signal
drop_mep_idx (List of int or None (Default: None)) – Which MEPs to remove before matching.
cfs_data_column (int or list of int) – Column(s) of dataset in cfs file. +1 for .txt
channels (list of str, optional, default: None) – Channel names
time_format (str, optional, default="delta") – Format of mep time stamps in time_mep_lst to return - “delta”: returns list of datetime.timedelta in seconds - “hms”: returns datetime.datetime(year, month, day, hour, minute, second, microsecond)
plot (bool, optional, default: False) –
- Returns
p2p_array (np.ndarray of float [N_stim]) – Peak to peak values of N sweeps
time_mep_lst (list of datetime.timedelta) – MEP-timestamps
mep_raw_data (np.ndarray of float [N_channel x N_stim x N_samples]) – Raw (unfiltered) MEP data
mep_filt_data (np.ndarray of float [N_channel x N_stim x N_samples]) – Filtered MEP data (Butterworth lowpass filter)
time (np.ndarray of float [N_samples]) – Time axis corresponding to MEP data
mep_onset_array (np.ndarray of float [S_samples]) – MEP onset after TMS pulse
- pynibs.expio.Mep.get_mep_sampling_rate(cfs_path)¶
Returns sampling rate [Hz] for CED Signal EMG data in .cfs, .mat or .txt file.
The sampling rate is saved in the cfs header like this: …Samplingrate” : 3999.999810,
…
- Parameters
- cfs_pathstring with path to …cfs-file or .txt file
- Returns
- floatsampling rate
- pynibs.expio.Mep.get_mep_virtual_subject_DVS(x, x0=0.5, r=10, amp=1, sigma_x=0, sigma_y=0, y0=0.01, seed=None)¶
Creates random mep data using the 2 variability source model from Goetz et al. 2014 together with a standard 3 parametric sigmoid function.
Goetz, S. M., Luber, B., Lisanby, S. H., & Peterchev, A. V. (2014). A novel model incorporating two variability sources for describing motor evoked potentials. Brain stimulation, 7(4), 541-552.
- Parameters
x (ndarray of float [n_x]) – Normalized stimulator intensities [0 … 1]
x0 (float, optional, default: 0.5) – Location of turning point sigmoidal function
r (float, optional, default: 0.25) – Steepness of sigmoidal function
amp (float, optional, default: 1.0) – Saturation amplitude of sigmoidal function
sigma_x (float, optional, default: 0.1) – Standard deviation of additive x variability source
sigma_y (float, optional, default: 0.1) – Standard deviation of additive y variability source
y0 (float, optional, default: 1e-2) – y-offset
seed (int, optional, default: None) – Seed to use.
- Returns
mep – Motor evoked potential values
- Return type
ndarray of float [n_x]
- pynibs.expio.Mep.get_mep_virtual_subject_TVS(x, p1=-5.0818, p2=-2.4677, p3=3.6466, p4=0.42639, p5=1.6665, mu_y_add=8.283235329759169e-06, mu_y_mult=-0.9645334, mu_x_add=0.68827324, sigma_y_add=1.4739e-06, k=0.39316, sigma2_y_mult=0.022759, sigma2_x_add=0.023671, subject_variability=False, trial_variability=True)¶
Creates random mep data using the 3 variability source model from Goetz et al. 2019.
Goetz, S. M., Alavi, S. M., Deng, Z. D., & Peterchev, A. V. (2019). Statistical Model of Motor-Evoked Potentials. IEEE Transactions on Neural Systems and Rehabilitation Engineering, 27(8), 1539-1545.
(There are typos in the paper but the code seems to be correct)
Originally from S. Goetz: https://github.com/sgoetzduke/Statistical-MEP-Model
rewritten from MATLAB to Python by Konstantin Weise
- Parameters
x (ndarray of float [n_x]) – Normalized stimulator intensities [0 … 1]
p1 (float, optional, default: -5.0818) – First parameter of sigmoidal hilltype function
p2 (float, optional, default: 4.5323) – Second parameter of sigmoidal hilltype function
p3 (float, optional, default: 3.6466) – Third parameter of sigmoidal hilltype function
p4 (float, optional, default: 0.42639) – Fourth parameter of sigmoidal hilltype function
p5 (float, optional, default: 1.6665) – Fifth parameter of sigmoidal hilltype function
mu_y_add (float, optional, default: 10**-5.0818) – Mean value of additive y variability source
mu_y_mult (float, optional, default: -0.9645334) – Mean value of multiplicative y variability source
mu_x_add (float, optional, default: -0.68827324) – Mean value of additive x variability source
sigma_y_add (float, optional, default: 1.4739*1e-6) – Standard deviation of additive y variability source
k (float, optional, default: 0.39316) – Shape parameter of generalized extreme value distribution
sigma2_y_mult (float, optional, default: 2.2759*1e-2) – Standard deviation of multiplicative y variability source
sigma2_x_add (float, optional, default: 2.3671*1e-2) – Standard deviation of additive x variability source
subject_variability (bool, optional, default: False) – Choose if shape parameters from IO curve are sampled from random distributions to model subject variability. This does not influence the trial-to-trial variability.
trial_variability (bool, optional, default: True) – Enable or disable trial-to-trial variability. Disabling it will result in ideal IO curves w/o noise.
- Returns
mep – Motor evoked potential values in mV
- Return type
ndarray of float [n_x]
- pynibs.expio.Mep.get_time_date(cfs_paths)¶
Get time and date of the start of the recording out of .cfs file.
- pynibs.expio.Mep.linear(x, m, n)¶
Parametrized linear function

- pynibs.expio.Mep.linear_log(x, m, n)¶
Parametrized log linear function

- pynibs.expio.Mep.load_mepobj(fname)¶
Loading Mep object.
- Parameters
fname (str) – Filename of Mep object with .pkl extension
- Returns
object
- Return type
pyfempp.Mep
- pynibs.expio.Mep.save_mepobj(obj, fname)¶
Saving an Mep object in pickle format.
- pynibs.expio.Mep.sigmoid(x, x0, r, amp)¶
Parametrized sigmoid function.

- pynibs.expio.Mep.sigmoid4(x, x0, r, amp, y0)¶
Parametrized sigmoid function with 4 parameters.

- Parameters
- Returns
y – (N_x) Function value at argument x.
- Return type
np.ndarray of float
- pynibs.expio.Mep.sigmoid4_log(x, x0, r, amp, y0)¶
Parametrized log transformed sigmoid function with 4 parameters.

- Parameters
- Returns
y – (N_x) Function value at argument x.
- Return type
np.ndarray of float
pynibs.expio.brainsight module¶
- pynibs.expio.brainsight.merge_exp_data(subject, exp_idx, mesh_idx, coil_outlier_corr_cond=False, remove_coil_skin_distance_outlier=True, coil_distance_corr=True, verbose=False, plot=False)¶
Merge the TMS coil positions and the mep data into an experiment.hdf5 file.
- Parameters
subject (pynibs.Subject) – Subject object
exp_idx (str) – Experiment ID
mesh_idx (str) – Mesh ID
coil_outlier_corr_cond (bool) – Correct outlier of coil position and orientation (+-2 mm, +-3 deg) in case of conditions
remove_coil_skin_distance_outlier (bool) – Remove outlier of coil position lying too far away from the skin surface (+- 5 mm)
coil_distance_corr (bool) – Perform coil <-> head distance correction (coil is moved towards head surface until coil touches scalp)
verbose (bool) – Plot output messages
plot (bool, optional, default: False) – Plot MEPs and p2p evaluation
- pynibs.expio.brainsight.read_targets_brainsight(fn)¶
Reads target coil position and orientations from .txt file and returns it as 4 x 4 x N_targets numpy array.
- pynibs.expio.brainsight.write_targets_brainsight(targets, fn_out, names=None, overwrite=True)¶
Writes coil position and orientations in .txt file for import into Brainsight.
- Parameters
targets (ndarray of float [4 x 4 x N_targets]) – Tensor containing the 4x4 matrices with coil orientation and position
fn_out (str) – Filename of output file
names (list of str, optional, default: None) – Target names (If nothing is provided they will be numbered by their order)
overwrite (bool, optional, default: True) – Overwrite existing .txt file
- Return type
<file> .txt file containing the targets for import into Brainsight
pynibs.expio.brainvis module¶
- pynibs.expio.brainvis.read_channel_names(fname)¶
Reads the channel names from .vhdr (info) file, which is recorded during EEG
pynibs.expio.cobot module¶
- pynibs.expio.cobot.merge_exp_data_cobot(subject, exp_idx, mesh_idx, coil_outlier_corr_cond=False, remove_coil_skin_distance_outlier=True, coil_distance_corr=True, verbose=False, plot=False)¶
Merge the TMS coil positions and the mep data into an experiment.hdf5 file.
- Parameters
subject (pyfempp.subject) – Subject object
exp_idx (str) – Experiment ID
mesh_idx (str) – Mesh ID
coil_outlier_corr_cond (bool) – Correct outlier of coil position and orientation (+-2 mm, +-3 deg) in case of conditions
remove_coil_skin_distance_outlier (bool) – Remove outlier of coil position lying too far away from the skin surface (+- 5 mm)
coil_distance_corr (bool) – Perform coil <-> head distance correction (coil is moved towards head surface until coil touches scalp)
verbose (bool) – Plot output messages
plot (bool, optional, default: False) – Plot MEPs and p2p evaluation
pynibs.expio.exp module¶
- pynibs.expio.exp.add_sigmoidal_bestfit(mep, p0, constraints=None)¶
Add best fitting sigmoidal function to instance (determined by multistart approach)
- Parameters
- Returns
mep – Updated Mep object class instance with the following attributes
- Return type
Notes
Adds Attributes
- Mep.fun_sigfunction
Sigmoid function
- Mep.popt_signp.ndarray of float [3]
Parameters of sigmoid function
- pynibs.expio.exp.calc_outlier(coords, dev_location, dev_radius, target=None, fn_out=None, print_msg=True)¶
Computes median coil position and angle, identifies outliers, plots neat figure. Returns a list of idx that are not outliers
- pynibs.expio.exp.cfs2hdf5(fn_cfs, fn_hdf5=None)¶
Converts EMG data included in .cfs file to .hdf5 format.
- Parameters
- Returns
<file> – File containing: - EMG data in f[“emg”][:] - Time axis in f[“time”][:]
- Return type
.hdf5 File
- pynibs.expio.exp.coil_distance_correction(exp=None, fn_exp=None, fn_exp_out=None, fn_geo_hdf5=None, remove_coil_skin_distance_outlier=False, fn_plot=None, min_dist=-5, max_dist=2)¶
Corrects the distance between the coil and the head assuming that the coil is touching the head surface during the experiments. This is done since the different coil tracker result in different coil head distances due to tracking inaccuracies. Also averages positions and orientations over the respective condition and writes both mean position and orientation for every condition in fn_exp_out.
Depending on if exp (dict containing lists) or fn_exp (csv file) is provided it returns the outlier corrected dict or writes a new <fn_exp_out>.csv file.
- Parameters
exp (list of dict or dict of list, optional, default: None) – List of dictionaries containing the experimental data
fn_exp (str) – Filename (incl. path) of experimental .csv file
fn_exp_out (str) – Filename (incl. path) of distance corrected experimental .csv file
fn_geo_hdf5 (str) – Filename (incl. path) of geometry mesh file (.hdf5)
remove_coil_skin_distance_outlier (bool) – Remove coil positions, which are more than +- 2 mm located from the zero mean skin surface.
fn_plot (str, default: None (fn_geo_hdf5 folder)) – Folder where plots will be saved in.
min_dist (int) – Ignored.
max_dist (int) – Ignored.
- Returns
<File> (.csv file) – experimental_dc.csv file with distance corrected coil positions
or
exp (dict) – Dictionary containing the outlier corrected experimental data
- pynibs.expio.exp.coil_distance_correction_matsimnibs(matsimnibs, fn_mesh_hdf5, distance=0, remove_coil_skin_distance_outlier=False)¶
Corrects the distance between the coil and the head assuming that the coil is located at a distance “d” with respect to the head surface during the experiments. This is done since the different coil tracker result in different coil head distances due to tracking inaccuracies.
- Parameters
matsimnibs (ndarray of float [4 x 4] or [4 x 4 x n_mat]) – Tensor containing matsimnibs matrices
fn_mesh_hdf5 (str) – .hdf5 file containing the head mesh
distance (float) – Target distance in (mm) between coil and head due to hair layer. All coil positions are moved to this distance.
remove_coil_skin_distance_outlier (bool) – Remove coil positions, which are more than +- 6 mm located from the skin surface.
- Returns
matsimnibs – Tensor containing matsimnibs matrices with distance corrected coil positions
- Return type
ndarray of float [4 x 4 x n_mat]
- pynibs.expio.exp.coil_outlier_correction_cond(exp=None, fn_exp=None, fn_exp_out=None, outlier_angle=5.0, outlier_loc=3.0)¶
Searches and removes outliers of coil orientation and location w.r.t. the average orientation and location from all zaps. It generates plots of the individual conditions showing the outliers in the folder of fn_exp_out. Depending on if exp (dict containing lists) or fn_exp (csv file) is provided it returns the outlier corrected dict or writes a new <fn_exp_out>.csv file. If _exp_ is provided, all keys are kept.
- Parameters
exp (list of dict, optional, default: None) – List of dictionaries containing the experimental data
fn_exp (str, optional, default: None) – Filename (incl. path) of experimental .csv file
fn_exp_out (str, optional, default: None) – Filename (incl. path) of corrected experimental .csv file
outlier_angle (float, optional, default: 5.) – Coil orientation outlier “cone” around axes in +- deg. All zaps with coil orientations outside of this cone are removed.
outlier_loc (float, optional, default: 3.) – Coil position outlier “sphere” in +- mm. All zaps with coil locations outside of this sphere are removed.
- Returns
<File> (.csv file) – experimental_oc.csv file with outlier corrected coil positions
<Files> (.png files) – Plot showing the coil orientations and locations (folder_of_fn_exp_out/COND_X_coil_position.png)
or
exp (dict) – Dictionary containing the outlier corrected experimental data
Creates dictionary containing all experimental data.
- Parameters
xml_paths (list of str) – Paths to coil0-file and optionally coil1-file if there is no coil1-file, use empty string
im (list of str) – List of path to the instrument-marker-file or list of strings containing the instrument marker
coil_sn (str) – Coil-serial-number
nii_exp_path (str) – Path to the .nii file that was used in the experiment
nii_conform_path (str) – Path to the conform*.nii file used to calculate the E-fields with SimNIBS
patient_id (str) – Patient id
tms_pulse_time (float) – Time in [s] of TMS pulse as specified in signal
drop_mep_idx (List of int or None) – Which MEPs to remove before matching.
mep_onsets (List of int or None (Default: None)) – If there are multiple .cfs per TMS Navigator sessions, onsets in [ms] of .cfs. E.g.: [0, 71186].
temp_dir (str, optional, default: None (fn_exp_mri_nii folder)) – Directory to save temporary files (transformation .nii and .mat files)
cfs_data_column (int or list of int) – Column(s) of dataset in .cfs file.
channels (list of str, optional, default: None) – Channel names
nnav_system (str) – Type of neuronavigation system (“Localite”, “Visor”)
mesh_approach (str, optional, default: "headreco") – Approach the mesh is generated with (“headreco” or “mri2mesh”)
plot (bool, optional, default: False) – Plot MEPs and p2p evaluation
- Returns
dict_lst – ‘number’ ‘condition’ ‘current’ ‘mep_raw_data’ ‘mep’ ‘mep_latency’ ‘mep_filt_data’ ‘mep_raw_data_time’ ‘time_tms’ ‘ts_tms’ ‘time_mep’ ‘date’ ‘coil_sn’ ‘patient_id’
- Return type
list of dicts, one dict for each zap
Creates dictionary containing all experimental data.
- Parameters
xml_paths (list of str) – Paths to coil0-file and optionally coil1-file if there is no coil1-file, use empty string
im (list of str) – List of path to the instrument-marker-file or list of strings containing the instrument marker
coil_sn (str) – Coil-serial-number
nii_exp_path (str) – Path to the .nii file that was used in the experiment
nii_conform_path (str) – Path to the conform*.nii file used to calculate the E-fields with SimNIBS
patient_id (str) – Patient id
drop_trial_idx (List of int or None) – Which MEPs to remove before matching.
temp_dir (str, optional, default: None (fn_exp_mri_nii folder)) – Directory to save temporary files (transformation .nii and .mat files)
nnav_system (str) – Type of neuronavigation system (“Localite”, “Visor”)
cond (str) – Condition name in data_path
mesh_approach (str, optional, default: "headreco") – Approach the mesh is generated with (“headreco” or “mri2mesh”)
plot (bool, optional, default: False) – Plot MEPs and p2p evaluation
- Returns
dict_lst – ‘number’ ‘condition’ ‘current’ ‘mep_raw_data’ ‘mep’ ‘mep_latency’ ‘mep_filt_data’ ‘mep_raw_data_time’ ‘time_tms’ ‘ts_tms’ ‘time_mep’ ‘date’ ‘coil_sn’ ‘patient_id’
- Return type
list of dicts, one dict for each zap
- pynibs.expio.exp.convert_csv_to_hdf5(fn_csv, fn_hdf5, overwrite_arr=True, verbose=False)¶
Wrapper from experiment.csv to experiment.hdf5
Saves all relevant columns from the (old) experiment.csv file to an .hdf5 file. fn_hdf5:/stim_data/
All columns not found in experiment.csv are ignored (and a warning is thrown).
- pynibs.expio.exp.get_cnt_infos(fn_cnt)¶
Read some meta information from .cnt file
- Return type
dict d
- pynibs.expio.exp.get_coil_flip_m(source_system='simnibs', target_system=None)¶
Returns a flimp matrix 4x4 to flip coil axis from one system to another.
- Parameters
source_system (str) – Atm only possible source: ‘simnibs’
target_system – tmsnavigator, visor, brainsight
- Returns
flip_m – shape: 4x4
- Return type
np.ndarray
- pynibs.expio.exp.get_coil_sn_lst(fn_coil)¶
- pynibs.expio.exp.get_csv_matrix(dictionary)¶
- pynibs.expio.exp.get_intensity_e(e1, e2, target1, target2, radius1, radius2, headmesh, rmt=1, roi='midlayer_lh_rh', verbose=False)¶
Computes the stimulator intensity adjustment factor based on the electric field
- Parameters
e1 (str) – .hdf5 e field with midlayer
e2 (str) – .hdf5 e field with midlayer
target1 (np.ndarray (3,)) – Coordinates of cortical site of MT
target2 (np.ndarray (3,)) – Coordinates of cortical target site
radius1 (float) – Electric field of field1 is averaged over elements inside this radius around target1
radius2 (float) – Electric field of field2 is averaged over elements inside this radius around target2
headmesh (str) – .hdf5 headmesh
rmt (float, optional, default=0) – Resting motor threshold to be corrected
roi (str, optional, default='midlayer_lh_rh') – Name of roi. Expected to sit in mesh[‘/data/midlayer/roi_surface/’]
verbose (bool, optional, Default: false) – Print verbosity information.
- Returns
rmt_e_corr – Adjusted stimulation intensity for target2
- Return type
- pynibs.expio.exp.get_intensity_e_old(mesh1, mesh2, target1, target2, radius1, radius2, rmt=1, verbose=False)¶
Computes the stimulator intensity adjustment factor based on the electric field
Something weird is going on here - check simnibs coordinates of midlayer before usage.
- Parameters
mesh1 (str or simnibs.msh.mesh_io.Msh) – Midlayer mesh containing results of the optimal coil position of MT in the midlayer (e.g.: …/subject_overlays/00001.hd_fixed_TMS_1-0001_MagVenture_MCF_B65_REF_highres.ccd_scalar_central.msh)
mesh2 (str or simnibs.msh.mesh_io.Msh) – Midlayer mesh containing results of the optimal coil position of the target in the midlayer (e.g.: …/subject_overlays/00001.hd_fixed_TMS_1-0001_MagVenture_MCF_B65_REF_highres.ccd_scalar_central.msh)
target1 (np.ndarray (3,)) – Coordinates of cortical site of MT
target2 (np.ndarray (3,)) – Coordinates of cortical target site
radius1 (float) – Electric field in target 1 is averaged over elements inside this radius
radius2 (float) – Electric field in target 2 is averaged over elements inside this radius
rmt (float, optional, default=0) – Resting motor threshold, which will be corrected
verbose (bool, optional, Default: false) – Print verbosity information.
- Returns
rmt_e_corr – Adjusted stimulation intensity for target2
- Return type
- pynibs.expio.exp.get_intensity_stokes(mesh, target1, target2, spat_grad=3, rmt=0, verbose=False, scalp_tag=1005, roi=None)¶
Computes the stimulator intensity adjustment factor according to Stokes et al. 2005 (doi:10.1152/jn.00067.2005). Adjustment is based on target-scalp distance differences: adj = (Dist2-Dist1)*spat_grad
- Parameters
mesh (str or simnibs.msh.mesh_io.Msh) – Mesh of the head model
target1 (np.ndarray (3,)) – Coordinates of cortical site of MT
target2 (np.ndarray (3,)) – Coordinates of cortical target site
spat_grad (float) – Spatial gradient. Default: 3
rmt (float, optional, default=0) – Resting motor threshold, which will be corrected
scalp_tag (int, optional, default: 1005) – Tag in the mesh where the scalp is to be set. Default: 1005
verbose (bool, optional, Default: false) – Print verbosity information.
roi (np.ndarray (3,N)) – Array of nodes to project targets onto
- Returns
rmt_stokes – Adjusted stimulation intensity for target2
- Return type
- pynibs.expio.exp.get_patient_id(xml_path)¶
Read patiend-ID.
- pynibs.expio.exp.get_trial_data_from_csv(behavior_fn, cond, drop_trial_idx=None, only_corr=True, startatzero=True)¶
Reads trial data from csv file. Reaction time is in [0.1ms]
- Parameters
behavior_fn (str) – Filename with columns: ‘trialtype’, ‘onset_time’, ‘rt’
- condstr
Which condition to choose from .csv file
- drop_trial_idxlist of int, optional
‘trialnum’ to remove
- only_corrbool, default: True
Only return trials with correct responses
- startatzerobool, default: True
Shift onset_time axis to zero
- Returns
rt (list of float)
onsets (list of float)
mean_isi (tuple of int) – in [s]
- pynibs.expio.exp.load_matsimnibs_txt(fn_matsimnibs)¶
Loading matsimnibs matrices from .txt file.
- pynibs.expio.exp.match_behave_and_triggermarker(mep_time_lst, xml_paths, bnd_factor=0.495, isi=None)¶
Sort out timestamps of mep and tms files that do not match.
- Parameters
mep_time_lst (list of datetime.timedelta) – timedeltas of MEP recordings.
xml_paths (list of str) – Paths to coil0-file and optionally coil1-file if there is no coil1-file, use empty string
bnd_factor (float, optional, default: 0.99/2) – Bound factor relative to interstimulus interval in which +- interval to match neuronavigation and mep data from their timestamps. (0 means perfect matching, 0.5 means +- half interstimulus interval)
isi (float, optional.) – Interstimulus intevals. Of not provided it’s estimated from the first trial.
- Returns
tms_index_lst (list of int) – Indices of tms-timestamps that match
mep_index_lst (list of int) – Indices of mep-timestamps that match
tms_time_lst (list of datetime) – TMS timstamps
Transforming TMS coil positions from neuronavigation to simnibs space
- Parameters
fn_exp_nii (str) – Filename of .nii file the experiments were conducted with
fn_conform_nii (str) – Filename of .nii file from SimNIBS mri2msh function (e.g.: …/fs_subjectID/subjectID_T1fs_conform.nii.gz)
m_nnav (np.ndarray [4 x 4 x N]) – Position matrices from neuronavigation
nnav_system (str) – Neuronavigation system: - “Localite” … Localite neuronavigation system - “Visor” … Visor neuronavigation system from ANT - “Brainsight” … Brainsight neuronavigation system from Rougue Research
mesh_approach (str, optional, default: "headreco") – Approach the mesh is generated with (“headreco” or “mri2mesh”)
fiducials (np.array of float [3 x 3]) – Fiducial points in ANT nifti space from file (e.g.: /data/pt_01756/probands/33791.b8/exp/1/33791.b8_recording/MRI/33791.b8_recording.mri) (x frontal-occipital, y right-left, z inferior-superior) VoxelOnPositiveXAxis (Nasion, first row) 221 131 127 VoxelOnPositiveYAxis (left ear, second row) 121 203 105 VoxelOnNegativeYAxis (right ear, third row) 121 57 105
orientation (str) – Orientation convention (‘RAS’ or ‘LPS’) (can be read from neuronavigation .xml file under coordinateSpace=”RAS”)
fsl_cmd (str) – bash command to start FSL environment (Default: FSL)
target (str, optional, default: 'simnibs') – Either transform to ‘simnibs’ or to ‘nnav’ space
temp_dir (str, optional, default: None (fn_exp_mri_nii folder)) – Directory to save temporary files (transformation .nii and .mat files)
rem_tmp (bool, optional, default: False) – Remove temporary files from registration
verbose (boolean) – Print output (True / False)
- Returns
m_simnibs
- Return type
np.ndarray of float [4 x 4 x N]
- pynibs.expio.exp.outliers_mask(data, m=2.0)¶
- pynibs.expio.exp.print_time(relation, tms_time, tms_time_index, mep_time, mep_time_index, time_bnd_l, time_bnd_h)¶
Print timestamps that do not match.
- Parameters
relation (str) – ‘bigger’ or ‘smaller’
tms_time (datetime.timedelta) – TMS timestamps
tms_time_index (int) – Index of tms timestamp
mep_time (datetime.timedelta) – Mep timestamps
mep_time_index (int) – Index of mep timestamps
time_bnd_l (datetime.timedelta) – Lowest datetime timestamp for matching
time_bnd_h (datetime.timdelta) – Highest datetime timestamp for matching
- pynibs.expio.exp.read_csv(csv_path)¶
Read dictionary from .csv-file.
- pynibs.expio.exp.read_exp_stimulations(fname_results_conditions, fname_simpos, filter_bad_trials=False, drop_idx=None)¶
Reads results_conditions.csv and simPos.csv and returns data.
- Parameters
- Returns
positions_all (list of np.ndarrays of float [N_zaps x [4 x 4]]) – List of position matrices of TMS coil, formatted in simnibs style

conditions (list of str [N_zaps]) – Str labels of the condition corresponding to each zap
position_list (list of float and str [N_zaps x 55]) – List of data stored in results_conditions.csv (condition, MEP amplitude, locations of neuronavigation trackers)
mep_amp (np.array of float [N_zaps]) – MEP amplitude in [V] corresponding to each zap
intensities (np.array of float [N_zaps]) – Stimulator intensities corresponding to each zap
fails_idx (np.array(N_fails_idx x 1) (only if filter_bad_trials)) – Which trials were dropped through filtering?
- pynibs.expio.exp.save_matsimnibs_txt(fn_matsimnibs, matsimnibs)¶
Saving matsimnibs matrices in .txt file.
- pynibs.expio.exp.sort_by_condition(exp, conditions_selected=None)¶
Sort experimental dictionary from experimental.csv into list by conditions.
- Parameters
- Returns
exp_cond – List of dictionaries containing the experimental data information sorted by condition
- Return type
- pynibs.expio.exp.sort_data_by_condition(conditions, return_alph_sorted=True, conditions_selected=None, *data)¶
Sorts data by condition and returns tuples of data with corresponding labels.
- Parameters
conditions (list of str [N_zaps]) – Str labels of the condition corresponding to each data
return_alph_sorted (Boolean, Default True) – Shall returns be in alphabetically or original order
conditions_selected (list of str or None) – List of conditions returned by the function (in this order), the others are omitted
data (tuple of data indexed by condition [N_data x N_zaps x m]) – Data to sort
- Returns
cond_labels (list of str [N_cond]) – Labels of conditions
data_sorted (tuple of sorted data [N_cond x N_data x N_zaps x m]) – Sorted data by condition
- pynibs.expio.exp.splitext_niigz(fn)¶
Splitting extension(s) from .nii or .nii.gz file
- Parameters
fn (str) – Filename of input image .nii or .nii.gz file
- Returns
path (str) – Path and filename without extension(s)
ext (str) – Extension, either .nii or .nii.gz
- pynibs.expio.exp.square(x, a, b, c)¶
Parametrized quadratic function

- pynibs.expio.exp.toRAS(fn_in, fn_out)¶
Transforming MRI .nii image to RAS space.
- pynibs.expio.exp.write_csv(csv_output_path, dict_lst)¶
Write dictionary into .csv-file.
- pynibs.expio.exp.write_triggermarker_stats(tm_array, idx_keep, idx_outlier, idx_zero, fn, **kwargs)¶
Write some stats about the triggermarker analyses to a .csv . Use kwargs to add some more information, like subject id, experiment, conditions, etc
Call example: pynibs.write_triggermarker_stats(tm_array, idx_keep, idx_outlier, idx_zero,
fn=f”{output_folder}/coil_stats.csv”,subject=subject_id, experiment=exp, cond=cond)
Parameters:¶
- tm_arraynp.ndarray
(N zaps * 4 * 4)
pynibs.expio.localite module¶
Functions to import data from Localite TMS Navigator
- pynibs.expio.localite.arrays_similar(tm_matrix, tm_matrix_post, pos_rtol=0, pos_atol=3.6, ang_rtol=0.1, ang_atol=0.1)¶
Compares angles and position for similarity.
Splitting the comparison into angles and position is angebracht, as the absolute tolereance (atol) should be different for angles (degree) and position (millimeter) comparisons.
- pynibs.expio.localite.get_instrument_marker(im_path)¶
- pynibs.expio.localite.get_marker(im_path, markertype)¶
Read instrument-marker and conditions from Neuronavigator .xml-file.
- pynibs.expio.localite.get_single_marker_file(im_path, markertype)¶
Read instrument-marker and conditions from Neuronavigator .xml-file.
- pynibs.expio.localite.get_tms_elements(xml_paths, verbose=False)¶
Read needed elements out of the tms-xml-file.
- Parameters
- Returns
coils_array (nparray of float [3xNx4x4]) – Coil0, coil1 and mean-value of N 4x4 coil-arrays
ts_tms_lst (list of int [N]) – Timestamps of valid tms-measurements
current_lst (list of int [N]) – Measured currents
idx_invalid (list of int) – List of indices of invalid coil positions (w.r.t. all timestamps incl invalid)
- pynibs.expio.localite.marker_is_empty(arr)¶
- pynibs.expio.localite.markers_are_empty(arr)¶
- pynibs.expio.localite.match_instrument_marker_file(xml_paths, im_path)¶
Assign right instrument marker condition to every triggermarker (get instrument marker out of file).
- pynibs.expio.localite.match_instrument_marker_string(xml_paths, condition_order)¶
Assign right instrument marker condition to every triggermarker (get instrument marker out of list of strings).
- pynibs.expio.localite.match_tm_to_im(tm_array, im_array, tms_time_arr, tms_cur_arr)¶
Match triggermarker with instrumentmarker and get index of best fitting instrumentmarker.
- pynibs.expio.localite.merge_exp_data_localite(subject, coil_outlier_corr_cond, remove_coil_skin_distance_outlier, coil_distance_corr, exp_idx=0, mesh_idx=0, drop_mep_idx=None, mep_onsets=None, cfs_data_column=None, channels=None, verbose=False, plot=False)¶
Merge the TMS coil positions (TriggerMarker) and the mep data into an experiment.hdf5 file.
- Parameters
subject (pyfempp.subject) – Subject object
exp_idx (str) – Experiment ID
mesh_idx (str) – Mesh ID
coil_outlier_corr_cond (bool) – Correct outlier of coil position and orientation (+-2 mm, +-3 deg) in case of conditions
remove_coil_skin_distance_outlier (bool) – Remove outlier of coil position lying too far away from the skin surface (+- 5 mm)
coil_distance_corr (bool) – Perform coil <-> head distance correction (coil is moved towards head surface until coil touches scalp)
drop_mep_idx (List of int or None) – Which MEPs to remove before matching.
mep_onsets (List of int or None (Default: None)) – If there are multiple .cfs per TMS Navigator sessions, onsets in [ms] of .cfs. E.g.: [0, 71186].
cfs_data_column (int or list of int) – Column(s) of dataset in .cfs file.
verbose (bool) – Plot output messages
plot (bool, optional, default: False) – Plot MEPs and p2p evaluation
- pynibs.expio.localite.merge_exp_data_rt(subject, coil_outlier_corr_cond, remove_coil_skin_distance_outlier, coil_distance_corr, cond=None, exp_idx=0, mesh_idx=0, drop_trial_idx=None, verbose=False, plot=False)¶
Merge the TMS coil positions (TriggerMarker) and the mep data into an experiment.hdf5 file.
- Parameters
subject (pynibs.subject) – Subject object
exp_idx (str) – Experiment ID
mesh_idx (str) – Mesh ID
coil_outlier_corr_cond (bool) – Correct outlier of coil position and orientation (+-2 mm, +-3 deg) in case of conditions
cond (string) – Which condition to analyse
remove_coil_skin_distance_outlier (bool) – Remove outlier of coil position lying too far away from the skin surface (+- 5 mm)
coil_distance_corr (bool) – Perform coil <-> head distance correction (coil is moved towards head surface until coil touches scalp)
drop_trial_idx (List of int or None) – Which MEPs to remove before matching.
verbose (bool) – Plot output messages
plot (bool, optional, default: False) – Plot MEPs and p2p evaluation
- pynibs.expio.localite.read_coil(xml_ma)¶
Read coil-data from xml element.
- Parameters
xml_ma (xml-element) – Coil data
- Returns
coil – Coil elements
- Return type
nparray of float [4x4]
- pynibs.expio.localite.read_triggermarker_localite(fn_xml)¶
Read instrument-marker and conditions from neuronavigator .xml-file.
- Parameters
fn_xml (str) – Path to TriggerMarker.xml file (e.g. Subject_0/Sessions/Session_YYYYMMDDHHMMSS/TMSTrigger/TriggerMarkers_Coil1_YYYYMMDDHHMMSS.xml)
- Returns
- m_nnavndarray of float [4x4xN]
Neuronavigation coordinates of N stimuli (4x4 matrices)
- didtndarray of float [N]
Rate of change of coil current in (A/us)
- stim_intndarray of float [N]
Stimulator intensity in (%)
- descrlist of str [N]
Labels of the instrument-marker-conditions
- rec_timelist of str [N]
Recording time in ms
- Return type
list of
pynibs.expio.visor module¶
Functions to import data from ANT Visor 2 / ANT EEG software go here
- pynibs.expio.visor.filter_emg(emg, fs)¶
Filter emg signals
- pynibs.expio.visor.get_cnt_data(fn, channels='all', trigger_val='1', max_duration=10, fn_hdf5=None, path_hdf5=None, verbose=False, return_data=False)¶
Reads ANT .cnt EMG/EEG data file and chunks timesieries into triggerN - trigggerN+1 Can directly write the zaps into hdf5 if argument is provided. Starting with the first trigger and ending with get_sample_count()-1
- Parameters
fn (str) – .cnt Filename
channels (str | int | list of int | list of str) – Which channel(s) to return. Default: all. Can be channel number(s) or channel name(s).
trigger_val (str) – Trigger value to read as zap trigger. Default: ‘1’
max_duration (int) – Maximum duration in [s] per chunk. Rest is dropped.
fn_hdf5 (str, optional, default: None) – If given, cnt data is written into hdf5 file under “path_hdf5” as pandas dataframe with column name “qoi_name” and nothing is returned. Default: None
path_hdf5 (str, optional, default: None) – If fn_hdf5, path of pandas dataframe where the data is saved (e.g. “/phys_data/raw/EEG”)
verbose (bool) – Some verbosity messages (default: False)
return_data (bool) – Return data as list of np.array
- Returns
data_lst – List of EEG/EMG data. Only returned if fn_hdf5 is not None
- Return type
list of np.ndarray with shape=(samples,channels), optional
- pynibs.expio.visor.get_instrument_marker(im_path, verbose=False)¶
Return all instrument markers from visor .cnt file Coordinate system in raw ANT space (NLR) defined as:
origin: intersection between line of ear fiducials and nasion x-axis: origin -> nasion y-axis: origin -> left ear z-axis: origin -> superior
- pynibs.expio.visor.merge_exp_data(subject, exp_id=0, mesh_idx=0, verbose=False)¶
Merges all experimental data from visor experiment into one .hdf5 file
- Parameters
- Returns
<File> – File containing the stimulation and physiological data as pandas dataframes: - “stim_data”: Stimulation parameters (e.g. coil positions, etc.) - “phys_data/info/EMG”: Information about EMG data recordings (e.g. sampling frequency, etc.) - “phys_data/info/EEG”: Information about EEG data recordings (e.g. sampling frequency, etc.) - “phys_data/raw/EMG”: Raw EMG data - “phys_data/raw/EEG”: Raw EEG data - “phys_data/postproc/EMG”: Post-processed EMG data (e.g. filtered, p2p, etc.) - “phys_data/postproc/EEG”: Post-processed EEG data (e.g. filtered, p2p, etc.)
- Return type
.hdf5 file

