SciPy

pynibs.util package

Submodules

pynibs.util.cross module

pynibs.util.cross_setup module

pynibs.util.pyCross module

pynibs.util.quality_measures module

pynibs.util.quality_measures.c_map_comparison(c1, c2, t1, t2, nodes, tris)

Compares two c-maps in terms of NRMSD and calculates the geodesic distance between the hotspots

Parameters
  • c1 (ndarray of float [n_ele]) – First c-map

  • c2 (ndarray of float [n_ele]) – Second c-map (reference)

  • t1 (ndarray of float [3]) – Coordinates of the hotspot in the first c-map

  • t2 (ndarray of float [3]) – Coordinates of the hotspot in the second c-map

  • nodes (ndarray of float [n_nodes x 3]) – Node coordinates

  • tris (ndarray of float [n_tris x 3]) – Connectivity of ROI elements

Returns

  • nrmsd (float) – Normalized root-mean-square deviation between the two c-maps in (%)

  • gdist (float) – Geodesic distance between the two hotspots in (mm)

pynibs.util.quality_measures.euclidean_dist(nodes, tris, source, source_is_node=True)

Returns euclidean_dist distance of all nodes to source node (tria).

This is just a wrapper for the gdist package.

Example: with h5py.File(fn,’r’) as f:

tris = f[‘/mesh/elm/triangle_number_list’][:] nodes = f[‘/mesh/nodes/node_coord’][:]

nodes_dist_euc, tris_dist_euc = euclidean_dist(nodes, tris, 3017)

pynibs.write_data_hdf5(data_fn,

data=[tris_dist_euc, nodes_dist_euc], data_names=[“tris_dist_euc”, “nodes_dist_euc”, “])

pynibs.write_xdmf(data_fn,hdf5_geo_fn=fn)

Parameters
  • nodes (np.ndarray(n_nodes,3)) –

  • tris (np.ndarray(n_tris,3)) –

  • source (np.ndarray(int) or int) – geodesic distances of all nodes to this will be computed

  • source_is_node (bool) – Is source a node idx or a tr idx

Returns

  • nodes_dist (np.ndarray(n_nodes,))

  • tres_dist (np.ndarray(n_tris,))

pynibs.util.quality_measures.geodesic_dist(nodes, tris, source, source_is_node=True)

Returns geodesic distance of all nodes to source node (or tri).

This is just a wrapper for the gdist package.

Example: with h5py.File(fn,’r’) as f:

tris = f[‘/mesh/elm/triangle_number_list’][:] nodes = f[‘/mesh/nodes/node_coord’][:]

nodes_dist_ged, tris_dist_ged = geodesic_dist(nodes, tris, 3017)

pynibs.write_data_hdf5(data_fn,

data=[tris_dist_ged, nodes_dist_ged], data_names=[“tris_dist_ged”, “nodes_dist_ged”])

pynibs.write_xdmf(data_fn,hdf5_geo_fn=fn)

Parameters
  • nodes (np.ndarray(n_nodes,3)) –

  • tris (np.ndarray(n_tris,3)) –

  • source (np.ndarray(int) or int) – Geodesic distances of all nodes (or tri) to this will be computed

  • source_is_node (bool) – Is source a node idx or a tr idx

Returns

  • nodes_dist (np.ndarray(n_nodes,))

  • tris_dist (np.ndarray(n_tris,))

pynibs.util.quality_measures.nrmsd(array, array_ref, error_norm='relative', x_axis=False)

Determine the normalized root-mean-square deviation between input data and reference data.

normalized_rms = get_normalized_rms(array, array_ref)

Parameters
  • array (np.ndarray) – input data [ (x), y0, y1, y2 … ]

  • array_ref (np.ndarray) – reference data [ (x_ref), y0_ref, y1_ref, y2_ref … ] if array_ref is 1D, all sizes have to match

  • error_norm (str, optional, default="relative") – Decide if error is determined “relative” or “absolute”

  • x_axis (boolean, optional, default=False) – If True, the first column of array and array_ref is interpreted as the x-axis, where the data points are evaluated. If False, the data points are assumed to be at the same location.

