Beispiel #1
0
    def group_degree(graph: Graph, nodes: list) -> float:
        r"""
        Computes the *group degree* for a subset of nodes in the input graph. This measure is an extension of the degree
        that counts the number of non-group nodes (:math:`N-k`) that are connected to group members (:math:`k`).
        Group degree is then normalized by dividing the tgotal number of incident edges of the group by :math:`N-k`

        :param igraph.Graph graph: a :class:`igraph.Graph` object. The graph must satisfy a series of requirements, described in the `Minimum requirements specifications <http://pyntacle.css-mendel.it/requirements.html>`_ section of the Pyntacle official page.
        :param list nodes: A list of  node ``name``s of the nodes that are used to compute group degree

        :return float: The normalized group degree centrality

        :raise TypeError: when ``nodes`` is not one of the valid types
        :raise KeyError: when any of the node ``name`` attribute passed to the function is not present in the input graph.
        """

        gu = gUtil(graph)
        nodes_ind = gu.get_node_indices(nodes)

        selected_neig = graph.neighborhood(nodes, order=1, mode="all")
        flat_list = [
            item for sublist in selected_neig for item in sublist
            if item not in nodes_ind
        ]
        normalized_score = len(set(flat_list)) / (len(graph.vs) - len(nodes))

        return round(normalized_score, 5)
Beispiel #2
0
    def eigenvector_centrality(graph: Graph,
                               nodes: list,
                               scaled: bool = False):
        r"""
        Calculate the *eigenvector centrality* for a single node, a list of nodes or all nodes in the input graph.
        The eigenvector centrality is a measure of the influence of a node in a network with respect to its neighbours.
        Relative scores are assigned to all nodes in the network based on the concept that connections to high-scoring
        nodes contribute more to the score of the node in question than equal connections to low-scoring nodes.

        :param igraph.Graph graph: a :class:`igraph.Graph` object. The graph must satisfy a series of requirements, described in the `Minimum requirements specifications <http://pyntacle.css-mendel.it/requirements.html>`_ section of the Pyntacle official page.
        :param None,str,list nodes: The input nodes on which to compute the selected index. When :py:class:`None`, it computes the degree for all nodes in the graph. Otherwise, a single node ``name`` or a list of node ``name``s can be passed to compute degree only for the subset of nodes
        :param bool scaled: a boolean value to scale the eigenvector centrality using the reciprocal of the eigenvector :math:`(frac{1}{eigenvector})`. Default is ``False`.
        :return list: a list of floats, the length being the number of input nodes. Each float represents the eigenvector of the input node. The order of the node list in input is preserved if a subset of nodes is provided.
        :raise TypeError: when ``nodes`` is a list of strings matching the vertex ``name`` attribute
        :raise KeyError: when any of the node ``name`` attribute passed to the function is not present in the input graph
        :raise ValueError: if ``scaled`` is not a :py:class:`bool`
        """

        if not isinstance(scaled, bool):
            raise ValueError(
                "'scaled' must be a boolean value (True or False)")
        elif nodes is None:
            evcent = graph.evcent(directed=False, scale=scaled)
            return [round(e, 5) for e in evcent]
        else:
            inds = gUtil(graph=graph).get_node_indices(nodes)
            evcent = graph.evcent(directed=False, scale=scaled)
            evcent_values = [round(evcent[i], 5) for i in inds]
            return evcent_values
