Пример #1
0
def plot_conn_mat_struct(conn_matrix, conn_model, atlas_select, dir_path, ID,
                         network, label_names, roi, thr, node_size, smooth,
                         c_boot):
    from pynets.plotting import plot_graphs
    if roi:
        out_path_fig = "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s" % (
            dir_path, '/', str(ID), '_', str(atlas_select), "%s" %
            ("%s%s%s" % ('_', network, '_') if network else "_"),
            str(op.basename(roi).split('.')[0]), '_struct_adj_mat_',
            str(conn_model), '_', str(thr), '_', str(node_size), '%s' %
            ("mm_" if node_size != 'parc' else "_"), "%s" %
            ("%s%s" %
             (int(c_boot), 'nb_') if float(c_boot) > 0 else 'nb_'), "%s" %
            ("%s%s" %
             (smooth, 'fwhm.png') if float(smooth) > 0 else 'nosm.png'))
    else:
        out_path_fig = "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s" % (
            dir_path, '/', str(ID), '_', str(atlas_select), "%s" %
            ("%s%s%s" %
             ('_', network, '_') if network else "_"), 'struct_adj_mat_',
            str(conn_model), '_', str(thr), '_', str(node_size), '%s' %
            ("mm_" if node_size != 'parc' else "_"), "%s" %
            ("%s%s" %
             (int(c_boot), 'nb_') if float(c_boot) > 0 else 'nb_'), "%s" %
            ("%s%s" %
             (smooth, 'fwhm.png') if float(smooth) > 0 else 'nosm.png'))
    plot_graphs.plot_conn_mat(conn_matrix, label_names, out_path_fig)
    return
Пример #2
0
def plot_conn_mat_func(conn_matrix, conn_model, atlas, dir_path, ID, network, labels, roi, thr, node_size, smooth, c_boot, hpass):
    """

    :param conn_matrix:
    :param conn_model:
    :param atlas:
    :param dir_path:
    :param ID:
    :param network:
    :param labels:
    :param roi:
    :param thr:
    :param node_size:
    :param smooth:
    :param c_boot:
    :param hpass:
    :return:
    """
    import networkx as nx
    import os.path as op
    import community
    from pynets.plotting import plot_graphs

    out_path_fig = "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s" % (dir_path, '/', ID, '_', atlas,
                                                           '%s' % ("%s%s%s" % ('_', network, '_') if network else "_"),
                                                           '%s' % (op.basename(roi).split('.')[0] + '_' if roi is not None else ''),
                                                           'func_adj_mat_', conn_model, '_', thr, '_', node_size,
                                                           '%s' % ("mm_" if node_size != 'parc' else "_"),
                                                           '%s' % ("%s%s" % (int(c_boot), 'nb_') if float(c_boot) > 0 else 'nb_'),
                                                           '%s' % ("%s%s" % (smooth, 'fwhm.png') if float(smooth) > 0 else ''),
                                                           '%s' % ("%s%s" % (hpass, 'Hz.png') if hpass is not None else '.png'))

    plot_graphs.plot_conn_mat(conn_matrix, labels, out_path_fig)

    # Plot community adj. matrix
    G = nx.from_numpy_matrix(conn_matrix)
    try:
        node_comm_aff_mat = community.best_partition(G)
        print("%s%s%s" % ('Found ', str(len(np.unique(node_comm_aff_mat))), ' communities...'))
        out_path_fig_comm = "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s" % (dir_path, '/', ID, '_', atlas,
                                                                    '%s' % ("%s%s%s" % ('_', network, '_') if network else "_"),
                                                                    '%s' % (op.basename(roi).split('.')[0] + '_' if roi is not None else ''),
                                                                    'func_adj_mat_comm_', conn_model, '_', thr, '_',
                                                                    node_size, '%s' % ("mm_" if node_size != 'parc' else "_"),
                                                                    '%s' % ("%s%s" % (int(c_boot), 'nb_') if float(c_boot) > 0 else 'nb_'),
                                                                    '%s' % ("%s%s" % (smooth, 'fwhm.png') if float(smooth) > 0 else ''),
                                                                    '%s' % ("%s%s" % (hpass, 'Hz.png') if hpass is not None else '.png'))
        plot_graphs.plot_community_conn_mat(conn_matrix, labels, out_path_fig_comm, node_comm_aff_mat)
    except:
        print('\nWARNING: Louvain community detection failed. Cannot plot community matrix...')

    return