Returns

normalized_rms – Normalized root-mean-square deviation between the columns of array and array_ref

Return type

ndarray of float [array.shape[1]]

pynibs.util.simnibs module

pynibs.util.simnibs.calc_e_in_midlayer_roi(phi_dadt, roi, subject, phi_scaling=1.0, mesh_idx=0, mesh=None, roi_hem='lh', depth=0.5, qoi=None)

This is to be called by Simnibs as postprocessing function per FEM solve.

Parameters
Returns

(roi.n_tris,4)

Return type

np.vstack((e_mag, e_norm, e_tan, e_angle)).transpose()

pynibs.util.simnibs.check_mesh(mesh, verbose=False)
pynibs.util.simnibs.fix_mesh(mesh, verbose=False)
pynibs.util.simnibs.read_coil_geo(fn_coil_geo)
Parameters

fn_coil_geo (str) – Filename of *.geo file created from SimNIBS containing the dipole information

Returns

  • dipole_pos (ndarray of float [n_dip x 3]) – Dipole positions (x, y, z)

  • dipole_mag (ndarray of float [n_dip x 1]) – Dipole magnitude

pynibs.util.simnibs.smooth_mesh(mesh, output_fn, smooth=0.8, approach='taubin', skin_only_output=False)

pynibs.util.util module

pynibs.util.util.add_center(var)

Adds center to argument list.

Parameters

var (list of float [2]) – List containing two values [f1,f2]

Returns

out – List containing the average value in the middle [f1, mean(f1,f2), f2]

Return type

list of float [3]

pynibs.util.util.bash(command)

Executes bash command and returns output message in stdout (uses os.popen).

Parameters

command (str) – Bash command

Returns

  • output (str) – Output from stdout

  • error (str) – Error message from stdout

pynibs.util.util.bash_call(command)

Executes bash command and returns output message in stdout (uses subprocess.Popen).

Parameters

command (str) – bash command

pynibs.util.util.calc_n_network_combs(n_e, n_c, n_i)

Determine number of combinations if all conditions may be replaced between N_i elements (mixed interaction)

Parameters
  • n_e (int) – Number of elements in the ROI

  • n_c (int) – Number of conditions (I/O curves)

  • n_i (int) – Number of maximum interactions

Returns

n_comb – Number of combinations

Return type

int

pynibs.util.util.compute_chunks(seq, num)

Splits up a sequence _seq_ into _num_ chunks of similar size. If len(seq) < num, (num-len(seq)) empty chunks are returned so that len(out) == num

Parameters
  • seq (list of something [N_ele]) – List containing data or indices, which is divided into chunks

  • num (int) – Number of chunks to generate

Returns

out – num sub-lists of seq with each of a similar number of elements (or empty).

Return type

list of num sublists

pynibs.util.util.cross_product(A, B)

Evaluates the cross product between the vector pairs in a and b using pure Python.

Parameters
  • A (nparray of float 2 x [N x 3]) –

  • B (nparray of float 2 x [N x 3]) – Input vectors, the cross product is evaluated between

Returns

c – Cross product between vector pairs in a and b

Return type

nparray of float [N x 3]

pynibs.util.util.cross_product_einsum2(a, b)

Evaluates the cross product between the vector pairs in a and b using the double Einstein sum.

Parameters
  • a (nparray of float 2 x [N x 3]) –

  • b (nparray of float 2 x [N x 3]) – Input vectors, the cross product is evaluated between

Returns

c – Cross product between vector pairs in a and b

Return type

nparray of float [N x 3]

pynibs.util.util.differential_evolution(fobj, bounds, mut=0.8, crossp=0.7, popsize=20, its=1000, **kwargs)

Differential evolution optimization algorithm