Beispiel #3
0
    def pagerank(graph: Graph,
                 nodes: list or str or None = None,
                 weights: list = None,
                 damping: float = 0.85) -> list:
        r"""
        The notorious `Google PageRank <http://infolab.stanford.edu/~backrub/google.html>`_ algorithm that can be calculated for
        a single node, a list of nodes or for all nodes of the input graph.
        The PageRank algorithm is a modified version of the :func:`~pyntacle.algorithms.local_topology.LocalTopology.eigenvector_centrality`.
        The importance of a node is here a function of the number of issuing edges and the importance of the neighbour nodes.
        A likelihood distribution is computed to check what is the chance that a random walk passes through the
        selected node(s). The higher is the centrality  value of the node, the higher is the probability of passing through it.

        :param igraph.Graph graph: a :class:`igraph.Graph` object. The graph must satisfy a series of requirements, described in the `Minimum requirements specifications <http://pyntacle.css-mendel.it/requirements.html>`_ section of the Pyntacle official page
        :param None,str,list nodes: The input nodes on which to compute the selected index. When :py:class:`None`, it computes the pagerank for all nodes in the graph. Otherwise, a single node ``name`` or a list of them can be passed to compute degree only for a selected subset of nodes
        :param list, None weights: a list of float numbers less or equal than the total number of edges. The order of the list shoould match the indices of the edge elements of the input graph. Defaults to :py:class:`None` (no weights added).

        :return list: a list of numeric values, the length being the number of input nodes. Each values represents the PageRank of the input node. The order of the node list in input is preserved.

        :raise TypeError: when ``nodes`` is a list of strings matching the vertex ``name`` attribute or ``weights`` is not a list
        :raise KeyError: when any of the node ``name`` attribute passed to the function is not present in the input graph
        :raise ValueError: if ``damping`` is not a positive float or if ``weights`` does not floats or integers
        """
        if weights is not None:
            if not isinstance(weights, list):
                raise TypeError(u"'weights' must be a list")
            if not all(isinstance(x, (float, type(None))) for x in weights):
                raise ValueError(u"'weights' must be a list of floats")
            if len(weights) > graph.ecount():
                raise ValueError(
                    u"The 'weights' must be equal or less than the total number of edges"
                )

        if not (isinstance(damping, (float, int)) or (damping < 0)):
            raise ValueError(u"Damping factor must be a float >= 0")

        if nodes is not None:
            nodes = gUtil(graph).get_node_indices(nodes)

        return graph.pagerank(vertices=nodes,
                              damping=damping,
                              directed=False,
                              weights=weights,
                              implementation="arpack")
Beispiel #4
0
    def radiality_reach(graph: Graph,
                        nodes: list or str or None = None,
                        cmode: CmodeEnum = CmodeEnum.igraph) -> list:
        r"""
        Compute the *radiality-reach* of a node or of a list of nodes of an undirected graph.
        The radiality-reach is a weighted version of the canonical radiality measure and it is recommended for
        graphs with multiple components. Specifically, if a graph has more than one components, we calculate the
        radiality for each node inside the component, then we multiply the radiality value by the proportion of nodes
        of that component over all nodes in the graph.
        Hence, the radiality-reach of a graph with only one component will be equal to the radiality, while nodes in
        a graph with two disconnected components will exhibit radiality values for each components and weighted over the
        contribution of that component to the whole graph.

        .. note:: the radiality reach of node isolates is zero by definition

        :param igraph.Graph graph: a :class:`igraph.Graph` object. The graph must satisfy a series of requirements, described in the `Minimum requirements specifications <http://pyntacle.css-mendel.it/requirements.html>`_ section of the Pyntacle official page.
        :param None,str,list nodes: The input nodes on which to compute the centrality index. When :py:class:`None`, it computes the radiality reach for all nodes in the graph. Otherwise, a single node  (identified using the ``name`` attribute) or a list of node names can be passed to compute radiality reach only for the subset of node of interest
        :param cmodeEnum cmode: the implementation that will be used to compute the shortest paths required for each radiality reach value. See :class:`~pyntacle.tools.enums.CmodeEnum`. Default is the igraph brute-force shortest path search.

        :return list: a list of floats, the length being the number of input nodes. Each float represents the radiality-reach of the input node. The order of the node list in input is preserved.

        :raise TypeError: when ``nodes`` is a list of strings matching the vertex ``name`` attribute
        :raise KeyError: when any of the node ``name`` attribute passed to the function is not present in the input graph
        """
        comps = graph.components()  # define the cases
        if len(comps) == 1:
            return LocalTopology.radiality(graph=graph,
                                           nodes=nodes,
                                           cmode=cmode)
        else:
            tot_nodes = graph.vcount()
            if nodes is None:
                result = [None] * tot_nodes

                for c in comps:
                    subg = graph.induced_subgraph(vertices=c)

                    if subg.ecount(
                    ) == 0:  # isolates do not have a radiality-reach value by definition
                        rad = [0]
                    else:
                        part_nodes = subg.vcount()
                        rad = LocalTopology.radiality(graph=subg,
                                                      nodes=nodes,
                                                      cmode=cmode)

                        # rebalance radiality by weighting it over the total number of nodes
                        proportion_nodes = part_nodes / tot_nodes
                        rad = [r * proportion_nodes for r in rad]

                    for i, ind in enumerate(c):
                        result[ind] = rad[i]

                return result
            else:
                result = [None] * len(nodes)
                inds = gUtil(graph=graph).get_node_indices(nodes)

                for c in comps:
                    if any(x in c for x in inds):
                        node_names = list(
                            set(nodes) & set(graph.vs(c)["name"]))
                        subg = graph.induced_subgraph(vertices=c)
                        part_nodes = subg.vcount()
                        rad = LocalTopology.radiality(graph=subg,
                                                      nodes=node_names,
                                                      cmode=cmode)

                        proportion_nodes = part_nodes / tot_nodes
                        rad = [r * proportion_nodes for r in rad]

                        for i, elem in enumerate(node_names):
                            orig_index = nodes.index(elem)
                            result[orig_index] = rad[i]
                return result