Пример #3
0
def test_plot_conn_mat_rois_gt_100():
    base_dir = str(Path(__file__).parent / "examples")
    dir_path = base_dir + '/002/fmri'
    conn_matrix = np.genfromtxt(
        dir_path +
        '/whole_brain_cluster_labels_PCA200/002_Default_est_sps_0.95.txt')
    labels_file_path = dir_path + '/whole_brain_cluster_labels_PCA200/Default_func_labelnames_wb.pkl'
    labels_file = open(labels_file_path, 'rb')
    labels = pickle.load(labels_file)
    out_path_fig = '/tmp/fig'

    start_time = time.time()
    plot_graphs.plot_conn_mat(conn_matrix, labels, out_path_fig)
    print("%s%s%s" % ('plot_timeseries --> finished: ',
                      str(np.round(time.time() - start_time, 1)), 's'))
Пример #4
0
def test_plot_conn_mat_rois_gt_100(plotting_data):
    """
    Test plot_conn_mat_rois_gt_100 functionality
    """

    temp_dir = tempfile.TemporaryDirectory()
    dir_path = str(temp_dir.name)

    conn_matrix = plotting_data['conn_matrix']
    labels = plotting_data['labels']

    start_time = time.time()
    plot_graphs.plot_conn_mat(conn_matrix, labels, dir_path, cmap='Blues')
    print("%s%s%s" % ('plot_timeseries --> finished: ', str(np.round(time.time() - start_time, 1)), 's'))

    temp_dir.cleanup()
Пример #5
0
def test_plot_conn_mat_rois_gt_100():
    """
    Test plot_conn_mat_rois_gt_100 functionality
    """
    base_dir = str(Path(__file__).parent / "examples")
    conn_matrix = np.genfromtxt(
        f"{base_dir}/miscellaneous/002_rsn-Default_nodetype-parc_est-sps_thrtype-PROP_thr-0.94.txt"
    )
    labels_file_path = f"{base_dir}/miscellaneous/Default_func_labelnames_wb.pkl"
    labels_file = open(labels_file_path, 'rb')
    labels = pickle.load(labels_file)
    out_path_fig = '/tmp/fig'

    start_time = time.time()
    plot_graphs.plot_conn_mat(conn_matrix, labels, out_path_fig, cmap='Blues')
    print("%s%s%s" % ('plot_timeseries --> finished: ',
                      str(np.round(time.time() - start_time, 1)), 's'))