Parameters
  • fobj (function object) – Function to optimize

  • bounds (dict) – Dictionary containing the bounds of the free variables to optimize

  • mut (float) – Mutation factor

  • crossp (float) – Cross population factor

  • popsize (int) – Population size

  • its (int) – Number of iterations

  • kwargs (dict) – Arguments passed to fobj (constants etc…)

Returns

  • best (dict) – Dictionary containing the best values

  • fitness (float) – Fitness value of best solution

pynibs.util.util.euler_angles_to_rotation_matrix(theta)

Determines the rotation matrix from the three Euler angles theta = [Psi, Theta, Phi] (in rad), which rotate the coordinate system in the order z, y’, x’’.

Parameters

theta (nparray [3]) – Euler angles in rad

Returns

r – Rotation matrix (z, y’, x’’)

Return type

nparray [3 x 3]

pynibs.util.util.generalized_extreme_value_distribution(x, mu, sigma, k)

Generalized extreme value distribution

Parameters
  • x (ndarray of float [n_x]) – Events

  • mu (float) – Mean value

  • sigma (float) – Standard deviation

  • k (float) – Shape parameter

Returns

y – Probability density of events

Return type

ndarray of float [n_x]

pynibs.util.util.get_cartesian_product(array_list)

Generate a cartesian product of input arrays (all combinations).

cartesian_product = get_cartesian_product(array_list)

Parameters

array_list (list of 1D ndarray of float) – Arrays to compute the cartesian product with

Returns

cartesian_product – Array containing the cartesian products (all combinations of input vectors) (M, len(arrays))

Return type

ndarray of float

Examples

>>> import pygpc
>>> out = pygpc.get_cartesian_product(([1, 2, 3], [4, 5], [6, 7]))
>>> out
pynibs.util.util.invert(trans)

Invert rotation matrix.

Parameters

trans (nparray of float [3 x 3]) – Rotation matrix

Returns

rot_inv – Inverse rotation matrix

Return type

nparray of float [3 x 3]

pynibs.util.util.likelihood_posterior(x, y, fun, bounds=None, verbose=True, normalized_params=False, **params)

Determines the likelihood of the data following the function “fun” assuming a two variability source of the data pairs (x, y) using the posterior distribution.

Parameters
  • x (ndarray of float [n_points]) – x data

  • y (ndarray of float [n_points]) – y data

  • fun (function) – Function to fit the data to (e.g. sigmoid)

  • bounds (dict, optional, default: None) – Dictionary containing the bounds of “sigma_x” and “sigma_y” and the free parameters of fun

  • verbose (bool, optional, default: True) – Print function output after every calculation

  • normalized_params (bool, optional, default: False) – Are the parameters passed in normalized space between [0, 1]? If so, bounds are used to denormalize them before calculation

  • **params (dict) – Free parameters to optimize. Contains “sigma_x”, “sigma_y”, and the free parameters of fun

Returns

l – Negative likelihood

Return type

float

pynibs.util.util.list2dict(l)

Transform list of dicts with same keys to dict of list

Parameters

l (list of dict) – List containing dictionaries with same keys

Returns

d – Dictionary containing the entries in a list

Return type

dict of lists

pynibs.util.util.load_muaps(fn_muaps, fs=1000000.0, fs_downsample=100000.0)
pynibs.util.util.mutual_coherence(array)

Calculate the mutual coherence of a matrix A. It can also be referred as the cosine of the smallest angle between two columns.

mutual_coherence = mutual_coherence(array)

Parameters

array (ndarray of float) – Input matrix

Returns

mutual_coherence – Mutual coherence

Return type

float

pynibs.util.util.norm_percentile(data, percentile)

Normalizes data to a given percentile.

Parameters
  • data (nparray [n_data, ]) – Dataset to normalize

  • percentile (float) – Percentile of normalization value [0 … 100]

Returns

data_norm – Normalized dataset

Return type

nparray [n_data, ]

pynibs.util.util.normalize_rot(rot)

