Пример #1
0
    def test_maximal_by_cardinality(self):
        """Tests that the maximal clique is computed according to maximum
        cardinality of the sets.

        For more information, see pull request #1531.

        """
        G = nx.complete_graph(5)
        G.add_edge(4, 5)
        clique = max_clique(G)
        assert_greater(len(clique), 1)

        G = nx.lollipop_graph(30, 2)
        clique = max_clique(G)
        assert_greater(len(clique), 2)
Пример #2
0
    def test_maximal_by_cardinality(self):
        """Tests that the maximal clique is computed according to maximum
        cardinality of the sets.

        For more information, see pull request #1531.

        """
        G = nx.complete_graph(5)
        G.add_edge(4, 5)
        clique = max_clique(G)
        assert len(clique) > 1

        G = nx.lollipop_graph(30, 2)
        clique = max_clique(G)
        assert len(clique) > 2
Пример #3
0
def Tabucol_opt(G, k, C_L=6, C_lambda=0.6, C_maxiter=100000, verbose=False):
    '''Tabucol_opt provides the graph coloring with the smallest number of
    colors'''
    assert len(G) > 0
    assert k > 0 and k <= len(G)
    best_colors, best_niter = {}, 0
    # compute length of max clique as number of colors cannot be less
    length_max_clique = len(max_clique(G))
    if k < length_max_clique:
        print(
            'Tabucol_opt cannot find a solution with less colors than length of maximum clique ',
            length_max_clique)
    else:
        ncolors = k
        while ncolors >= length_max_clique:
            colors, niter = Tabucol(G, ncolors, C_L, C_lambda, C_maxiter)
            if is_coloring_feasible(G, colors):
                best_colors = dict(colors)
                best_niter = niter
                ncolors = max(colors.values())
                if verbose:
                    print('Tabucol_opt found a solution with %d colors' %
                          (max(colors.values()) + 1))
            else:
                if not best_colors:
                    print(
                        'Tabucol_opt did not find a solution with %d colors' %
                        k)
                break

    return best_colors, best_niter
Пример #4
0
def only_max_clique(num_seeds, G):
	max_cliq = max_clique(G)
	print("GOT CLIQUE")
	seeds = random.sample(max_cliq, min(num_seeds, len(max_cliq)))
	print("GOT FIRST SAMPLE")

	if len(seeds)<num_seeds:
		seeds.extend(random.sample(max_cliq, num_seeds- len(seeds)))
		# seeds = list(set(seeds))
	print("GOT SECOND SAMPLE")
	return seeds
Пример #5
0
def details(graph):
    cliques_number = nx.graph_clique_number(graph)
    print("Number of cliques in the graph %d:" % cliques_number)
    clique = approximation.max_clique(graph)
    print("Maximum clique of the graph is: %.2d" % len(clique))
    print(clique)
    shortest_path = nx.shortest_path(graph)
    print("Shortest path: ", shortest_path)
    try:
        diameter = nx.diameter(graph)
        print("Diameter of the graph: %d" % diameter)
    except:
        print("Graph is not connected!")
Пример #6
0
def only_max_clique(num_seeds, G):
	max_cliq = max_clique(G)
	print("GOT CLIQUE")
	seeds = random.sample(max_cliq, min(num_seeds, len(max_cliq)))
	print("GOT FIRST SAMPLE")

	for i in range(num_seeds - len(seeds)):
		node_degrees = G.degree()
		sorted_node_degrees = np.array(sorted(node_degrees,key=itemgetter(1), reverse = True))
		sorted_list = list(set(sorted_node_degrees[:num_seeds, 0])-set(seeds))

		seeds.extend(sorted_list[i])
		# seeds = list(set(seeds))
	print("GOT SECOND SAMPLE")
	return seeds