Пример #6
0
def plot_conn_mat_struct(conn_matrix, conn_model, atlas, dir_path, ID, network,
                         labels, roi, thr, node_size, target_samples,
                         track_type, directget, max_length):
    """
    API for selecting among various structural connectivity matrix plotting approaches.

    Parameters
    ----------
    conn_matrix : array
        NxN matrix.
    conn_model : str
       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.
    atlas : str
        Name of atlas parcellation used.
    dir_path : str
        Path to directory containing subject derivative data for given run.
    ID : str
        A subject id or other unique identifier.
    network : str
        Resting-state network based on Yeo-7 and Yeo-17 naming (e.g. 'Default') used to filter nodes in the study of
        brain subgraphs.
    labels : list
        List of string labels corresponding to ROI nodes.
    roi : str
        File path to binarized/boolean region-of-interest Nifti1Image file.
    thr : float
        A value, between 0 and 1, to threshold the graph using any variety of methods
        triggered through other options.
    node_size : int
        Spherical centroid node size in the case that coordinate-based centroids
        are used as ROI's.
    target_samples : int
        Total number of streamline samples specified to generate streams.
    track_type : str
        Tracking algorithm used (e.g. 'local' or 'particle').
    directget : str
        The statistical approach to tracking. Options are: det (deterministic), closest (clos), boot (bootstrapped),
        and prob (probabilistic).
    max_length : int
        Maximum fiber length threshold in mm to restrict tracking.
    """
    from pynets.plotting import plot_graphs
    import networkx as nx
    import os.path as op
    out_path_fig = "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s" % (
        dir_path, '/', ID, '_modality-dwi_', '%s' %
        ("%s%s%s" %
         ('rsn-', network, '_') if network is not None else ''), '%s' %
        ("%s%s%s" % ('roi-', op.basename(roi).split('.')[0], '_')
         if roi is not None else ''), 'est-', conn_model, '_', '%s' %
        ("%s%s%s" % ('nodetype-spheres-', node_size, 'mm_') if
         ((node_size != 'parc') and
          (node_size is not None)) else 'nodetype-parc_'), "%s" %
        ("%s%s%s" % ('samples-', int(target_samples), 'streams_')
         if float(target_samples) > 0 else '_'), 'tt-', track_type, '_dg-',
        directget, '_ml-', max_length, '_thr-', thr, '_adj_mat.png')
    plot_graphs.plot_conn_mat(conn_matrix, labels, out_path_fig)

    # Plot community adj. matrix
    try:
        from pynets.stats.netstats import community_resolution_selection
        G = nx.from_numpy_matrix(np.abs(conn_matrix))
        _, node_comm_aff_mat, resolution, num_comms = community_resolution_selection(
            G)
        out_path_fig_comm = "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s" % (
            dir_path, '/', ID, '_modality-dwi_', '%s' %
            ("%s%s%s" %
             ('rsn-', network, '_') if network is not None else ''), '%s' %
            ("%s%s%s" % ('roi-', op.basename(roi).split('.')[0], '_')
             if roi is not None else ''), 'est-', conn_model, '_', '%s' %
            ("%s%s%s" % ('nodetype-spheres-', node_size, 'mm_') if
             ((node_size != 'parc') and
              (node_size is not None)) else 'nodetype-parc_'), "%s" %
            ("%s%s%s" % ('samples-', int(target_samples), 'streams_')
             if float(target_samples) > 0 else '_'), 'tt-', track_type, '_dg-',
            directget, '_ml-', max_length, '_thr-', thr, '_adj_mat_comm.png')
        plot_graphs.plot_community_conn_mat(conn_matrix, labels,
                                            out_path_fig_comm,
                                            node_comm_aff_mat)
    except:
        print(
            '\nWARNING: Louvain community detection failed. Cannot plot community matrix...'
        )

    return
