Python networkx.adjacency_matrix() Examples

The following are 30 code examples of networkx.adjacency_matrix(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module networkx , or try the search function .
Example #1
Source File: safe_io.py    From safepy with GNU General Public License v3.0 6 votes vote down vote up
def calculate_edge_lengths(G, verbose=True):

    # Calculate the lengths of the edges

    if verbose:
        print('Calculating edge lengths...')

    x = np.matrix(G.nodes.data('x'))[:, 1]
    y = np.matrix(G.nodes.data('y'))[:, 1]

    node_coordinates = np.concatenate([x, y], axis=1)
    node_distances = squareform(pdist(node_coordinates, 'euclidean'))

    adjacency_matrix = np.array(nx.adjacency_matrix(G).todense())
    adjacency_matrix = adjacency_matrix.astype('float')
    adjacency_matrix[adjacency_matrix == 0] = np.nan

    edge_lengths = np.multiply(node_distances, adjacency_matrix)

    edge_attr_dict = {index: v for index, v in np.ndenumerate(edge_lengths) if ~np.isnan(v)}
    nx.set_edge_attributes(G, edge_attr_dict, 'length')

    return G 
Example #2
Source File: prone.py    From cogdl with MIT License 6 votes vote down vote up
def train(self, G):
        self.num_node = G.number_of_nodes()

        self.matrix0 = sp.csr_matrix(nx.adjacency_matrix(G))

        t_1 = time.time()
        features_matrix = self._pre_factorization(self.matrix0, self.matrix0)
        t_2 = time.time()

        embeddings_matrix = self._chebyshev_gaussian(
            self.matrix0, features_matrix, self.step, self.mu, self.theta
        )
        t_3 = time.time()

        print("sparse NE time", t_2 - t_1)
        print("spectral Pro time", t_3 - t_2)
        self.embeddings = embeddings_matrix

        return self.embeddings 
Example #3
Source File: dataset_utils.py    From rl_graph_generation with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __getitem__(self, item):
    """
    Returns an rdkit mol object
    :param item:
    :return:
    """
    smiles = self.df['smiles'][item]
    mol = Chem.MolFromSmiles(smiles)
    return mol

# # TESTS
# path = 'gdb13.rand1M.smi.gz'
# dataset = gdb_dataset(path)
#
# print(len(dataset))
# mol,_ = dataset[0]
# graph = mol_to_nx(mol)
# graph_sub = graph.subgraph([0,3,5,7,9])
# graph_sub_new = nx.convert_node_labels_to_integers(graph_sub,label_attribute='old')
# graph_sub_node = graph_sub.nodes()
# graph_sub_new_node = graph_sub_new.nodes()
# matrix = nx.adjacency_matrix(graph_sub)
# np_matrix = matrix.toarray()
# print(np_matrix)
# print('end') 
Example #4
Source File: katz.py    From EvalNE with MIT License 6 votes vote down vote up
def _fit(self):

        # Versions using sparse matrices
        # adj = nx.adjacency_matrix(self._G)
        # ident = sparse.identity(len(self._G.nodes)).tocsc()
        # sim = inv(ident - adj.multiply(self.beta).T) - ident
        # adj = nx.adjacency_matrix(self._G)
        # aux = adj.multiply(-self.beta).T
        # aux.setdiag(1+aux.diagonal(), k=0)
        # sim = inv(aux)
        # sim.setdiag(sim.diagonal()-1)
        # print(sim.nnz)
        # print(adj.nnz)

        # Version using dense matrices
        adj = nx.adjacency_matrix(self._G)
        aux = adj.T.multiply(-self.beta).todense()
        np.fill_diagonal(aux, 1+aux.diagonal())
        sim = np.linalg.inv(aux)
        np.fill_diagonal(sim, sim.diagonal()-1)
        return sim 
Example #5
Source File: netmf.py    From cogdl with MIT License 6 votes vote down vote up
def train(self, G):
        A = sp.csr_matrix(nx.adjacency_matrix(G))
        if not self.is_large:
            print("Running NetMF for a small window size...")
            deepwalk_matrix = self._compute_deepwalk_matrix(
                A, window=self.window_size, b=self.negative
            )

        else:
            print("Running NetMF for a large window size...")
            vol = float(A.sum())
            evals, D_rt_invU = self._approximate_normalized_laplacian(
                A, rank=self.rank, which="LA"
            )
            deepwalk_matrix = self._approximate_deepwalk_matrix(
                evals, D_rt_invU, window=self.window_size, vol=vol, b=self.negative
            )
        # factorize deepwalk matrix with SVD
        u, s, _ = sp.linalg.svds(deepwalk_matrix, self.dimension)
        self.embeddings = sp.diags(np.sqrt(s)).dot(u.T).T
        return self.embeddings 
Example #6
Source File: graphs.py    From Hands-On-Genetic-Algorithms-with-Python with MIT License 6 votes vote down vote up
def __init__(self, graph, hardConstraintPenalty):
        """
        :param graph: a NetworkX graph to be colored
        :param hardConstraintPenalty: penalty for hard constraint (coloring violation)
        """

        # initialize instance variables:
        self.graph = graph
        self.hardConstraintPenalty = hardConstraintPenalty

        # a list of the nodes in the graph:
        self.nodeList = list(self.graph.nodes)

        # adjacency matrix of the nodes -
        # matrix[i,j] equals '1' if nodes i and j are connected, or '0' otherwise:
        self.adjMatrix = nx.adjacency_matrix(graph).todense() 
Example #7
Source File: modularity_nmf.py    From M-NMF with GNU General Public License v3.0 6 votes vote down vote up
def optimize(self):
        """
        Method to run the optimization and halt it when overfitting started.
        The output matrices are all saved when optimization has finished.
        """
        self.best_modularity = 0
        self.stop_index = 0
        with tf.Session(graph=self.computation_graph) as session:
            self.init.run()
            self.logs = log_setup(self.args)
            print("Optimization started.\n")
            self.build_graph()
            feed_dict = {self.S_0: overlap_generator(self.G), self.B1: np.array(nx.adjacency_matrix(self.G).todense()), self.B2:modularity_generator(self.G)}
            for i in tqdm(range(self.args.iteration_number)):
                start = time.time()
                H = session.run(self.H, feed_dict=feed_dict)
                current_modularity = self.update_state(H)
                end = time.time()
                log_updater(self.logs, i, end-start, current_modularity)
                if self.stop_index > self.args.early_stopping:
                    break
            self.initiate_dump(session, feed_dict) 
Example #8
Source File: neu.py    From karateclub with GNU General Public License v3.0 6 votes vote down vote up
def _update_embedding(self, graph, original_embedding):
        r"""Performs the Network Embedding Update on the original embedding.
        Args:
            original_embedding (Numpy array): An array containing an embedding.
            graph (NetworkX graph): The embedded graph.

        Return types:
            embedding (Numpy array): An array containing the updated embedding.
        """
        embedding = self._normalize_embedding(original_embedding)
        adjacency = nx.adjacency_matrix(graph, nodelist=range(graph.number_of_nodes()))
        normalized_adjacency = normalize(adjacency, norm='l1', axis=1)
        for _ in range(self.iterations):
            embedding = (embedding + 
                         self.L1*(normalized_adjacency @ embedding) + 
                         self.L2*(normalized_adjacency @ (normalized_adjacency @ embedding)))
        return embedding 
Example #9
Source File: utils.py    From PaperRobot with MIT License 6 votes vote down vote up
def get_subgraph(triples, triple_dict, whole_graph):
    # Only handle 1-hop for now
    # Data Types for Nodes are INT
    in_graph = set()
    for triple in triples:
        head = triple[0]
        tail = triple[1]
        in_graph.add(tuple(triple))
        for tri in triple_dict[head.item()]:
            single1 = (head, tri[0], tri[1])
            in_graph.add(single1)
        for tri in triple_dict[tail.item()]:
            single2 = (tail, tri[0], tri[1])
            in_graph.add(single2)
    in_kg = KnowledgeGraph()
    in_kg.load_triple_noweight(in_graph)
    in_kg.triple2graph_noweight()
    included_nodes = list(in_kg.G)
    adj_ingraph = nx.adjacency_matrix(whole_graph.G, nodelist=included_nodes).todense()
    return np.array(included_nodes), adj_ingraph 
Example #10
Source File: tadw.py    From karateclub with GNU General Public License v3.0 6 votes vote down vote up
def _create_target_matrix(self, graph):
        """
        Creating a normalized sparse adjacency matrix power target.

        Arg types:
            * **graph** *(NetworkX graph)* - The graph to be embedded.

        Return types:
            * **A_tilde** *(Scipy COO matrix) - The target matrix.
        """
        weighted_graph = nx.Graph()
        for (u, v) in graph.edges():
            weighted_graph.add_edge(u, v, weight=1.0/graph.degree(u))
            weighted_graph.add_edge(v, u, weight=1.0/graph.degree(v))
        A_hat = nx.adjacency_matrix(weighted_graph,
                                    nodelist=range(graph.number_of_nodes()))

        A_tilde = A_hat.dot(A_hat)
        return coo_matrix(A_tilde) 
Example #11
Source File: DER.py    From cdlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __graph_transition_matrix(G, sparse=True):
    A = nx.adjacency_matrix(G).astype('float')
    # normalize rows to sum to 1
    degs = A.sum(axis=1)

    # take care of zero degree
    degs[degs == 0] = 1

    N = len(degs)

    if sparse == True:
        rev_degs = 1 / degs
        diag = scipy.sparse.dia_matrix((rev_degs.reshape((1, N)), np.array([0])), shape=(N, N))
        A = diag.dot(A)
    else:
        A = A.todense()
        A = A / degs.reshape((A.shape[0], 1))

    return A 
Example #12
Source File: smoothness.py    From CS-GNN with MIT License 6 votes vote down vote up
def compute_label_smoothness(path, rate=0.):
    G_org = json_graph.node_link_graph(json.load(open(path+'-G.json')))
    # G_org = remove_unlabeled(G_org)
    if nx.is_directed(G_org):
        G_org = G_org.to_undirected()
    class_map = json.load(open(path+'-class_map.json'))
    for k, v in class_map.items():
        if type(v) != list:
            class_map = convert_list(class_map)
        break
    labels = convert_ndarray(class_map)
    labels = np.squeeze(label_to_vector(labels))

    # smooth
    G_org = label_broadcast(G_org, labels, rate)
    with open(path+'-G_'+str(rate)+'.json', 'w') as f:
        f.write(json.dumps(json_graph.node_link_data(G_org)))

    edge_num = G_org.number_of_edges()
    G = pygsp.graphs.Graph(nx.adjacency_matrix(G_org))
    smoothness = 0
    for src, dst in G_org.edges():
        if labels[src] != labels[dst]:
            smoothness += 1
    print('The smoothness is: ', 2*smoothness/edge_num) 
Example #13
Source File: prone.py    From CogDL-TensorFlow with MIT License 6 votes vote down vote up
def train(self, G):
        self.num_node = G.number_of_nodes()

        self.matrix0 = sp.csr_matrix(nx.adjacency_matrix(G))

        t_1 = time.time()
        features_matrix = self._pre_factorization(self.matrix0, self.matrix0)
        t_2 = time.time()

        embeddings_matrix = self._chebyshev_gaussian(
            self.matrix0, features_matrix, self.step, self.mu, self.theta
        )
        t_3 = time.time()

        print("sparse NE time", t_2 - t_1)
        print("spectral Pro time", t_3 - t_2)
        self.embeddings = embeddings_matrix

        return self.embeddings 
Example #14
Source File: smoothness.py    From CS-GNN with MIT License 6 votes vote down vote up
def compute_feature_smoothness(path, times=0):
    G_org = json_graph.node_link_graph(json.load(open(path+'-G.json')))
    # G_org = remove_unlabeled(G_org)
    if nx.is_directed(G_org):
        G_org = G_org.to_undirected()
    edge_num = G_org.number_of_edges()
    G = pygsp.graphs.Graph(nx.adjacency_matrix(G_org))
    feats = np.load(path+'-feats.npy')
    # smooth
    for i in range(times):
        feats = feature_broadcast(feats, G_org)
    np.save(path+'-feats_'+str(times)+'.npy', feats)

    min_max_scaler = preprocessing.MinMaxScaler()
    feats = min_max_scaler.fit_transform(feats)
    smoothness = np.zeros(feats.shape[1])
    for src, dst in G_org.edges():
        smoothness += (feats[src]-feats[dst])*(feats[src]-feats[dst])
    smoothness = np.linalg.norm(smoothness,ord=1)
    print('The smoothness is: ', 2*smoothness/edge_num/feats.shape[1]) 
Example #15
Source File: nodesketch.py    From karateclub with GNU General Public License v3.0 6 votes vote down vote up
def fit(self, graph):
        """
        Fitting a NodeSketch model.

        Arg types:
            * **graph** *(NetworkX graph)* - The graph to be embedded.
        """
        self._set_seed()
        self._check_graph(graph)
        self._graph = graph
        self._num_nodes = len(graph.nodes)
        self._hash_values = self._generate_hash_values()
        self._sla = nx.adjacency_matrix(self._graph, nodelist=range(self._num_nodes)).tocoo()
        self._sla.data = np.array([1 for _ in range(len(self._sla.data))])
        self._sla_original = self._sla.copy()
        self._do_single_sketch()
        for _ in range(self.iterations-1):
            self._augment_sla()
            self._do_single_sketch() 
Example #16
Source File: graphwave.py    From karateclub with GNU General Public License v3.0 6 votes vote down vote up
def fit(self, graph):
        """
        Fitting a GraphWave model.

        Arg types:
            * **graph** *(NetworkX graph)* - The graph to be embedded.
        """
        self._set_seed()
        self._check_graph(graph)
        graph.remove_edges_from(nx.selfloop_edges(graph))
        self._create_evaluation_points()
        self._check_size(graph)
        self._G = pygsp.graphs.Graph(nx.adjacency_matrix(graph))

        if self.mechanism == "exact":
            self._exact_structural_wavelet_embedding()
        elif self.mechanism == "approximate":
            self._approximate_structural_wavelet_embedding()
        else:
            raise NameError("Unknown method.") 
Example #17
Source File: utils.py    From GraphWaveletNeuralNetwork with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, graph, scale, approximation_order, tolerance):
        """
        :param graph: NetworkX graph object.
        :param scale: Kernel scale length parameter.
        :param approximation_order: Chebyshev polynomial order.
        :param tolerance: Tolerance for sparsification.
        """
        self.graph = graph
        self.pygsp_graph = pygsp.graphs.Graph(nx.adjacency_matrix(self.graph))
        self.pygsp_graph.estimate_lmax()
        self.scales = [-scale, scale]
        self.approximation_order = approximation_order
        self.tolerance = tolerance
        self.phi_matrices = [] 