Пример #7
0
    def preprocess_graph(self):
        '''remove nodes with fewer degrees than the degree of a maximal
        clique and from dominated sets'''
        entering()

        G = self.originalgraph.copy()
        # compute maximum clique from networkx.algorithms.approximation
        maxclique = max_clique(G)
        len_maxclique = len(maxclique)

        pruned_nodes = []
        while True:
            nnodes_at_start = len(G)
            # iteration to remove nodes with degree < |max_clique|
            partial_node_list = [
                n for (n, deg) in G.degree()
                if n not in maxclique and deg < len_maxclique
            ]
            if partial_node_list:
                G.remove_nodes_from(partial_node_list)
                pruned_nodes.extend(partial_node_list)
            # iteration to remove nodes from dominated neighborhoods
            partial_node_list = []
            for u in (u for u in G.nodes() if u not in maxclique):
                for v in G.nodes():
                    if u == v or G.has_edge(u, v):
                        continue
                    if set(G[u]).issubset(set(G[v])):
                        partial_node_list.append(u)
                        break
            if partial_node_list:
                G.remove_nodes_from(partial_node_list)
                pruned_nodes.extend(partial_node_list)
            # repeat whenever there is improvement
            if nnodes_at_start == len(G):
                break
        # update working graph and keep pruned nodes for post processing
        self.graph.remove_nodes_from(pruned_nodes)
        self.pruned_nodes = pruned_nodes[:]
        if self.pruned_nodes:
            print("pruned nodes are:", pruned_nodes)
            self.graph = G.copy()
            del G
        else:
            print("no nodes were pruned at pre-processing stage")
        leaving()
Пример #8
0
def process(graph_file):
    with open(graph_file, 'rt') as fileobj:
        g = nx.Graph()
        for line, text in enumerate(fileobj):
            words = text.split()
            assert len(words) == 2
            if line == 0:
                assert words[0] == 'keys'
                num_keys = int(words[1])
                vertices = range(num_keys)
                g.add_nodes_from(vertices)
            else:
                v1 = int(words[0])
                v2 = int(words[1])
                assert v1 >= 0 and v1 < num_keys
                assert v2 >= 0 and v2 < num_keys
                g.add_edge(v1, v2)

        print len(nx_alg.max_clique(g)), num_keys
Пример #9
0
    def print_graph_features(self, graph):
        res = {}
        try:
            print('diameter: ', nx.diameter(graph))
            print('eccentricity: ', nx.eccentricity(graph))
            print('center: ', nx.center(graph))
            print('periphery: ', nx.periphery(graph))
            res['connected'] = True
        except Exception as e:
            print('Graph not connected')
            res['connected'] = False

        res['density'] = '{:.6f}'.format(nx.density(graph))
        res['Avg_degree'] = '{:.6f}'.format(
            sum([i[1] for i in nx.degree(graph)]) / len(nx.degree(graph)))
        res['Avg_weight'] = '{:.6f}'.format(
            sum([graph[edge[0]][edge[1]]['weight'] for edge in graph.edges]) /
            len([graph[edge[0]][edge[1]]['weight'] for edge in graph.edges]))
        res['edges'] = len(graph.edges)
        res['nodes'] = len(graph.nodes)
        res['self_loops'] = len(list(nx.nodes_with_selfloops(graph)))
        res['edge_to_node_ratio'] = '{:.6f}'.format(
            len(graph.nodes) / len(graph.edges))
        res['negative_edges'] = nx.is_negatively_weighted(graph)
        print(algo.max_clique(graph))
        # print('density: ', res['density'])
        # print('Average degree: ', res['Avg_degree'])
        # print('Average weight: ', res['Avg_weight'])
        # print('edges: ', len(graph.edges))
        # print('Nodes: ', len(graph.nodes))
        # print('self loops: ', res['self_loops'])
        # print('edges to nodes ratio: ', res['edge_to_node_ratio'])
        # print('negative edges: ', res['negative_edges'])
        # nodes = [node for node in graph.nodes]
        # print(nodes)

        return res
Пример #10
0
numberConnectedComponents = nx.number_connected_components(b)



