pynibs.coil package¶
All functions to operate on TMS coils go here, for example to create .xdmf files to visualize coil positions.
Submodules¶
pynibs.coil.coil module¶
- pynibs.coil.coil.calc_coil_position_pdf(fn_rescon=None, fn_simpos=None, fn_exp=None, orientation='quaternions', folder_pdfplots=None)¶
Determines the probability density functions of the transformed coil position (x’, y’, z’) and quaternions of the coil orientations (x’’, y’’, z’’)
- Parameters:
fn_rescon (str) – Filename of the results file from TMS experiments (results_conditions.csv)
fn_simpos (str) – Filename of the positions and orientation from TMS experiments (simPos.csv)
fn_exp (str) – Filename of experimental.csv file from experiments
orientation (str) – Type of orientation estimation: ‘quaternions’ or ‘euler’
folder_pdfplots (str) – Folder, where the plots of the fitted pdfs are saved (omitted if not provided)
- Returns:
pdf_paras_location (list of list of np.ndarray) –
[n_conditions] Pdf parameters (limits and shape) of the coil position for x’, y’, and z’ for each:
beta_paras … [p, q, a, b] (2 shape parameters and limits)
moments … [data_mean, data_std, beta_mean, beta_std]
p_value … p-value of the Kolmogorov Smirnov test
uni_paras … [a, b] (limits)
pdf_paras_orientation_euler (list of np.ndarray) –
[n_conditions] Pdf parameters (limits and shape) of the coil orientation Psi, Theta, and Phi for each:
beta_paras … [p, q, a, b] (2 shape parameters and limits)
moments … [data_mean, data_std, beta_mean, beta_std]
p_value … p-value of the Kolmogorov Smirnov test
uni_paras … [a, b] (limits)
OP_mean (List of [3 x 4] np.ndarray) – [n_conditions] List of mean coil position and orientation for different conditions (global coordinate system)

OP_zeromean (list of [3 x 4 x n_con_each] np.ndarray [n_conditions]) – List over conditions containing zero-mean coil orientations and positions
V (list of [3 x 3] np.ndarrays [n_conditions]) – Transformation matrix of coil positions from global coordinate system to transformed coordinate system
P_transform (list of np.ndarray [n_conditions]) – List over conditions containing transformed coil positions [x’, y’, z’] of all stimulations (zero-mean, rotated by SVD)
quaternions (list of np.ndarray [n_conditions]) – List over conditions containing imaginary part of quaternions [x’’, y’’, z’’] of all stimulations
- pynibs.coil.coil.calc_coil_transformation_matrix(LOC_mean, ORI_mean, LOC_var, ORI_var, V)¶
Calculate the modified coil transformation matrix needed for SimNIBS based on location and orientation variations observed in the framework of uncertainty analysis
- Parameters:
LOC_mean (np.ndarray of float) – (3), Mean location of TMS coil
ORI_mean (np.ndarray of float) –
(3 x 3) Mean orientations of TMS coil

LOC_var (np.ndarray of float) –
Location variation in normalized space (dx’, dy’, dz’), i.e. zero mean and projected on principal axes
ORI_var (np.ndarray of float) –
Orientation variation expressed in Euler angles [alpha, beta, gamma] in deg
V (np.ndarray of float) – (3x3) V-matrix containing the eigenvectors from _,_,V = numpy.linalg.svd
- Returns:
mat (np.ndarray of float)
(4, 4) Transformation matrix containing 3 axis and 1 location vector –