Example #18
Source File: nbd.py    From netrd with MIT License 5 votes vote down vote up
def pseudo_hashimoto(graph):
    """Return the pseudo-Hashimoto matrix.

    The pseudo Hashimoto matrix of a graph is the block matrix defined as
    B' = [0  D-I]
         [-I  A ]

    Where D is the degree-diagonal matrix, I is the identity matrix and A
    is the adjacency matrix.  The eigenvalues of B' are always eigenvalues
    of B, the non-backtracking or Hashimoto matrix.

    Parameters
    ----------

    graph (nx.Graph): A NetworkX graph object.

    Returns
    -------

    A sparse matrix in csr format.

    """
    # Note: the rows of nx.adjacency_matrix(graph) are in the same order as
    # the list returned by graph.nodes().
    degrees = graph.degree()
    degrees = sparse.diags([degrees[n] for n in graph.nodes()])
    adj = nx.adjacency_matrix(graph)
    ident = sparse.eye(graph.order())
    pseudo = sparse.bmat([[None, degrees - ident], [-ident, adj]])
    return pseudo.asformat('csr') 
Example #19
Source File: hope.py    From cogdl with MIT License 5 votes vote down vote up
def train(self, G):
        r"""The author claim that Katz has superior performance in related tasks
        S_katz = (M_g)^-1 * M_l = (I - beta*A)^-1 * beta*A = (I - beta*A)^-1 * (I - (I -beta*A))
        = (I - beta*A)^-1 - I
        """
        self.G = G
        adj = nx.adjacency_matrix(self.G).todense()
        n = adj.shape[0]
        katz_matrix = np.asarray((np.eye(n) - self.beta * np.mat(adj)).I - np.eye(n))
        self.embeddings = self._get_embedding(katz_matrix, self.dimension)
        return self.embeddings 