# diameter(b) 
# This will work only for graphs that are connected
diameter = -1
if numberConnectedComponents == 1:
    diameter = nx.diameter(b)

#print(diameter, sizeMaxClique)


# The maximum clique is returned as a set of nodes
# max_clique(b)
maxClique = naa.max_clique(b)
sizeMaxClique = len(maxClique)

print (diameter, sizeMaxClique)

# The dominating set is returned as a set of nodes
# min_weighted_dominating_set(b)
minDominatingSet = naa.min_weighted_dominating_set(b)
sizeMinDominatingSet = len(minDominatingSet)

# The number of maximal cliques in the graph 
# graph_number_of_cliques(b)
numberOfCliques = nx.graph_number_of_cliques(b)


print (numberConnectedComponents,diameter,sizeMaxClique,sizeMinDominatingSet,numberOfCliques)
Пример #11
0
    vertex_colored_graph.node(i,
                              style='filled',
                              fillcolor=colors[vertex_coloring.get(i)])
# vertex_colored_graph.view(filename='vertex_colored_graph', quiet_view=True)
print("d", file=main)
edge_coloring = nx.greedy_color(nx.line_graph(Main_graph))
print(edge_coloring, file=main)
edge_colored_graph = gv.Graph()
for i in edge_coloring:
    edge_colored_graph.edge(i[0], i[1], color=colors[edge_coloring.get(i)])
for i in Main_graph.nodes:
    edge_colored_graph.node(i)
# edge_colored_graph.view(filename='edge_colored_graph', quiet_view=True)
a = nx.find_cliques(Main_graph)
print("e", file=main)
maximum_clique = approximation.max_clique(Main_graph)
print(maximum_clique, file=main)
maximum_clique_list = []
for i in maximum_clique:
    maximum_clique_list.append(i)
maximum_clique_subgraph = gv.Graph()
for i in range(0, len(maximum_clique_list)):
    maximum_clique_subgraph.node(maximum_clique_list[i])
    for j in range(i + 1, len(maximum_clique_list)):
        if i != j:
            maximum_clique_subgraph.edge(maximum_clique_list[i],
                                         maximum_clique_list[j])
