pynibs package¶
Subpackages¶
Submodules¶
pynibs.coil module¶
All functions to operate on TMS coils go here, for example to create .xdmf
files to visualize coil positions.
- pynibs.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.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.check_coil_position(points, hull)¶
Check if magnetic dipoles are lying inside head region
- pynibs.coil.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
data
data (np.ndarray, optional) – Dataset array with shape =
(len(poslist.pos), len(datanames())
.overwrite (bool, default: False) – Overwrite existing files.
- pynibs.coil.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.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.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.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.get_coil_dipole_pos(coil_fn, matsimnibs)¶
Apply transformation to coil dipoles and return position.
- pynibs.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.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.ndarry) – (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.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.test_coil_position_gpc(parameters)¶
Testing valid coil positions for gPC analysis
- pynibs.coil.write_coil_pos_hdf5(fn_hdf, centers, m0, m1, m2, datanames=None, data=None, overwrite=False)¶
Creates a
.hdf5
+.xdmf
file tuple for all coil positions. Coil centers and coil orientations are saved, and - optionally - data for each position ifdata
anddatanames
are 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
data
data (np.ndarray, optional) – (n_pos, n_data) Dataset array with (len(poslist.pos), len(datanames()).
overwrite (bool, default: False) – Overwrite existing files.
pynibs.freesurfer module¶
This holds methods to interact with FreeSurfer ([1]), for example to translate FreeSurfer files into Paraview readable .vtk files.
References
Dale, A.M., Fischl, B., Sereno, M.I., 1999. Cortical surface-based analysis. I. Segmentation and surface reconstruction. Neuroimage 9, 179-194.
- pynibs.freesurfer.data_sub2avg(fn_subject_obj, fn_average_obj, hemisphere, fn_in_hdf5_data, data_hdf5_path, data_label, fn_out_hdf5_geo, fn_out_hdf5_data, mesh_idx=0, roi_idx=0, subject_data_in_center=True, data_substitute=-1, verbose=True, replace=True, reg_fn='sphere.reg')¶
Maps the data from the subject space to the average template. If the data is given only in an ROI, the data is mapped to the whole brain surface.
- Parameters:
fn_subject_obj (str) – Filename of subject object .hdf5 file (incl. path), e.g.
.../probands/subjectID/subjectID.hdf5
fn_average_obj (str) – Filename of average template object .pkl file (incl. path), e.g.
.../probands/avg_template/avg_template.hdf5
.hemisphere (str) – Define hemisphere to work on (
'lh'
or'rh'
for left or right hemisphere, respectively).fn_in_hdf5_data (str) – Filename of .hdf5 data input file containing the subject data.
data_hdf5_path (str) – Path in .hdf5 data file where data is stored (e.g.
'/data/tris/'
).data_label (str or list of str) – Label of datasets contained in hdf5 input file to map.
fn_out_hdf5_geo (str) – Filename of .hdf5 geo output file containing the geometry information.
fn_out_hdf5_data (str) – Filename of .hdf5 data output file containing the mapped data.
mesh_idx (int) – Index of mesh used in the simulations.
roi_idx (int) – Index of region of interest used in the simulations.
subject_data_in_center (bool, default: True) – Specify if the data is given in the center of the triangles or in the nodes.
data_substitute (float) – Data substitute with this number for all points outside the ROI mask
verbose (bool) – Verbose output (Default: True)
replace (bool) – Replace output files (Default: True)
reg_fn (str) – Sphere.reg fn
- Returns:
<Files> – Geometry and corresponding data files to plot with Paraview:
fn_out_hdf5_geo.hdf5: geometry file containing the geometry information of the average template
fn_out_hdf5_data.hdf5: geometry file containing the data
- Return type:
.hdf5 files
- pynibs.freesurfer.freesurfer2vtk(in_fns, out_folder, hem='lh', surf='pial', prefix=None, fs_subject='fsaverage', fs_subjects_dir=None)¶
Transform multiple FreeSurfer .mgh files into one .vtk file. This can be read with Paraview and others.
- Parameters:
out_folder (str) – Output folder.
hem (str, default: 'lh') – Which hemisphere:
'lh'
or'rh'
.surf (str, default: 'pial') – Which FreeSurfer surface:
'pial'
,'inflated'
, …prefix (str, optional) – Prefix to add to each filename.
fs_subject (str, default: 'fsaverage') – FreeSurfer subject.
fs_subjects_dir (str, optional) – FreeSurfer subjects directory. If not provided, read from environment.
- Returns:
<File> – One .vtk file with data as overlays from all .mgh files provided
- Return type:
out_folder/{prefix}_{hem}_{surf}.vtk
- pynibs.freesurfer.make_average_subject(subjects, subject_dir, average_dir, fn_reg='sphere.reg')¶
Generates the average template from a list of subjects using the FreeSurfer average.
- Parameters:
subjects (list of str) – Paths of subjects directories, where the FreeSurfer files are located, e.g. for simnibs mri2mesh
.../fs_SUBJECT_ID
.subject_dir (str) – Temporary subject directory of FreeSurfer (symlinks of subjects will be generated in there and average template will be temporarily stored before it is copied to
average_dir
).average_dir (str) – path to directory where average template will be stored, e.g. probands/avg_template_15/mesh/0/fs_avg_template_15.
fn_reg (str, default: 'sphere.reg' --> ?h.sphere.reg>) – Filename suffix of FreeSurfer registration file containing registration information to template.
- Returns:
<Files> – Average template in average_dir and registered curvature files,
?h.sphere.reg
in subjects/surf folders.- Return type:
.tif and .reg files
- pynibs.freesurfer.make_group_average(subjects=None, subject_dir=None, average=None, hemi='lh', template='mytemplate', steps=3, n_cpu=2, average_dir=None)¶
Creates a group average from scratch, based on one subject. This prevents for example the fsaverage problems of large elements at M1, etc. This is an implemntation of [2] ‘Creating a registration template from scratch (GW)’.
References
- Parameters:
subject_dir (str) – Temporary subject directory of FreeSurfer (symlinks of subjects will be generated in there and average template will be temporarily stored before it is copied to
average_dir
).average (str, default:
subjects[0]
) – Which subject to base new average template on.hemi (str, default: 'lh') –
Which hemisphere:
lh
orrh
.Deprecated since version 0.0.1: Don’t use any more.
template (str, default: 'mytemplate') – Basename of new template.
steps (int, default: 2) – Number of iterations.
n_cpu (int, default: 4) – How many cores for multithreading.
average_dir (str) – Path to directory where average template will be stored, e.g.
probands/avg_template_15/mesh/0/fs_avg_template_15
.
- Returns:
<File> (.tif file) –
SUBJECT_DIR/TEMPLATE*.tif
, TEMPLATE0.tif based on AVERAGE, rest on all subjects.<File> (.myreg file) –
SUBJECT_DIR/SUBJECT*/surf/HEMI.sphere.myreg*
.<File> (.tif file) – Subject wise sphere registration based on
TEMPLATE*.tif
.
- pynibs.freesurfer.read_curv_data(fname_curv, fname_inf, raw=False)¶
Read curvature data provided by FreeSurfer with optional normalization.
- Parameters:
fname_curv (str) – Filename of the FreeSurfer curvature file (e.g. ?h.curv), contains curvature data in nodes can be found in mri2mesh proband folder:
proband_ID/fs_ID/surf/?h.curv
.fname_inf (str) – Filename of inflated brain surface (e.g.
?h.inflated
), contains points and connectivity data of surface can be found in mri2mesh proband folder:proband_ID/fs_ID/surf/?h.inflated
.raw (bool) – If raw-data is returned or if the data is normalized to -1 for neg. and +1 for pos. curvature.
- Returns:
curv – Curvature data in element centers.
- Return type:
pynibs.muap module¶
pynibs.subject module¶
- class pynibs.subject.Subject(subject_id, subject_folder)¶
Bases:
object
Subject containing subject specific information, like mesh, roi, uncertainties, plot settings.
Notes
Initialization
sub = pynibs.subject(subject_ID, mesh)
Parameters
- idstr
Subject id.
- fn_meshstr
.msh or .hdf5 file containing the mesh information.
Subject.seg, segmentation information dictionary
- fn_lh_wmstr
Filename of left hemisphere white matter surface.
- fn_rh_wmstr
Filename of right hemisphere white matter surface.
- fn_lh_gmstr
Filename of left hemisphere grey matter surface.
- fn_rh_gmstr
Filename of right hemisphere grey matter surface.
- fn_lh_curvstr
Filename of left hemisphere curvature data on grey matter surface.
- fn_rh_curvstr
Filename of right hemisphere curvature data on grey matter surface.
Subject.mri, mri information dictionary
- fn_mri_T1str
Filename of T1 image.
- fn_mri_T2str
Filename of T2 image.
- fn_mri_DTIstr
Filename of DTI dataset.
- fn_mri_DTI_bvecstr
Filename of DTI bvec file.
- fn_mri_DTI_bvalstr
Filename of DTI bval file.
- fn_mri_conformstr
Filename of conform T1 image resulting from SimNIBS mri2mesh function.
Subject.ps, plot settings dictionary
see plot functions in para.py for more details
Subject.exp, experiment dictionary
- infostr
General information about the experiment.
- datestr
Date of experiment (e.g. 01/01/2018).
- fn_tms_navstr
Path to TMS navigator folder.
- fn_datastr
Path to data folder or files.
- fn_exp_csvstr
Filename of experimental data .csv file containing the merged experimental data information.
- fn_coilstr
Filename of .ccd or .nii file of coil used in the experiment (contains ID).
- fn_mri_niistr
Filename of MRI .nii file used during the experiment.
- condstr or list of str
Conditions in the experiment in the recorded order (e.g. [‘PA-45’, ‘PP-00’]).
- experimenterstr
Name of experimenter who conducted the experiment.
- incidentsstr
Description of special events occurred during the experiment.
Subject.mesh, mesh dictionary
- infostr
Information about the mesh (e.g. dicretization, etc.).
- fn_mesh_mshstr
Filename of the .msh file containing the FEM mesh.
- fn_mesh_hdf5str
Filename of the .hdf5 file containing the FEM mesh.
- seg_idxint
Index indicating to which segmentation dictionary the mesh belongs.
Subject.roi region of interest dictionary
- typestr
Specify type of ROI (‘surface’, ‘volume’)
- infostr
Info about the region of interest, e.g. “M1 midlayer from freesurfer mask xyz”.
- regionlist of str or float
Filename for freesurfer mask or
[[X_min, X_max], [Y_min, Y_max], [Z_min, Z_max]]
.- deltafloat
Distance parameter between WM and GM (0 -> WM, 1 -> GM) (for surfaces only).
- add_experiment_info(exp_dict)¶
Adding information about a particular experiment.
- Parameters:
exp_dict (dict of dict or list of dict) – Dictionary containing information about the experiment.
Notes
Adds Attributes
- explist of dict
Dictionary containing information about the experiment.
- add_mesh_info(mesh_dict)¶
Adding filename information of the mesh to the subject object (multiple filenames possible).
Notes
Adds Attributes
- Subject.meshlist of dict
Dictionaries containing the mesh information.
- add_mri_info(mri_dict)¶
Adding MRI information to the subject object (multiple MRIs possible).
- Parameters:
mri_dict (dict or list of dict) – Dictionary containing the MRI information of the subject.
Notes
Adds Attributes
- Subject.mrilist of dict
Dictionary containing the MRI information of the subject.
- add_plotsettings(ps_dict)¶
Adding ROI information to the subject object (multiple ROIs possible).
Notes
Adds Attributes
- Subject.pslist of dict
Dictionary containing plot settings of the subject.
- add_roi_info(roi_dict)¶
Adding ROI (surface) information of the mesh with mesh_index to the subject object (multiple ROIs possible).
- Parameters:
roi_dict (dict of dict or list of dict) – Dictionary containing the ROI information of the mesh with mesh_index
[mesh_idx][roi_idx]
.
Notes
Adds Attributes
- Subject.mesh[mesh_index].roilist of dict
Dictionaries containing ROI information.
- pynibs.subject.check_file_and_format(fname)¶
Checking existence of file and transforming to list if necessary.
- pynibs.subject.create_plot_settings_dict(plotfunction_type)¶
Creates a dictionary with default plotsettings.
- Parameters:
plotfunction_type (str) –
Plot function the dictionary is generated for:
’surface_vector_plot’
’surface_vector_plot_vtu’
’volume_plot’
’volume_plot_vtu’
- Returns:
ps (dict) – Dictionary containing the plotsettings.
axes (bool) – Show orientation axes.
background_color (nparray) – (1m 3) Set background color of exported image RGB (0…1).
calculator (str) – Format string with placeholder of the calculator expression the quantity to plot is modified with, e.g.: “{}^5”.
clip_coords (nparray of float) – (N_clips, 3) Coordinates of clip surface origins (x,y,z).
clip_normals (nparray of float) – (N_clips, 3) Surface normals of clip surfaces pointing in the direction where the volume is kept for clip_type = [‘clip’ …] (x,y,z).
clip_type (list of str) – Type of clipping:
’clip’: cut geometry but keep volume behind
’slice’: cut geometry and keep only the slice
coil_dipole_scaling (list [1 x 2]) – Specify the scaling type of the dipoles (2 entries):
coil_dipole_scaling[0]
:’uniform’: uniform scaling, i.e. all dipoles have the same size
’scaled’: size scaled according to dipole magnitude
coil_dipole_scaling[1]
:scalar scale parameter of dipole size
coil_dipole_color (str or list) – Color of the dipoles; either str to specify colormap (e.g. ‘jet’) or list of RGB values [1 x 3] (0…1).
coil_axes (bool, default: True) – Plot coil axes visualizing the principle direction and orientation of the coil.
colorbar_label (str) – Label of plotted data close to colorbar.
colorbar_position (list of float) – (1, 2) Position of colorbar (lower left corner) 0…1 [x_pos, y_pos].
colorbar_orientation (str) – Orientation of colorbar (
'Vertical'
,'Horizontal'
).colorbar_aspectratio (int) – Aspectratio of colorbar (higher values make it thicker).
colorbar_titlefontsize (float) – Fontsize of colorbar title.
colorbar_labelfontsize (float) – Fontsize of colorbar labels (numbers).
colorbar_labelformat (str) – Format of colorbar labels (e.g.: ‘%-#6.3g’).
colorbar_numberoflabels (int) – maximum number of colorbar labels.
colorbar_labelcolor (list of float) – (1, 3) Color of colorbar labels in RGB (0…1).
colormap (str or nparray) – If nparray [1 x 4*N]: custom colormap providing data and corresponding RGB values
if str: colormap of plotted data chosen from included presets:
’Cool to Warm’,
’Cool to Warm (Extended)’,
’Blue to Red Rainbow’,
’X Ray’,
’Grayscale’,
’jet’,
’hsv’,
’erdc_iceFire_L’,
’Plasma (matplotlib)’,
’Viridis (matplotlib)’,
’gray_Matlab’,
’Spectral_lowBlue’,
’BuRd’
’Rainbow Blended White’
’b2rcw’
colormap_categories (bool) – Use categorized (discrete) colormap.
datarange (list) – (1, 2) Minimum and Maximum of plotted datarange [MIN, MAX] (default: automatic).
domain_IDs (int or list of int) – Domain IDs surface plot: Index of surface where the data is plotted on (Default: 0) volume plot: Specify the domains IDs to show in plot (default: all) Attention! Has to be included in the dataset under the name ‘tissue’! e.g. for SimNIBS:
1 -> white matter (WM)
2 -> grey matter (GM)
3 -> cerebrospinal fluid (CSF)
4 -> skull
5 -> skin
domain_label (str) – Label of the dataset which contains the domain IDs (default: ‘tissue_type’).
edges (BOOL) – Show edges of mesh.
fname_in (str or list of str) – Filenames of input files, 2 possibilities:
.xdmf-file: filename of .xmdf (needs the corresponding .hdf5 file(s) in the same folder)
.hdf5-file(s): filename(s) of .hdf5 file(s) containing the data and the geometry. The data can be provided in the first hdf5 file and the geometry can be provided in the second file. However, both can be also provided in a single hdf5 file.
fname_png (str) – Name of output .png file (incl. path).
fname_vtu_volume (str) – Name of .vtu volume file containing volume data (incl. path).
fname_vtu_surface (str) – Name of .vtu surface file containing surface data (incl. path) (to distinguish tissues).
fname_vtu_coil (str, optional) – Name of coil .vtu file (incl. path).
info (str) – Information about the plot the settings belong to.
interpolate (bool) – Interpolate data for visual smoothness.
NanColor (list of float) –
RGB color values for “Not a Number” values (range 0 … 1).
opacitymap (np.ndarray) – Points defining the piecewise linear opacity transfer function (transparency) (default: no transparency) connecting data values with opacity (alpha) values ranging from 0 (max. transparency) to 1 (no transparency).
plot_function (str) – Function the plot is generated with:
’surface_vector_plot’
’surface_vector_plot_vtu’
’volume_plot’
’volume_plot_vtu’
png_resolution (float) – Resolution parameter of output image (1…5).
quantity (str) – Label of magnitude dataset to plot.
surface_color (np.ndarray) – (1, 3) Color of brain surface in RGB (0…1) for better visibility of tissue borders.
surface_smoothing (bool) – Smooth the plotted surface (True/False).
show_coil (bool, default: True) – show coil if present in dataset as block termed ‘coil’.
vcolor (np.ndarray of float) – (N_vecs, 3) Array containing the RGB values between 0…1 of the vector groups in dataset to plot.
vector_mode (dict) – Key determines the type how many vectors are shown:
’All Points’
’Every Nth Point’
’Uniform Spatial Distribution’
Value (int) is the corresponding number of vectors:
’All Points’ (not set)
’Every Nth Point’ (every Nth vector is shown in the grid)
’Uniform Spatial Distribution’ (not set)
view (list) – Camera position and angle in 3D space:
[[3 x CameraPosition], [3 x CameraFocalPoint], [3 x CameraViewUp], 1 x CameraParallelScale]
.viewsize (nparray [1 x 2]) – Set size of exported image in pixel [width x height] will be extra scaled by parameter png_resolution.
vlabels (list of str) – Labels of vector datasets to plot (other present datasets are ignored).
vscales (list of float) – Scale parameters of vector groups to plot.
vscale_mode (list of str [N_vecs x 1]) – List containing the type of vector scaling:
’off’: all vectors are normalized
’vector’: vectors are scaled according to their magnitudeeee
- pynibs.subject.fill_from_dict(obj, d)¶
Set all attributes from d in obj.
- Parameters:
obj (pynibs.Mesh or pynibs.roi.ROI) – Object to fill with
d
.d (dict) – Dictionary containing the attributes to set.
- Returns:
obj – Object with attributes set from
d
.- Return type:
pynibs.Mesh or pynibs.ROI
- pynibs.subject.load_subject(fname, filetype=None)¶
Wrapper for pkl and hdf5 subject loader
- Parameters:
- Returns:
subject – Loaded Subject object.
- Return type:
- pynibs.subject.load_subject_hdf5(fname)¶
Loading subject information from .hdf5 file and returning subject object.
- Parameters:
fname (str) – Filename with .hdf5 extension (incl. path).
- Returns:
subject – The Subject object.
- Return type:
- pynibs.subject.load_subject_pkl(fname)¶
Loading subject object from .pkl file.
- Parameters:
fname (str) – Filename with .pkl extension.
- Returns:
subject – Loaded Subject object.
- Return type:
- pynibs.subject.save_subject(subject_id, subject_folder, fname, mri_dict=None, mesh_dict=None, roi_dict=None, exp_dict=None, ps_dict=None, **kwargs)¶
Saves subject information in .pkl or .hdf5 format (preferred)
- Parameters:
- Returns:
<File> – Subject information
- Return type:
.hdf5 file
- pynibs.subject.save_subject_hdf5(subject_id, subject_folder, fname, mri_dict=None, mesh_dict=None, roi_dict=None, exp_dict=None, ps_dict=None, overwrite=True, check_file_exist=False, verbose=False, **kwargs)¶
Saving subject information in hdf5 file.
- Parameters:
subject_id (str) – ID of subject.
subject_folder (str) – Subject folder.
fname (str) – Filename with .hdf5 extension (incl. path).
exp_dict (list of dict or dict of dict, optional) – Experiment info.
ps_dict (list of dict, optional, default:None) – Plot-settings info.
overwrite (bool) – Overwrites existing .hdf5 file.
check_file_exist (bool) – Hide warnings.
verbose (bool) – Print information about meshes and ROIs.
kwargs (str or np.ndarray) – Additional information saved in the parent folder of the .hdf5 file.
- Returns:
<File> – Subject information.
- Return type:
.hdf5 file
pynibs.tensor_scaling module¶
- pynibs.tensor_scaling.ellipse_eccentricity(a, b)¶
Calculates the eccentricity of an 2D ellipse with the semi axis a and b. An eccentricity of 0 corresponds to a sphere and an eccentricity of 1 means complete eccentric (line) with full restriction to the other axis
- pynibs.tensor_scaling.rescale_lambda_centerized(D, s, tsc=False)¶
Rescales the eigenvalues of the matrix D according to their eccentricity. The scale factor is between 0…1 a scale factor of 0.5 would not alter the eigenvalues of the matrix D. A scale factor of 0 would unify all eigenvalues to one value such that it corresponds to a isotropic sphere. A scale factor of 1 alters the eigenvalues in such a way that the resulting ellipsoid is fully eccentric and anisotropic.
- pynibs.tensor_scaling.rescale_lambda_centerized_workhorse(D, s, tsc=False)¶
Rescales the eigenvalues of the matrix D according to their eccentricity. The scale factor is between 0…1 a scale factor of 0.5 would not alter the eigenvalues of the matrix D. A scale factor of 0 would unify all eigenvalues to one value such that it corresponds to a isotropic sphere. A scale factor of 1 alters the eigenvalues in such a way that the resulting ellipsoid is fully eccentric and anisotropic