SciPy

pynibs.expio package

Submodules

pynibs.expio.Mep module

class pynibs.expio.Mep.Mep(intensities, mep, intensity_min_threshold=None, mep_min_threshold=None)

Bases: object

Mep object.

fun

Function type to fit data with (pynibs.sigmoid / pynibs.exp / pynibs.linear).

Type:

function

fun_sig

Best fitting equivalent sigmoidal function (added by self.add_sigmoidal_bestfit()).

Type:

function

popt

(N_para) Fitted optimal function parameters.

Type:

np.ndarray of float

popt_sig
  1. Best fitting parameters x0, r, and amp of equivalent sigmoidal function.

Type:

np.ndarray of float

copt

(N_para, N_para) covariance matrix of fitted parameters.

Type:

np.ndarray of float

pstd

(N_para) Standard deviation of fitted parameters.

Type:

np.ndarray of float

fit

Gmodel object instance of parameter fit.

Type:

object instance

x_limits
  1. Minimal and maximal value of intensity data.

Type:

np.ndarray of float

y_limits
  1. Minimal and maximal value of mep data.

Type:

np.ndarray of float

mt

Motor threshold (MEP > 50 uV), evaluated from fitted curve, added after fitting.

Type:

float

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.

Parameters:
  • x (np.ndarray of float) – (N_x) Function arguments.

  • p (tuple of float) – Function parameters.

Returns:

y – (N_x) Function values.

Return type:

np.ndarray of float

eval_fun_sig(x, p)

Evaluating optimally fitted sigmoidal function with optimal parameters in points x.

Parameters:
  • x (np.ndarray of float) – (N_x) Function arguments.

  • p (tuple of float) – Function parameters.

Returns:

y – (N_x) Function values.

Return type:

np.ndarray of float

eval_opt(x)

Evaluating fitted function with optimal parameters in points x.

Parameters:

x (np.ndarray of float) – (N_x) Function arguments.

Returns:

y – (N_x) Function values.

Return type:

np.ndarray of float

eval_uncertainties(x, sigma=1)

Evaluating approximated uncertainty interval around fitted distribution.

Parameters:
  • x (np.ndarray of float) – (N_x) Function values where uncertainty is evaluated.

  • sigma (float, default: 1) – Standard deviation of parameters taken into account when evaluating uncertainty interval.