Beispiel #5
0
    def group_closeness(
            graph: Graph,
            nodes: list,
            distance: GroupDistanceEnum = GroupDistanceEnum.minimum,
            cmode: CmodeEnum = CmodeEnum.igraph,
            np_paths: np.ndarray or None = None) -> float:
        r"""
        Computes the closeness centrality for a group of nodes, rather than a single-node resolution as in
        :func:`~pyntacle.algorithms.local_topology.LocalTopology.closeness`. The *group closeness* is defined as the sum
        of the distances from the group to all vertices outside the group.
        As with individual closeness, this produces an inverse measure of closeness as larger numbers indicate
        less centrality.

        This definition deliberately leaves unspecified how distance from the group to an outside
        vertex is to be defined. `Everett and Borgatti <https://doi.org/10.1080/0022250X.1999.9990219>`_
        propose to consider the set :math:`D` of all distances from a single vertex to a set of vertices.

        The distance from the vertex to the set can be defined as either the *maximum*
        the *minimum* or the *mean* of values in :math:`D`. Following `Freeman convention <http://dx.doi.org/10.1016/0378-8733(78)90021-7>`_, we can normalize
        group closeness by dividing the distance score into the number of non-group members, with the result
        that larger numbers indicate greater centrality.

        .. warning :: The group closeness of a group of completely disconnected nodes (node isolates) is 0.

        :param igraph.Graph graph: a :class:`igraph.Graph` object. The graph must satisfy a series of requirements, described in the `Minimum requirements specifications <http://pyntacle.css-mendel.it/requirements.html>`_ section of the Pyntacle official page.
        :param list nodes: A list of node ``name``\s (the vertex ``name`` attribute) of the nodes belonging to the group
        :param GroupDistanceEnum distance: The definition of distance between any non-group and group nodes. It can be any value of the enumerator :class:`~pyntacle.tools.enums.GroupDistanceEnum`. By default, the minimum least distance :math:`D` between the group :math:`k` and the rest of the graph :math:`N-k` is used
        :param cmodeEnum cmode: the implementation that will be used to compute the shortest paths required for group closeness. See :class:`~pyntacle.tools.enums.CmodeEnum`. Default is the igraph brute-force shortest path search. Will be ignored if ``np_cpunts`` is provided
        :param np.ndarray,None np_paths: a :py:class:`numpy.ndarray` of positive integers representing a :math`NxN` squared matrix storing shortest paths between any pair of nodes of the graph. Passing this argument would make the overall calculation faster. Recommended for large Graps (:math:`N>1000`)

        :return float: The normalized group closeness centrality, obtained by dividing the group closeness by the number of non-group nodes..

        :raise TypeError: when ``nodes`` is a list of strings matching the vertex ``name`` attribute
        :raise KeyError: when any of the node ``name`` attribute passed to the function is not present in the input graph
        """

        MAX_PATH_LENGHT = len(graph.vs) + 1

        if not isinstance(np_paths, (type(None), np.ndarray)):
            raise TypeError("'np_paths' is not one NoneType or a numpy array")

        if distance == GroupDistanceEnum.maximum:

            def dist_func(x: list) -> int:
                return max(x)
        elif distance == GroupDistanceEnum.minimum:

            def dist_func(x: list) -> int:
                return min(x)
        elif distance == GroupDistanceEnum.mean:

            def dist_func(x: list):
                return sum(x) / len(x)
        else:
            raise ValueError(
                u"'distance' is not one of the appropriate GroupDistanceEnum")

        if np_paths is None:
            np_paths = ShortestPath.get_shortestpaths(graph=graph, cmode=cmode)

        group_indices = gUtil(graph).get_node_indices(nodes)
        nongroup_nodes = list(set(graph.vs["name"]) - set(nodes))
        nongroup_nodes_indices = gUtil(graph).get_node_indices(nongroup_nodes)
        # nongroup_np_paths2 = ShortestPath.get_shortestpaths(graph, nongroup_nodes, cmode=cmode)
        nongroup_np_paths = np_paths.take(nongroup_nodes_indices, axis=0)
        # assert (nongroup_np_paths == nongroup_np_paths2).all(), "Error"

        group_closeness = 0
        for np_path in nongroup_np_paths:
            temp_list = [
                elem for elem in np_path[group_indices]
                if elem != MAX_PATH_LENGHT
            ]
            if temp_list:
                group_closeness += dist_func(temp_list)
        if group_closeness != 0:
            normalized_score = len(nongroup_nodes) / group_closeness
            return round(normalized_score, 5)
        else:
            sys.stdout.error(
                "Node set {} is disconnected from the rest of the graph using the {} distance. Returning 0.\n"
                .format(nodes, distance.name))
            return 0.0