- pynibs.coil.coil.check_coil_position(points, hull)¶
Check if magnetic dipoles are lying inside head region
- pynibs.coil.coil.get_coil_dipole_pos(coil_fn, matsimnibs)¶
Apply transformation to coil dipoles and return position.
- pynibs.coil.coil.get_invalid_coil_parameters(param_dict, coil_position_mean, svd_v, del_obj, fn_coil, fn_hdf5_coilpos=None)¶
Finds gpc parameter combinations, which place coil dipoles inside subjects head. Only endpoints (and midpoints) of the parameter ranges are examined.
get_invalid_coil_parameters(param_dict, pos_mean, v, del_obj, fn_coil, fn_hdf5_coilpos=None)
- Parameters:
param_dict (dict) – Dictionary containing dictionary with
'limits'and'pdfshape'. keys:'x','y','z','psi','theta','phi'.coil_position_mean (np.ndarray) – (3, 4) Mean coil positions and orientations.
svd_v (np.ndarray) – (3, 3) SVD matrix V.
del_obj (
scipy.spatial.Delaunay) – Skin surface.fn_coil (str) – Filename of coil .ccd file.
fn_hdf5_coilpos (str) – Filename of .hdf5 file to save coil_pos in (incl. path and .hdf5 extension).
- Returns:
fail_params – Index and combination of failed parameter.
- Return type:
- pynibs.coil.coil.random_walk_coil(start_mat, n_steps, fn_mesh_hdf5, angles_dev=3, distance_low=1, distance_high=4, angles_metric='deg', coil_pos_fn=None)¶
Computes random walk coil positions/orientations for a SimNIBS matsimnibs coil pos/ori.
- Parameters:
start_mat (np.ndarray) – (4, 4) SimNIBS matsimnibs.
n_steps (int) – Number of steps to walk.
fn_mesh_hdf5 (str) – .hdf5 mesh filename, used to compute skin-coil distances.
angles_dev (float or list of float, default: 3) – Angles deviation,`` np.random.normal(scale=angles_dev)``. If list, angles_dev = [alpha, beta, theta].
distance_low (float, default: 1) – Minimum skin-coil distance.
distance_high (float, default: 4) – Maximum skin-coil distance.
angles_metric (str, default: 'deg') – One of
('deg', 'rad').coil_pos_fn (str, optional) – If provided, .hdf5/.xdmf tuple is written with coil positions/orientations.
- Returns:
walked_coils (np.ndarray) – (4, 4, n_steps + 1) coil positions / orientations.
<file> (.hdf5/.xdmf file tupel with n_steps + 1 coil positions/orientations.)
- pynibs.coil.coil.shift_coil_to_skin(mesh, coil, matsimnibs, dist=1, dist_neigh=50, coil_elm_idx=None, verbose=False)¶
Shifts the coil position to the skin surface, also works for bent coil models.
- Parameters:
mesh (simnibs.mesh_io.Mesh or str) – SimNIBS .msh.
coil (simnibs.simulation.tms_coil.tms_coil.TmsCoil or str) – .tcd coil model.
matsimnibs (np.ndarray) – (4, 4) SimNIBS matsimnibs coil position / orientation.
dist (float, default: 0) – Target (minimum) coil-skin distance.
dist_neigh (float, default: 50) –
- If set, only mesh nodes with a distance < dist_neigh are considered for
the distance calculation to speed up computation.
coil_elm_idx (list of int, optional) – Which coil elements to use.
verbose (bool, default: False) – Print output messages.
- Returns:
matsimnibs_shifted (np.ndarray) – (4, 4) Shifted coil position / orientation.
min_dist (float) – (Minimum) coil-skin distance before shifting.
- pynibs.coil.coil.shift_many_coil_placements(mesh, coil, matsimnibs, dist=1, dist_neigh=50, flat_coil=False, z_cut_off=None, verbose=False)¶
Shifts many coil placements to the cortex surface.
- Parameters:
mesh (simnibs.mesh_io.Mesh or str) – SimNIBD .msh.
coil (simnibs.simulation.tms_coil.tms_coil.TmsCoil or str) – .tcd coil model.
matsimnibs (np.ndarray) – (4, 4, N) SimNIBS matsimnibs coil position / orientation.
dist (float, default: 0) – Target (minimum) coil-skin distance.
dist_neigh (float, default: 50) –
- If set, only mesh nodes with a distance < dist_neigh are considered for
the distance calculation to speed up computation.
flat_coil (bool, default: False) – If True, the coil is assumed to be flat and shifts for the same position are applied across all rotations.
z_cut_off (float, optional) – Cut coil case at this z-offset to speed up computation
verbose (bool, default: False) – Print output messages.
- Returns:
matsimnibs – (4, 4, N) Shifted coil positions / orientations.
- Return type:
np.ndarray
- pynibs.coil.coil.sort_opt_coil_positions(fn_coil_pos_opt, fn_coil_pos, fn_out_hdf5=None, root_path='/0/0/', verbose=False, print_output=False)¶
Sorts coil positions according to Traveling Salesman problem.
- Parameters:
fn_coil_pos_opt (str) – Name of .hdf5 file containing the optimal coil position indices
fn_coil_pos (str) – Name of .hdf5 file containing the matsimnibs matrices of all coil positions
fn_out_hdf5 (str) – Name of output .hdf5 file (will be saved in the same format as fn_coil_pos_opt)
verbose (bool, default: False) – Print output messages
print_output (bool or str, default: False) – Print output image as .png file showing optimal path
- Return type:
<file> .hdf5 file containing the sorted optimal coil position indices
- pynibs.coil.coil.test_coil_position_gpc(parameters)¶
Testing valid coil positions for gPC analysis
pynibs.coil.export module¶
- pynibs.coil.export.create_stimsite_from_exp_hdf5(fn_exp, fn_hdf, datanames=None, data=None, overwrite=False)¶
This takes an experiment.hdf5 file and creates an .hdf5 + .xdmf tuple for all coil positions for visualization.
- Parameters:
fn_exp (str) – Path to experiment.hdf5
fn_hdf (str) – Filename for the resulting .hdf5 file. The .xdmf is saved with the same basename. Folder should already exist.
datanames (str or list of str, optional) – Dataset names for
datadata (np.ndarray, optional) – Dataset array with shape =
(len(poslist.pos), len(datanames()).overwrite (bool, default: False) – Overwrite existing files.
- pynibs.coil.export.create_stimsite_from_list(fn_hdf, poslist, datanames=None, data=None, overwrite=False)¶
This takes a list of matsimnibs-style coil position and orientations and creates an .hdf5 + .xdmf tuple for all positions.
Centers and coil orientations are written to disk, with optional data for each coil configuration.
- Parameters:
fn_hdf (str) – Filename for the .hdf5 file. The .xdmf is saved with the same basename. Folder should already exist.
poslist (list of np.ndarray) – (4,4) Positions.
datanames (str or list of str, optional) – Dataset names for
data.data (np.ndarray, optional) – Dataset array with shape =
(len(poslist.pos), len(datanames()).overwrite (bool, defaul: False) – Overwrite existing files.
- pynibs.coil.export.create_stimsite_from_matsimnibs(fn_hdf, matsimnibs, datanames=None, data=None, overwrite=False)¶
This takes a matsimnibs array and creates an .hdf5 + .xdmf tuple for all coil positions for visualization.
Centers and coil orientations are written disk.
- Parameters:
fn_hdf (str) – Filename for the .hdf5 file. The .xdmf is saved with the same basename. Folder should already exist.
matsimnibs (np.ndarray) –
(4, 4, n_pos) Matsimnibs matrices containing the coil orientation (x,y,z) and position (p)

datanames (str or list of str, optional) – Dataset names for
data.data (np.ndarray, optional) – (len(poslist.pos), len(datanames).
overwrite (bool, default: False) – Overwrite existing files.
- pynibs.coil.export.create_stimsite_from_tmslist(fn_hdf, poslist, datanames=None, data=None, overwrite=False)¶
This takes a :py:class:simnibs.sim_struct.TMSLIST from simnibs and creates an .hdf5 + .xdmf tuple for all positions.
Centers and coil orientations are written to disk, with optional data for each coil configuration.
- Parameters:
fn_hdf (str) – Filename for the .hdf5 file. The .xdmf is saved with the same basename. Folder should already exist.
poslist (simnibs.sim_struct.TMSLIST) – poslist.pos[*].matsimnibs have to be set.
datanames (str or list of str, optional) – Dataset names for
data.data (np.ndarray, optional) – Dataset array with shape =
(len(poslist.pos), len(datanames()).overwrite (bool, default: False) – Overwrite existing files
- pynibs.coil.export.create_stimsite_hdf5(fn_exp, fn_hdf, conditions_selected=None, sep='_', merge_sites=False, fix_angles=False, data_dict=None, conditions_ignored=None)¶
Reads results_conditions and creates an hdf5/xdmf pair with condition-wise centers of stimulation sites and coil directions as data.
- Parameters:
fn_exp (str) – Path to results.csv.
fn_hdf (str) – Path where to write file. Gets overridden if already existing.
conditions_selected (str or list of str, optional) – List of conditions returned by the function, the others are omitted. If None, all conditions are returned.
sep (str, default: "_") – Separator between condition label and angle (e.g. M1_0, or M1-0).
merge_sites (bool) – If true, only one coil center per site is generated.
fix_angles (bool) – rename 22.5 -> 0, 0 -> -45, 67.5 -> 90, 90 -> 135.
data_dict (dict ofnp.ndarray of float [n_stimsites] (optional), default: None) – Dictionary containing data corresponding to the stimulation sites (keys).
conditions_ignored (str or list of str, optional) – Conditions, which are not going to be included in the plot.
- Returns:
<Files> – Contains information about condition-wise stimulation sites and coil directions (fn_hdf)
- Return type:
hdf5/xdmf file pair
Example
pynibs.create_stimsite_hdf5('/exp/1/experiment_corrected.csv', '/stimsite', True, True)
- pynibs.coil.export.write_coil_pos_hdf5(fn_hdf, centers, m0, m1, m2, datanames=None, data=None, overwrite=False)¶
Creates a
.hdf5+.xdmffile tuple for all coil positions. Coil centers and coil orientations are saved, and - optionally - data for each position ifdataanddatanamesare provided.- Parameters:
fn_hdf (str) – Filename for the .hdf5 file. The .xdmf is saved with the same basename. Folder should already exist.
centers (np.ndarray of float) – (n_pos, 3) Coil positions.
m0 (np.ndarray of float) – (n_pos, 3) Coil orientation x-axis (looking at the active (patient) side of the coil pointing to the right).
m1 (np.ndarray of float) – (n_pos, 3) Coil orientation y-axis (looking at the active side of the coil pointing up away from the handle).
m2 (np.ndarray of float) – (n_pos, 3) Coil orientation z-axis (looking at the active (patient) side of the coil pointing to the patient).
datanames (str or list of str, optional) – (n_data) Dataset names for
datadata (np.ndarray, optional) – (n_pos, n_data) Dataset array with (len(poslist.pos), len(datanames()).
overwrite (bool, default: False) – Overwrite existing files.