Example #20
Source File: distributional_nbd.py    From netrd with MIT License 5 votes vote down vote up
def pseudo_hashimoto(graph):
    """
    Return the pseudo-Hashimoto matrix.

    The pseudo Hashimoto matrix of a graph is the block matrix defined as
    B' = [0  D-I]
         [-I  A ]

    Where D is the degree-diagonal matrix, I is the identity matrix and A
    is the adjacency matrix.  The eigenvalues of B' are always eigenvalues
    of B, the non-backtracking or Hashimoto matrix.

    Parameters
    ----------

    graph (nx.Graph): A NetworkX graph object.

    Returns
    -------

    A sparse matrix in csr format.

    NOTE: duplicated from "nbd.py" to avoid excessive imports.

    """
    # Note: the rows of nx.adjacency_matrix(graph) are in the same order as
    # the list returned by graph.nodes().
    degrees = graph.degree()
    degrees = sp.diags([degrees[n] for n in graph.nodes()])
    adj = nx.adjacency_matrix(graph)
    ident = sp.eye(graph.order())
    pseudo = sp.bmat([[None, degrees - ident], [-ident, adj]])
    return pseudo.asformat('csr') 
Example #21
Source File: preprocess_planetoid.py    From graph-tutorial.pytorch with MIT License 5 votes vote down vote up
def pitfall(path, dataset):
    x, y, tx, ty, allx, ally, graph = read_data(path=args.data_path, dataset=args.dataset)

    print("Redundant edges in the Graph!")
    # 데이터 그래프 내의 redundant한 edge가 존재합니다. 따라서 원 논문과 node 개수는 동일하나,
    # 엣지 개수는 다른 adjacency matrix가 출력됩니다.
    edges = 0
    idx = 0
    for key in graph:
        orig_lst = (graph[key])
        set_lst = set(graph[key])
        edges += len(orig_lst)

        if len(orig_lst) != len(set_lst):
            print(orig_lst)
            idx += (len(orig_lst) - len(set_lst))

    print("Number of Redundant Edges : %d" %idx)
    print("Reported Edges : %d" %(edges/2))

    # adj
    adj = nx.adjacency_matrix(nx.from_dict_of_lists(graph))

    # edge from adj
    print("There also exists {} self inferences!!".format(adj.diagonal().sum()))
    # Self inference도 존재하므로 (원래 adjacency matrix의 diagonal의 합은 0이어야 합니다)
    act_edges = adj.sum().sum() + adj.diagonal().sum() # diagonal 은 한 번만 계산되므로 /2 이전 한 번 더 더해줍니다.
    print("Actual Edges in the Adjacency Matrix : %d" %(act_edges/2)) 
