def fit(self, adjacency: Union[sparse.csr_matrix, np.ndarray]) -> 'Harmonic': """Harmonic centrality for connected graphs. Parameters ---------- adjacency : Adjacency matrix of the graph. Returns ------- self: :class:`Harmonic` """ adjacency = check_format(adjacency) check_square(adjacency) n = adjacency.shape[0] indices = np.arange(n) paths = shortest_path(adjacency, n_jobs=self.n_jobs, indices=indices) np.fill_diagonal(paths, 1) inv = (1 / paths) np.fill_diagonal(inv, 0) self.scores_ = inv.dot(np.ones(n)) return self
def fit(self, adjacency: Union[sparse.csr_matrix, np.ndarray]) -> 'Closeness': """Closeness centrality for connected graphs. Parameters ---------- adjacency : Adjacency matrix of the graph. Returns ------- self: :class:`Closeness` """ adjacency = check_format(adjacency) check_square(adjacency) check_connected(adjacency) n = adjacency.shape[0] if self.method == 'exact': nb_samples = n indices = np.arange(n) elif self.method == 'approximate': nb_samples = min(int(log(n) / self.tol**2), n) indices = np.random.choice(np.arange(n), nb_samples, replace=False) else: raise ValueError( "Method should be either 'exact' or 'approximate'.") paths = shortest_path(adjacency, n_jobs=self.n_jobs, indices=indices) self.scores_ = ( (n - 1) * nb_samples / n) / paths.T.dot(np.ones(nb_samples)) return self
def fit(self, adjacency: Union[sparse.csr_matrix, np.ndarray]) -> 'Harmonic': """ Harmonic centrality for connected graphs. Parameters ---------- adjacency : Adjacency matrix of the graph. Returns ------- self: :class:`Harmonic` """ adjacency = check_format(adjacency) n = adjacency.shape[0] if not is_square(adjacency): raise ValueError( "The adjacency is not square. Please use 'bipartite2undirected' or " "'bipartite2directed'.") indices = np.arange(n) paths = shortest_path(adjacency, n_jobs=self.n_jobs, indices=indices) np.fill_diagonal(paths, 1) inv = (1 / paths) np.fill_diagonal(inv, 0) self.scores_ = inv.dot(np.ones(n)) return self
def test_predecessors(self): adjacency = karate_club() _, predecessors = shortest_path(adjacency, return_predecessors=True) self.assertTupleEqual(predecessors.shape, adjacency.shape)
def test_parallel(self): adjacency = karate_club() path1 = shortest_path(adjacency) path2 = shortest_path(adjacency, n_jobs=-1) self.assertTrue((path1 == path2).all())
def test_parallel(self): karate = karate_club() truth = shortest_path(karate) parallel = shortest_path(karate, n_jobs=None) self.assertEqual(np.equal(truth, parallel).sum(), 34 ** 2)