pynets.core package

Submodules

pynets.core.nodemaker module

Created on Tue Nov 7 10:40:07 2017 Copyright (C) 2017

pynets.core.nodemaker.VoxTomm(img_affine, voxcoords)[source]

Function to convert a list of voxel coordinates to mm coordinates.

Parameters
img_affinearray

4 x 4 2D Numpy array that is the affine of the image space that the coordinates inhabit.

voxcoordslist

List of [x, y, z] or (x, y, z) coordinates in voxel-space.

pynets.core.nodemaker.coords_masker(roi, coords, labels, error, vox_size='2mm')[source]

Evaluate the affinity of any arbitrary list of coordinate nodes for a user-specified ROI mask.

Parameters
roistr

File path to binarized/boolean region-of-interest Nifti1Image file.

coordslist

List of (x, y, z) tuples in mm-space corresponding to a coordinate atlas used or which represent the center-of-mass of each parcellation node.

labelslist

List of string labels corresponding to ROI nodes.

errorint

Rounded euclidean distance, in units of voxel number, to use as a spatial error cushion in the case of evaluating the spatial affinity of a given list of coordinates to the given ROI mask.

Returns
coordslist

Filtered list of (x, y, z) tuples in mm-space with a spatial affinity for the specified ROI mask.

labelslist

Filtered list of string labels corresponding to ROI nodes with a spatial affinity for the specified ROI mask.

pynets.core.nodemaker.create_parcel_atlas(parcels_4d_img, label_intensities=None)[source]

Create a 3D Nifti1Image atlas parcellation of consecutive integer intensities from an input list of ROI’s.

Parameters
parcels_4d_imgNifti1Image

4D image stack of boolean numpy arrays or binarized Nifti1Images corresponding to ROI masks.

Returns
net_parcels_map_niftiNifti1Image

A nibabel-based nifti image consisting of a 3D array with integer voxel intensities corresponding to ROI membership.

parcel_list_explist

List of 3D boolean numpy arrays or binarized Nifti1Images corresponding to ROI masks, prepended with a background image of zeros.

pynets.core.nodemaker.create_spherical_roi_volumes(node_radius, coords, template_mask)[source]

Create volume ROI mask of spheres from a given set of coordinates and radius.

Parameters
node_radiusint

Spherical centroid node size in the case that coordinate-based centroids are used as ROI’s for tracking.

coordslist

List of (x, y, z) tuples in mm-space corresponding to a coordinate atlas used or which represent the center-of-mass of each parcellation node.

template_maskstr

Path to binarized version of standard (MNI)-space template Nifti1Image file.

Returns
parcels_4dlist
List of 3D boolean numpy arrays or binarized Nifti1Images corresponding

to ROI masks.

par_maxint

The maximum label intensity in the parcellation image.

node_radiusint

Spherical centroid node size in the case that coordinate-based centroids are used as ROI’s for tracking.

parcbool

Indicates whether to use the raw parcels as ROI nodes instead of coordinates at their center-of-mass.

pynets.core.nodemaker.drop_badixs_from_parcellation(parcellation, bad_idxs, enf_hemi=True)[source]
pynets.core.nodemaker.drop_coords_labels_from_restricted_parcellation(parcellation, coords, labels)[source]
pynets.core.nodemaker.enforce_hem_distinct_consecutive_labels(parcellation, label_names=None, background_label=0)[source]

Check for hemispherically distinct and consecutive labels and rebuild parcellation.

Parameters
parcellationstr

File path to atlas parcellation Nifti1Image in MNI template space.

label_nameslist

List of string label names corresponding to ROI nodes.

Returns
parcellationstr

File path to atlas parcellation Nifti1Image in MNI template space.

label_nameslist

List of string label names corresponding to ROI nodes.

pynets.core.nodemaker.fetch_nilearn_atlas_coords(atlas)[source]

Meta-API for nilearn’s coordinate atlas fetching API to retrieve any publically-available coordinate atlas by string name.

Parameters
atlasstr

Name of a Nilearn-hosted coordinate atlas supported for fetching. See Nilearn’s datasets.atlas module for more detailed reference.

Returns
coordslist

List of (x, y, z) tuples corresponding to a coordinate atlas.

atlas_namestr

Name of atlas parcellation (can differ slightly from fetch API string).

networks_listlist

List of subnet’s and their associated cooordinates, if predefined uniquely for a given atlas.

labelslist

List of string labels corresponding to atlas nodes.

pynets.core.nodemaker.gen_network_parcels(parcellation, subnet, labels, dir_path)[source]

Return a modified verion of an atlas parcellation label, where labels have been filtered based on their spatial affinity for a specified subnet definition.

Parameters
parcellationstr

File path to atlas parcellation Nifti1Image in MNI template space.

subnetstr
Resting-state subnet based on Yeo-7 and Yeo-17 naming (e.g. ‘Default’)

used to filter nodes in the study of brain subgraphs.

labelslist

List of string labels corresponding to ROI nodes.

dir_pathstr

Path to directory containing subject derivative data for given run.

Returns
out_pathstr

File path to a new, subnetwork-filtered atlas parcellation Nifti1Image.

pynets.core.nodemaker.get_names_and_coords_of_parcels(parcellation, background_label=0)[source]

Return list of coordinates and max label intensity for a 3D atlas parcellation image.

Parameters
parcellationstr

File path to atlas parcellation Nifti1Image in MNI template space.

Returns
coordslist

List of (x, y, z) tuples corresponding to the center-of-mass of each parcellation node.

atlasstr

An arbitrary identified for the atlas based on the filename.

par_maxint

The maximum label intensity in the parcellation image.

label_intensitieslist

A list of integer label intensity values from the parcellation.

pynets.core.nodemaker.get_node_attributes(node_files, emb_shape, atlas='BrainnetomeAtlasFan2016')[source]
pynets.core.nodemaker.get_node_membership(subnet, infile, coords, labels, parc, parcels_4d, perc_overlap=0.75, error=4)[source]

Evaluate the affinity of any arbitrary list of coordinate or parcel nodes for a user-specified subnet based on Yeo-7 or Yeo-17 definitions.

Parameters
subnetstr
Resting-state subnet based on Yeo-7 and Yeo-17 naming (e.g. ‘Default’)

used to filter nodes in the study of brain subgraphs.

infilestr

File path to Nifti1Image object whose affine will provide resampling reference for evaluation spatial proximity. Typically, this is an MNI-space template image.

coordslist

List of (x, y, z) tuples in mm-space corresponding to a coordinate atlas used or which represent the center-of-mass of each parcellation node.

labelslist

List of string labels corresponding to ROI nodes.

parcbool

Indicates whether to use parcels instead of coordinates as ROI nodes.

parcels_4dlist

List of 3D boolean numpy arrays or binarized Nifti1Images corresponding to ROI masks.

perc_overlapfloat

Value 0-1 indicating a threshold of spatial overlap to use as a spatial error cushion in the case of evaluating subnet membership from a given list of parcel masks. Default is 0.75.

errorint

Rounded euclidean distance, in units of voxel number, to use as a spatial error cushion in the case of evaluating subnet membership from a given list of coordinates. Default is 4.

Returns
coords_mmlist

Filtered list of (x, y, z) tuples in mm-space with a spatial affinity for the specified subnet.

RSN_parcelslist

Filtered list of 3D boolean numpy arrays or binarized Nifti1Images corresponding to ROI masks with a spatial affinity for the specified subnet.

net_labelslist

Filtered list of string labels corresponding to ROI nodes with a spatial affinity for the specified subnet.

subnetstr

Resting-state subnet based on Yeo-7 and Yeo-17 naming (e.g. ‘Default’) used to filter nodes in the study of brain subgraphs.

References

1

