pynibs.congruence package¶
pynibs.congruence holds the initial congruence factor implementation as described in Weise, Numssen, et al., 2020 [1].
This code is mainly stored here for reproducibility reasons. The current approach (Numssen et al., 2021; [2]; Jing et al., 2024; [3]) uses
the pynibs.regression methods.
References
Weise, K., Numssen, O., Thielscher, A., Hartwigsen, G., & Knösche, T. R. (2020). A novel approach to localize cortical TMS effects. Neuroimage, 209, 116486.
Numssen, O., Zier, A. L., Thielscher, A., Hartwigsen, G., Knösche, T. R., & Weise, K. (2021). Efficient high-resolution TMS mapping of the human motor cortex by nonlinear regression. NeuroImage, 245, 118654.
Jing, Y., Numssen, O., Weise, K., Kalloch, B., Buchberger, L., Haueisen, J., Hartwigsen, G., Knösche, T. (2023). Modeling the Effects of Transcranial Magnetic Stimulation on Spatial Attention. Physics in Medicine & Biology. doi: 10.1088/1361-6560/acff34
Submodules¶
pynibs.congruence.congruence module¶
- pynibs.congruence.congruence.cf_curveshift_kernel(e_curve, mep_curve)¶
Curve congruence (overlap) measure for multiple MEP curves per element. Determines the average displacement between the MEP curves. The congruence factor is weighted by
median(E)and summed up. This favors elements which have greater E, as these are more likely to produce MEPs.
->
congruence_factor ~ np.linalg.norm(dE)/median(E)/n_cond/2- Parameters:
- Returns:
congruence_factor – Congruence factor for the n_cond electric field and MEP curves.
- Return type:
- pynibs.congruence.congruence.cf_curveshift_workhorse(elm_idx_list, mep, mep_params, e, n_samples=100)¶
Worker function for congruence factor computation - call from
multiprocessing.Pool. Calculates congruence factor fore = (E_mag, E_norm and/or E_tan)for given zaps and elements. The computations are parallelized in terms of element indices (elm_idx_list). n_samples are taken from fitted_mep, within the range of theMep.- Parameters:
elm_idx_list (np.ndarray) – (chunksize) List of element indices, the congruence factor is computed for.
mep (list of
Mep) – (n_cond) List of fitted Mep object instances for all conditions.mep_params (np.ndarray of float) –
(n_mep_params_total) List of all mep parameters of curve fits used to calculate the MEP, accumulated into one array.
e.g. [
mep_#1_para_#1,mep_#1_para_#2,mep_#1_para_#3,``mep_#2_para_#1``,mep_#2_para_#1, …]
e (list of list of np.ndarray of float) –
[n_cond][n_datasets][n_elm] Tuple of
n_datasetsof the electric field to compute the congruence factor for, e.g.(e_mag, e_norm, e_tan). Each dataset is a list over all conditions containing the electric field component of interest.len(e) = n_condlen(e[0]) = n_comp(e.g:e_mag = e[0]))
n_samples (int, default=100) – Number of data points to generate discrete mep and e curves.
- Returns:
congruence_factor – (n_roi, n_datasets) Congruence factor in each element specified in elm_idx_list and for each input dataset.
- Return type:
np.ndarray of float
- pynibs.congruence.congruence.cf_curveshift_workhorse_stretch_correction(elm_idx_list, mep, mep_params, e, n_samples=100)¶
Worker function for congruence factor computation - call from multiprocessing.pool Calculates congruence factor for
e = (E_mag, E_norm and/or E_tan)for given zaps and elements. The computations are parallelized in terms of element indices (elm_idx_list).n_samplesare taken from fitted_mep, within the range of theMep.- Parameters:
elm_idx_list (np.ndarray) – (chunksize) List of element indices, the congruence factor is computed for.
mep (list of
Mep) – (n_cond) List of fitted Mep object instances for all conditions.mep_params (np.ndarray of float) –
(n_mep_params_total) List of all mep parameters of curve fits used to calculate the MEP, accumulated into one array.
e.g. [
mep_#1_para_#1,mep_#1_para_#2,mep_#1_para_#3,mep_#2_para_#1,mep_#2_para_#1, …]
e (list of list of np.ndarray of float) –
[n_cond][n_datasets][n_elm] Tuple of n_datasets of the electric field to compute the congruence factor for, e.g.
(e_mag, e_norm, e_tan). Each dataset is a list over all conditions containing the electric field component of intereste.g.:
len(e) = n_condlen(e[0]) = n_comp(e.g:e_mag = e[0])
n_samples (int, default=100) – Number of data points to generate discrete mep and e curves.
- Returns:
congruence_factor – (n_roi, n_datasets) Congruence factor in each element specified in elm_idx_list and for each input dataset.
- Return type:
np.ndarray of float
- pynibs.congruence.congruence.cf_curveshift_workhorse_stretch_correction_new(mep, mep_params, e, n_samples=100, ref_idx=0)¶
Worker function for congruence factor computation - call from
multiprocessing.Pool. Calculates congruence factor fore = (E_mag, E_norm and/or E_tan)for given zaps and elements. The computations are parallelized in terms of element indices (elm_idx_list).n_samplesare taken from fitted_mep, within the range of theMep.- Parameters:
mep (list of
Mep) – (n_cond) List of fitted Mep object instances for all conditions.mep_params (np.ndarray of float [n_mep_params_total]) –
List of all mep parameters of curve fits used to calculate the MEP (accumulated into one array)
e.g. [
mep_#1_para_#1,mep_#1_para_#2,mep_#1_para_#3,mep_#2_para_#1,mep_#2_para_#1, …]
e (np.ndarray of float) – (n_elm, n_cond) Electric field in elements.
n_samples (int, default=100) – Number of data points to generate discrete mep and e curves.
- Returns:
congruence_factor – (n_elm) Congruence factor in each element specified in elm_idx_list and for each input dataset.
- Return type:
np.ndarray of float
- pynibs.congruence.congruence.cf_curveshift_workhorse_stretch_correction_sign_new(mep, mep_params, e, n_samples=100, ref_idx=0)¶
Worker function for congruence factor computation - call from
multiprocessing.Pool. Calculates congruence factor fore = (E_mag, E_norm and/or E_tan)for given zaps and elements. The computations are parallelized in terms of element indices (elm_idx_list).n_sampleare taken from fitted_mep, within the range of theMep.- Parameters:
mep (list of
Mep) – (n_cond) List of fitted Mep object instances for all conditions.mep_params (np.ndarray of float) –
(n_mep_params_total) List of all mep parameters of curve fits used to calculate the MEP, accumulated into one array.
e.g. [
mep_#1_para_#1,mep_#1_para_#2,mep_#1_para_#3,mep_#2_para_#1,mep_#2_para_#1, …]
e (np.ndarray of float) – (n_elm, n_cond) Electric field in elements.
n_samples (int, default=100) – Number of data points to generate discrete mep and e curves.
- Returns:
congruence_factor – (n_elm, 1) Congruence factor in each element specified in elm_idx_list and for each input dataset.
- Return type:
np.ndarray of float
- pynibs.congruence.congruence.cf_curveshift_workhorse_stretch_correction_variance(elm_idx_list, mep, mep_params, e, n_samples=100)¶
Worker function for congruence factor computation - call from
multiprocessing.Pool. Calculates congruence factor fore = (E_mag, E_norm and/or E_tan)for given zaps and elements. The computations are parallelized in terms of element indices (elm_idx_list).n_samplesare taken from fitted_mep, within the range of theMep.- Parameters:
elm_idx_list (np.ndarray) – (chunksize) List of element indices, the congruence factor is computed for.
mep (list of
Mep) – (n_cond) List of fitted Mep object instances for all conditionsmep_params (np.ndarray of float [n_mep_params_total]) –
List of all mep parameters of curve fits used to calculate the MEP (accumulated into one array)
e.g. [
mep_#1_para_#1,mep_#1_para_#2,mep_#1_para_#3,mep_#2_para_#1,mep_#2_para_#1, …]
e (list of list of np.ndarray of float) –
[n_cond][n_datasets][n_elm] Tuple of n_datasets of the electric field to compute the congruence factor for, e.g.
(e_mag, e_norm, e_tan). Each dataset is a list over all conditions containing the electric field component of intereste.g.:
len(e) = n_condlen(e[0]) = n_comp(e.g:e_mag = e[0]))
n_samples (int, default=100) – Number of data points to generate discrete mep and e curves
- Returns:
congruence_factor – Congruence factor in each element specified in elm_idx_list and for each input dataset
- Return type:
np.ndarray of float [n_roi, n_datasets]
- pynibs.congruence.congruence.cf_variance_sign_workhorse(elm_idx_list, mep, mep_params, e)¶
Worker function for congruence factor computation - call from
multiprocessing.Pool. Calculates congruence factor fore = (E_mag, E_norm and/or E_tan)for given zaps and elements.- Parameters:
elm_idx_list (np.ndarray) – (chunksize) List of element indices, the congruence factor is computed for.
mep (list of
Mep) – (n_cond) List of fitted Mep object instances for all conditions.mep_params (np.ndarray of float) – (n_mep_params_total) List of all mep parameters of curve fits used to calculate the MEP, accumulated into one array), e.g. [
mep_#1_para_#1,mep_#1_para_#2,mep_#1_para_#3,mep_#2_para_#1,mep_#2_para_#1, …])e (list of list of np.ndarray of float) –
[n_cond][n_datasets][n_elm] Tuple of
n_datasetsof the electric field to compute the congruence factor for, e.g.(e_mag, e_norm, e_tan). Each dataset is a list over all conditions containing the electric field component of interestlen(e) = n_condlen(e[0]) = n_comp(e.g:e_mag = e[0]))
- Returns:
congruence_factor – (n_roi, n_datasets) Congruence factor in each element specified in elm_idx_list and for each input dataset.
- Return type:
np.ndarray of float
- pynibs.congruence.congruence.cf_variance_workhorse(elm_idx_list, mep, mep_params, e, old_style=True)¶
Worker function for congruence factor computation - call from
multiprocessing.Pool. Calculates congruence factor fore = (E_mag, E_norm and/or E_tan)for given zaps and elements.- Parameters:
elm_idx_list (np.ndarray) – (chunksize) List of element indices, the congruence factor is computed for.
mep (list of
Mep) – (n_cond) List of fitted Mep object instances for all conditions.mep_params (np.ndarray of float) –
(n_mep_params_total) List of all mep parameters used to calculate the MEP, accumulated into one array.
e.g. [
mep_#1_para_#1,mep_#1_para_#2,mep_#1_para_#3,mep_#2_para_#1,``mep_#2_para_#1``, …])
e (list of list of np.ndarray of float) –
[n_cond][n_datasets][n_elm] Tuple of
n_datasetsof the electric field to compute the congruence factor for, e.g.(e_mag, e_norm, e_tan). Each dataset is a list over all conditions containing the electric field component of interestlen(e) = n_condlen(e[0]) = n_comp(e.g:e_mag = e[0])
old_style (bool, default: True) – True: Weight
var(x_0_prime(r))withmean(e(r) * mean(Stimulator Intensity), taken frommepFalse: Weightvar(x_0_prime(r))withmean(E(r)), taken from e
- Returns:
congruence_factor – (n_roi, n_datasets) Congruence factor in each element specified in elm_idx_list and for each input dataset.
- Return type:
np.ndarray of float
- pynibs.congruence.congruence.extract_condition_combination(fn_config_cfg, fn_results_hdf5, conds, fn_out_prefix)¶
Extract and plot congruence factor results for specific condition combinations from permutation analysis.
- Parameters:
fn_config_cfg (str) – Filename of .cfg file the permutation study was conducted with.
fn_results_hdf5 (str) – Filename of
.hdf5results file generated by00_run_c_standard_compute_all_permutations.pycontaining congruence factors and condition combinations.conds (list of str) – (n_cond) List containing condition combinations to extract and plot, e.g.
['P_0', 'I_225', 'M1_0', 'I_675', 'P_225'].fn_out_prefix (str) – Prefix of output filenames of *_data.xdmf, *_data.hdf5 and *_geo.hdf5.
- Returns:
<fn_out_prefix_data.xdmf> (.xdmf file) – Output file linking *_data.hdf5 and *_geo.hdf5 file to plot in paraview.
<fn_out_prefix_data.hdf5> (.hdf5 file) – Output .hdf5 file containing the data.
<fn_out_prefix_geo.xdmf> (.hdf5 file) – Output .hdf5 file containing the geometry information.
pynibs.congruence.ext_metrics module¶
- pynibs.congruence.ext_metrics.dvs_likelihood(params, x, y, verbose=True, normalize=False, bounds=[(1, 2), (1, 2)])¶
Calculate the log likelihood of the DVS model with test data.
- Parameters:
params (list of float) – List of parameters for the DVS model. The first two parameters are sigma_x and sigma_y, and the remaining parameters are model-specific.
x (np.ndarray) – Array of input data for the DVS model.
y (np.ndarray) – Array of observed data corresponding to x.
verbose (bool, optional) – If True, print detailed information about the likelihood calculation. Default is True.
normalize (bool, optional) – If True, normalize the parameters to the specified bounds. Default is False.
bounds (list of tuple of float, optional) – List of bounds for the parameters. Default is [(1, 2), (1, 2)].
- Returns:
Negative log likelihood of the DVS model.
- Return type:
Notes
The function calculates the posterior of the DVS model with test data by generating a posterior distribution and binning the data. It then determines the log likelihood based on the kernel density estimate of the binned data.
The function prints the likelihood and parameter values if verbose is True.
- pynibs.congruence.ext_metrics.e_cog_workhorse(elm_idx_list, mep, mep_params, e)¶
Worker function for electric field center of gravity (e_cog) computation after Opitz et al. (2013) [1] - call from
multiprocessing.Pool. Calculates the e_cog fore = (E_mag, E_norm and/or E_tan)for given zaps and elements. The electric field is weighted by the mean MEP amplitude (turning point of the sigmoid) and summed up. The computations are parallelized in terms of element indices (elm_idx_list).- Parameters:
elm_idx_list (np.ndarray) – (chunksize) List of element indices, the congruence factor is computed for.
mep (list of
Mep) – (n_cond) List of fitted Mep object instances for all conditions.mep_params (np.ndarray of float) –
(n_mep_params_total) List of all mep parameters of curve fits used to calculate the MEP, accumulated into one array.
e.g. [
mep_#1_para_#1,mep_#1_para_#2,mep_#1_para_#3,mep_#2_para_#1,mep_#2_para_#1, …]
- elist of list of np.ndarray of float
[n_cond][n_datasets][n_elm] Tuple of n_datasets of the electric field to compute the congruence factor for, e.g.
(e_mag, e_norm, e_tan). Each dataset is a list over all conditions containing the electric field component of intereste.g.:
len(e) = n_condlen(e[0]) = n_comp(e.g:e_mag = e[0])
- Returns:
e_cog – (n_roi, n_datasets) RSD inverse in each element specified in
elm_idx_listand for each input dataset.- Return type:
np.ndarray of float
Notes
[1]Opitz, A., Legon, W., Rowlands, A., Bickel, W. K., Paulus, W., & Tyler, W. J. (2013). Physiological observations validate finite element models for estimating subject-specific electric field distributions induced by transcranial magnetic stimulation of the human motor cortex. Neuroimage, 81, 253-264.
- pynibs.congruence.ext_metrics.e_focal_workhorse(elm_idx_list, e)¶
Worker function to determine the site of stimulation after Aonuma et al. (2018) [1], call from
multiprocessing.Pool. Calculates the site of stimulation fore = (E_mag, E_norm and/or E_tan)for given zaps and elements by multiplying the electric fields with each other. The computations are parallelized in terms of element indices (elm_idx_list).- Parameters:
elm_idx_list (np.ndarray) – (chunksize) List of element indices, the congruence factor is computed for.
e (list of list of np.ndarray of float) –
[n_cond][n_datasets][n_elm] Tuple of
n_datasetsof the electric field to compute the congruence factor for, e.g.(e_mag, e_norm, e_tan). Each dataset is a list over all conditions containing the electric field component of interest.len(e) = n_condlen(e[0]) = n_comp(e.g:e_mag = e[0])
- Returns:
e_focal – (n_roi, n_datasets) Focal electric field in each element specified in
elm_idx_listand for each input.- Return type:
np.ndarray of float
Notes
[1]Aonuma, S., Gomez-Tames, J., Laakso, I., Hirata, A., Takakura, T., Tamura, M., & Muragaki, Y. (2018). A high-resolution computational localization method for transcranial magnetic stimulation mapping. NeuroImage, 172, 85-93.
- pynibs.congruence.ext_metrics.rsd_inverse_workhorse(elm_idx_list, mep, e)¶
Worker function for RSD inverse computation after Bungert et al. (2017) [1], call from
multiprocessing.Pool. Calculates the RSD inverse fore = (E_mag, E_norm and/or E_tan)for given zaps and elements. The computations are parallelized in terms of element indices (elm_idx_list).- Parameters:
elm_idx_list (np.ndarray) – (chunksize) List of element indices, the congruence factor is computed for
mep (list of
Mep) – (n_cond) List of fitted Mep object instances for all conditions.e (list of list of np.ndarray of float) –
[n_cond][n_datasets][n_elm] Tuple of
n_datasetsof the electric field to compute the congruence factor for, e.g.(e_mag, e_norm, e_tan). Each dataset is a list over all conditions containing the electric field component of interestlen(e) = n_condlen(e[0]) = n_comp(e.g:e_mag = e[0]))
- Returns:
rsd_inv – (n_roi, n_datasets) RSD inverse in each element specified in
elm_idx_listand for each input dataset.- Return type:
np.ndarray of float
Notes
[1]Bungert, A., Antunes, A., Espenhahn, S., & Thielscher, A. (2016). Where does TMS stimulate the motor cortex? Combining electrophysiological measurements and realistic field estimates to reveal the affected cortex position. Cerebral Cortex, 27(11), 5083-5094.
pynibs.congruence.stimulation_threshold module¶
- pynibs.congruence.stimulation_threshold.intensity_thresh(mep_curve, intensities, mep_threshold)¶
Determines the stimulation threshold of one particular condition (usually the most sensitive e.g. M1-45). The stimulation threshold is the stimulator intensity value in [A/us] where the mep curves exceed the value of mep_threshold (in [mV]).
- Parameters:
mep_curve (list [1] of np.ndarray of float [n_samples]) – MEP curve values for every conditions
intensities (list [1] of np.ndarray of float [n_samples]) – To the MEP values corresponding stimulator intensities in [A/us]
mep_threshold (float) – MEP value in [mV], which has to be exceeded for threshold definition
- Returns:
stim_threshold_avg – Average stimulation threshold in [V/m] where c_factor is greater than c_factor_percentile
- Return type:
- pynibs.congruence.stimulation_threshold.mean_mep_threshold(elm_idx, mep_curve, intensities, e, mep_threshold)¶
Determines the stimulation threshold by calculating the average electric field over all conditions, where the mep curves exceed the value of mep_threshold (in [mV]).
- Parameters:
elm_idx (list of np.ndarray of int) – [n_datasets](n_elements) Element indices where the congruence factor exceeds a certain percentile, defined during the call of
stimulation_threshold().mep_curve (list of np.ndarray of float) – [n_conditions](n_samples) MEP curve values for every condition.
intensities (list of np.ndarray of float) – [n_conditions](n_samples) To the MEP values corresponding stimulator intensities in [A/us].
e (list of list of np.ndarray of float) –
[n_cond][n_datasets][n_elm] Tuple of n_datasets of the electric field to compute the congruence factor for, e.g.
(e_mag, e_norm, e_tan). Each dataset is a list over all conditions containing the electric field component of intereste.g.:
len(e) = n_condlen(e[0]) = n_comp(e.g:e_mag = e[0]))
mep_threshold (float) – MEP value in [mV], which has to be exceeded for threshold definition.
- Returns:
stim_threshold_avg – Average stimulation threshold in [V/m] where c_factor is greater than c_factor_percentile
- Return type:
- pynibs.congruence.stimulation_threshold.sigmoid_thresh(elm_idx, mep_curve, intensities, e, mep_threshold)¶
Determines the stimulation threshold by calculating an equivalent
pynibs.expio.Mep.sigmoidover all conditions. The stimulation threshold is the electric field value where the mep curves exceed the value of mep_threshold (in [mV]).- Parameters:
elm_idx (list of np.ndarray of int) – [n_datasets](n_elements) Element indices where the congruence factor exceeds a certain percentile, defined during the call of
stimulation_threshold().mep_curve (list of np.ndarray of float) – [n_conditions](n_samples) MEP curve values for every condition.
intensities (list of np.ndarray of float) – [n_conditions](n_samples) To the MEP values corresponding stimulator intensities in [A/us].
e (list of list of np.ndarray of float) –
[n_cond][n_datasets][n_elm] Tuple of n_datasets of the electric field to compute the congruence factor for, e.g.
(e_mag, e_norm, e_tan). Each dataset is a list over all conditions containing the electric field component of intereste.g.:
len(e) = n_condlen(e[0]) = n_comp(e.g:e_mag = e[0]))
mep_threshold (float) – MEP value in [mV], which has to be exceeded for threshold definition
- Returns:
stim_threshold_avg – Average stimulation threshold in [V/m] where c_factor is greater than c_factor_percentile
- Return type:
- pynibs.congruence.stimulation_threshold.stimulation_threshold(elm_idx_list, mep, mep_params, n_samples, e, c_factor_percentile=95, mep_threshold=0.5, c_factor=None, c_function=None, t_function=None)¶
Computes the stimulation threshold in terms of the electric field in [V/m]. The threshold is defined as the electric field value where the mep exceeds mep_threshold. The average value is taken over all mep curves in each condition and over an area where the congruence factor exceeds
c_factor_percentile.- Parameters:
elm_idx_list (np.ndarray) – (chunksize) List of element indices, the congruence factor is computed for.
mep (list of Mep object instances) – (n_cond) List of fitted
Mepobject instances for all conditions.mep_params (np.ndarray of float [n_mep_params_total]) –
List of all mep parameters of curve fits used to calculate the MEP (accumulated into one array)
e.g. [
mep_#1_para_#1,mep_#1_para_#2,mep_#1_para_#3,mep_#2_para_#1,mep_#2_para_#1, …]
n_samples (int) – Number of data points to generate discrete mep and e curves.
e (list of list of np.ndarray of float) –
[n_cond][n_datasets][n_elm] Tuple of
n_datasetsof the electric field to compute the congruence factor for, e.g.(e_mag, e_norm, e_tan). Each dataset is a list over all conditions containing the electric field component of intereste.g.:
len(e) = n_condlen(e[0]) = n_comp(e.g:e_mag = e[0]))
c_factor_percentile (float) – Percentile of the c_factor taken into account for the threshold evaluation. Only c_factors are considered exceeding this.
mep_threshold (float) – MEP value in [mV], which has to be exceeded for threshold definition.
c_factor (np.ndarray of float) –
(n_roi –
dataset. (n_datasets) Congruence factor in each element specified in elm_idx_list and for each input) –
c_function (function) –
Defines the function to use during c_gpc to calculate the congruence factor.
congruence_factor_curveshift_workhorse: determines the average curve shift
congruence_factor_curveshift_workhorse_stretch_correction: determines the average curve shift
congruence_factor_curveshift_workhorse_stretch_correction_variance: determines the average curve shift
congruence_factor_variance_workhorse: evaluates the variance of the shifting and stretching parameters
t_function (function) –
Defines the function to determine the stimulation_threshold.
stimulation_threshold_mean_mep_threshold: uses mep_threshold to determine the corresponding e_threshold over all conditions and takes the average values as the stimulation threshold
stimulation_threshold_pynibs.sigmoid: Fits a new pynibs.sigmoid using all datapoints in the mep-vs-E space and evaluates the threshold from the turning point or the intersection of the derivative in the crossing point with the e-axis
- Returns:
stim_threshold_avg – Average stimulation threshold in [V/m] where c_factor is greater than
c_factor_percentile.- Return type:
