def test_reverse_havel_hakimi_graph(self): aseq = [] bseq = [] G = reverse_havel_hakimi_graph(aseq, bseq) assert len(G) == 0 aseq = [0, 0] bseq = [0, 0] G = reverse_havel_hakimi_graph(aseq, bseq) assert len(G) == 4 assert G.number_of_edges() == 0 aseq = [3, 3, 3, 3] bseq = [2, 2, 2, 2, 2] pytest.raises(nx.NetworkXError, reverse_havel_hakimi_graph, aseq, bseq) bseq = [2, 2, 2, 2, 2, 2] G = reverse_havel_hakimi_graph(aseq, bseq) assert (sorted( d for n, d in G.degree()) == [2, 2, 2, 2, 2, 2, 3, 3, 3, 3]) aseq = [2, 2, 2, 2, 2, 2] bseq = [3, 3, 3, 3] G = reverse_havel_hakimi_graph(aseq, bseq) assert (sorted( d for n, d in G.degree()) == [2, 2, 2, 2, 2, 2, 3, 3, 3, 3]) aseq = [2, 2, 2, 1, 1, 1] bseq = [3, 3, 3] G = reverse_havel_hakimi_graph(aseq, bseq) assert G.is_multigraph() assert not G.is_directed() assert (sorted(d for n, d in G.degree()) == [1, 1, 1, 2, 2, 2, 3, 3, 3]) GU = nx.project(nx.Graph(G), range(len(aseq))) assert GU.number_of_nodes() == 6 GD = nx.project(nx.Graph(G), range(len(aseq), len(aseq) + len(bseq))) assert GD.number_of_nodes() == 3 G = reverse_havel_hakimi_graph(aseq, bseq, create_using=nx.Graph) assert not G.is_multigraph() assert not G.is_directed() pytest.raises(nx.NetworkXError, reverse_havel_hakimi_graph, aseq, bseq, create_using=nx.DiGraph) pytest.raises(nx.NetworkXError, reverse_havel_hakimi_graph, aseq, bseq, create_using=nx.DiGraph) pytest.raises(nx.NetworkXError, reverse_havel_hakimi_graph, aseq, bseq, create_using=nx.MultiDiGraph)
def create_bipartite_network(input_data): # create bipartite network by using networkx g = nx.Graph() g.add_edges_from(input_data) if bipartite.is_bipartite(g): NSet = nx.bipartite.sets(g) Net1 = nx.project(g,NSet[0]) Net2 = nx.project(g,NSet[1]) return Net1, Net2 else: print "Can't create bipartite network from input data"
def test_make_clique_bipartite(self): G = self.G B = nx.make_clique_bipartite(G) assert sorted(B) == [-5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] # Project onto the nodes of the original graph. H = nx.project(B, range(1, 12)) assert H.adj == G.adj # Project onto the nodes representing the cliques. H1 = nx.project(B, range(-5, 0)) # Relabel the negative numbers as positive ones. H1 = nx.relabel_nodes(H1, {-v: v for v in range(1, 6)}) assert sorted(H1) == [1, 2, 3, 4, 5]
def test_make_clique_bipartite(self): G = self.G B = nx.make_clique_bipartite(G) assert_equal(sorted(B), [-5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) # Project onto the nodes of the original graph. H = nx.project(B, range(1, 12)) assert_equal(H.adj, G.adj) # Project onto the nodes representing the cliques. H1 = nx.project(B, range(-5, 0)) # Relabel the negative numbers as positive ones. H1 = nx.relabel_nodes(H1, {-v: v for v in range(1, 6)}) assert_equal(sorted(H1), [1, 2, 3, 4, 5])
def test_make_clique_bipartite(self): G = self.G B = nx.make_clique_bipartite(G) assert_equal(sorted(B), [-5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) # Project onto the nodes of the original graph. H = nx.project(B, range(1, 12)) assert_equal(H.adj, G.adj) # Project onto the nodes representing the cliques. H1 = nx.project(B, range(-5, 0)) # Relabel the negative numbers as positive ones. H1 = nx.relabel_nodes(H1, dict((-v, v) for v in range(1, 6))) assert_equal(sorted(H1), [1, 2, 3, 4, 5])
def get_bipartite_proj(G,proj1_name=None,proj2_name=None): """docstring for get_bipartite_proj Returns the bipartite projection for each set of nodes in the bipartite graph G """ if networkx.is_bipartite(G): set1,set2=networkx.bipartite_sets(G) net1=networkx.project(G,set1) net1.name=proj1_name net2=networkx.project(G,set2) net2.name=proj2_name return net1,net2 else: raise networkx.NetworkXError("Network is not bipartite")
def main(): # Load data an symmetrize ssrn_mc=nx.read_graphml("../data/ssrn_mc.graphml") ssrn_mc=ssrn_mc.to_undirected() # Create projections author_graph=nx.project(ssrn_mc,[(a) for (a,b) in ssrn_mc.nodes(data=True) if b["type"]=="1"]) article_graph=nx.project(ssrn_mc,[(a) for (a,b) in ssrn_mc.nodes(data=True) if b["type"]=="0"]) # Reset vertex attibutes author_graph.add_nodes_from([(a,b) for (a,b) in ssrn_mc.nodes(data=True) if b["type"]=="1"]) article_graph.add_nodes_from([(a,b) for (a,b) in ssrn_mc.nodes(data=True) if b["type"]=="0"]) # Write graph data nx.write_graphml(author_graph,"../data/authors_mc.graphml") nx.write_graphml(article_graph,"../data/articles_mc.graphml")
def main(): # Load data an symmetrize ssrn_mc = nx.read_graphml("../data/ssrn_mc.graphml") ssrn_mc = ssrn_mc.to_undirected() # Create projections author_graph = nx.project( ssrn_mc, [(a) for (a, b) in ssrn_mc.nodes(data=True) if b["type"] == "1"]) article_graph = nx.project( ssrn_mc, [(a) for (a, b) in ssrn_mc.nodes(data=True) if b["type"] == "0"]) # Reset vertex attibutes author_graph.add_nodes_from([(a, b) for (a, b) in ssrn_mc.nodes(data=True) if b["type"] == "1"]) article_graph.add_nodes_from([(a, b) for (a, b) in ssrn_mc.nodes(data=True) if b["type"] == "0"]) # Write graph data nx.write_graphml(author_graph, "../data/authors_mc.graphml") nx.write_graphml(article_graph, "../data/articles_mc.graphml")
def test_make_max_clique_graph(self): """Tests that the maximal clique graph is the same as the bipartite clique graph after being projected onto the nodes representing the cliques. """ G = self.G B = nx.make_clique_bipartite(G) # Project onto the nodes representing the cliques. H1 = nx.project(B, range(-5, 0)) # Relabel the negative numbers as nonnegative ones, starting at # 0. H1 = nx.relabel_nodes(H1, {-v: v - 1 for v in range(1, 6)}) H2 = nx.make_max_clique_graph(G) assert H1.adj == H2.adj
def test_make_max_clique_graph(self): """Tests that the maximal clique graph is the same as the bipartite clique graph after being projected onto the nodes representing the cliques. """ G = self.G B = nx.make_clique_bipartite(G) # Project onto the nodes representing the cliques. H1 = nx.project(B, range(-5, 0)) # Relabel the negative numbers as nonnegative ones, starting at # 0. H1 = nx.relabel_nodes(H1, {-v: v - 1 for v in range(1, 6)}) H2 = nx.make_max_clique_graph(G) assert_equal(H1.adj, H2.adj)
def test_project(self): G = networkx.path_graph(4) P = networkx.project(G, [1, 3]) assert_equal(sorted(P.nodes()), [1, 3]) assert_equal(sorted(P.edges()), [(1, 3)])
#!/usr/bin/env python # Funtion: # Filename: import networkx as nx from networkx.algorithms import bipartite import matplotlib.pyplot as plt B = nx.Graph() #添加一个项目101,它有3个参与者:201,202,203 B.add_edge(101, 201) B.add_edge(101, None) B.add_edge(101, 202) B.add_edge(101, 203) #添加一个项目102,它有2个参与者:203,202,2034 B.add_edge(102, 203) B.add_edge(102, 204) NSet = bipartite.sets(B) #将二分图中的两类节点分别提取出来 print('NSet', NSet) Act = nx.project(B, NSet[0]) #向项目节点投影 Actor = nx.project(B, NSet[1]) #向参与者节点投影 print(Act.edges()) #输出 [(101, 102)] print(Actor.edges()) #输出 [(201, 202), (201, 203), (202, 203), (203, 204)] G = nx.make_clique_bipartite(Actor) print(G.edges()) #输出:[(201, -1), (202, -1), (203, -2), (203, -1), (204, -2)] nx.draw(G) plt.show()
def optimize(self): # observation_set = ["weight", "nnet_outputs"] factors = self.factors all_variables = sorted( set(v for factor in factors for v in factor.names)) factors = [ new_factor for factor in factors for new_factor in factor.factorize() ] adjacency_matrix = np.eye(len(all_variables), dtype=bool) indices_to_factor = [] for factor in factors: for v1 in (v for v in factor.names): for v2 in (v for v in factor.names): adjacency_matrix[all_variables.index(v1), all_variables.index(v2)] = 1 indices_to_factor.append({ "indices": [all_variables.index(var) for var in factor.names], "factor": factor, "assigned": False }) g = nx.from_numpy_matrix(adjacency_matrix) G = nx.make_clique_bipartite(g) cliques = [v for v in G.nodes() if G.nodes[v]['bipartite'] == 0] clique_graph = nx.project(G, cliques) # sort by decreasing number of neighbor cliques mapping = [] new_cliques = [] new_factors = [] not_yet_mapped_names = set(self.names) changed_variables = set() ################################### # Merge ConstraintFactor together # # and compute new variables # ################################### for clique_idx in sorted( clique_graph, key=lambda node_idx: len(clique_graph[node_idx]), reverse=True): # merge clique factors together clique_var_indices = list(G[clique_idx].keys()) clique_factors = [] for ind_fac in indices_to_factor: if set(ind_fac["indices"]) <= set( clique_var_indices) and not ind_fac["assigned"]: ind_fac["assigned"] = True clique_factors.append(ind_fac["factor"]) constraint_factors = [ fac for fac in clique_factors if isinstance(fac, ConstraintFactor) ] non_constraint_factors = [ fac for fac in clique_factors if fac not in constraint_factors ] clique_factors = ([ ConstraintFactor(And( *(fac.expr for fac in constraint_factors))), *non_constraint_factors ] if len(constraint_factors) else non_constraint_factors) new_cliques.append( list( range(len(new_factors), len(new_factors) + len(clique_factors)))) new_factors.extend(clique_factors) for factor in clique_factors: if isinstance(factor, ConstraintFactor): variables_to_group = [ v for v in factor.names if v not in changed_variables ] valid_assignements = torch.unique( factor.get_states(variables_to_group).long(), dim=0).bool() super_variable_name = "/".join(map(str, variables_to_group)) indices_in_input = pd.factorize( [*self.names, *variables_to_group])[0][len(self.names):] mapping.append((super_variable_name, variables_to_group, valid_assignements, indices_in_input)) not_yet_mapped_names -= set(variables_to_group) changed_variables |= set(variables_to_group) for name in sorted(not_yet_mapped_names): indice_in_input = self.names.index(name) mapping.append((name, [name], None, [indice_in_input])) # new_variables.extend(set(all_variables) - changed_variables) factors = [factor.change_variables(mapping) for factor in new_factors] cliques = new_cliques new_cliques = [] new_factors = [] cluster_hints = [] ############################## # Merge HintFactors together # ############################## for clique in cliques: clique_factors = [factors[i] for i in clique] clique_hint_factors = [ fac for fac in clique_factors if isinstance(fac, (HintFactor, ObservationFactor)) and isinstance(fac.fn, Indexer) ] cluster_hints = [] for fac in clique_hint_factors: matching_cluster_hint = next( (cluster_hint for cluster_hint in cluster_hints if can_merge(cluster_hint, fac)), None) if matching_cluster_hint is None: matching_cluster_hint = fac.clone() matching_cluster_hint.mask = matching_cluster_hint.mask.long( ) cluster_hints.append(matching_cluster_hint) else: last_indexers_1 = matching_cluster_hint.fn.indexers[-1] last_indexers_1 = list(last_indexers_1) if isinstance( last_indexers_1, (list, tuple)) else [last_indexers_1] last_indexers_2 = fac.fn.indexers[-1] last_indexers_2 = list(last_indexers_2) if isinstance( last_indexers_2, (list, tuple)) else [last_indexers_2] new_last_indexer = last_indexers_1 + last_indexers_2 matching_cluster_hint.fn = Indexer[(*fac.fn.indexers[:-1], new_last_indexer)] offseted_mask = fac.mask.long() + len(last_indexers_1) offseted_mask[~fac.mask] = 0 matching_cluster_hint.mask = matching_cluster_hint.mask + offseted_mask for cluster_hint in cluster_hints: cluster_hint.mask -= 1 new_factors.extend((fac for fac in clique_factors if fac not in clique_hint_factors)) new_factors.extend(cluster_hints) factors_input_indices = factorize( values=[np.asarray(factor.names) for factor in new_factors], reference_values=[entry[0] for entry in mapping], freeze_reference=True)[0] return CRF(new_factors, mapping, names=self.names, shape=self.shape, factors_input_indices=factors_input_indices)
def test_project(self): G=networkx.path_graph(4) P=networkx.project(G,[1,3]) assert_equal(sorted(P.nodes()),[1,3]) assert_equal(sorted(P.edges()),[(1,3)])