Beispiel #6
0
    def group_betweenness(graph: Graph,
                          nodes: list,
                          cmode: CmodeEnum = CmodeEnum.igraph,
                          np_counts: np.ndarray = None) -> float:
        r"""
        Computes the betweenness centrality of a group of nodes :math:`k`.
        The *group betweenness* indicates the proportion of geodesics connecting pairs of non-group members that
        pass through the group :math:`k`. This measure is computed as follows:

            #. Count the number of geodesics between every pair of non-group members, yielding a node-by-node matrix of counts
            #. Delete all ties involving group members and redo the calculation, creating a new node-by-node matrix of counts
            #. Divide each cell in the new matrix by the corresponding cell in the first matrix
            #. Take the sum of all these ratios.

        .. warning:: The group betwenness of sets made of peripheral nodes, isolates or sets whose removal disrupt the graph is 0, because these special cases have no geodesics passing through them.

        :param igraph.Graph graph: a :class:`igraph.Graph` object. The graph must satisfy a series of requirements, described in the `Minimum requirements specifications <http://pyntacle.css-mendel.it/requirements.html>`_ section of the Pyntacle official page.
        :param np.ndarray,None np_counts: Optional: a :py:class:`numpy.ndarray` of positive integers representing a :math`NxN` squared matrix storing shortest paths between any pair of nodes of the graph. Passing this argument would make the overall calculation faster. Recommended for large Graps (:math:`N>1000`)
        :param list nodes: A list of  node ``name``s of the nodes that are used to compute group betweenness

        :param cmodeEnum cmode: the implementation that will be used to compute the shortest paths. See :class:`~pyntacle.tools.enums.CmodeEnum`. Default is the igraph brute-force shortest path search. Will be ignored if ``np_cpunts`` is provided

        :return float: The normalized group betweenness centrality, obtained by dividing the group betweenness by the number of non-group nodes.

        :raise TypeError: when ``nodes`` is a list of strings matching the vertex ``name`` attribute or ``np_counts`` is not either a :py:class:`numpy.ndarray` or is empty
        :raise KeyError: when any of the node ``name`` attribute passed to the function is not present in the input graph
        """

        # Count geodesics of the original graph
        if np_counts is not None:
            if not isinstance(np_counts, np.ndarray):
                raise TypeError(
                    "np_counts must be None or a nump.nparray, {} found".
                    format(type(np_counts).__name__))

            if not all(x == graph.vcount() for x in np_counts.shape):
                raise ValueError(
                    "np_counts must be squared and of the same size of the graph ({})"
                    .format(graph.vcount()))

            count_all = np_counts

        else:
            count_all = ShortestPath.get_shortestpath_count(graph,
                                                            nodes=None,
                                                            cmode=cmode)

        # Get the corresponding node indices
        nodes_index = gUtil(graph).get_node_indices(nodes)

        # Count geodesics that do not pass through the group
        del_edg = [graph.incident(vertex=nidx) for nidx in nodes_index]
        del1 = set(list(itertools.chain(*del_edg)))

        graph_notgroup = graph.copy()
        graph_notgroup.delete_edges(del1)
        if graph_notgroup.ecount() == 0:
            sys.stdout.write("Node set dis: {} \n".format(nodes))
            return 0

        count_notgroup = ShortestPath.get_shortestpath_count(graph_notgroup,
                                                             nodes=None,
                                                             cmode=cmode)
        # Count geodesics that do pass through the group
        count_group = ShortestPath.subtract_count_dist_matrix(
            count_all, count_notgroup)

        # Divide the number of geodesics (g(C) / g)
        group_btw_temp = np.divide(count_group,
                                   count_all,
                                   out=np.zeros_like(count_group,
                                                     dtype=np.float),
                                   where=count_all != 0)

        # discard group-nodes (set group nodes' rows and columns to zero)
        group_btw_temp[nodes_index] = 0
        group_btw_temp[:, nodes_index] = 0

        # sum not-nan counts upper triangular matrix (SUM u<v)
        group_btw = np.sum(np.triu(group_btw_temp, 0), dtype=np.float) / 2

        # normalization
        graph_size = len(graph.vs)
        group_size = len(nodes_index)
        group_btw = (2 * group_btw) / ((graph_size - group_size) *
                                       (graph_size - group_size - 1))

        return round(group_btw, 5)