Пример #7
0
def plot_conn_mat_func(conn_matrix, conn_model, atlas, dir_path, ID, network,
                       labels, roi, thr, node_size, smooth, c_boot, hpass):
    """
    API for selecting among various functional connectivity matrix plotting approaches.

    Parameters
    ----------
    conn_matrix : array
        NxN matrix.
    conn_model : str
       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.
    atlas : str
        Name of atlas parcellation used.
    dir_path : str
        Path to directory containing subject derivative data for given run.
    ID : str
        A subject id or other unique identifier.
    network : str
        Resting-state network based on Yeo-7 and Yeo-17 naming (e.g. 'Default') used to filter nodes in the study of
        brain subgraphs.
    labels : list
        List of string labels corresponding to ROI nodes.
    roi : str
        File path to binarized/boolean region-of-interest Nifti1Image file.
    thr : float
        A value, between 0 and 1, to threshold the graph using any variety of methods
        triggered through other options.
    node_size : int
        Spherical centroid node size in the case that coordinate-based centroids
        are used as ROI's.
    smooth : int
        Smoothing width (mm fwhm) to apply to time-series when extracting signal from ROI's.
    c_boot : int
        Number of bootstraps if user specified circular-block bootstrapped resampling of the node-extracted time-series.
    hpass : bool
        High-pass filter values (Hz) to apply to node-extracted time-series.
    """
    import networkx as nx
    import os.path as op
    from pynets.plotting import plot_graphs

    out_path_fig = "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s" % (
        dir_path, '/', ID, '_modality-func_', '%s' %
        ("%s%s%s" %
         ('rsn-', network, '_') if network is not None else ''), '%s' %
        ("%s%s%s" % ('roi-', op.basename(roi).split('.')[0], '_')
         if roi is not None else ''), 'est-', conn_model, '_', '%s' %
        ("%s%s%s" % ('nodetype-spheres-', node_size, 'mm_') if
         ((node_size != 'parc') and
          (node_size is not None)) else 'nodetype-parc_'), "%s" %
        ("%s%s%s" %
         ('boot-', int(c_boot), 'iter_') if float(c_boot) > 0 else ''), "%s" %
        ("%s%s%s" %
         ('smooth-', smooth, 'fwhm_') if float(smooth) > 0 else ''), "%s" %
        ("%s%s%s" % ('hpass-', hpass, 'Hz_') if hpass is not None else ''),
        '_thr-', thr, '_adj_mat.png')

    plot_graphs.plot_conn_mat(conn_matrix, labels, out_path_fig)

    # Plot community adj. matrix
    try:
        from pynets.stats.netstats import community_resolution_selection
        G = nx.from_numpy_matrix(np.abs(conn_matrix))
        _, node_comm_aff_mat, resolution, num_comms = community_resolution_selection(
            G)
        out_path_fig_comm = "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s" % (
            dir_path, '/', ID, '_modality-func_', '%s' %
            ("%s%s%s" %
             ('rsn-', network, '_') if network is not None else ''), '%s' %
            ("%s%s%s" % ('roi-', op.basename(roi).split('.')[0], '_')
             if roi is not None else ''), 'est-', conn_model, '_', '%s' %
            ("%s%s%s" % ('nodetype-spheres-', node_size, 'mm_') if
             ((node_size != 'parc') and
              (node_size is not None)) else 'nodetype-parc_'), "%s" %
            ("%s%s%s" %
             ('boot-', int(c_boot), 'iter_') if float(c_boot) > 0 else ''),
            "%s" %
            ("%s%s%s" %
             ('smooth-', smooth, 'fwhm_') if float(smooth) > 0 else ''), "%s" %
            ("%s%s%s" % ('hpass-', hpass, 'Hz_') if hpass is not None else ''),
            '_thr-', thr, '_adj_mat_comm.png')
        plot_graphs.plot_community_conn_mat(conn_matrix, labels,
                                            out_path_fig_comm,
                                            node_comm_aff_mat)
    except:
        print(
            '\nWARNING: Louvain community detection failed. Cannot plot community matrix...'
        )

    return