# maximum_clique_subgraph.view(filename='maximum_clique_subgraph')
print("f", file=main)
independent_set_graph = gv.Graph()
maximum_independent_set = [
next_level_communities = next(communities_generator)
next_level_communities


# In[54]:


approximation.k_components(G)


# In[55]:


## This crashes the session
approximation.max_clique(G)


# In[86]:


#lab.write_pandas_to_csv_on_gcs(bucket='swe-files' ,data=dfxtest2 ,fileName='swe-files/dfxtest2.csv')


# In[32]:


##### Write the dataframe to BQ.
#dfxtest2.to_gbq('ConnectionModeling.dfxtest2', "network-sec-analytics", verbose=True, reauth=False, 
  #if_exists='replace', private_key=None)
Пример #13
0
 def test_null_graph(self):
     G = nx.null_graph()
     assert_equal(len(max_clique(G)), 0)
Пример #14
0
def test_max_clique_smoke():
    # smoke test
    G = nx.Graph()
    assert_equal(len(apxa.max_clique(G)),0)
Пример #15
0
def setup(graph, num_players, num_seeds):
    print approx.max_clique(graph)
    return list(approx.max_clique(graph))
Пример #16
0
 def test_complete_graph(self):
     graph = nx.complete_graph(30)
     # this should return the entire graph
     mc = max_clique(graph)
     assert 30 == len(mc)
Пример #17
0
def test_max_clique_smoke():
    # smoke test
    G = nx.Graph()
    eq_(len(apxa.max_clique(G)), 0)
Пример #18
0
def cliques_in_nodes(graph):
    return [apxa.max_clique(graph)]
def cliques_for_nodes(G, nodes):
    return [apxa.max_clique(G)]
Пример #20
0
def test_max_clique():
    # create a complete graph
    graph = nx.complete_graph(30)
    # this should return the entire graph
    mc = apxa.max_clique(graph)
    assert_equals(30, len(mc))
Пример #21
0
def test_max_clique_smoke():
    # smoke test
    G = nx.Graph()
    assert_equal(len(apxa.max_clique(G)), 0)
Пример #22
0
 def test_null_graph(self):
     G = nx.null_graph()
     eq_(len(max_clique(G)), 0)
Пример #23
0
import util
import networkx as nx
from networkx.algorithms import approximation
from networkx.algorithms import connectivity
state_ = 15
input_ = 4
output_ = 1
file_name = 'test.kiss2'
repeated = 5
experiment = 10

util.create_fsm(state_, input_, output_, file_name)
G, g_data = util.create_graph(file_name)

print(nx.average_neighbor_degree(G))
print(approximation.max_clique(G))
print(nx.k_nearest_neighbors(G))
print(nx.min_edge_cover(G))
Пример #24
0
 def test_complete_graph(self):
     graph = nx.complete_graph(30)
     # this should return the entire graph
     mc = max_clique(graph)
     eq_(30, len(mc))
Пример #25
0
def test_max_clique():
    # create a complete graph
    graph = nx.complete_graph(30)
    # this should return the entire graph
    mc = apxa.max_clique(graph)
    eq_(30, len(mc))
Пример #26
0
def find_max_clique_approx(graph_):
    '''
    Wrapper for suitable time estimation
    '''
    return max_clique(graph_)
Пример #27
0
def create_graph(edgelist):

    G = nx.DiGraph()

    G.add_weighted_edges_from(edgelist)

    # Graph layout
    pos = nx.spring_layout(G)

    # Remove nodes with out-degree = 1------------------------------------------

    outdeg = nx.degree(G)

    while 1 in outdeg.values():

        to_remove = [n for n in outdeg if outdeg[n] == 1]

        G.remove_nodes_from(to_remove)

        # Remove edges also checking the two values of the tuple
        edgelist = [x for x in edgelist if x[0] not in to_remove]
        edgelist = [x for x in edgelist if x[1] not in to_remove]

        outdeg = nx.degree(G)
    # ---------------------------------------------------------------------------

    # Node size ================================================================

    d = nx.degree(G)

    nx.draw_networkx_nodes(G, pos, nodelist=d.keys(), node_size=[v * 100 for v in d.values()])

    # ===========================================================================

    nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap("jet"), node_size=1)

    edge_labels = dict([((u, v), d["weight"]) for u, v, d in G.edges(data=True)])

    nx.draw_networkx_edges(G, pos, width=0.5, alpha=0.2)

    nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)

    labels = {}

    for node in G.nodes():
        labels[node] = node

    nx.draw_networkx_labels(G, pos, labels, font_size=8)

    if not len(G) == 1:

        from networkx.algorithms import approximation as apxm

        print apxm.min_edge_dominating_set(G)
        print apxm.max_clique(G)
        print apxm.maximum_independent_set(G)
        print apxm.min_maximal_matching(G)

        print nx.degree_centrality(G)

    plt.savefig("directed.png")  # save as png

    # clean old graph
    plt.clf()
Пример #28
0
def test_max_clique():
    # create a complete nxgraph
    graph = nx.complete_graph(30)
    # this should return the entire nxgraph
    mc = apxa.max_clique(graph)
    assert_equals(30, len(mc))
Пример #29
0
def cliques_for_nodes(graph):
    return [apprx.max_clique(graph)]
Пример #30
0
 def test_null_graph(self):
     G = nx.null_graph()
     assert len(max_clique(G)) == 0
Пример #31
0
def cliques_for_nodes(G, nodes):
    return [apxa.max_clique(G)]
Пример #32
0
def test_max_clique_smoke():
    # smoke test
    G = nx.Graph()
    eq_(len(apxa.max_clique(G)),0)
Пример #33
0
def find_max_clique(points):
    g = nx.Graph()
    g.add_edges_from(points)
    import pdb
    pdb.set_trace()
    print(max_clique(g))