Example #22
Source File: process.py    From DGI with MIT License 5 votes vote down vote up
def load_data(dataset_str): # {'pubmed', 'citeseer', 'cora'}
    """Load data."""
    names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph']
    objects = []
    for i in range(len(names)):
        with open("data/ind.{}.{}".format(dataset_str, names[i]), 'rb') as f:
            if sys.version_info > (3, 0):
                objects.append(pkl.load(f, encoding='latin1'))
            else:
                objects.append(pkl.load(f))

    x, y, tx, ty, allx, ally, graph = tuple(objects)
    test_idx_reorder = parse_index_file("data/ind.{}.test.index".format(dataset_str))
    test_idx_range = np.sort(test_idx_reorder)

    if dataset_str == 'citeseer':
        # Fix citeseer dataset (there are some isolated nodes in the graph)
        # Find isolated nodes, add them as zero-vecs into the right position
        test_idx_range_full = range(min(test_idx_reorder), max(test_idx_reorder)+1)
        tx_extended = sp.lil_matrix((len(test_idx_range_full), x.shape[1]))
        tx_extended[test_idx_range-min(test_idx_range), :] = tx
        tx = tx_extended
        ty_extended = np.zeros((len(test_idx_range_full), y.shape[1]))
        ty_extended[test_idx_range-min(test_idx_range), :] = ty
        ty = ty_extended

    features = sp.vstack((allx, tx)).tolil()
    features[test_idx_reorder, :] = features[test_idx_range, :]
    adj = nx.adjacency_matrix(nx.from_dict_of_lists(graph))

    labels = np.vstack((ally, ty))
    labels[test_idx_reorder, :] = labels[test_idx_range, :]

    idx_test = test_idx_range.tolist()
    idx_train = range(len(y))
    idx_val = range(len(y), len(y)+500)

    return adj, features, labels, idx_train, idx_val, idx_test 