Пример #8
0
def plot_conn_mat_struct(conn_matrix, conn_model, atlas, dir_path, ID, network,
                         labels, roi, thr, node_size, target_samples,
                         track_type, directget, min_length, error_margin):
    """
    API for selecting among various structural connectivity matrix plotting
    approaches.

    Parameters
    ----------
    conn_matrix : array
        NxN matrix.
    conn_model : str
       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.
    atlas : str
        Name of atlas parcellation used.
    dir_path : str
        Path to directory containing subject derivative data for given run.
    ID : str
        A subject id or other unique identifier.
    network : str
        Resting-state network based on Yeo-7 and Yeo-17 naming
        (e.g. 'Default') used to filter nodes in the study of brain subgraphs.
    labels : list
        List of string labels corresponding to ROI nodes.
    roi : str
        File path to binarized/boolean region-of-interest Nifti1Image file.
    thr : float
        A value, between 0 and 1, to threshold the graph using any variety of
        methods triggered through other options.
    node_size : int
        Spherical centroid node size in the case that coordinate-based
        centroids are used as ROI's.
    target_samples : int
        Total number of streamline samples specified to generate streams.
    track_type : str
        Tracking algorithm used (e.g. 'local' or 'particle').
    directget : str
        The statistical approach to tracking. Options are:
        det (deterministic), closest (clos), boot (bootstrapped), and prob
        (probabilistic).
    min_length : int
        Minimum fiber length threshold in mm to restrict tracking.
    """
    import matplotlib.pyplot as plt
    from pynets.core.utils import load_runconfig
    import sys
    from pynets.plotting import plot_graphs
    import networkx as nx
    import os.path as op

    out_path_fig = \
        "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s" % \
        (dir_path,
         "/adjacency_",
         ID,
         "_modality-dwi_",
         "%s" % ("%s%s%s" % ("rsn-",
                             network,
                             "_") if network is not None else ""),
         "%s" % ("%s%s%s" % ("roi-",
                             op.basename(roi).split(".")[0],
                             "_") if roi is not None else ""),
         "model-",
         conn_model,
         "_",
         "%s" % ("%s%s%s" % ("nodetype-spheres-",
                             node_size,
                             "mm_") if (
             (node_size != "parc") and (
                 node_size is not None)) else "nodetype-parc_"),
         "%s" % ("%s%s%s" % ("samples-",
                             int(target_samples),
                             "streams_") if float(target_samples) > 0
                 else "_"),
         "tracktype-",
         track_type,
         "_directget-",
         directget,
         "_minlength-",
         min_length,
         "_tol-",
         error_margin,
         "_thr-",
         thr,
         ".png",
         )

    hardcoded_params = load_runconfig()
    try:
        cmap_name = hardcoded_params["plotting"]["structural"]["adjacency"][
            "color_theme"][0]
    except KeyError as e:
        print(
            e, "Plotting configuration not successfully extracted from"
            " runconfig.yaml")

    plot_graphs.plot_conn_mat(conn_matrix,
                              labels,
                              out_path_fig,
                              cmap=plt.get_cmap(cmap_name))

    # Plot community adj. matrix
    try:
        from pynets.stats.netstats import community_resolution_selection

        G = nx.from_numpy_matrix(np.abs(conn_matrix))
        _, node_comm_aff_mat, resolution, num_comms = \
            community_resolution_selection(G)
        out_path_fig_comm = \
            "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s" \
            % (dir_path,
               "/adjacency-communities_",
               ID,
               "_modality-dwi_",
               "%s" % ("%s%s%s" % ("rsn-",
                                   network,
                                   "_") if network is not None else ""),
               "%s" % ("%s%s%s" % ("roi-",
                                   op.basename(roi).split(".")[0],
                                   "_") if roi is not None else ""),
               "model-",
               conn_model,
               "_",
               "%s" % ("%s%s%s" % ("nodetype-spheres-",
                                   node_size,
                                   "mm_") if (
                   (node_size != "parc") and (
                       node_size is not None)) else "nodetype-parc_"),
               "%s" % ("%s%s%s" % ("samples-",
                                   int(target_samples),
                                   "streams_") if float(target_samples) > 0
                       else "_"),
               "tracktype-",
               track_type,
               "_directget-",
               directget,
               "_minlength-",
               min_length,
               "_tol-",
               error_margin,
               "_thr-",
               thr,
               ".png",
               )
        plot_graphs.plot_community_conn_mat(
            conn_matrix,
            labels,
            out_path_fig_comm,
            node_comm_aff_mat,
            cmap=plt.get_cmap(cmap_name),
        )
    except BaseException:
        print("\nWARNING: Louvain community detection failed. Cannot plot"
              " community matrix...")

    return