Thomas Yeo, B. T., Krienen, F. M., Sepulcre, J., Sabuncu, M. R., Lashkari, D., Hollinshead, M., … Buckner, R. L. (2011). The organization of the human cerebral cortex estimated by intrinsic functional connectivity. Journal of Neurophysiology. https://doi.org/10.1152/jn.00338.2011

2

Schaefer A, Kong R, Gordon EM, Laumann TO, Zuo XN, Holmes AJ, Eickhoff SB, Yeo BTT. Local-Global parcellation of the human cerebral cortex from intrinsic functional connectivity MRI, Cerebral Cortex, 29:3095-3114, 2018.

pynets.core.nodemaker.get_sphere(coords, r, vox_dims, dims)[source]

Return all points within r mm of coords. Generates a cube and then discards all points outside sphere.

Parameters
coordslist

List of (x, y, z) tuples corresponding to a coordinate atlas used or which represent the center-of-mass of each parcellation node.

rint

Radius for sphere.

vox_dimsarray/tuple

1D vector (x, y, z) of mm voxel resolution for sphere.

dimsarray/tuple

1D vector (x, y, z) of image dimensions for sphere.

Returns
neighborslist

A list of indices, within the dimensions of the image, that fall within a spherical neighborhood defined by the specified error radius of the list of the input coordinates.

References

1

Tor D., W. (2011). NeuroSynth: a new platform for large-scale automated synthesis of human functional neuroimaging data. Frontiers in Neuroinformatics.

pynets.core.nodemaker.mask_roi(dir_path, roi, mask, img_file)[source]

Create derivative ROI based on intersection of roi and brain mask.

Parameters
dir_pathstr

Path to directory containing subject derivative data for given run.

roistr

File path to binarized/boolean region-of-interest Nifti1Image file.

maskstr

Path to binarized/boolean brain mask Nifti1Image file.

img_filestr

File path to Nifti1Image to use to generate an epi-mask.

Returns
roistr

File path to binarized/boolean region-of-interest Nifti1Image file, reduced to the spatial intersection with the input brain mask.

pynets.core.nodemaker.mmToVox(img_affine, mmcoords)[source]

Function to convert a list of mm coordinates to voxel coordinates.

Parameters
img_affinearray

4 x 4 2D Numpy array that is the affine of the image space that the coordinates inhabit.

mmcoordslist

List of [x, y, z] or (x, y, z) coordinates in mm-space.

pynets.core.nodemaker.nilearn_atlas_helper(atlas, parc)[source]

Meta-API for nilearn’s parcellation-based atlas fetching API to retrieve any publically-available parcellation-based atlas by string name.

Parameters
atlasstr

Name of a Nilearn-hosted parcellation/label-based atlas supported for fetching. See Nilearn’s datasets.atlas module for more detailed references.

parcbool

Indicates whether to use the raw parcels as ROI nodes instead of coordinates at their center-of-mass.

Returns
labelslist

List of string labels corresponding to atlas nodes.

networks_listlist

List of subnet’s and their associated cooordinates, if predefined uniquely for a given atlas.

parcellationstr

File path to atlas parcellation Nifti1Image in MNI template space.

pynets.core.nodemaker.node_gen(coords, parcels_4d, labels, dir_path, ID, parc, atlas, parcellation)[source]

In the case that masking was not applied, this function generate nodes based on atlas definitions established by fetch_nodes_and_labels.

Parameters
coordslist

List of (x, y, z) tuples in mm-space corresponding to a coordinate atlas used or which represent the center-of-mass of each parcellation node.

parcels_4dlist
List of 3D boolean numpy arrays or binarized Nifti1Images corresponding

to ROI masks.

labelslist

List of string labels corresponding to ROI nodes.

dir_pathstr

Path to directory containing subject derivative data for given run.

IDstr

A subject id or other unique identifier.

parcbool

Indicates whether to use parcels instead of coordinates as ROI nodes.

atlasstr

Name of a Nilearn-hosted coordinate or parcellation/label-based atlas supported for fetching. See Nilearn’s datasets.atlas module for more detailed reference.

parcellationstr

File path to atlas parcellation Nifti1Image in MNI template space.

Returns
net_parcels_map_niftiNifti1Image
A nibabel-based nifti image consisting of a 3D array with integer voxel

intensities corresponding to ROI membership.

coordslist

List of (x, y, z) tuples in mm-space corresponding to a coordinate atlas used or which represent the center-of-mass of each parcellation node.

labelslist

List of string labels corresponding to ROI nodes.

atlasstr

Name of a Nilearn-hosted coordinate or parcellation/label-based atlas supported for fetching. See Nilearn’s datasets.atlas module for more detailed reference.

parcellationstr

File path to atlas parcellation Nifti1Image in MNI template space.

dir_pathstr

Path to directory containing subject derivative data for given run.

pynets.core.nodemaker.node_gen_masking(roi, coords, parcels_4d, labels, dir_path, ID, parc, atlas, parcellation, vox_size, perc_overlap=0.1, error=2)[source]

In the case that masking was applied, this function generate nodes based on atlas definitions established by fetch_nodes_and_labels.

Parameters
roistr

File path to binarized/boolean region-of-interest Nifti1Image file.

coordslist

List of (x, y, z) tuples in mm-space corresponding to a coordinate atlas used or which represent the center-of-mass of each parcellation node.

parcels_4dlist
List of 3D boolean numpy arrays or binarized Nifti1Images corresponding

to ROI masks.

labelslist

List of string labels corresponding to ROI nodes.

dir_pathstr

Path to directory containing subject derivative data for given run.

IDstr

A subject id or other unique identifier.

parcbool

Indicates whether to use parcels instead of coordinates as ROI nodes.

atlasstr

Name of a Nilearn-hosted coordinate or parcellation/label-based atlas supported for fetching. See Nilearn’s datasets.atlas module for more detailed reference.

parcellationstr

File path to atlas parcellation Nifti1Image in MNI template space.

perc_overlapfloat
Value 0-1 indicating a threshold of spatial overlap to use as a spatial

error cushion in the case of evaluating mask/subnet membership from a given list of parcel masks. Default is 0.75.

errorint

Rounded euclidean distance, in units of voxel number, to use as a spatial error cushion in the case of evaluating mask/subnet membership from a given list of coordinates. Default is 4.

Returns
net_parcels_map_niftiNifti1Image

A nibabel-based nifti image consisting of a 3D array with integer voxel intensities corresponding to ROI membership.

coordslist

List of (x, y, z) tuples in mm-space corresponding to a coordinate atlas used or which represent the center-of-mass of each parcellation node.

labelslist

List of string labels corresponding to ROI nodes.

atlasstr

Name of a Nilearn-hosted coordinate or parcellation/label-based atlas supported for fetching. See Nilearn’s datasets.atlas module for more detailed reference.

parcellationstr

File path to atlas parcellation Nifti1Image in MNI template space.

dir_pathstr

Path to directory containing subject derivative data for given run.

pynets.core.nodemaker.parcel_masker(roi, coords, parcels_4d, labels, dir_path, ID, perc_overlap, vox_size)[source]

Evaluate the affinity of any arbitrary list of parcel nodes for a user-specified ROI mask.

Parameters
roistr

File path to binarized/boolean region-of-interest Nifti1Image file.

coordslist

List of (x, y, z) tuples in mm-space corresponding to a coordinate atlas used or which represent the center-of-mass of each parcellation node.

parcels_4dlist
List of 3D boolean numpy arrays or binarized Nifti1Images corresponding

to ROI masks.

labelslist

List of string labels corresponding to ROI nodes.

dir_pathstr

Path to directory containing subject derivative data for given run.

IDstr

A subject id or other unique identifier.

perc_overlapfloat

Value 0-1 indicating a threshold of spatial overlap to use as a spatial error cushion in the case of evaluating ROI-mask membership from a given list of parcel masks.

Returns
coords_adjlist

