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¶
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_sig¶
Best fitting parameters
x0,r, andampof equivalent sigmoidal function.
- Type:
np.ndarray of float
- fit¶
Gmodel object instance of parameter fit.
- Type:
object instance
- 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 (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) –
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_multistartoptimizations are performed based on random variations of the initial guess parametersp0. 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.
- pynibs.expio.Mep.butter_lowpass_filter(data, cutoff, fs, order=5)¶
Applies Butterworth lowpass filter.
- 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.
- 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:
- 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.
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)¶
- 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.get_virtual_mep_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.read_biosig_emg_data(fn_data, include_first_trigger=False, type='cfs')¶
Reads EMG data from a biosig file.
- Parameters:
- 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.scale_e_for_dvs(e, mt=60, upper_limit=100)¶
Scale the electric field for DVS and TVS to 0-1 range, with 0 being motor threshold.
pynibs.expio.brainsight module¶
Functions to import data from Rogue Research Brainsight neuronavigation systems
- class pynibs.expio.brainsight.BrainsightCSVParser¶
Bases:
objectParser for Brainsight CSV files.
- current_state¶
The current state of the parser.
- check_state_transition(line)¶
Checks the state transition based on the given line.
- parse_line(line)¶
Parses a line and updates the corresponding attributes.
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.get_marker(fn, markertype)¶
Read instrument-marker and conditions from Brainsight session.
BrainSight stores recorded coil placements as ‘Samples’ and predefined coil placements as ‘Targets’.
Coil axes definitions as defined by Brainsight.
- Parameters:
- Returns:
matsimnibs (np.ndarray of float) – (M, 4, 4) Instrument marker matrices.
marker_descriptions (list of str) – Labels of the marker conditions.
marker_times (list of str) – YYYY-MM-DD HH:MM:SS.sss time stamps of the samples. [-1] for InstrumentMarkers.
- 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) – 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/+2 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 (int, default: 18) – Start of time frame after TMS pulse where p2p value is evaluated (in ms).
end_mep (int, default: 35) – End of time frame after TMS pulse where p2p value is evaluated (in ms).
- pynibs.expio.brainsight.read_samples_brainsight(fn_tms_nav)¶
Reads sample data from a Brainsight navigation system file.
- Parameters:
fn_tms_nav (str) – The file path of the Brainsight navigation system file.
- Returns:
d_bs (collections.OrderedDict) – An ordered dictionary containing the parsed data from the Brainsight file. The keys of the dictionary correspond to the column headers in the Brainsight file, and the values are lists of the data in those columns.
m_nnav (numpy.ndarray) – A 3D numpy array of shape (4, 4, n_stims) containing the 4x4 transformation matrices for each stimulation.
n_stims (int) – The number of stimulations, inferred from the number of rows in the Brainsight file.
- 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.read_triggermarker(fn)¶
Read instrument-marker and conditions from Brainsight session.
- BrainSight stores recorded coil placements as ‘Samples’ and predefined coil placements
as ‘Targets’.
Coil axes definitions as defined by Brainsight. dI/dt is returned as list of [-1] to keep consistent with read_triggermarker functions for other neuronavigation
systems.
- Parameters:
- Returns:
matsimnibs (np.ndarray of float) – (4, 4, N) Instrument marker matrices
didt (np.ndarray of float) –
Rate of change of coil current in (A/us).
stim_int (np.ndarray of float) –
Stimulator intensity in (% MSO).
marker_descriptions (list of str) – Labels of the marker conditions.
marker_times (list of str) – YYYY-MM-DD HH:MM:SS.sss time stamps of the samples. [-1] for InstrumentMarkers.
- pynibs.expio.brainsight.simnibs2brainsight()¶
Flip matrix for brainsight -> simnibs and vice versa.
Example
if brainsight_mat.shape = (n_pos, 4, 4): simnibs_mat = brainsight_mat @ simnibs2localite() localite_mat = simnibs_mat @ brainsight2localite()
- pynibs.expio.brainsight.transform_brainsight(data, col_names)¶
Transforms Brainsight coil position/orientation into SimNIBS matsimnibs
data: list of lists with positions col_names: list of str
- 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.
pynibs.expio.cobot module¶
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
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.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>.csvfile.- 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) – Lower boundary for distance correction.
max_dist (int, default: 2) – Lower boundary for distance correction.
- 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
distanceis 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.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).
- pynibs.expio.exp.get_cnt_infos(fn_cnt)¶
Read some meta information from .cnt file.
- 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.
- pynibs.expio.exp.get_coil_sn_lst(fn_coil)¶
Extract coil serial numbers from a list of coil paths.
- pynibs.expio.exp.get_csv_matrix(dictionary)¶
Process the given dictionary to create a 4x4 matrix for each coil specified.
- pynibs.expio.exp.get_ft_data_from_csv(behavior_fn, cond, drop_trial_idx=None, startatzero=True)¶
Reads trial data from csv file.
- Parameters:
- Returns:
ft (list of float)
TMS_onsets (list of float) – in [ms]
mean_isi (tuple of int) – in [s]
- 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.
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 undercoordinateSpace="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.
- 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, (4, 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.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.
- 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 (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.

- 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.
- 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.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)
pynibs.expio.fit_funs module¶
- pynibs.expio.fit_funs.dummy_fun(x, a)¶
Dummy function for congruence factor calculation.
- pynibs.expio.fit_funs.exp(x, x0, r, y0)¶
Parametrized exponential function.

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

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

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

- pynibs.expio.fit_funs.linear(x, m, n)¶
Parametrized linear function.

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

- pynibs.expio.fit_funs.sigmoid(x, x0, r, amp)¶
Parametrized sigmoid function.

- Parameters:
- Returns:
y – (N_x) Function value at argument x.
- Return type:
np.ndarray of float
- pynibs.expio.fit_funs.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.fit_funs.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.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:
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 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
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) – 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.
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
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.
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.localite.get_marker(im_path, markertype)¶
Read instrument-marker and conditions from Neuronavigator .xml-file.
Coil axes definition as defined by Localite.
- Parameters:
- 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_patient_id(xml_path)¶
Read patient-ID.
- pynibs.expio.localite.get_single_marker_file(im_path, markertype)¶
Read instrument-marker and conditions from Neuronavigator .xml-file.
- Parameters:
- 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:
- 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_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.localite.match_instrument_marker_file(xml_paths, im_path)¶
Assign right instrument marker condition to every triggermarker (get instrument marker out of file).
- Parameters:
- 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:
- Returns:
coil_cond_lst – Strings containing the right conditions. drop_idx : list of int
Indices of trigger markers that were dropped.
- Return type:
- 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:
- 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.
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(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
(4, 4, N) Neuronavigation coordinates of N stimuli (4x4 matrices).
- didtnp.ndarray of float
Rate of change of coil current in (A/us).
- stim_intnp.ndarray of float
Stimulator intensity in (% MSO).
- descrlist of str
Labels of the instrument-marker-conditions.
- rec_timelist of str
Recording time in ms.
- Return type:
list of
- pynibs.expio.localite.read_triggermarker_localite(fn_xml)¶
pynibs.expio.signal_ced module¶
- pynibs.expio.signal_ced.cfs2hdf5(fn_cfs, fn_hdf5=None)¶
Converts EMG data included in .cfs file to .hdf5 format.
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 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:
- Returns:
im_list – List containing stimulation parameters.
coil_mean_raw: 4 x 4 numpy array
StimulusID: int
etc…
- Return type:
- 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

