SciPy

Welcome to pynibs’s documentation!

Contents:

pynibs

pynibs package

Subpackages

pynibs.exp package
Submodules
pynibs.exp.Mep module
pynibs.exp.brainsight module
pynibs.exp.brainvis module
pynibs.exp.exp module
pynibs.exp.tmsnav module
pynibs.exp.visor module
Module contents
pynibs.models package
Module contents
pynibs.util package
Submodules
pynibs.util.cross module
pynibs.util.cross_setup module
pynibs.util.pyCross module
pynibs.util.quality_measures module
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.calc_tet_volume(points, abs=True)

Calculate tetrahedra volumes.

pynibs.util.util.calc_tri_surface(points)

Calculate triangle surface areas.

pynibs.util.util.cell_data_to_point_data(tris, data_tris, nodes, method='nearest')

A wrapper for scipy.interpolate.griddata to interpolate cell data to node data.

Parameters
  • tris (np.ndarray) – element number list, (n_tri, 3)

  • data_tris (np.ndarray) – data in tris, , (n_tri x 3)

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

  • method (str, default: 'nearest') – Which method to use for interpolation. Default uses NearestNDInterpolator

Returns

data_nodes – Data in nodes

Return type

np.ndarray

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.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.find_nearest(array, value)

Given an “array”, and given a “value” , returns an index j such that “value” is between array[j] and array[j+1]. “array” must be monotonic increasing. j=-1 or j=len(array) is returned to indicate that “value” is out of range below and above respectively.

Parameters
  • array (nparray of float) – Monotonic increasing array

  • value (float) – Target value the nearest neighbor index in “array” is computed for

Returns

idx – Index j such that “value” is between array[j] and array[j+1]

Return type

int

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.get_indices_discontinuous_data(data, con, neighbor=False, deviation_factor=2, min_val=None, not_fitted_elms=None, crit='median', neigh_style='point')

Get element indices (and the best neighbor index), where the data is discontinuous

Parameters
  • data (ndarray of float [n_data]) – Data array to analyze given in the element center

  • con (ndarray of float [n_data, 3 or 4]) – Connectivity matrix

  • neighbor (boolean, optional, default=False) – Return also the element index of the “best” neighbor (w.r.t. median of data)

  • deviation_factor (float) – Allows data deviation from 1/deviation_factor < data[i]/median < deviation_factor

  • min_val (float, optional) – If given, only return elements which have a neighbor with data higher than min_val.

  • not_fitted_elms (ndarray) – If given, these elements are not used as neighbors

  • crit (str, default: median) – Criterium for best neighbor. Either median or max value

  • neigh_style (str, default: 'point') – Should neighbors share point or ‘edge’

Returns

  • idx_disc (list of int [n_disc]) – Index list containing the indices of the discontinuous elements

  • idx_neighbor (list of int [n_disc]) – Index list containing the indices of the “best” neighbors of the discontinuous elements

pynibs.util.util.get_sphere(mesh=None, mesh_fn=None, target=None, radius=None, roi_idx=None, roi=None, elmtype='tris')

Return element idx of elements within a certain distance to provided target. Elements might be ‘tris’ (default) or ‘tets’

If roi object / idx and mesh fn is provided, the roi is expected to have midlayer information and the roi geometry is used.

pynibs.util.util.in_hull(points, hull)

Test if points in points are in hull. points should be a [N x K] coordinates of N points in K dimensions. hull is either a scipy.spatial.Delaunay object or the [M x K] array of the coordinates of M points in Kdimensions for which Delaunay triangulation will be computed.

Parameters
  • points (nparray [N_points x 3]) – Set of floating point data to test whether they are lying inside the hull or not

  • hull (Delaunay instance or nparray [M x K]) – Surface data

Returns

inside – TRUE: point inside the hull FALSE: point outside the hull

Return type

boolean array

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 object) – Function object 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 list (recursively).

Parameters

item (list of list) – List of list

Returns

len – Total length of list of list

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

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

Returns

theta – Euler angles in rad

Return type

np.array [3]

pynibs.util.util.sample_sphere(n_points, r)

Creates n_points evenly spread in a sphere of radius r.

Parameters
  • n_points (int) – Number of points to be spread, must be odd

  • r (float) – Radius of sphere

Returns

points – Evenly spread points in a unit sphere

Return type

ndarray of float [N x 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.tets_in_sphere(mesh, target, radius, roi)

Worker function for get_sphere()

pynibs.util.util.tris_in_sphere(mesh, target, radius, roi)

Worker function for get_sphere()

Parameters
  • mesh (simnibs.mesh_io.Msh) –

  • target (np.ndarry) – Target coordinates x,y,z

  • roi (pynibs.ROI) –

Returns

tri_target_idx

Return type

np.ndarry

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

Submodules

pynibs.coil module

pynibs.freesurfer module

pynibs.hdf5_io module

pynibs.main module

pynibs.muap module

pynibs.neuron module

pynibs.opt module

pynibs.para module

pynibs.postproc module

pynibs.regression module

pynibs.roi module

pynibs.simnibs module

pynibs.subject module

pynibs.tensor_scaling module

pynibs.test_match_instrument_marker_string module

pynibs.tms_pulse module

Module contents

Indices and tables