Example #23
Source File: helpers.py    From FSCNMF with GNU General Public License v3.0 5 votes vote down vote up
def normalize_adjacency(graph):
    """
    Method to calculate a sparse degree normalized adjacency matrix.
    :param graph: Sparse graph adjacency matrix.
    :return A: Normalized adjacency matrix.
    """
    ind = range(len(graph.nodes()))
    degs = [1.0/graph.degree(node) for node in graph.nodes()]
    A = sparse.csr_matrix(nx.adjacency_matrix(graph), dtype=np.float32)
    degs = sparse.csr_matrix(sparse.coo_matrix((degs, (ind, ind)),
                                               shape=A.shape,
                                               dtype=np.float32))
    A = A.dot(degs)
    return A 
Example #24
Source File: graph.py    From Graphonomy with MIT License 5 votes vote down vote up
def preprocess_adj(adj):
    """Preprocessing of adjacency matrix for simple GCN model and conversion to tuple representation."""
    adj = nx.adjacency_matrix(nx.from_dict_of_lists(adj)) # return a adjacency matrix of adj ( type is numpy)
    adj_normalized = normalize_adj(adj + sp.eye(adj.shape[0])) #
    # return sparse_to_tuple(adj_normalized)
    return adj_normalized.todense() 
Example #25
Source File: grarep.py    From cogdl with MIT License 5 votes vote down vote up
def train(self, G):
        self.G = G
        self.num_node = G.number_of_nodes()
        A = np.asarray(nx.adjacency_matrix(self.G).todense(), dtype=float)
        A = preprocessing.normalize(A, "l1")

        log_beta = np.log(1.0 / self.num_node)
        A_list = [A]
        T_list = [sum(A).tolist()]
        temp = A
        # calculate A^1, A^2, ... , A^step, respectively
        for i in range(self.step - 1):
            temp = temp.dot(A)
            A_list.append(A)
            T_list.append(sum(temp).tolist())

        final_emb = np.zeros((self.num_node, 1))
        for k in range(self.step):
            for j in range(A.shape[1]):
                A_list[k][:, j] = (
                    np.log(A_list[k][:, j] / T_list[k][j] + 1e-20) - log_beta
                )
                for i in range(A.shape[0]):
                    A_list[k][i, j] = max(A_list[k][i, j], 0)
            # concatenate all k-step representations
            if k == 0:
                dimension = self.dimension - int(self.dimension / self.step) * (
                    self.step - 1
                )
                final_emb = self._get_embedding(A_list[k], dimension)
            else:
                W = self._get_embedding(A_list[k], self.dimension / self.step)
                final_emb = np.hstack((final_emb, W))

        self.embeddings = final_emb
        return self.embeddings 