Beispiel #7
0
    def get_shortestpaths(graph: Graph,
                          nodes: int or list or None = None,
                          cmode: CmodeEnum = CmodeEnum.igraph) -> np.ndarray:
        r"""
        Returns the *shortest paths*, the minimum least distance between a node :math:`i` and any node :math:`j` of the
        input graph.

        :param igraph.Graph graph: a :class:`igraph.Graph` object. The graph must satisfy a series of requirements, described in the `Minimum requirements specifications <http://pyntacle.css-mendel.it/requirements.html>`_ section of the Pyntacle official page.
        :param None,str,list nodes: The input nodes  in the graph. When :py:class:`None`, it returns the shortest paths for all nodes in the graph, sorted by index. Otherwise, a single node ``name`` or a list of node ``name`` s can be passed.
        :param cmodeEnum cmode: the implementation that will be used to compute the shortest paths. See :class:`~pyntacle.tools.enums.CmodeEnum`.

        :return numpy.ndarray: a matrix stored in a numpy array, the number of rows corresponding to the input nodes, while the number of columns is the size of the graph. Each row contains a series of integer values representing the distance from any input node to every other node in the input graph. The rows are sorted by vertex ``index`` if ``nodes`` is :py:class:`None`, or in the same order in which they are given otherwise. :warning: disconnected nodes  exhibit a distance greater than the size of the graph

        :raise TypeError: when ``nodes`` is a list of strings matching the vertex ``name`` attribute
        :raise KeyError: when any of the node ``name`` attribute passed to the function is not present in the input graph
        :raise: ValueError: if ``cmode`` is not one of ther valid :class:`~pyntacle.tools.enums.GroupCentralityEnum`
        """

        if cmode == CmodeEnum.igraph:
            sps = ShortestPath.shortest_path_length_igraph(graph=graph,
                                                           nodes=nodes)
            sps = [[graph.vcount() + 1 if isinf(x) else x for x in y]
                   for y in sps]
            sps = np.array(sps)  #convert to a numpy array
            return sps

        elif cmode == CmodeEnum.cpu or cmode == CmodeEnum.gpu:
            if virtual_memory().free < (graph.vcount()**
                                        2) * 2:  # the rightmost "2" is int16/8
                sys.stdout.write(
                    u"WARNING: Memory seems to be low; loading the graph given as input could fail.\n"
                )

            graph_size = graph.vcount() + 1
            # np.set_printoptions(linewidth=graph_size * 10)
            adjmat = np.array(graph.get_adjacency().data,
                              dtype=np.uint16,
                              copy=True)
            adjmat[adjmat == 0] = np.uint16(
                graph_size)  #replace infinite distances with vcount +1
            np.fill_diagonal(adjmat, 0)  ##replace the diagonal with 0s

            if cmode == CmodeEnum.cpu:
                if nodes is None:
                    sps = ShortestPath.shortest_path_length_cpu(adjmat=adjmat)
                else:
                    sps = ShortestPath.shortest_path_length_cpu(adjmat=adjmat)
                    nodes = gUtil(graph=graph).get_node_indices(nodes=nodes)
                    sps = sps[nodes, :]
                return sps

            elif cmode == CmodeEnum.gpu:
                if cmode == CmodeEnum.gpu and cuda.current_context(
                ).get_memory_info().free < (graph.vcount()**2) * 2:
                    sys.stdout.write(
                        u"WARNING: GPU Memory seems to be low; loading the graph given as input could fail.\n"
                    )

                if nodes is None:
                    nodes = list(range(0, graph.vcount()))
                else:
                    nodes = gUtil(graph=graph).get_node_indices(nodes)

                if "shortest_path_gpu" not in sys.modules:
                    from algorithms.shortest_path_gpu import shortest_path_gpu

                N = adjmat.shape[0]
                threadsperblock = (32, 32)
                blockspergrid_x = math.ceil(N / threadsperblock[0])
                blockspergrid_y = math.ceil(N / threadsperblock[1])
                blockspergrid = (blockspergrid_x, blockspergrid_y)

                sps = np.array(adjmat, copy=True, dtype=np.uint16)
                # copy sps from host to device
                d_sps = cuda.to_device(sps)

                for k in range(0, N):
                    shortest_path_gpu[blockspergrid, threadsperblock](d_sps, k,
                                                                      N)

                # copy sps back from device to host
                d_sps.copy_to_host(sps)

                if len(nodes) < graph.vcount():
                    sps = sps[nodes, :]

                return sps