Пример #9
0
def plot_conn_mat_func(
    conn_matrix,
    conn_model,
    atlas,
    dir_path,
    ID,
    network,
    labels,
    roi,
    thr,
    node_size,
    smooth,
    hpass,
    extract_strategy,
):
    """
    API for selecting among various functional connectivity matrix plotting
    approaches.

    Parameters
    ----------
    conn_matrix : array
        NxN matrix.
    conn_model : str
       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.
    atlas : str
        Name of atlas parcellation used.
    dir_path : str
        Path to directory containing subject derivative data for given run.
    ID : str
        A subject id or other unique identifier.
    network : str
        Resting-state network based on Yeo-7 and Yeo-17 naming (e.g.
        'Default') used to filter nodes in the study of brain subgraphs.
    labels : list
        List of string labels corresponding to ROI nodes.
    roi : str
        File path to binarized/boolean region-of-interest Nifti1Image file.
    thr : float
        A value, between 0 and 1, to threshold the graph using any variety of
        methods triggered through other options.
    node_size : int
        Spherical centroid node size in the case that coordinate-based
        centroids are used as ROI's.
    smooth : int
        Smoothing width (mm fwhm) to apply to time-series when extracting
        signal from ROI's.
    hpass : bool
        High-pass filter values (Hz) to apply to node-extracted time-series.
    extract_strategy : str
        The name of a valid function used to reduce the time-series region
        extraction.
    """
    import matplotlib.pyplot as plt
    from pynets.core.utils import load_runconfig
    import sys
    import networkx as nx
    import os.path as op
    from pynets.plotting import plot_graphs

    out_path_fig = \
        "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s" % \
        (dir_path,
         "/adjacency_",
         ID,
         "_modality-func_",
         "%s" % ("%s%s%s" % ("rsn-",
                             network,
                             "_") if network is not None else ""),
         "%s" % ("%s%s%s" % ("roi-",
                             op.basename(roi).split(".")[0],
                             "_") if roi is not None else ""),
         "model-",
         conn_model,
         "_",
         "%s" % ("%s%s%s" % ("nodetype-spheres-",
                             node_size,
                             "mm_") if (
             (node_size != "parc") and (
                 node_size is not None)) else "nodetype-parc_"),
         "%s" % ("%s%s%s" % ("smooth-",
                             smooth,
                             "fwhm_") if float(smooth) > 0 else ""),
         "%s" % ("%s%s%s" % ("hpass-",
                             hpass,
                             "Hz_") if hpass is not None else ""),
         "%s" % ("%s%s%s" % ("extract-",
                             extract_strategy,
                             "") if extract_strategy is not None else ""),
         "_thr-",
         thr,
         ".png",
         )

    hardcoded_params = load_runconfig()
    try:
        cmap_name = hardcoded_params["plotting"]["functional"]["adjacency"][
            "color_theme"][0]
    except KeyError as e:
        print(
            e, "Plotting configuration not successfully extracted from"
            " runconfig.yaml")

    plot_graphs.plot_conn_mat(conn_matrix,
                              labels,
                              out_path_fig,
                              cmap=plt.get_cmap(cmap_name))

    # Plot community adj. matrix
    try:
        from pynets.stats.netstats import community_resolution_selection

        G = nx.from_numpy_matrix(np.abs(conn_matrix))
        _, node_comm_aff_mat, resolution, num_comms = \
            community_resolution_selection(G)
        out_path_fig_comm = \
            "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s" % \
            (dir_path,
             "/adjacency-communities_",
             ID,
             "_modality-func_",
             "%s" % ("%s%s%s" % ("rsn-",
                                 network,
                                 "_") if network is not None else ""),
             "%s" % ("%s%s%s" % ("roi-",
                                 op.basename(roi).split(".")[0],
                                 "_") if roi is not None else ""),
             "model-",
             conn_model,
             "_",
             "%s" % ("%s%s%s" % ("nodetype-spheres-",
                                 node_size,
                                 "mm_") if (
                 (node_size != "parc") and (
                     node_size is not None)) else "nodetype-parc_"),
             "%s" % ("%s%s%s" % ("smooth-",
                                 smooth,
                                 "fwhm_") if float(smooth) > 0 else ""),
             "%s" % ("%s%s%s" % ("hpass-",
                                 hpass,
                                 "Hz_") if hpass is not None else ""),
             "%s" % ("%s%s%s" % ("extract-",
                                 extract_strategy,
                                 "") if extract_strategy is not None else ""),
             "_thr-",
             thr,
             ".png",
             )
        plot_graphs.plot_community_conn_mat(
            conn_matrix,
            labels,
            out_path_fig_comm,
            node_comm_aff_mat,
            cmap=plt.get_cmap(cmap_name),
        )
    except BaseException:
        print("\nWARNING: Louvain community detection failed. Cannot plot "
              "community matrix...")

    return