Returns:

  • y_min (np.ndarray of float) – (N_x) Lower bounds of y-values.

  • y_max (np.ndarray 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 (np.ndarray of float, optional) – Initial guess of parameter values.

Notes

Additional attributes:

Mep.poptnp.ndarray of float

(N_para) Fitted optimal function parameters.

Mep.coptnp.ndarray of float

(N_para, N_para) Covariance matrix of fitted parameters.

Mep.pstdnp.ndarray 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:
  • p0 (np.ndarray of float, optional) – Initial guess of parameter values.

  • constraints (dict, optional) – Dictionary with parameter names as keys and [min, max] values as constraints.

  • fun (list of functions, optional) – Functions to incorporate in the multistart fit (e.g. [pynibs.sigmoid, pynibs.exp0, pynibs.linear]).

Notes

Add Attributes:

Mep.poptnp.ndarray of float

(N_para) Best fitted optimal function parameters.

Mep.coptnp.ndarray of float

(N_para, N_para) Covariance matrix of best fitted parameters.

Mep.pstdnp.ndarray 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. If ``fun == None`, the optimal function is plotted.

Parameters:
  • label (str) – Plot title.

  • sigma (float, default: 3) – Factor of standard deviations the uncertainty of the fit is plotted with.

  • plot_samples (bool, default: True) – Plot sampling curves of the fit in the uncertainty interval.

  • show_plot (bool, default: False) – Show or hide plot window (TRUE / FALSE).

  • fname_plot (str, default: '') – Filename of plot showing fitted data (with .png extension).

  • ylim (list of float, optional) –

    1. Min and max values of y-axis.

  • fontsize_axis (int, default: 10) – Fontsize of axis numbers.

  • fontsize_legend (int, default: 10) – Fontsize of Legend labels.

  • fontsize_label (int, default: 10) – Fontsize of axis labels.

  • fontsize_title (int, default: 10) – Fontsize of title.

  • fun (str, default: None) – Which function to plot (None, sigmoid, exp, linear).

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 (np.ndarray of float) – (N_data) Independent variable the data is fitted on.

  • y (np.ndarray of float) – (N_data) Dependent data the curve is fitted through.

  • p0 (np.ndarray of float or list of float) – Initial guess of parameter values.

  • constraints (dict, optional) – Dictionary with parameter names as keys and [min, max] values as constraints.

  • verbose (bool, default: False) – Show output messages.

  • n_multistart (int, default: 100) – 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.

Parameters:
  • cutoff (float) – Cutoff frequency in [Hz].

  • fs (float) – Sampling frequency in [Hz].

  • order (int, default: 5) – Filter order.

Returns:

b, a – Numerator (b) and denominator (a) polynomials of the IIR filter.

Return type:

np.ndarray, np.ndarray

pynibs.expio.Mep.butter_lowpass_filter(data, cutoff, fs, order=5)

Applies Butterworth lowpass filter.

Parameters:
  • data (np.ndarray of float) – (N_samples) Input of the digital filter.

  • cutoff (float) – Cutoff frequency in [Hz].

  • fs (float) – Sampling frequency in [Hz].

  • order (int) – Filter order.

Returns:

y – (N_samples) Output of the digital filter.

Return type:

np.ndarray

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.ndarray 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 in Hz.

  • fn_plot (str, optional) – Filename of sweep to plot (.png). If None, plot is omitted.

Returns:

  • p2p (float) – Peak-to-peak value of input curve.

  • sweep_filt (np.ndarray 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.

Parameters:
  • sweep (np.ndarray of float) – (Nx1) Input curve.

  • start_mep (None) – Not used.

  • end_mep (None) – Not used.

  • tms_pulse_time (None) – Not used.

  • sampling_rate (None) – Not used.

Returns:

p2p – Peak-to-peak value of input curve.

Return type:

float

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.ndarray of float) – (Nx1) Input curve.

  • start_mep (float, default: 18) – Starttime in [ms] after TMS for MEP search window.

  • end_mep (float, default: 35) – Endtime in [ms] after TMS for MEP search 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:

float

pynibs.expio.Mep.dummy_fun(x, a)

Dummy function for congruence factor calculation.

pynibs.expio.Mep.exp(x, x0, r, y0)

Parametrized exponential function.

y = y_0 + e^{r(x-x_0)}

Parameters:
  • x (np.ndarray of float) – (N_x) X-values the function is evaluated in.

  • x0 (float) – Horizontal shift along the abscissa.

  • r (float) – Slope parameter (steepness).

  • y0 (float) – Offset parameter.

Returns:

y – Function value at x

Return type:

np.ndarray of float [N_x]

pynibs.expio.Mep.exp0(x, x0, r)

Parametrized exponential function w/o offset.

y = e^{r(x-x_0)}

Parameters:
  • x (np.ndarray of float) – (N_x) X-values the function is evaluated in.

  • x0 (float) – Horizontal shift along the abscissa.

  • r (float) – Slope parameter (steepness).

Returns:

y – (N_x) Function value at x.

Return type:

np.ndarray of float

pynibs.expio.Mep.exp0_log(x, x0, r)

Parametrized exponential function w/o offset.

y = e^{r(x-x_0)}

Parameters:
  • x (np.ndarray of float) – (N_x) X-values the function is evaluated in.

  • x0 (float) – Horizontal shift along the abscissa.

  • r (float) – Slope parameter.

Returns:

y – (N_x) Function value at x.

Return type:

np.ndarray of float

pynibs.expio.Mep.exp_log(x, x0, r, y0)

Parametrized exponential function (log).

y = y_0 + e^{r(x-x_0)}

Parameters:
  • x (np.ndarray of float) – (N_x) X-values the function is evaluated in.

  • x0 (float) – Horizontal shift along the abscissa.

  • r (float) – Slope parameter (steepness).

  • y0 (float) – y-offset parameter.

Returns:

y – (N_x) Function value at x.

Return type:

np.ndarray of float

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, start_mep=18, end_mep=35)

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, optional) – Which MEPs to remove before matching.

  • cfs_data_column (int or list of int, default: 0) – Column(s) of dataset in cfs file. +1 for .txt.

  • channels (list of str, optional) – Channel names.

  • time_format (str, 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, default: False) – Plot MEPs.

  • start_mep (float, default: 18) – Start of time frame after TMS pulse where p2p value is evaluated (in ms).

  • end_mep (float, default: 35) – End of time frame after TMS pulse where p2p value is evaluated (in ms).

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, N_stim, N_samples) Raw (unfiltered) MEP data.

  • mep_filt_data (np.ndarray of float) – (N_channel, N_stim, 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_pathstr

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, rng=None)

Creates random mep data using the 2 variability source model from Goetz et al. 2014 [1] together with a standard 3 parametric sigmoid function.

Parameters:
  • x (np.ndarray of float) – (n_x) Normalized stimulator intensities [0 … 1].

  • x0 (float, default: 0.5) – Location of turning point sigmoidal function.

  • r (float, default: 0.25) – Steepness of sigmoidal function.

  • amp (float, default: 1.0) – Saturation amplitude of sigmoidal function.

  • sigma_x (float, default: 0.1) – Standard deviation of additive x variability source.

  • sigma_y (float, default: 0.1) – Standard deviation of additive y variability source.

  • y0 (float, default: 1e-2) – y-offset.

  • seed (int, optional) – Seed to use.

  • rng (numpy._generator.Generator, optional) – An already initialized random number generator that will be used instead of intializing a new one with seed.

Returns:

mep – (n_x) Motor evoked potential values

Return type:

np.ndarray of float

References

[1]

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.

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 [1]. 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 (np.ndarray of float) – (n_x) Normalized stimulator intensities [0 … 1].

  • p1 (float, default: -5.0818) – First parameter of sigmoidal hilltype function.

  • p2 (float, default: 4.5323) – Second parameter of sigmoidal hilltype function.

  • p3 (float, default: 3.6466) – Third parameter of sigmoidal hilltype function.

  • p4 (float, default: 0.42639) – Fourth parameter of sigmoidal hilltype function.

  • p5 (float, default: 1.6665) – Fifth parameter of sigmoidal hilltype function.

  • mu_y_add (float, default: 10**-5.0818) – Mean value of additive y variability source.

  • mu_y_mult (float, default: -0.9645334) – Mean value of multiplicative y variability source.

  • mu_x_add (float, default: -0.68827324) – Mean value of additive x variability source.

  • sigma_y_add (float, default: 1.4739*1e-6) – Standard deviation of additive y variability source.

  • k (float, default: 0.39316) – Shape parameter of generalized extreme value distribution.

  • sigma2_y_mult (float, default: 2.2759*1e-2) – Standard deviation of multiplicative y variability source.

  • sigma2_x_add (float, default: 2.3671*1e-2) – Standard deviation of additive x variability source.

  • subject_variability (bool, 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, default: True) – Enable or disable trial-to-trial variability. Disabling it will result in ideal IO curves w/o noise.

Returns:

mep – (n_x) Motor evoked potential values in mV.

Return type:

np.ndarray of float

References

[1]

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.

pynibs.expio.Mep.get_time_date(cfs_paths)

Get time and date of the start of the recording out of .cfs file.

Parameters:

cfs_paths (str) – Path to .cfs mep file.

Returns:

time_date – Date and time.

Return type:

str

pynibs.expio.Mep.linear(x, m, n)

Parametrized linear function.

y = mx+n

Parameters:
  • x (np.ndarray of float) – (N_x) X-values the function is evaluated in.

  • m (float) – Slope parameter.

  • n (float) – Y-offset.

Returns:

y – (N_x) Function value at argument x.

Return type:

np.ndarray of float

pynibs.expio.Mep.linear_log(x, m, n)

Parametrized log linear function.

y = mx+n

Parameters:
  • x (np.ndarray of float) – (N_x) X-values the function is evaluated in.

  • m (float) – Slope parameter (steepness).

  • n (float) – Y-offset.

Returns:

y – (N_x) Function value at x.

Return type:

np.ndarray of float

pynibs.expio.Mep.read_biosig_emg_data(fn_data, include_first_trigger=False, type='cfs')

Reads EMG data from a biosig file.

Parameters:
  • fn_data (str) – Path to the biosig file.

  • include_first_trigger (bool, default: False) – Whether to include the first trigger event in the data (default: False).

  • type (str, default: 'cfs') – Type of the biosig file.

Returns:

  • emg_data (np.ndarray) – (num_sweeps, num_channels, samples_per_sweep) EMG data with shape.

  • time_diff_list (list) – Time differences between trigger events in seconds.

  • num_sweeps (int) – Number of sweeps in the EMG data.

  • num_channels (int) – Number of channels in the EMG data.

  • samples_per_sweep (int) – Number of samples per sweep in the EMG data.

  • sampling_rate (int) – Sampling rate of the EMG data.

pynibs.expio.Mep.sigmoid(x, x0, r, amp)

Parametrized sigmoid function.

y = \frac{amp}{1+e^{-r(x-x_0)}}

Parameters:
  • x (np.ndarray of float) – (N_x) X-values the function is evaluated in.

  • x0 (float) – Horizontal shift along the abscissa.

  • r (float) – Slope parameter (steepness).

  • amp (float) – Maximum value the sigmoid converges to.

Returns:

y – (N_x) Function value at argument x.

Return type:

np.ndarray of float

pynibs.expio.Mep.sigmoid4(x, x0, r, amp, y0)

Parametrized sigmoid function with 4 parameters.

y = y_0 + \frac{amp - y_0}{1+e^{-r(x-x_0)}}

Parameters:
  • x (np.ndarray of float) – (N_x) x-values the function is evaluated in.

  • x0 (float) – Horizontal shift along the abscissa.

  • r (float) – Slope parameter (steepness).

  • amp (float) – Maximum value the sigmoid converges to.

  • y0 (float) – Offset value of the sigmoid.

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.

y = \log\left(y_0 + \frac{amp - y_0}{1+e^{-r(x-x_0)}}\right)

Parameters:
  • x (np.ndarray of float) – (N_x) X-values the function is evaluated in.

  • x0 (float) – Horizontal shift along the abscissa.

  • r (float) – Slope parameter (steepness).

  • amp (float) – Maximum value the sigmoid converges to (upper saturation).

  • y0 (float) – Y-offset value of the sigmoid.

Returns:

y – (N_x) Function value at argument x.

Return type:

np.ndarray of float

pynibs.expio.Mep.sigmoid_log(x, x0, r, amp)

Parametrized log transformed sigmoid function.

y = \log\left(\frac{amp}{1+e^{-r(x-x_0)}}\right)

Parameters:
  • x (np.ndarray of float) – (N_x) x-values the function is evaluated in.

  • x0 (float) – Horizontal shift along the abscissa.

  • r (float) – Slope parameter (steepness).

  • amp (float) – Maximum value the sigmoid converges to.

Returns:

y – (N_x) Function value at argument x.

Return type:

np.ndarray of float

pynibs.expio.brainsight module

Functions to import data from Rogue Research Brainsight neuronavigation systems

class pynibs.expio.brainsight.BrainsightCSVParser

Bases: object

Parser for Brainsight CSV files.

current_state

The current state of the parser.

Type:

BrainsightCSVParser.State

header_file

The file header.

Type:

str

header_data

The header data.

Type:

list of str

data

The parsed data rows.

Type:

list of list of str

check_state_transition(line)

Checks the state transition based on the given line.

parse_line(line)

Parses a line and updates the corresponding attributes.

class State

Bases: object

DATA = 3
DATA_HEADER = 2
FILE_HEADER = 0
FIN = 4
SKIPPING = 1
check_state_transition(line)

Checks the state transition based on the given line.

Parameters:

line (str) – The line to check.

parse_line(line)

Parses a line and updates the corresponding attributes.

Parameters:

line (str) – The line to parse.

pynibs.expio.brainsight.create_merged_nnav_emg_file_brainsight(fn_brainsight_nnav_info, fn_emg_info, fn_out, p2p_window_start=18, p2p_window_end=35)

Creates a merged file containing TMS coil positions and EMG data from Brainsight information.

Parameters:
  • fn_brainsight_nnav_info (str) – File path of the Brainsight nnav coil information.

  • fn_emg_info (str) – File path of the EMG information.

  • fn_out (str) – File path of the output merged file.

  • p2p_window_start (int, default: 18) – Start of the time frame after TMS pulse where p2p value is evaluated (in ms).

  • p2p_window_end (int, default: 35) – End of the time frame after TMS pulse where p2p value is evaluated (in ms).

pynibs.expio.brainsight.merge_exp_data_brainsight(subject, exp_idx, mesh_idx, coil_outlier_corr_cond=False, remove_coil_skin_distance_outlier=True, coil_distance_corr=True, average_emg_data_from_same_condition=False, verbose=False, plot=False, start_mep=18, end_mep=35)

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, default: False) – Correct outlier of coil position and orientation (+-2 mm, +-3 deg) in case of conditions.

  • remove_coil_skin_distance_outlier (bool, default: True) – Remove outlier of coil position lying too far away from the skin surface (+- 5 mm).

  • coil_distance_corr (bool, default: True) – Perform coil <-> head distance correction (coil is moved towards head surface until coil touches scalp).

  • average_emg_data_from_same_condition (bool, default: False) – Flag indicating whether to average EMG data from the same condition. Only meaningful in conjunction with ‘coil_distance_correction’, which averages the coil position within a condition.

  • verbose (bool, default: False) – Plot output messages.

  • plot (bool, default: False) – Plot MEPs and p2p evaluation.

  • start_mep (float, default: 18) – Start of time frame after TMS pulse where p2p value is evaluated (in ms).

  • end_mep (float, default: 35) – End of time frame after TMS pulse where p2p value is evaluated (in ms).

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.

Parameters:

fn (str) – Filename of output file.

Returns:

m_nnav – (4, 4, N_targets) Tensor containing the 4x4 matrices with coil orientation and position.

Return type:

np.ndarray of float

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 (np.ndarray of float) –

  • (4

  • 4

  • N_targets)

  • position. (Tensor containing the 4x4 matrices with coil orientation and) –

  • fn_out (str) – Filename of output file.

  • names (list of str, optional) – Target names (if None they will be numbered by their order).

  • overwrite (bool, 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.

Parameters:

fname (str) – Filename of .vhdr info file.

Returns:

channel_names – List containing the channel names.

Return type:

list of str

pynibs.expio.brainvis.read_sampling_frequency(fname)

Reads the sampling frequency from .vhdr (info) file, which is recorded during EEG.

Parameters:

fname (str) – Filename of .vhdr info file.

Returns:

sampling_frequency – Sampling frequency.

Return type:

float

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 (pynibs.subject.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:
  • mep (pynibs.expio.mep.Mep) – Mep.

  • p0 (float) – Initial guess for the parameters of the sigmoidal function.

  • constraints (dict, optional) – Dictionary with parameter names as keys and [min, max] values as constraints.

Returns:

mep – Updated Mep object class instance with the following attributes.

Return type:

object

Notes

Adds Attributes:

Mep.fun_sigfunction

Sigmoid function

Mep.popt_signp.ndarray of float
  1. Parameters of sigmoid function

pynibs.expio.exp.calc_outlier(coords, dev_location, dev_radius, target=None, fn_out=None, verbose=True)

Computes median coil position and angle, identifies outliers, plots neat figure. Returns a list of idx that are not outliers

Parameters:
  • coords (np.ndarray) – (4, 4, n_zaps)

  • dev_location (float) – Max allowed location deviation.

  • dev_radius (float) – Max allowed radius deviation.

  • target (np.ndarray, optional) – (4, 4) matrix with target coordinates.

  • fn_out (string, optional) – Output filename.

  • verbose (bool, default: True) – Flag indicating verbosity.

Returns:

list of int, list of int, list of int

Return type:

idx_keep, idx_zero, idx_outlier

pynibs.expio.exp.cfs2hdf5(fn_cfs, fn_hdf5=None)

Converts EMG data included in .cfs file to .hdf5 format.

Parameters:
  • fn_cfs (str) – Filename of .cfs file.

  • fn_hdf5 (str, optional) – Filename of .hdf5 file (if not provided, a file with same name as fn_cfs will be created with .hdf5 extension).

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) – List of dictionaries containing the experimental data.

  • fn_exp (str, optional) – Filename (incl. path) of experimental .csv file.

  • fn_exp_out (str, optional) – Filename (incl. path) of distance corrected experimental .csv file.

  • fn_geo_hdf5 (str, optional) – Filename (incl. path) of geometry mesh file (.hdf5).

  • remove_coil_skin_distance_outlier (bool, default: False) – Remove coil positions, which are more than +- 2 mm located from the zero mean skin surface.

  • fn_plot (str, optional) – Folder where plots will be saved in (fn_geo_hdf5 folder).

  • min_dist (int, default: -5) – Ignored.

  • max_dist (int, default: 2) – 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 (np.ndarray of float) – (4, 4) or (4, 4, n_mat) Tensor containing matsimnibs matrices.

  • fn_mesh_hdf5 (str) – .hdf5 file containing the head mesh.

  • distance (float or list of float, default: 0) – Target distance in (mm) between coil and head due to hair layer. All coil positions are moved to this distance. If distance is list: len(distance) == n_mat.

  • remove_coil_skin_distance_outlier (bool, default: False) – Remove coil positions, which are more than +- 6 mm located from the skin surface.

Returns:

matsimnibs – (4, 4, n_mat) Tensor containing matsimnibs matrices with distance corrected coil positions.

Return type:

np.ndarray of float

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) – List of dictionaries containing the experimental data.

  • fn_exp (str, optional) – Filename (incl. path) of experimental .csv file.

  • fn_exp_out (str, optional) – Filename (incl. path) of corrected experimental .csv file.

  • outlier_angle (float, default: 5.) – Coil orientation outlier “cone” around axes in +- deg. All zaps with coil orientations outside of this cone are removed.

  • outlier_loc (float, 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.

pynibs.expio.exp.combine_nnav_ft(xml_paths, behavior_paths, im, coil_sn, nii_exp_path, nii_conform_path, patient_id, drop_trial_idx, nnav_system, cond, mesh_approach='headreco', temp_dir=None, plot=False)

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

  • behavior_paths (list of str) – Paths to .csv ft file

  • 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 fts to remove before matching.

  • temp_dir (str, 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) – behavioral outcome

  • mesh_approach (str, default: "headreco") – Approach the mesh is generated with (“headreco” or “mri2mesh”)

  • plot (bool, 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.combine_nnav_mep(xml_paths, cfs_paths, im, coil_sn, nii_exp_path, nii_conform_path, patient_id, tms_pulse_time, drop_mep_idx, mep_onsets, nnav_system, mesh_approach='headreco', temp_dir=None, cfs_data_column=0, channels=None, plot=False, start_mep=18, end_mep=35)

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.

  • cfs_paths (list of str) – Paths to .cfs mep file.

  • 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) – If there are multiple .cfs per TMS Navigator sessions, onsets in [ms] of .cfs. E.g.: [0, 71186].

  • nnav_system (str) – Type of neuronavigation system (“Localite”, “Visor”).

  • mesh_approach (str, default: "headreco") – Approach the mesh is generated with (“headreco” or “mri2mesh”).

  • temp_dir (str, default: None (fn_exp_mri_nii folder)) – Directory to save temporary files (transformation .nii and .mat files) (fn_exp_mri_nii folder).

  • cfs_data_column (int or list of int, default: 0) – Column(s) of dataset in .cfs file.

  • channels (list of str, optional) – Channel names.

  • plot (bool, default: False) – Plot MEPs and p2p evaluation.

  • start_mep (float, default: 18) – Start of time frame after TMS pulse where p2p value is evaluated (in ms).

  • end_mep (float, default: 35) – End of time frame after TMS pulse where p2p value is evaluated (in ms).

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.combine_nnav_rt(xml_paths, behavior_paths, im, coil_sn, nii_exp_path, nii_conform_path, patient_id, drop_trial_idx, nnav_system, cond, mesh_approach='headreco', temp_dir=None, plot=False)

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.

  • behavior_paths (list of str) – Paths to .cfs mep file.

  • 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.

  • nnav_system (str) – Type of neuronavigation system (“Localite”, “Visor”).

  • cond (str) – Condition name in data_path.

  • mesh_approach (str, default: "headreco") – Approach the mesh is generated with (“headreco” or “mri2mesh”).

  • temp_dir (str, optional) – Directory to save temporary files (transformation .nii and .mat files) (fn_exp_mri_nii folder).

  • plot (bool, 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/
                |--coil_sn
                |--current
                |--date
                |--time_diff
                |--time_mep
                |--time_tms
                |--ts_tms
                |--coil0      # <- all coil0_** columns
                |--coil1      # <- all coil1_** columns
                |--coil_mean  # <- all coil_mean_** columns

All columns not found in experiment.csv are ignored (and a warning is thrown).

Parameters:
  • fn_csv (str) – experiment.csv filename.

  • fn_hdf5 (str) – experiment.hdf5 filename. File is created if not existing.

  • overwrite_arr (bool, default: True.) – Overwrite existing arrays. Otherwise: fail.

  • verbose (bool, default: False) – Flag indicating verbosity.

pynibs.expio.exp.get_cnt_infos(fn_cnt)

Read some meta information from .cnt file.

Parameters:

fn_cnt (str) – Path to the .cnt file.

Returns:

d – A dictionary containing the meta-information.

Return type:

dict

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, default: 'simnibs') – Atm only possible source: 'simnibs'.

  • target_system (str, optional) – tmsnavigator, visor, brainsight.

Returns:

flip_m – (4, 4) Flipped matrix.

Return type:

np.ndarray

pynibs.expio.exp.get_coil_sn_lst(fn_coil)

Extract coil serial numbers from a list of coil paths.

Parameters:

fn_coil (list of list of str) – List containing coil path information.

Returns:

coil_sn_lst – A list of coil serial numbers extracted from the provided coil paths.

Return type:

list of str

pynibs.expio.exp.get_csv_matrix(dictionary)

Process the given dictionary to create a 4x4 matrix for each coil specified.

Parameters:

dictionary (dict) – The input dictionary containing the data.

Returns:

The input dictionary updated with the newly created matrices and redundant keys removed.

Return type:

dict

pynibs.expio.exp.get_ft_data_from_csv(behavior_fn, cond, drop_trial_idx=None, startatzero=True)

Reads trial data from csv file.

Parameters:
  • behavior_fn (str) – Filename with columns: ‘TMS_onset_time’, ‘p_p_amp’, ‘ct’. TMS_onset_time in 0.1 ms; p_p_amp in ms.

  • cond (str) – behavioral output

  • drop_trial_idx (list of int, optional) – ‘trialnum’ to remove.

  • startatzero (bool, default: True) – Shift onset_time axis to zero.

Returns:

  • ft (list of float)

  • TMS_onsets (list of float) – in [ms]

  • mean_isi (tuple of int) – in [s]

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, default: 1) – Resting motor threshold to be corrected.

  • roi (str, default: 'midlayer_lh_rh') – Name of roi. Expected to sit in mesh['/data/midlayer/roi_surface/'].

  • verbose (bool, default: False) – Flag indicating verbosity.

Returns:

rmt_e_corr – Adjusted stimulation intensity for target2.

Return type:

float

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, default: 1) – Resting motor threshold, which will be corrected.

  • verbose (bool, default: False) – Flag indicating verbosity.

Returns:

rmt_e_corr – Adjusted stimulation intensity for target2.

Return type:

float

pynibs.expio.exp.get_intensity_stokes(mesh, target1, target2, spat_grad=3, rmt=0, scalp_tag=1005, roi=None, verbose=False)

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, default: 3) – Spatial gradient.

  • rmt (float, default: 0) – Resting motor threshold, which will be corrected.

  • scalp_tag (int, default: 1005) – Tag in the mesh where the scalp is to be set.

  • roi (np.ndarray, optional) – (3,N) Array of nodes to project targets onto.

  • verbose (bool, default: False) – Print verbosity information.

Returns:

rmt_stokes – Adjusted stimulation intensity for target2.

Return type:

float

pynibs.expio.exp.get_patient_id(xml_path)

Read patient-ID.

Parameters:

xml_path (str) – Path to coil0-file.

Returns:

xml_pd.find(‘patientID’).text – ID of patient.

Return type:

str

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’.

  • cond (str) – Which condition to choose from .csv file.

  • drop_trial_idx (list of int, optional) – ‘trialnum’ to remove.

  • only_corr (bool, default: True) – Only return trials with correct responses.

  • startatzero (bool, 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.

Parameters:

fn_matsimnibs (str) – Filename of .txt file the matsimnibs matrices are stored in.

Returns:

matsimnibs – (4, 4) or (4, 4, n_mat) Tensor containing matsimnibs matrices.

Return type:

np.ndarray of float

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, 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 intervals. If 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 timestamps.

pynibs.expio.exp.nnav2simnibs(fn_exp_nii, fn_conform_nii, m_nnav, nnav_system, mesh_approach='headreco', fiducials=None, orientation='RAS', fsl_cmd=None, target='simnibs', temp_dir=None, rem_tmp=False, verbose=True)

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, 4, 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, default: "headreco") – Approach the mesh is generated with ("headreco" or "mri2mesh").

  • fiducials (np.ndarray of float, optional) – (3, 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).

  • orientation (str, default: 'RAS') – Orientation convention ('RAS' or 'LPS'), can be read from neuronavigation .xml file under coordinateSpace="RAS".

  • fsl_cmd (str, optional) – bash command to start FSL environment.

  • target (str, default: 'simnibs') – Either transform to 'simnibs' or to 'nnav' space.

  • temp_dir (str, optional) – Directory to save temporary files (transformation .nii and .mat files) (fn_exp_mri_nii folder).

  • rem_tmp (bool, default: False) – Remove temporary files from registration.

  • verbose (bool, default: True) – Print output.

Returns:

m_simnibs – (4, 4, N) Transformed coil positions.

Return type:

np.ndarray of float

pynibs.expio.exp.outliers_mask(data, m=2.0)

Generate a mask to identify outliers in a dataset using the Median Absolute Deviation (MAD) method.

Parameters:
  • data (array-like) – Input data for which outliers are to be detected.

  • m (float, default: 2.0) – The threshold multiplier for identifying outliers.

Returns:

mask – A boolean mask with the same shape as ‘data’ where True indicates outliers.

Return type:

array-like

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.

Parameters:

csv_path (str) – Path to .csv-file.

Returns:

dict_lst – Field name of the .csv-file as the key.

Return type:

dict of list

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:
  • fname_results_conditions (str) – Filename of results_conditions.csv file.

  • fname_simpos (str) – Filename of simPos.csv file.

  • filter_bad_trials (bool, default: False) – If true, some filtering will be done to exclude erroneous data.

  • drop_idx (list, optional) – Indices of trials to drop.

Returns:

  • positions_all (list of np.ndarrays of float) – (N_zaps, (4, 4)) List of position matrices of TMS coil, formatted in simnibs style.

    \begin{bmatrix}
 | & | & | &  |   \\
 x & y & z & pos  \\
 | & | & | &  |   \\
 0 & 0 & 0 &  1   \\
\end{bmatrix}

  • 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.ndarray of float) – (N_zaps) Stimulator intensities corresponding to each zap.

  • fails_idx (np.ndarray) – (N_fails_idx, 1) Which trials were dropped through filtering (only if filter_bad_trials).

pynibs.expio.exp.save_matsimnibs_txt(fn_matsimnibs, matsimnibs)

Saving matsimnibs matrices in .txt file.

Parameters:
  • fn_matsimnibs (str) – Filename of .txt file the matsimnibs matrices are stored in.

  • matsimnibs (np.ndarray of float) – (4, 4) or (4, 4, n_mat) Tensor containing matsimnibs matrices.

Returns:

<File> – Textfile containing the matsimnibs matrices.

Return type:

.txt file

pynibs.expio.exp.sort_by_condition(exp, conditions_selected=None)

Sort experimental dictionary from experimental.csv into list by conditions.

Parameters:
  • exp (dict or list of dict) – Dictionary containing the experimental data information.

  • conditions_selected (str or list of str, optional) – List of conditions returned by the function (in this order), the others are omitted, If None, all conditions are returned.

Returns:

exp_cond – List of dictionaries containing the experimental data information sorted by condition.

Return type:

list of dict

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 (bool, default: True) – Shall returns be in alphabetically or original order.

  • conditions_selected (list of str, optional) – List of conditions returned by the function (in this order), the others are omitted.

  • data (tuple of data indexed by condition) – (N_data, N_zaps, m) Data to sort.

Returns:

  • cond_labels (list of str) – (N_cond) Labels of conditions.

  • data_sorted (tuple of sorted data) – (N_cond, N_data, N_zaps, 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.

y = ax^2+bx+c

Parameters:
  • x (np.ndarray of float) – (N_x) X-values the function is evaluated in.

  • a (float) – Slope parameter of x^2.

  • b (float) – Slope parameter of x.

  • c (float) – Offset parameter.

Returns:

y – (N_x) Function value at argument x.

Return type:

np.ndarray of float

pynibs.expio.exp.toRAS(fn_in, fn_out)

Transforming MRI .nii image to RAS space.

Parameters:
  • fn_in (str) – Filename of input image .nii file.

  • fn_out (str) – Filename of output image .nii file in RAS space.

Returns:

<File> – .nii image in RAS space with filename fn_out.

Return type:

.nii file

pynibs.expio.exp.write_csv(csv_output_path, dict_lst)

Write dictionary into .csv-file.

Parameters:
  • csv_output_path (str) – Path to output-file.

  • dict_lst (list of dict) – Fields of the .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.

Parameters:
  • tm_array (np.ndarray) – (N_zaps, 4, 4) The input array containing the triggermarker data.

  • idx_keep (list) – List of indices to keep in the array for calculation.

  • idx_outlier (list) – List of outlier indices in the array.

  • idx_zero (list) – List of zero indices in the array.

  • fn (str) – File name (including path) for the CSV file to be written.

  • kwargs (dict, optional) – Additional information to be written to the CSV file. Example: subject=subject_id, experiment=experiment_name.

Example

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 advisable, as the absolute tolerance (atol) should be different for angles (degree) and position (millimeter) comparisons.

Parameters:
  • tm_matrix (array-like) – (4, 4) TMS Navigator trigger marker or instrument marker array.

  • tm_matrix_post (array-like) – (4, 4) TMS Navigator trigger marker or instrument marker array.

  • pos_rtol (float, default: 0) – Relative tolerance for position comparison.

  • pos_atol (float, default: 3.6) – Absolute tolerance for position comparison in millimeters.

  • ang_rtol (float, default: 0.1) – Relative tolerance for angle comparison in degrees.

  • ang_atol (float, default: 0.1) – Absolute tolerance for angle comparison in degrees.

Returns:

next_same – True if the position and angle differences between tm_matrix and tm_matrix_post are within the specified tolerances, False otherwise.

Return type:

bool

pynibs.expio.localite.get_instrument_marker(im_path)

Wrapper function to read instrument-marker and conditions from Neuronavigator .xml-file.

This function allows you to read instrument-marker data from either a single file or a list of files. If a single file path is provided, the function reads the instrument-marker data from the specified file. If a list of file paths is provided, the function reads instrument-marker data from each file and selects the appropriate marker for each timestamp.

Parameters:

im_path (str or list of str) – Path to the instrument-marker file(s) or a list of paths if multiple files are provided.

Returns:

  • im_array (np.ndarray of float) – A consolidated array of instrument-marker matrices with shape (N, 4, 4), where N is the number of instrument-marker matrices across all files.

  • marker_descriptions (list of str) – Labels of the marker conditions.

  • marker_times (list of float) – Onset times.

pynibs.expio.localite.get_marker(im_path, markertype)

Read instrument-marker and conditions from Neuronavigator .xml-file.

Parameters:
  • im_path (str or list of str) – Path to instrument-marker-file.

  • markertype (str) – One of [‘TriggerMarker’,’InstrumentMarker’].

Returns:

  • im_array (np.ndarray of float) – (M, 4, 4) Instrument marker matrices.

  • marker_descriptions (list of str) – Labels of the marker conditions.

  • marker_times (list of float) – Onset times.

pynibs.expio.localite.get_single_marker_file(im_path, markertype)

Read instrument-marker and conditions from Neuronavigator .xml-file.

Parameters:
  • im_path (str or list of str) – Path to instrument-marker-file.

  • markertype (str) – One of [‘TriggerMarker’,’InstrumentMarker’].

Returns:

  • im_array (np.ndarray of float) – (M, 4, 4) Instrument marker matrices.

  • marker_descriptions (list of str) – Labels of the marker conditions.

  • marker_times (list of float) – Onset times.

pynibs.expio.localite.get_tms_elements(xml_paths, verbose=False)

Read needed elements out of the tms-xml-file.

Parameters:
  • xml_paths (list of str or str) – Paths to coil0-file and optionally coil1-file. If there is no coil1-file, use empty string.

  • verbose (bool, default: False) – Flag indicating verbosity.

Returns:

  • coils_array (np.ndarray of float) – (3, NX4, 4), 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).

Parameters:
  • xml_paths (list of str) – Paths to coil0-file and optionally coil1-file if there is no coil1-file, use empty string.

  • im_path (str) – Path to instrument-marker-file.

Returns:

  • coil_cond_lst (list of str) – Right conditions.

  • drop_idx (list of int) – Indices of trigger markers that were dropped.

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).

Parameters:
  • xml_paths (list of str) – Paths to coil0-file and optionally coil1-file if there is no coil1-file, use empty string.

  • condition_order (list of str) – Conditions in the right order.

Returns:

coil_cond_lst – Strings containing the right conditions. drop_idx : list of int

Indices of trigger markers that were dropped.

Return type:

list of str

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.

Parameters:
  • tm_array (np.ndarray of float) – (N, 4, 4) Mean-value of Nx4x4 coil matrices.

  • im_array (np.ndarray of float) – (M, 4, 4) Instrument-marker-matrices.

  • tms_time_arr (np.ndarray) – Array of TMS times in seconds.

  • tms_cur_arr (np.ndarray) – Array of TMS currents corresponding to `tms_time_arr`.

Returns:

  • im_index_lst (list of int) – Indices of best fitting instrument markers.

  • drop_idx (list of int) – Indices of trigger markers that were dropped.

pynibs.expio.localite.merge_exp_data_ft(subject, coil_outlier_corr_cond, remove_coil_skin_distance_outlier, coil_distance_corr, cond, 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) – 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 behavioral measurement 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 RTs and a running average over 10 trials.

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, start_mep=18, end_mep=35)

Merge the TMS coil positions (TriggerMarker) and the mep data into an experiment.hdf5 file.

Parameters:
  • subject (pynibs.subject.Subject) – Subject object.

  • 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).

  • exp_idx (str, default: 0) – Experiment ID.

  • mesh_idx (str, default: 0) – Mesh ID.

  • drop_mep_idx (List of int, optional) – Which MEPs to remove before matching.

  • mep_onsets (List of int, optional) – 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, optional) – Column(s) of dataset in .cfs file.

  • channels (list of str, optional) – List of channel names.

  • verbose (bool, default: false) – Flag to indicate verbosity.

  • plot (bool, default: False) – Plot MEPs and p2p evaluation.

  • start_mep (float, default: 18) – Start of time frame after TMS pulse where p2p value is evaluated (in ms).

  • end_mep (float, default: 35) – End of time frame after TMS pulse where p2p value is evaluated (in ms).

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) – Subject object.

  • 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).

  • cond (string, optional) – Which condition to analyse.

  • exp_idx (str, default: 0) – Experiment ID.

  • mesh_idx (str, default: 0) – Mesh ID.

  • drop_trial_idx (List of int, optional) – Which MEPs to remove before matching.

  • verbose (bool, default: False) – Flag indicating verbosity.

  • plot (bool, default: False) – Plot RTs and a running average over 10 trials.

pynibs.expio.localite.read_coil(xml_ma)

Read coil-data from xml element.

Parameters:

xml_ma (xml-element) – Coil data.

Returns:

coil – (4, 4) Coil elements.

Return type:

np.ndarray of float

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_nnavnp.ndarray of float

(M, 4, 4) Neuronavigation coordinates of N stimuli (4x4 matrices).

didtnp.ndarray of float
  1. Rate of change of coil current in (A/us).

stim_intnp.ndarray of float
  1. Stimulator intensity in (%).

descrlist of str
  1. Labels of the instrument-marker-conditions.

rec_timelist of str
  1. 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.

Parameters:
  • emg (list of np.ndarray) – (n_stimuli), Raw EMG data. Each list entry contains a np.ndarray of size [n_samples x n_channel]. Each channel is filtered in the same way.

  • fs (float) – Sampling frequency.

Returns:

emg_filt – (n_stimuli), Filtered EMG data.

Return type:

list of np.ndarray

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 timeseries into triggerN - trigggerN+1.

It 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) – Path to the .cnt file.

  • channels (str, int, list of int, or list of str, default: 'all') – Which channel(s) to return. Can be channel number(s) or channel name(s).

  • trigger_val (str, default: '1') – Trigger value to read as zap trigger.

  • max_duration (int, default: 10) – Maximum duration in [s] per chunk. Rest is dropped.

  • fn_hdf5 (str, optional) – If provided, the cnt data is written into an hdf5 file under “path_hdf5” as pandas dataframe with column name “qoi_name” and nothing is returned.

  • path_hdf5 (str, default: None) – If fn_hdf5, path within the HDF5 file where the data is saved (e.g. “/phys_data/raw/EEG”)

  • verbose (bool, default: False) – Flag indicating verbosity.

  • return_data (bool, default: False) – If true, the data is returned as list of numpy arrays.

Returns:

data_lst – (samples,channels), List of EEG/EMG data. Only returned if “fn_hdf5” is not None.

Return type:

list of np.ndarray, 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) is defined as: - origin: intersection between line of ear fiducials and nasion - x-axis: origin -> nasion - y-axis: origin -> left ear - z-axis: origin -> superior

Parameters:
  • im_path (str) – Path to instrument-marker-file .cnt file.

  • verbose (bool, default: False) – Flag indicating verbosity.

Returns:

im_list – List containing stimulation parameters.

  • coil_mean_raw: 4 x 4 numpy array

  • StimulusID: int

  • etc…

Return type:

list of dict

Raises:

AssertionError – If the .cnt file contains no instrument markers.

pynibs.expio.visor.merge_exp_data_visor(subject, exp_id=0, mesh_idx=0, verbose=False, start_mep=18, end_mep=35)

Merges all experimental data from visor experiment into one .hdf5 file.

Parameters:
  • subject (pynibs.Subject) – Subject object.

  • exp_id (int, default: 0) – Experiment index.

  • mesh_idx (int, default: 0) – Mesh index.

  • verbose (bool, default: False) – Flag indicating verbosity.

  • start_mep (float, default: 18) – Start of time frame after TMS pulse where p2p value is evaluated (in ms).

  • end_mep (float, default: 35) – End of time frame after TMS pulse where p2p value is evaluated (in ms).

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

pynibs.expio.visor.read_nlr(fname)

Reads NLR coordinates from *_recording.mri file.

Parameters:

fname (str) – FIle path of the NLR recording MRI file.

Returns:

fiducials – (3, 3) The rows contain the fiducial points in ANT NIfTI space (nasion, left ear, right ear). Each fiducial point is represented as [x, y, z] coordinates.

Return type:

np.ndarray of float

Table of Contents

Previous topic

pynibs.congruence package

Next topic

pynibs.mesh package

This Page