Normalize rotation matrix.

Parameters

rot (nparray of float [3 x 3]) – Rotation matrix

Returns

rot_norm – Normalized rotation matrix

Return type

nparray of float [3 x 3]

pynibs.util.util.quat_rotation_angle(q)

Computes the rotation angle from the quaternion in rad.

Parameters

q (nparray of float) – Quaternion, either only the imaginary part (length=3) [qx, qy, qz] or the full quaternion (length=4) [qw, qx, qy, qz]

Returns

alpha – Rotation angle of quaternion in rad

Return type

float

pynibs.util.util.quat_to_rot(q)

Computes the rotation matrix from quaternions.

Parameters

q (nparray of float) – Quaternion, either only the imaginary part (length=3) or the full quaternion (length=4)

Returns

rot – Rotation matrix, containing the x, y, z axis in the columns

Return type

nparray of float [3 x 3]

pynibs.util.util.quaternion_conjugate(q)

https://stackoverflow.com/questions/15425313/inverse-quaternion

Parameters

q

Returns

Return type

pynibs.util.util.quaternion_diff(q1, q2)

https://math.stackexchange.com/questions/2581668/ error-measure-between-two-rotations-when-one-matrix-might-not-be-a-valid-rotatio

Parameters
  • q1

  • q2

Returns

Return type

pynibs.util.util.quaternion_inverse(q)

https://stackoverflow.com/questions/15425313/inverse-quaternion

Parameters

q

Returns

Return type

pynibs.util.util.rd(array, array_ref)

Determine the relative difference between input data and reference data.

Parameters
  • array (np.ndarray) – input data [ (x), y0, y1, y2 … ]

  • array_ref (np.ndarray) – reference data [ (x_ref), y0_ref, y1_ref, y2_ref … ] if array_ref is 1D, all sizes have to match

Returns

rd – Relative difference between the columns of array and array_ref

Return type

ndarray of float [array.shape[1]]

pynibs.util.util.recursive_len(item)

Determine len of list of lists (recursively).

Parameters

item (list of list) – List of list

Returns

len – Total length of list of lists

Return type

int

pynibs.util.util.rot_to_quat(rot)

Computes the quaternions from rotation matrix. (see e.g. http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/)

Parameters

rot (nparray of float [3 x 3]) – Rotation matrix, containing the x, y, z axis in the columns

Returns

q – Quaternion, full (length=4)

Return type

nparray of float

pynibs.util.util.rotation_matrix_to_euler_angles(r)

Calculates the euler angles theta = [Psi, Theta, Phi] (in rad) from the rotation matrix R which, rotate the coordinate system in the order z, y’, x’’. (https://www.learnopencv.com/rotation-matrix-to-euler-angles/)

Parameters

r (np.array [3 x 3]) – Rotation matrix (z, y’, x’’)

Returns

theta – Euler angles in rad

Return type

np.array [3]

pynibs.util.util.sigmoid_log_p(x, p)
pynibs.util.util.tal2mni(coords, direction='tal2mni', style='nonlinear')

Transform Talairach coordinates into (SPM) MNI space and vice versa.

This is taken from https://imaging.mrc-cbu.cam.ac.uk/imaging/MniTalairach and http://gibms.mc.ntu.edu.tw/bmlab/tools/data-analysis-codes/mni2tal-m/

Parameters
  • coords (np.ndarray or list) – x,y,z coordinates

  • direction (str, default: 'tal2mni) – Transformation direction. One of (‘tal2mni’, ‘mni2tal’)

  • style (str, default: 'nonlinear') – Transformation style. One of (‘linear’, ‘nonlinear’)

Returns

coords_trans

Return type

np.ndarray

pynibs.util.util.unique_rows(a)

Returns the unique rows of np.array(a).

Parameters

a (nparray of float [m x n]) – Array to search for double row entries

Returns

a_unique – array a with only unique rows

Return type

np.array [k x n]

Module contents