Пример #10
0
def plot_conn_mat_func(conn_matrix, conn_model, atlas, dir_path, ID, network,
                       labels, roi, thr, node_size, smooth, hpass,
                       extract_strategy):
    """
    API for selecting among various functional connectivity matrix plotting approaches.

    Parameters
    ----------
    conn_matrix : array
        NxN matrix.
    conn_model : str
       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.
    atlas : str
        Name of atlas parcellation used.
    dir_path : str
        Path to directory containing subject derivative data for given run.
    ID : str
        A subject id or other unique identifier.
    network : str
        Resting-state network based on Yeo-7 and Yeo-17 naming (e.g. 'Default') used to filter nodes in the study of
        brain subgraphs.
    labels : list
        List of string labels corresponding to ROI nodes.
    roi : str
        File path to binarized/boolean region-of-interest Nifti1Image file.
    thr : float
        A value, between 0 and 1, to threshold the graph using any variety of methods
        triggered through other options.
    node_size : int
        Spherical centroid node size in the case that coordinate-based centroids
        are used as ROI's.
    smooth : int
        Smoothing width (mm fwhm) to apply to time-series when extracting signal from ROI's.
    hpass : bool
        High-pass filter values (Hz) to apply to node-extracted time-series.
    extract_strategy : str
        The name of a valid function used to reduce the time-series region extraction.
    """
    import matplotlib.pyplot as plt
    import pkg_resources
    import yaml
    import sys
    import networkx as nx
    import os.path as op
    from pynets.plotting import plot_graphs

    out_path_fig = "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s" % (
        dir_path, '/', ID, '_modality-func_', '%s' %
        ("%s%s%s" %
         ('rsn-', network, '_') if network is not None else ''), '%s' %
        ("%s%s%s" % ('roi-', op.basename(roi).split('.')[0], '_')
         if roi is not None else ''), 'est-', conn_model, '_', '%s' %
        ("%s%s%s" % ('nodetype-spheres-', node_size, 'mm_') if
         ((node_size != 'parc') and
          (node_size is not None)) else 'nodetype-parc_'), "%s" %
        ("%s%s%s" %
         ('smooth-', smooth, 'fwhm_') if float(smooth) > 0 else ''), "%s" %
        ("%s%s%s" %
         ('hpass-', hpass, 'Hz_') if hpass is not None else ''), "%s" %
        ("%s%s%s" % ('extract-', extract_strategy, '_') if extract_strategy
         is not None else ''), '_thr-', thr, '_adj_mat.png')

    with open(pkg_resources.resource_filename("pynets", "runconfig.yaml"),
              'r') as stream:
        hardcoded_params = yaml.load(stream)
        try:
            cmap_name = hardcoded_params['plotting']['functional'][
                'adjacency']['color_theme'][0]
        except KeyError:
            print(
                'ERROR: Plotting configuration not successfully extracted from runconfig.yaml'
            )
            sys.exit(0)
    stream.close()

    plot_graphs.plot_conn_mat(conn_matrix,
                              labels,
                              out_path_fig,
                              cmap=plt.get_cmap(cmap_name))

    # Plot community adj. matrix
    try:
        from pynets.stats.netstats import community_resolution_selection
        G = nx.from_numpy_matrix(np.abs(conn_matrix))
        _, node_comm_aff_mat, resolution, num_comms = community_resolution_selection(
            G)
        out_path_fig_comm = "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s" % (
            dir_path, '/', ID, '_modality-func_', '%s' %
            ("%s%s%s" %
             ('rsn-', network, '_') if network is not None else ''), '%s' %
            ("%s%s%s" % ('roi-', op.basename(roi).split('.')[0], '_')
             if roi is not None else ''), 'est-', conn_model, '_', '%s' %
            ("%s%s%s" % ('nodetype-spheres-', node_size, 'mm_') if
             ((node_size != 'parc') and
              (node_size is not None)) else 'nodetype-parc_'), "%s" %
            ("%s%s%s" %
             ('smooth-', smooth, 'fwhm_') if float(smooth) > 0 else ''), "%s" %
            ("%s%s%s" %
             ('hpass-', hpass, 'Hz_') if hpass is not None else ''), "%s" %
            ("%s%s%s" % ('extract-', extract_strategy, '_') if extract_strategy
             is not None else ''), '_thr-', thr, '_adj_mat_comm.png')
        plot_graphs.plot_community_conn_mat(conn_matrix,
                                            labels,
                                            out_path_fig_comm,
                                            node_comm_aff_mat,
                                            cmap=plt.get_cmap(cmap_name))
    except:
        print(
            '\nWARNING: Louvain community detection failed. Cannot plot community matrix...'
        )

    return