Example #26
Source File: utils.py    From graph-representation-learning with MIT License 5 votes vote down vote up
def create_adj_from_edgelist(dataset_str):
    """ dataset_str: arxiv-grqc, blogcatalog """
    dataset_path = 'data/' + dataset_str + '.txt'
    with open(dataset_path, 'r') as f:
        header = next(f)
        edgelist = []
        for line in f:
            i,j = map(int, line.split())
            edgelist.append((i,j))
    g = nx.Graph(edgelist)
    return sp.lil_matrix(nx.adjacency_matrix(g)) 
Example #27
Source File: unsupervised_node_classification.py    From cogdl with MIT License 5 votes vote down vote up
def enhance_emb(self, G, embs):
        A = sp.csr_matrix(nx.adjacency_matrix(G))
        self.args.model = 'prone'
        self.args.step, self.args.theta, self.args.mu = 5, 0.5, 0.2
        model = build_model(self.args)
        embs = model._chebyshev_gaussian(A, embs)
        return embs 
Example #28
Source File: encode.py    From CS-GNN with MIT License 5 votes vote down vote up
def __init__(self, G, node_id, sample_number):
        """
        This method 
        :param G: Input networkx graph object.
        """
        self.approximation = 100
        self.step_size = 20
        self.heat_coefficient = 1000.0
        self.node_label_type = str
        self.index=G.nodes()
        self.G = pygsp.graphs.Graph(nx.adjacency_matrix(G))
        self.number_of_nodes = len(nx.nodes(G))
        self.node_id = node_id
        self.sample_number = sample_number
        self.steps = [x*self.step_size for x in range(self.sample_number)] 