Beispiel #8
0
    def get_shortestpath_count(graph: Graph, nodes: str or list or None,
                               cmode: CmodeEnum) -> np.ndarray:
        r"""
        Returns the number of shortest paths (*shortest path counts*) for a node, a list of nodes or all nodes in the
        graph in a numpy array of positive integers.

        :param igraph.Graph graph: a :class:`igraph.Graph` object. The graph must satisfy a series of requirements, described in the `Minimum requirements specifications <http://pyntacle.css-mendel.it/requirements.html>`_ section of the Pyntacle official page.
        :param None,str,list nodes: The input nodes on which to compute the counts of shortest paths. When :py:class:`None`, the counts are computed for all nodes in the graph. Otherwise, a single node (identified using the ``name`` attribute) or a list of node names can be passed.
        :param cmodeEnum cmode: the implementation that will be used to compute the shortest paths counts. See :class:`~pyntacle.tools.enums.CmodeEnum`. Default is the igraph brute-force shortest path search wrapped in :func:`~pyntacle.algorithms.shortest_path.ShortestPath.shortest_path_length_igraph`

        :return numpy.ndarray: a matrix stored in a :py:class:`numpy.ndarray`, the number of rows corresponding to the length of the input nodes and the number of columns being the size of the graph. The nodes are sorted by index if ``nodes`` is :py:class:`None`, or they are in the same order in which they're presented otherwise.

        :raise: ValueError: if ``cmode`` is not one of the valid :class:`~pyntacle.tools.enums.GroupCentralityEnum`
        """

        if cmode == CmodeEnum.igraph:
            count_all = ShortestPath.shortest_path_count_igraph(graph, nodes)
            count_all = np.array(count_all)
            return count_all
        else:
            if virtual_memory().free < (graph.vcount()**
                                        2) * 2:  # the rightmost "2" is int16/8
                sys.stdout.write(
                    u"WARNING: Memory seems to be low; loading the graph given as input could fail."
                )

            adj_mat = np.array(graph.get_adjacency().data,
                               dtype=np.uint16,
                               copy=True)
            adj_mat[adj_mat == 0] = adj_mat.shape[0]

            if cmode == CmodeEnum.cpu:
                count_all = ShortestPath.shortest_path_count_cpu(adj_mat)

                if nodes:
                    nodes_idx = gUtil(graph=graph).get_node_indices(
                        nodes=nodes)
                    count_all = count_all[nodes_idx, :]

                return count_all
            elif cmode == CmodeEnum.gpu:
                if cuda.current_context().get_memory_info().free < (
                        graph.vcount()**2) * 2:
                    sys.stdout.write(
                        u"WARNING: GPU Memory seems to be low; loading the graph given as input could fail."
                    )

                if nodes is None:
                    nodes = list(range(0, graph.vcount()))
                else:
                    nodes = gUtil(graph=graph).get_node_indices(nodes)

                if "shortest_path_count_gpu" not in sys.modules:
                    from algorithms.shortest_path_gpu import shortest_path_count_gpu

                count_all = np.copy(adj_mat)
                tpb = threadsperblock
                blockspergrid = math.ceil(graph.vcount() / tpb)
                shortest_path_count_gpu[blockspergrid, tpb](adj_mat, count_all)

                if len(nodes) < graph.vcount():
                    count_all = count_all[nodes, :]

                return count_all
            else:
                raise ValueError(
                    u"The specified 'computing mode' is invalid. Choose from: {}"
                    .format(list(CmodeEnum)))