Пример #11
0
def plot_conn_mat_func(conn_matrix, conn_model, atlas_select, dir_path, ID,
                       network, label_names, roi, thr, node_size, smooth,
                       c_boot):
    import networkx as nx
    import os.path as op
    from pynets.plotting import plot_graphs
    from pynets.stats.netstats import modularity_louvain_und_sign
    if roi:
        out_path_fig = "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s" % (
            dir_path, '/', str(ID), '_', str(atlas_select), "%s" %
            ("%s%s%s" % ('_', network, '_') if network else "_"),
            str(op.basename(roi).split('.')[0]), '_func_adj_mat_',
            str(conn_model), '_', str(thr), '_', str(node_size), '%s' %
            ("mm_" if node_size != 'parc' else "_"), "%s" %
            ("%s%s" %
             (int(c_boot), 'nb_') if float(c_boot) > 0 else 'nb_'), "%s" %
            ("%s%s" %
             (smooth, 'fwhm.png') if float(smooth) > 0 else 'nosm.png'))
        out_path_fig_comm = "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s" % (
            dir_path, '/', str(ID), '_', str(atlas_select), "%s" %
            ("%s%s%s" % ('_', network, '_') if network else "_"),
            str(op.basename(roi).split('.')[0]), '_func_adj_mat_communities_',
            str(conn_model), '_', str(thr), '_', str(node_size), '%s' %
            ("mm_" if node_size != 'parc' else "_"), "%s" %
            ("%s%s" %
             (int(c_boot), 'nb_') if float(c_boot) > 0 else 'nb_'), "%s" %
            ("%s%s" %
             (smooth, 'fwhm.png') if float(smooth) > 0 else 'nosm.png'))
    else:
        out_path_fig = "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s" % (
            dir_path, '/', str(ID), '_', str(atlas_select), "%s" %
            ("%s%s%s" %
             ('_', network, '_') if network else "_"), 'func_adj_mat_',
            str(conn_model), '_', str(thr), '_', str(node_size), '%s' %
            ("mm_" if node_size != 'parc' else "_"), "%s" %
            ("%s%s" %
             (int(c_boot), 'nb_') if float(c_boot) > 0 else 'nb_'), "%s" %
            ("%s%s" %
             (smooth, 'fwhm.png') if float(smooth) > 0 else 'nosm.png'))
        out_path_fig_comm = "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s" % (
            dir_path, '/', str(ID), '_', str(atlas_select), "%s" %
            ("%s%s%s" % ('_', network, '_') if network else "_"),
            'func_adj_mat_communities_', str(conn_model), '_', str(thr), '_',
            str(node_size), '%s' %
            ("mm_" if node_size != 'parc' else "_"), "%s" %
            ("%s%s" %
             (int(c_boot), 'nb_') if float(c_boot) > 0 else 'nb_'), "%s" %
            ("%s%s" %
             (smooth, 'fwhm.png') if float(smooth) > 0 else 'nosm.png'))

    plot_graphs.plot_conn_mat(conn_matrix, label_names, out_path_fig)
    # Plot community adj. matrix
    gamma = nx.density(nx.from_numpy_array(conn_matrix))
    try:
        if network or len(conn_matrix) < 100:
            [node_comm_aff_mat,
             q] = modularity_louvain_und_sign(conn_matrix,
                                              gamma=float(gamma * 0.001))
        else:
            [node_comm_aff_mat,
             q] = modularity_louvain_und_sign(conn_matrix,
                                              gamma=float(gamma * 0.01))
        print("%s%s%s%s%s" % ('Found ', str(len(np.unique(node_comm_aff_mat))),
                              ' communities using γ=', str(gamma), '...'))
        plot_graphs.plot_community_conn_mat(conn_matrix, label_names,
                                            out_path_fig_comm,
                                            node_comm_aff_mat)
    except:
        print(
            '\nWARNING: Louvain community detection failed. Cannot plot community matrix...'
        )

    return