Example #29
Source File: networkclustering.py    From PyPSA with GNU General Public License v3.0 5 votes vote down vote up
def busmap_by_spectral_clustering(network, n_clusters, **kwds):
        lines = network.lines.loc[:,['bus0', 'bus1']].assign(weight=network.lines.num_parallel).set_index(['bus0','bus1'])
        lines.weight+=0.1
        G = nx.Graph()
        G.add_nodes_from(network.buses.index)
        G.add_edges_from((u,v,dict(weight=w)) for (u,v),w in lines.itertuples())
        return pd.Series(list(map(str,sk_spectral_clustering(nx.adjacency_matrix(G), n_clusters, **kwds) + 1)),
                         index=network.buses.index) 
Example #30
Source File: spectral_machinery.py    From GraphWaveMachine with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, G, settings):
        """
        Initialization.
        :param G: Input networkx graph object.
        :param settings: argparse object with settings.
        """
        self.index = G.nodes()
        self.G = pygsp.graphs.Graph(nx.adjacency_matrix(G))
        self.number_of_nodes = len(nx.nodes(G))
        self.settings = settings
        if self.number_of_nodes > self.settings.switch:
            self.settings.mechanism = "approximate"

        self.steps = [x*self.settings.step_size for x in range(self.settings.sample_number)]