Filtered list of (x, y, z) tuples in mm-space with a spatial affinity for the specified ROI mask.

labels_adjlist

Filtered list of string labels corresponding to ROI nodes with a spatial affinity for the specified ROI mask.

parcel_list_adjlist

Filtered list of 3D boolean numpy arrays or binarized Nifti1Images corresponding to ROI masks with a spatial affinity to the specified ROI mask.

pynets.core.nodemaker.parcel_naming(coords, vox_size)[source]

Perform Automated-Anatomical Labeling of each coordinate from a list of a voxel coordinates. This was adapted from a function of the same name created by Cameron Craddock and included in PyClusterROI (See: <https://github.com/ccraddock/cluster_roi/blob/master/parcel_naming.py>).

Parameters
coordslist

List of (x, y, z) tuples in voxel-space corresponding to a coordinate atlas used or which represent the center-of-mass of each parcellation node.

vox_sizestr

Voxel resolution (1mm or 2mm stored as strings with units).

Returns
labelslist

List of string labels corresponding to each coordinate’s closest anatomical label.

References

1

Craddock, R. C., James, G. A., Holtzheimer, P. E., Hu, X. P., & Mayberg, H. S. (2012). A whole brain fMRI atlas generated via spatially constrained spectral clustering. Human Brain Mapping. https://doi.org/10.1002/hbm.21333

2

N. Tzourio-Mazoyer; B. Landeau; D. Papathanassiou; F. Crivello; O. Etard; N. Delcroix; Bernard Mazoyer & M. Joliot (January 2002). “Automated Anatomical Labeling of activations in SPM using a Macroscopic Anatomical Parcellation of the MNI MRI single-subject brain”. NeuroImage. 15 (1): 273–289. doi:10.1006/nimg.2001.0978.

pynets.core.nodemaker.three_to_four_parcellation(parcellation)[source]

Return 4d Nifti1Image of boolean nifti masks where each masks corresponds to a unique atlas label for the provided atlas parcellation. Path string to Nifti1Image is input.

Parameters
parcellationstr

File path to atlas parcellation Nifti1Image in MNI template space.

Returns
img_listIterator of NiftiImages

List of binarized Nifti1Images corresponding to ROI masks for each unique atlas label.

pynets.core.thresholding module

Created on Tue Nov 7 10:40:07 2017 Copyright (C) 2017

pynets.core.thresholding.autofix(W, copy=True)[source]

Fix a bunch of common problems. More specifically, remove Inf and NaN, ensure exact binariness and symmetry (i.e. remove floating point instability), and zero diagonal.

Parameters
Wnp.ndarray

weighted connectivity matrix.

copybool

if True, returns a copy of the matrix. Otherwise, modifies the matrix in place. Default value=True.

Returns
——-
Wnp.ndarray

connectivity matrix with fixes applied.

References

1

Complex subnet measures of brain connectivity: Uses and interpretations. Rubinov M, Sporns O (2010) NeuroImage 52:1059-69.

pynets.core.thresholding.binarize(W, copy=True)[source]

Binarizes an input weighted connection matrix. If copy is not set, this function will modify W in place.

Parameters
WNxN np.ndarray

weighted connectivity matrix

copybool

if True, returns a copy of the matrix. Otherwise, modifies the matrix in place. Default value=True.

Returns
WNxN np.ndarray

binary connectivity matrix

References

1

Complex subnet measures of brain connectivity: Uses and interpretations. Rubinov M, Sporns O (2010) NeuroImage 52:1059-69.

pynets.core.thresholding.density_thresholding(conn_matrix, thr, max_iters=10000, interval=0.01)[source]

Iteratively apply an absolute threshold to achieve a target density.

Parameters
conn_matrixnp.ndarray

Weighted connectivity matrix

thrfloat

Density value between 0-1.

max_itersint

Maximum number of iterations for performing absolute thresholding. Default is 1000.

intervalfloat

Interval for increasing the absolute threshold for each iteration. Default is 0.01.

Returns
conn_matrixnp.ndarray

Thresholded connectivity matrix

References

1

van Wijk, B. C. M., Stam, C. J., & Daffertshofer, A. (2010). Comparing brain networks of different size and connectivity density using graph theory. PLoS ONE. https://doi.org/10.1371/journal.pone.0013701

2

Complex subnet measures of brain connectivity: Uses and interpretations. Rubinov M, Sporns O (2010) NeuroImage 52:1059-69.

pynets.core.thresholding.disparity_filter(G, weight='weight')[source]

Compute significance scores (alpha) for weighted edges in G as defined in Serrano et al. 2009.

Parameters
GObject

Weighted NetworkX graph.

weightstr

Key for edge data used as the edge weight w_ij. Default is ‘weight’.

Returns
BObject

Weighted NetworkX graph with a significance score (alpha) assigned to each edge.

References

1

M. A. Serrano et al. (2009) Extracting the Multiscale backbone of complex weighted networks. PNAS, 106:16, pp. 6483-6488.

pynets.core.thresholding.disparity_filter_alpha_cut(G, weight='weight', alpha_t=0.4, cut_mode='or')[source]

Compute significance scores (alpha) for weighted edges in G as defined in Serrano et al. 2009.

Parameters
GObject

Weighted NetworkX graph.

weightstr

Key for edge data used as the edge weight w_ij. Default is ‘weight’.

alpha_tfloat

The threshold, between 0 and 1, for the alpha parameter used to select the surviving edges. Default is 0.4.

cut_modestr

In the case of directed graphs. It represents the logic operation to filter out edges that do not pass the threshold value, combining the alpha_in and alpha_out attributes resulting from the disparity_filter function. Default is ‘or’. Possible strings: ‘or’, ‘and’.

Returns
BObject

Weighted NetworkX graph with a significance score (alpha) assigned to each edge. The resulting graph contains only edges that survived from the filtering with the alpha_t threshold.

References

1

M. A. Serrano et al. (2009) Extracting the Multiscale backbone of complex weighted networks. PNAS, 106:16, pp. 6483-6488.

pynets.core.thresholding.est_density(in_mat)[source]

Calculates the density of a given undirected graph.

Parameters
in_matNxN np.ndarray

weighted connectivity matrix.

Returns
densityfloat

Density of the graph.

pynets.core.thresholding.invert(W, copy=False)[source]

Inverts elementwise the weights in an input connection matrix. In other words, change the from the matrix of internode strengths to the matrix of internode distances. If copy is not set, this function will modify W in place.

Parameters
Wnp.ndarray

weighted connectivity matrix

copybool

if True, returns a copy of the matrix. Otherwise, modifies the matrix in place. Default value=True.

Returns
Wnp.ndarray

inverted connectivity matrix

References

1

Complex subnet measures of brain connectivity: Uses and interpretations. Rubinov M, Sporns O (2010) NeuroImage 52:1059-69.

pynets.core.thresholding.knn(conn_matrix, k)[source]

Creates a k-nearest neighbour graph.

Parameters
conn_matrixarray

Weighted NxN matrix.

kint

Number of nearest neighbours to include in the knn estimation.

Returns
graObj

KNN Weighted NetworkX graph.

pynets.core.thresholding.local_thresholding_prop(conn_matrix, thr)[source]

Threshold the adjacency matrix by building from the minimum spanning tree (MST) and adding successive N-nearest neighbour degree graphs to achieve target proportional threshold.

Parameters
conn_matrixarray

Weighted NxN matrix.

thrfloat

A proportional threshold, between 0 and 1, to achieve through local thresholding.

Returns
conn_matrix_thrarray

Weighted local-thresholding using MST, NxN matrix.

References

1

Alexander-Bloch, A. F., Gogtay, N., Meunier, D., Birn, R., Clasen, L., Lalonde, F., … Bullmore, E. T. (2010). Disrupted modularity and local connectivity of brain functional networks in childhood-onset schizophrenia. Frontiers in Systems Neuroscience. https://doi.org/10.3389/fnsys.2010.00147

2

Tewarie, P., van Dellen, E., Hillebrand, A., & Stam, C. J. (2015). The minimum spanning tree: An unbiased method for brain subnet analysis. NeuroImage. https://doi.org/10.1016/j.neuroimage.2014.10.015

pynets.core.thresholding.normalize(W)[source]

Normalizes an input weighted connection matrix.

Parameters
Wnp.ndarray

weighted connectivity matrix

Returns
Wnp.ndarray

normalized connectivity matrix

References

1

Complex subnet measures of brain connectivity: Uses and interpretations. Rubinov M, Sporns O (2010) NeuroImage 52:1059-69.

pynets.core.thresholding.perform_thresholding(conn_matrix, thr, min_span_tree, dens_thresh, disp_filt)[source]

References

1

Fornito, A., Zalesky, A., & Bullmore, E. T. (2016). Fundamentals of Brain subnet Analysis. In Fundamentals of Brain subnet Analysis. https://doi.org/10.1016/C2012-0-06036-X

pynets.core.thresholding.standardize(W)[source]

Normalizes an input weighted connection matrix [0, 1]

Parameters
Wnp.ndarray

weighted connectivity matrix

Returns
Wnp.ndarray

standardized connectivity matrix

References

1

Complex subnet measures of brain connectivity: Uses and interpretations. Rubinov M, Sporns O (2010) NeuroImage 52:1059-69.

pynets.core.thresholding.thr2prob(W, copy=True)[source]

Thresholds the near-zero ranks of a ranked graph.

Parameters
WNxN np.ndarray

Weighted connectivity matrix of ranks.

Returns
WNxN np.ndarray

Weighted connectivity matrix of ranks with no near-zero entries.

References

1

Complex subnet measures of brain connectivity: Uses and interpretations. Rubinov M, Sporns O (2010) NeuroImage 52:1059-69.

pynets.core.thresholding.thresh_func(dens_thresh, thr, conn_matrix, conn_model, subnet, ID, dir_path, roi, node_radius, min_span_tree, smooth, disp_filt, parc, prune, atlas, parcellation, labels, coords, norm, binary, hpass, signal, check_consistency=True)[source]

Threshold a functional connectivity matrix using any of a variety of methods.

Parameters
dens_threshbool

Indicates whether a target graph density is to be used as the basis for thresholding.

thrfloat

A value, between 0 and 1, to threshold the graph using any variety of methods triggered through other options.

conn_matrixarray

Adjacency matrix stored as an m x n array of nodes and edges.

conn_modelstr

Connectivity estimation model (e.g. corr for correlation, cov for covariance, sps for precision covariance, partcorr for partial correlation). sps type is used by default.

subnetstr

Resting-state subnet based on Yeo-7 and Yeo-17 naming (e.g. ‘Default’) used to filter nodes in the study of brain subgraphs.

IDstr

A subject id or other unique identifier.

dir_pathstr

Path to directory containing subject derivative data for given run.

roistr

File path to binarized/boolean region-of-interest Nifti1Image file.

node_radiusint

Spherical centroid node size in the case that coordinate-based centroids are used as ROI’s.

min_span_treebool

Indicates whether local thresholding from the Minimum Spanning Tree should be used.

smoothint

Smoothing width (mm fwhm) to apply to time-series when extracting signal from ROI’s.

disp_filtbool

Indicates whether local thresholding using a disparity filter and ‘backbone subnet’ should be used.

parcbool

Indicates whether to use parcels instead of coordinates as ROI nodes.

prunebool

Indicates whether to prune final graph of disconnected nodes/isolates.

atlasstr

Name of atlas parcellation used.

parcellationstr

File path to atlas parcellation Nifti1Image in MNI template space.

labelslist

List of string labels corresponding to ROI nodes.

coordslist

List of (x, y, z) tuples corresponding to a coordinate atlas used or which represent the center-of-mass of each parcellation node.

normint

Indicates method of normalizing resulting graph.

binarybool

Indicates whether to binarize resulting graph edges to form an unweighted graph.

hpassfloat

High-pass filter values (Hz) to apply to node-extracted time-series.

signalstr

The name of a valid function used to reduce the time-series region extraction.

Returns
conn_matrix_thrarray

Weighted, thresholded, NxN matrix.

edge_thresholdstr

The string percentage representation of thr.

est_pathstr

File path to the thresholded graph, conn_matrix_thr, saved as a numpy array in .npy format.

thrfloat

The value, between 0 and 1, used to threshold the graph using any variety of methods triggered through other options.

node_radiusint

Spherical centroid node size in the case that coordinate-based centroids are used as ROI’s.

subnetstr

Resting-state subnet based on Yeo-7 and Yeo-17 naming (e.g. ‘Default’) used to filter nodes in the study of brain subgraphs.

conn_modelstr

Connectivity estimation model (e.g. corr for correlation, cov for covariance, sps for precision covariance, partcorr for partial correlation). sps type is used by default.

roistr

File path to binarized/boolean region-of-interest Nifti1Image file.

smoothint

Smoothing width (mm fwhm) to apply to time-series when extracting signal from ROI’s.

prunebool

Indicates whether to prune final graph of disconnected nodes/isolates.

IDstr

A subject id or other unique identifier.

dir_pathstr

Path to directory containing subject derivative data for given run.

atlasstr

Name of atlas parcellation used.

parcellationstr

File path to atlas parcellation Nifti1Image in MNI template space.

labelslist

List of string labels corresponding to ROI nodes.

coordslist

List of (x, y, z) tuples corresponding to a coordinate atlas used or which represent the center-of-mass of each parcellation node.

normint

Indicates method of normalizing resulting graph.

binarybool

Indicates whether to binarize resulting graph edges to form an unweighted graph.

hpassfloat

High-pass filter values (Hz) to apply to node-extracted time-series.

signalstr

The name of a valid function used to reduce the time-series region extraction.

References

1

van Wijk, B. C. M., Stam, C. J., & Daffertshofer, A. (2010). Comparing brain networks of different size and connectivity density using graph theory. PLoS ONE. https://doi.org/10.1371/journal.pone.0013701

pynets.core.thresholding.thresh_raw_graph(conn_matrix, thr, min_span_tree, dens_thresh, disp_filt, est_path)[source]
pynets.core.thresholding.thresh_struct(dens_thresh, thr, conn_matrix, conn_model, subnet, ID, dir_path, roi, node_radius, min_span_tree, disp_filt, parc, prune, atlas, parcellation, labels, coords, norm, binary, track_type, atlas_for_streams, streams, traversal, min_length, error_margin, check_consistency=True)[source]

Threshold a structural connectivity matrix using any of a variety of methods.

Parameters
dens_threshbool

Indicates whether a target graph density is to be used as the basis for thresholding.

thrfloat

A value, between 0 and 1, to threshold the graph using any variety of methods triggered through other options.

conn_matrixarray

Adjacency matrix stored as an m x n array of nodes and edges.

conn_modelstr

Connectivity estimation model (e.g. corr for correlation, cov for covariance, sps for precision covariance, partcorr for partial correlation). sps type is used by default.

subnetstr

Resting-state subnet based on Yeo-7 and Yeo-17 naming (e.g. ‘Default’) used to filter nodes in the study of brain subgraphs.

IDstr

A subject id or other unique identifier.

dir_pathstr

Path to directory containing subject derivative data for given run.

roistr

File path to binarized/boolean region-of-interest Nifti1Image file.

node_radiusint

Spherical centroid node size in the case that coordinate-based centroids are used as ROI’s.

min_span_treebool

Indicates whether local thresholding from the Minimum Spanning Tree should be used.

disp_filtbool

Indicates whether local thresholding using a disparity filter and ‘backbone subnet’ should be used.

parcbool

Indicates whether to use parcels instead of coordinates as ROI nodes.

prunebool

Indicates whether to prune final graph of disconnected nodes/isolates.

atlasstr

Name of atlas parcellation used.

parcellationstr

File path to atlas parcellation Nifti1Image in MNI template space.

labelslist

List of string labels corresponding to ROI nodes.

coordslist

List of (x, y, z) tuples corresponding to a coordinate atlas used or which represent the center-of-mass of each parcellation node.

normint

Indicates method of normalizing resulting graph.

binarybool

Indicates whether to binarize resulting graph edges to form an unweighted graph.

track_typestr

Tracking algorithm used (e.g. ‘local’ or ‘particle’).

atlas_for_streamsstr

File path to atlas parcellation Nifti1Image in the morphological space of the streamlines.

streamsstr

File path to save streamline array sequence in .trk format.

traversalstr

The statistical approach to tracking. Options are: det (deterministic), closest (clos), boot (bootstrapped), and prob (probabilistic).

min_lengthint

Minimum fiber length threshold in mm to restrict tracking.

Returns
conn_matrix_thrarray

Weighted, thresholded, NxN matrix.

edge_thresholdstr

The string percentage representation of thr.

est_pathstr

File path to the thresholded graph, conn_matrix_thr, saved as a numpy array in .npy format.

thrfloat

The value, between 0 and 1, used to threshold the graph using any variety of methods triggered through other options.

node_radiusint

Spherical centroid node size in the case that coordinate-based centroids are used as ROI’s.

subnetstr

Resting-state subnet based on Yeo-7 and Yeo-17 naming (e.g. ‘Default’) used to filter nodes in the study of brain subgraphs.

conn_modelstr

Connectivity estimation model (e.g. corr for correlation, cov for covariance, sps for precision covariance, partcorr for partial correlation). sps type is used by default.

roistr

File path to binarized/boolean region-of-interest Nifti1Image file.

prunebool

Indicates whether to prune final graph of disconnected nodes/isolates.

IDstr

A subject id or other unique identifier.

dir_pathstr

Path to directory containing subject derivative data for given run.

atlasstr

Name of atlas parcellation used.

parcellationstr

File path to atlas parcellation Nifti1Image in MNI template space.

labelslist

List of string labels corresponding to ROI nodes.

coordslist

List of (x, y, z) tuples corresponding to a coordinate atlas used or which represent the center-of-mass of each parcellation node.

normint

Indicates method of normalizing resulting graph.

binarybool

Indicates whether to binarize resulting graph edges to form an unweighted graph.

track_typestr

Tracking algorithm used (e.g. ‘local’ or ‘particle’).

atlas_for_streamsstr

File path to atlas parcellation Nifti1Image in the morphological space of the streamlines.

streamsstr

File path to save streamline array sequence in .trk format.

traversalstr

The statistical approach to tracking. Options are: det (deterministic), closest (clos), boot (bootstrapped), and prob (probabilistic).

min_lengthint

Minimum fiber length threshold in mm to restrict tracking.

References

1

van Wijk, B. C. M., Stam, C. J., & Daffertshofer, A. (2010). Comparing brain networks of different size and connectivity density using graph theory. PLoS ONE. https://doi.org/10.1371/journal.pone.0013701

pynets.core.thresholding.threshold_absolute(W, thr, copy=True)[source]

This function thresholds the connectivity matrix by absolute weight magnitude. All weights below the given threshold, and all weights on the main diagonal (self-self connections) are set to 0. If copy is not set, this function will modify W in place.

Parameters
Wnp.ndarray

weighted connectivity matrix

thrfloat

absolute weight threshold

copybool

if True, returns a copy of the matrix. Otherwise, modifies the matrix in place. Default value=True.

Returns
Wnp.ndarray

thresholded connectivity matrix

References

1

Complex subnet measures of brain connectivity: Uses and interpretations. Rubinov M, Sporns O (2010) NeuroImage 52:1059-69.

pynets.core.thresholding.threshold_proportional(W, p, copy=True)[source]

This function “thresholds” the connectivity matrix by preserving a proportion p (0<p<1) of the strongest weights. All other weights, and all weights on the main diagonal (self-self connections) are set to 0. If copy is not set, this function will modify W in place.

Parameters
Wnp.ndarray

weighted connectivity matrix

pfloat

proportional weight threshold (0<p<1)

copybool

if True, returns a copy of the matrix. Otherwise, modifies the matrix in place. Default value=True.

Returns
Wnp.ndarray

thresholded connectivity matrix

Notes

The proportion of elements set to 0 is a fraction of all elements in the matrix, whether or not they are already 0. That is, this function has the following behavior: >> x = np.random.random_sample((10,10)) >> x_25 = threshold_proportional(x, .25) >> np.size(np.where(x_25)) #note this double counts each nonzero element 46 >> x_125 = threshold_proportional(x, .125) >> np.size(np.where(x_125)) 22 >> x_test = threshold_proportional(x_25, .5) >> np.size(np.where(x_test)) 46 That is, the 50% thresholding of x_25 does nothing because >=50% of the elements in x_25 are aleady <=0. This behavior is the same as in BCT. Be careful with matrices that are both signed and sparse.

References

1

Complex subnet measures of brain connectivity: Uses and interpretations. Rubinov M, Sporns O (2010) NeuroImage 52:1059-69.

pynets.core.thresholding.weight_conversion(W, wcm, copy=True)[source]

W_bin = weight_conversion(W, ‘binarize’); W_nrm = weight_conversion(W, ‘normalize’); L = weight_conversion(W, ‘lengths’); This function may either binarize an input weighted connection matrix, normalize an input weighted connection matrix or convert an input weighted connection matrix to a weighted connection-length matrix. Binarization converts all present connection weights to 1. Normalization scales all weight magnitudes to the range [0,1] and should be done prior to computing some weighted measures, such as the weighted clustering coefficient. Conversion of connection weights to connection lengths is needed prior to computation of weighted distance-based measures, such as distance and betweenness centrality. In a weighted connection subnet, higher weights are naturally interpreted as shorter lengths. The connection-lengths matrix here is defined as the inverse of the connection-weights matrix. If copy is not set, this function will modify W in place.

Parameters
WNxN np.ndarray

weighted connectivity matrix

wcmstr

weight conversion command. ‘binarize’ : binarize weights ‘normalize’ : normalize weights ‘lengths’ : convert weights to lengths (invert matrix)

copybool

if True, returns a copy of the matrix. Otherwise, modifies the matrix in place. Default value=True.

Returns
WNxN np.ndarray

connectivity matrix with specified changes

Notes

This function is included for compatibility with BCT. But there are other functions binarize(), normalize() and invert() which are simpler to call directly.

References

1

Complex subnet measures of brain connectivity: Uses and interpretations. Rubinov M, Sporns O (2010) NeuroImage 52:1059-69.

pynets.core.thresholding.weight_to_distance(G)[source]

Inverts all the edge weights so they become equivalent to distance measure. With a weight, the higher the value the stronger the connection. With a distance, the higher the value the “weaker” the connection. In this case there is no measurement unit for the distance, as it is just a conversion from the weights. The distances can be accessed in each node’s property with constants.

Parameters
GObject

Weighted NetworkX graph.

Returns
GObject

Inverted NetworkX graph equivalent to the distance measure.

pynets.core.utils module

Created on Fri Nov 10 15:44:46 2017 Copyright (C) 2017

pynets.core.utils.as_directory(dir_, remove=False, return_as_path=False)[source]

Convenience function to make a directory while returning it.

Parameters
dir_str, Path

File location to directory.

removebool, optional

Whether to remove a previously existing directory, by default False

Returns
str

Directory string.

pynets.core.utils.as_list(x)[source]

A function to convert an item to a list if it is not, or pass it through otherwise.

pynets.core.utils.build_args_from_config(modality, arg_dict)[source]
pynets.core.utils.checkConsecutive(l)[source]
pynets.core.utils.check_est_path_existence(est_path_list)[source]

Checks for the existence of each graph estimated and saved to disk.

Parameters
est_path_listlist

List of file paths to .npy file containing graph with thresholding applied.

Returns
est_path_list_exlist

List of existing file paths to .npy file containing graph with thresholding applied.

bad_ixsint

List of indices in est_path_list with non-existent and/or corrupt files.

pynets.core.utils.check_template_loads(template, template_mask, template_name)[source]
pynets.core.utils.collect_pandas_df(subnet, ID, net_mets_csv_list, plot_switch, multi_nets, multimodal, embed)[source]
API for summarizing independent lists of pickled pandas dataframes of

graph metrics for each modality, RSN, and roi.

Parameters
subnetstr

Resting-state subnet based on Yeo-7 and Yeo-17 naming (e.g. ‘Default’) used to filter nodes in the study of brain subgraphs.

IDstr

A subject id or other unique identifier.

net_mets_csv_listlist

List of file paths to pickled pandas dataframes as themselves.

plot_switchbool

Activate summary plotting (histograms, ROC curves, etc.)

multi_netslist

List of Yeo RSN’s specified in workflow(s).

multimodalbool

Indicates whether multiple modalities of input data have been specified.

Returns
combination_completebool

If True, then collect_pandas_df completed successfully.

pynets.core.utils.collectpandasjoin(net_mets_csv)[source]

Passes csv pandas dataframe as metadata.

Parameters
net_mets_csvstr

File path to csv pandas dataframe.

Returns
net_mets_csv_outstr

File path to csv pandas dataframe as itself.

pynets.core.utils.create_csv_path(dir_path, est_path)[source]

Create a csv path to save graph metrics.

Parameters
dir_pathstr

Path to directory containing subject derivative data for given run.

est_pathstr

File path to .npy file containing graph with thresholding applied.

Returns
out_pathstr

File path to .csv with graph metrics.

pynets.core.utils.create_est_path_diff(ID, subnet, conn_model, thr, roi, dir_path, node_radius, track_type, thr_type, parc, traversal, min_length, error_margin)[source]

Name the thresholded structural connectivity matrix file based on relevant graph-generating parameters.

Parameters
IDstr

A subject id or other unique identifier.

subnetstr

Resting-state subnet based on Yeo-7 and Yeo-17 naming (e.g. ‘Default’) used to filter nodes in the study of brain subgraphs.

conn_modelstr

Connectivity estimation model (e.g. corr for correlation, cov for covariance, sps for precision covariance, partcorr for partial correlation). sps type is used by default.

thrfloat

A value, between 0 and 1, to threshold the graph using any variety of methods triggered through other options.

roistr

File path to binarized/boolean region-of-interest Nifti1Image file.

dir_pathstr

Path to directory containing subject derivative data for given run.

node_radiusint

Spherical centroid node size in the case that coordinate-based centroids are used as ROI’s.

track_typestr

Tracking algorithm used (e.g. ‘local’ or ‘particle’).

thr_typestr

Type of thresholding performed (e.g. prop, abs, dens, mst, disp)

parcbool

Indicates whether to use parcels instead of coordinates as ROI nodes.

traversalstr

The statistical approach to tracking. Options are: det (deterministic), closest (clos), boot (bootstrapped), and prob (probabilistic).

min_lengthint

Minimum fiber length threshold in mm to restrict tracking.

Returns
est_pathstr

File path to .npy file containing graph with thresholding applied.

pynets.core.utils.create_est_path_func(ID, subnet, conn_model, thr, roi, dir_path, node_radius, smooth, thr_type, hpass, parc, signal)[source]

Name the thresholded functional connectivity matrix file based on relevant graph-generating parameters.

Parameters
IDstr

A subject id or other unique identifier.

subnetstr

Resting-state subnet based on Yeo-7 and Yeo-17 naming (e.g. ‘Default’) used to filter nodes in the study of brain subgraphs.

conn_modelstr

Connectivity estimation model (e.g. corr for correlation, cov for covariance, sps for precision covariance, partcorr for partial correlation). sps type is used by default.

thrfloat

A value, between 0 and 1, to threshold the graph using any variety of methods triggered through other options.

roistr

File path to binarized/boolean region-of-interest Nifti1Image file.

dir_pathstr

Path to directory containing subject derivative data for given run.

node_radiusint

Spherical centroid node size in the case that coordinate-based centroids are used as ROI’s.

smoothint

Smoothing width (mm fwhm) to apply to time-series when extracting signal from ROI’s.

thr_typestr

Type of thresholding performed (e.g. prop, abs, dens, mst, disp)

hpassbool

High-pass filter values (Hz) to apply to node-extracted time-series.

parcbool

Indicates whether to use parcels instead of coordinates as ROI nodes.

signalstr

The name of a valid function used to reduce the time-series region extraction.

Returns
est_pathstr

File path to .npy file containing graph with all specified combinations of hyperparameter characteristics.

pynets.core.utils.create_raw_path_diff(ID, subnet, conn_model, roi, dir_path, node_radius, track_type, parc, traversal, min_length, error_margin)[source]

Name the raw structural connectivity matrix file based on relevant graph-generating parameters.

Parameters
IDstr

A subject id or other unique identifier.

subnetstr

Resting-state subnet based on Yeo-7 and Yeo-17 naming (e.g. ‘Default’) used to filter nodes in the study of brain subgraphs.

conn_modelstr

Connectivity estimation model (e.g. corr for correlation, cov for covariance, sps for precision covariance, partcorr for partial correlation). sps type is used by default.

roistr

File path to binarized/boolean region-of-interest Nifti1Image file.

dir_pathstr

Path to directory containing subject derivative data for given run.

node_radiusint

Spherical centroid node size in the case that coordinate-based centroids are used as ROI’s.

track_typestr

Tracking algorithm used (e.g. ‘local’ or ‘particle’).

parcbool

Indicates whether to use parcels instead of coordinates as ROI nodes.

traversalstr

The statistical approach to tracking. Options are: det (deterministic), closest (clos), boot (bootstrapped), and prob (probabilistic).

min_lengthint

Minimum fiber length threshold in mm to restrict tracking.

Returns
est_pathstr

File path to .npy file containing graph with thresholding applied.

pynets.core.utils.create_raw_path_func(ID, subnet, conn_model, roi, dir_path, node_radius, smooth, hpass, parc, signal)[source]

Name the raw functional connectivity matrix file based on relevant graph-generating parameters.

Parameters
IDstr

A subject id or other unique identifier.

subnetstr

Resting-state subnet based on Yeo-7 and Yeo-17 naming (e.g. ‘Default’) used to filter nodes in the study of brain subgraphs.

conn_modelstr

Connectivity estimation model (e.g. corr for correlation, cov for covariance, sps for precision covariance, partcorr for partial correlation). sps type is used by default.

roistr

File path to binarized/boolean region-of-interest Nifti1Image file.

dir_pathstr

Path to directory containing subject derivative data for given run.

node_radiusint

Spherical centroid node size in the case that coordinate-based centroids are used as ROI’s.

smoothint

Smoothing width (mm fwhm) to apply to time-series when extracting signal from ROI’s.

hpassbool

High-pass filter values (Hz) to apply to node-extracted time-series.

parcbool

Indicates whether to use parcels instead of coordinates as ROI nodes.

signalstr

The name of a valid function used to reduce the time-series region extraction.

Returns
est_pathstr

File path to .npy file containing graph with all specified combinations of hyperparameter characteristics.

pynets.core.utils.decompress_nifti(infile)[source]
pynets.core.utils.do_dir_path(atlas, outdir)[source]

Creates an atlas subdirectory from the base directory of the given subject’s input file.

Parameters
atlasstr

Name of atlas parcellation used.

outdirstr

Path to base derivatives directory.

Returns
dir_pathstr

Path to directory containing subject derivative data for given run.

pynets.core.utils.dumpstacks(signal, frame)[source]
pynets.core.utils.filter_cols_from_targets(df, targets)[source]
pynets.core.utils.flatten(l)[source]

Flatten list of lists.

pynets.core.utils.get_file()[source]

Get a file’s base directory path.

pynets.core.utils.get_template_tf(template_name, vox_size)[source]
pynets.core.utils.kill_process_family(parent_pid)[source]
pynets.core.utils.load_mat(est_path)[source]

Load an adjacency matrix using any of a variety of methods.

Parameters
est_pathstr

File path to .npy file containing graph with thresholding applied.

pynets.core.utils.load_mat_ext(est_path, ID, subnet, conn_model, roi, prune, norm, binary, min_span_tree, dens_thresh, disp_filt)[source]
pynets.core.utils.load_runconfig(location=None)[source]
pynets.core.utils.merge_dicts(x, y)[source]

A function to merge two dictionaries, making it easier for us to make modality specific queries for dwi images (since they have variable extensions due to having an nii, bval, and bvec file).

pynets.core.utils.mergedicts(dict1, dict2)[source]
pynets.core.utils.missing_elements(L)[source]
pynets.core.utils.pass_meta_ins(conn_model, est_path, subnet, thr, prune, ID, roi, norm, binary)[source]

Passes parameters as metadata.

Parameters
conn_modelstr

Connectivity estimation model (e.g. corr for correlation, cov for covariance, sps for precision covariance, partcorr for partial correlation). sps type is used by default.

est_pathstr

File path to .npy file containing graph with thresholding applied.

subnetstr

Resting-state subnet based on Yeo-7 and Yeo-17 naming (e.g. ‘Default’) used to filter nodes in the study of brain subgraphs.

thrfloat

A value, between 0 and 1, to threshold the graph using any variety of methods triggered through other options.

prunebool

Indicates whether to prune final graph of disconnected nodes/isolates.

IDstr

A subject id or other unique identifier.

roistr

File path to binarized/boolean region-of-interest Nifti1Image file.

normint

Indicates method of normalizing resulting graph.

binarybool

Indicates whether to binarize resulting graph edges to form an unweighted graph.

Returns
conn_modelstr

Connectivity estimation model (e.g. corr for correlation, cov for covariance, sps for precision covariance, partcorr for partial correlation). sps type is used by default.

est_pathstr

File path to .npy file containing graph with thresholding applied.

subnetstr

Resting-state subnet based on Yeo-7 and Yeo-17 naming (e.g. ‘Default’) used to filter nodes in the study of brain subgraphs.

thrfloat

A value, between 0 and 1, to threshold the graph using any variety of methods triggered through other options.

prunebool

Indicates whether to prune final graph of disconnected nodes/isolates.

IDstr

A subject id or other unique identifier.

roistr

File path to binarized/boolean region-of-interest Nifti1Image file.

normint

Indicates method of normalizing resulting graph.

binarybool

Indicates whether to binarize resulting graph edges to form an unweighted graph.

pynets.core.utils.pass_meta_ins_multi(conn_model_func, est_path_func, network_func, thr_func, prune_func, ID_func, roi_func, norm_func, binary_func, conn_model_struct, est_path_struct, network_struct, thr_struct, prune_struct, ID_struct, roi_struct, norm_struct, binary_struct)[source]

Passes multimodal iterable parameters as metadata.

Parameters
conn_model_funcstr

Functional connectivity estimation model (e.g. corr for correlation, cov for covariance, sps for precision covariance, partcorr for partial correlation). sps type is used by default.

est_path_funcstr

File path to .npy file containing functional graph with thresholding applied.

network_funcstr

Functional resting-state subnet based on Yeo-7 and Yeo-17 naming (e.g. ‘Default’) used to filter nodes in the study of brain subgraphs.

thr_funcfloat

A value, between 0 and 1, to threshold the functional graph using any variety of methods triggered through other options.

prune_funcbool

Indicates whether to prune final functional graph of disconnected nodes/isolates.

ID_funcstr

A subject id or other unique identifier for the functional workflow.

roi_funcstr

File path to binarized/boolean region-of-interest Nifti1Image file applied to the functional data.

norm_funcint

Indicates method of normalizing resulting functional graph.

binary_funcbool

Indicates whether to binarize resulting graph edges to form an unweighted functional graph.

conn_model_structstr

Diffusion structural connectivity estimation model (e.g. corr for correlation, cov for covariance, sps for precision covariance, partcorr for partial correlation). sps type is used by default.

est_path_structstr

File path to .npy file containing diffusion structural graph with thresholding applied.

network_structstr

Diffusion structural resting-state subnet based on Yeo-7 and Yeo-17 naming (e.g. ‘Default’) used to filter nodes in the study of brain subgraphs.

thr_structfloat

A value, between 0 and 1, to threshold the diffusion structural graph using any variety of methods triggered through other options.

prune_structbool

Indicates whether to prune final diffusion structural graph of disconnected nodes/isolates.

ID_structstr

A subject id or other unique identifier for the diffusion structural workflow.

roi_structstr

File path to binarized/boolean region-of-interest Nifti1Image file applied too the dwi data.

norm_structint

Indicates method of normalizing resulting diffusion structural graph.

binary_structbool

Indicates whether to binarize resulting diffusion structural graph edges to form an unweighted graph.

Returns
conn_model_iterlistlist

List of connectivity estimation model parameters (e.g. corr for correlation, cov for covariance, sps for precision covariance, partcorr for partial correlation). sps type is used by default.

est_path_iterlistlist

List of file paths to .npy file containing graph with thresholding applied.

network_iterlistlist

List of resting-state networks based on Yeo-7 and Yeo-17 naming (e.g. ‘Default’) used to filter nodes in the study of brain subgraphs.

thr_iterlistlist

List of values, between 0 and 1, to threshold the graph using any variety of methods triggered through other options.

prune_iterlistlist

List of booleans indicating whether final graphs were pruned of disconnected nodes/isolates.

ID_iterlistlist

List of repeated subject id strings.

roi_iterlistlist

List of file paths to binarized/boolean region-of-interest Nifti1Image files.

norm_iterlistlist

Indicates method of normalizing resulting graph.

binary_iterlistlist

List of booleans indicating whether resulting graph edges to form an unweighted graph were binarized.

embed_iterlistlist

List of booleans indicating whether omnibus embedding of graph population was performed.

multimodal_iterlistlist

List of booleans indicating whether multiple modalities of input data have been specified.

pynets.core.utils.pass_meta_outs(conn_model_iterlist, est_path_iterlist, network_iterlist, thr_iterlist, prune_iterlist, ID_iterlist, roi_iterlist, norm_iterlist, binary_iterlist)[source]

Passes lists of iterable parameters as metadata.

Parameters
conn_model_iterlistlist

List of connectivity estimation model parameters (e.g. corr for correlation, cov for covariance, sps for precision covariance, partcorr for partial correlation). sps type is used by default.

est_path_iterlistlist

List of file paths to .npy file containing graph with thresholding applied.

network_iterlistlist

List of resting-state networks based on Yeo-7 and Yeo-17 naming (e.g. ‘Default’) used to filter nodes in the study of brain subgraphs.

thr_iterlistlist

List of values, between 0 and 1, to threshold the graph using any variety of methods triggered through other options.

prune_iterlistlist

List of booleans indicating whether final graphs were pruned of disconnected nodes/isolates.

ID_iterlistlist

List of repeated subject id strings.

roi_iterlistlist

List of file paths to binarized/boolean region-of-interest Nifti1Image files.

norm_iterlistlist

Indicates method of normalizing resulting graph.

binary_iterlistlist

List of booleans indicating whether resulting graph edges to form an unweighted graph were binarized.

Returns
conn_model_iterlistlist

List of connectivity estimation model parameters (e.g. corr for correlation, cov for covariance, sps for precision covariance, partcorr for partial correlation). sps type is used by default.

est_path_iterlistlist

List of file paths to .npy file containing graph with thresholding applied.

network_iterlistlist

List of resting-state networks based on Yeo-7 and Yeo-17 naming (e.g. ‘Default’) used to filter nodes in the study of brain subgraphs.

thr_iterlistlist

List of values, between 0 and 1, to threshold the graph using any variety of methods triggered through other options.

prune_iterlistlist

List of booleans indicating whether final graphs were pruned of disconnected nodes/isolates.

ID_iterlistlist

List of repeated subject id strings.

roi_iterlistlist

List of file paths to binarized/boolean region-of-interest Nifti1Image files.

norm_iterlistlist

Indicates method of normalizing resulting graph.

binary_iterlistlist

List of booleans indicating whether resulting graph edges to form an unweighted graph were binarized.

embed_iterlistlist

List of booleans indicating whether omnibus embedding of graph population was performed.

multimodal_iterlistlist

List of booleans indicating whether multiple modalities of input data have been specified.

pynets.core.utils.prune_suffices(res)[source]
pynets.core.utils.save_3d_to_4d(in_files)[source]
pynets.core.utils.save_4d_to_3d(in_file)[source]
pynets.core.utils.save_coords_and_labels_to_json(coords, labels, dir_path, subnet='all_nodes', indices=None)[source]

Save coordinates and labels to json.

Parameters
coordslist

List of (x, y, z) tuples corresponding to a coordinate atlas used or which represent the center-of-mass of each parcellation node.

labelslist

List of string labels corresponding to ROI nodes.

dir_pathstr

Path to directory containing subject derivative data for given run.

subnetstr

Restricted sub-subnet name.

Returns
nodes_pathstr

Path to nodes json metadata file.

pynets.core.utils.save_mat(conn_matrix, est_path, fmt=None)[source]

Save an adjacency matrix using any of a variety of methods.

Parameters
conn_matrixarray

Adjacency matrix stored as an m x n array of nodes and edges.

est_pathstr

File path to .npy file containing graph.

fmtstr
Format to save connectivity matrix/graph (e.g. .npy, .pkl, .graphml,

.txt, .ssv, .csv).

pynets.core.utils.save_mat_thresholded(conn_matrix, est_path_orig, thr_type, ID, subnet, thr, conn_model, roi, prune, norm, binary)[source]
pynets.core.utils.save_nifti_parcels_map(ID, dir_path, subnet, net_parcels_map_nifti, vox_size)[source]

This function takes a Nifti1Image parcellation object resulting from some form of masking and saves it to disk.

Parameters
IDstr

A subject id or other unique identifier.

dir_pathstr

Path to directory containing subject derivative data for given run.

subnetstr

Resting-state subnet based on Yeo-7 and Yeo-17 naming (e.g. ‘Default’) used to filter nodes in the study of brain subgraphs.

net_parcels_map_niftiNifti1Image

A nibabel-based nifti image consisting of a 3D array with integer voxel intensities corresponding to ROI membership.

vox_sizestr

Voxel size in mm. (e.g. 2mm).

Returns
net_parcels_nii_pathstr

File path to Nifti1Image consisting of a 3D array with integer voxel intensities corresponding to ROI membership.

pynets.core.utils.save_ts_to_file(roi, subnet, ID, dir_path, ts_within_nodes, smooth, hpass, node_radius, signal)[source]

This function saves the time-series 4D numpy array to disk as a .npy file.

Parameters
roistr

File path to binarized/boolean region-of-interest Nifti1Image file.

subnetstr

Resting-state subnet based on Yeo-7 and Yeo-17 naming (e.g. ‘Default’) used to filter nodes in the study of brain subgraphs.

IDstr

A subject id or other unique identifier.

dir_pathstr

Path to directory containing subject derivative data for given run.

ts_within_nodesarray

2D m x n array consisting of the time-series signal for each ROI node where m = number of scans and n = number of ROI’s, where ROI’s are parcel volumes.

smoothint

Smoothing width (mm fwhm) to apply to time-series when extracting signal from ROI’s.

hpassbool

High-pass filter values (Hz) to apply to node-extracted time-series.

node_radiusint

Spherical centroid node size in the case that coordinate-based centroids are used as ROI’s for time-series extraction.

signalstr

The name of a valid function used to reduce the time-series region extraction.

Returns
out_path_tsstr

Path to .npy file containing array of fMRI time-series extracted from nodes.

pynets.core.utils.timeout(seconds)[source]

Timeout function for hung calculations.

class pynets.core.utils.watchdog[source]

Bases: object

Methods

run

run()[source]

pynets.core.workflows module

Created on Tue Nov 7 10:40:07 2017 Copyright (C) 2017

pynets.core.workflows.dmri_connectometry(ID, atlas, subnet, node_radius, roi, parcellation, plot_switch, parc, ref_txt, procmem, dwi_file, fbval, fbvec, anat_file, thr, dens_thresh, conn_model, user_atlas_list, multi_thr, multi_atlas, max_thr, min_thr, step_thr, node_radii_list, conn_model_list, min_span_tree, use_parcel_naming, disp_filt, plugin_type, multi_nets, prune, mask, norm, binary, curv_thr_list, step_list, track_type, min_length, maxcrossing, error_margin, traversal, tiss_class, runtime_dict, execution_dict, multi_traversal, template_name, vox_size, waymask, min_length_list, error_margin_list, outdir)[source]

A function interface for generating a dMRI connectometry nested workflow

pynets.core.workflows.fmri_connectometry(func_file, ID, atlas, subnet, node_radius, roi, thr, parcellation, conn_model, dens_thresh, conf, plot_switch, parc, ref_txt, procmem, multi_thr, multi_atlas, max_thr, min_thr, step_thr, k, clust_mask, k_list, k_clustering, user_atlas_list, clust_mask_list, node_radii_list, conn_model_list, min_span_tree, use_parcel_naming, smooth, smooth_list, disp_filt, prune, multi_nets, clust_type, clust_type_list, plugin_type, mask, norm, binary, anat_file, runtime_dict, execution_dict, hpass, hpass_list, template_name, vox_size, local_corr, signal, signal_list, outdir)[source]

A function interface for generating an fMRI connectometry nested workflow

pynets.core.workflows.raw_graph_workflow(multi_thr, thr, multi_graph, graph, ID, subnet, conn_model, roi, prune, norm, binary, min_span_tree, dens_thresh, disp_filt, min_thr, max_thr, step_thr, wf, net_mets_node, runtime_dict)[source]
pynets.core.workflows.workflow_selector(func_file, ID, atlas, subnet, node_radius, roi, thr, parcellation, multi_nets, conn_model, dens_thresh, conf, plot_switch, dwi_file, anat_file, parc, ref_txt, procmem, multi_thr, multi_atlas, max_thr, min_thr, step_thr, k, clust_mask, k_list, k_clustering, user_atlas_list, clust_mask_list, prune, node_radii_list, conn_model_list, min_span_tree, verbose, plugin_type, use_parcel_naming, smooth, smooth_list, disp_filt, clust_type, clust_type_list, mask, norm, binary, fbval, fbvec, curv_thr_list, step_list, track_type, min_length, maxcrossing, error_margin, traversal, tiss_class, runtime_dict, execution_dict, embed, multi_traversal, multimodal, hpass, hpass_list, vox_size, multiplex, waymask, local_corr, min_length_list, error_margin_list, signal, signal_list, outdir, clean=True)[source]

A meta-interface for selecting modality-specific workflows to nest into a single-subject workflow

Module contents