Example #1
0
def solve_mis(G):
    """
    最大独立集合問題を既存の近似解法で解く
    (Reference: Approximating Maximum Independent Sets by Excluding Subgraphs)
    補グラフの最大クリークを近似的に求めることで元グラフの最大独立集合を近似値として求めている
    入力
        G: 無向グラフ
    出力
        なし
        

    # ><><><><><><><><><><><><><><><><><><><><><
    # ><><><><><><><><><><><><><><><><><><><><><

    """
    
    start = time.time()

    indep_nodes = maximum_independent_set(G)

    elapsed_time = time.time() - start
    
    print('elapsed_time :', elapsed_time)
    print(f'independent set number: {len(indep_nodes)}')
    print(f'independent set: {indep_nodes}')
def graph_three_sat(three_sat, find_unsat):

    graph = nx.Graph()

    for sat in three_sat:

        graph.add_edges_from(sat.edge_list)

    graph.add_edges_from(three_sat.edge_list)
    pos = nx.shell_layout(graph, scale=0.4)
    k = maximum_independent_set(graph)

    color_map = []

    for node in graph:
        if node in k:
            color_map.append("cyan")
        else:
            color_map.append("gray")

    satisfiable = len(k) >= three_sat.size

    if find_unsat and satisfiable:

        return

    nx.draw_networkx(graph, font_size=8, node_color=color_map, pos=pos)
    plt.title(
        f"{three_sat}\nk={len(k)} size={three_sat.size}\nSatisfiable: {satisfiable}",
        size=8,
    )
    plt.show()
Example #3
0
    def compute_independence_number(self, d, resp_lst):
        for t in range(self.T):
            indicator_vec   = [1]*self.calA_size
            fg              = self.compute_in_probs(indicator_vec, d, resp_lst, t)

        ind_set = approximation.maximum_independent_set(self.G)
        a_G = len(ind_set)
        return a_G
Example #4
0
def getGraphBounds(graph, p, k, filename):
    #creates the file to store the results
    filename = "results\\" + filename + ".csv"
    file = open(filename, 'w')

    #runs the greedy algorithm and outputs the results
    greedyAlgResult = greedyAlg(graph.copy())
    print("Greedy Alg result:")
    print(greedyAlgResult)
    print(len(greedyAlgResult))
    print()
    file.write(str(len(greedyAlgResult)) + "\n")

    #run the vertex cover approximation algorithm 50 times and outputs the best result
    vertexCoverIndepResult = vertexCoverApprox(graph.copy())
    for i in range(50):
        temp = vertexCoverApprox(graph.copy())
        if (len(temp) < len(vertexCoverIndepResult)):
            vertexCoverIndepResult = temp
    print("vertex cover result:")
    print(len(graph.nodes()) - len(vertexCoverIndepResult))
    print()
    file.write(str(len(graph.nodes()) - len(vertexCoverIndepResult)) + "\n")

    #runs the algorithm for approximating clique and outputs its results
    cliqueApproxResult = cliqueMaxApprox(nx.complement(graph), 0.01)
    print("Clique approximation result:")
    print(cliqueApproxResult)
    print(len(cliqueApproxResult))
    print()
    file.write(str(len(cliqueApproxResult)) + "\n")

    #if the graph isn't too large we run the algorithm for networkx and outputs its results
    if (len(graph.nodes()) < 2200):
        networkxIndep = approximation.maximum_independent_set(graph)
        print("networkx result:")
        print(networkxIndep)
        print(len(networkxIndep))
        print()
        file.write(str(len(networkxIndep)) + "\n")
    else:
        print("Too big for networkx")

    #if the graph isn't too large for the stochastic algorithm then we run it and output its results
    if (len(graph.nodes()) < 400):
        b = 2
        stochasticResult = search(graph, b, p, k)
        print("Stochastic result:")
        print(stochasticResult)
        print(len(stochasticResult))
        print()
        file.write(str(len(stochasticResult)))
        file.write("\n")
        file.write(str(stochasticResult))
    else:
        print("Graph too big for stochastic")
def find_max_independent_set(graph, params):
    """Find the maximum independent set of an input graph given some optimized QAOA parameters.

    The code you write for this challenge should be completely contained within this function
    between the # QHACK # comment markers. You should create a device, set up the QAOA ansatz circuit
    and measure the probabilities of that circuit using the given optimized parameters. Your next
    step will be to analyze the probabilities and determine the maximum independent set of the
    graph. Return the maximum independent set as an ordered list of nodes.

    Args:
        graph (nx.Graph): A NetworkX graph
        params (np.ndarray): Optimized QAOA parameters of shape (2, 10)

    Returns:
        list[int]: the maximum independent set, specified as a list of nodes in ascending order
    """

    max_ind_set = []

    # QHACK #
    '''
    cost_h, mixer_h = qml.qaoa.min_vertex_cover(graph, constrained=False)
    
    def qaoa_layer(gamma, alpha):
        qml.qaoa.cost_layer(gamma, cost_h)
        qml.qaoa.mixer_layer(alpha, mixer_h)
    
    biggest = 0
    for i in graph.edges():
        if i[0] > biggest: biggest = i[0]
        if i[1] > biggest: biggest = i[1]
    
    wires = range(biggest+1)
    depth = 10

    def circuit(params):
        for w in wires:
            qml.Hadamard(wires=w)
        qml.layer(qaoa_layer, depth, params[0], params[1])
    
    dev = qml.device("default.qubit", wires=wires)
    @qml.qnode(dev)
    def probability_circuit(gamma, alpha):
        circuit([gamma, alpha])
        return qml.probs(wires=wires)


    probs = probability_circuit(params[0], params[1])'''
    from networkx.algorithms import approximation
    max_ind_set = nx.maximal_independent_set(graph, approximation.maximum_independent_set(graph))
    max_ind_set.sort()
    
    # QHACK #

    return max_ind_set
def main():
	# build up a graph
	filename = '../../florentine_families_graph.gpickle'
	G = nx.read_gpickle(filename)

	# Indepedent set
	maximal_iset = nx.maximal_independent_set(G)
	out_file = 'florentine_families_graph_maximal_iset.png'
	PlotGraph.plot_graph(G, filename=out_file, colored_nodes=maximal_iset)

	maximum_iset = nxaa.maximum_independent_set(G)
	out_file = 'florentine_families_graph_maximum_iset.png'
	PlotGraph.plot_graph(G, filename=out_file, colored_nodes=maximum_iset)
def main():
    # build up a graph
    filename = '../../florentine_families_graph.gpickle'
    G = nx.read_gpickle(filename)

    # Indepedent set
    maximal_iset = nx.maximal_independent_set(G)
    out_file = 'florentine_families_graph_maximal_iset.png'
    PlotGraph.plot_graph(G, filename=out_file, colored_nodes=maximal_iset)

    maximum_iset = nxaa.maximum_independent_set(G)
    out_file = 'florentine_families_graph_maximum_iset.png'
    PlotGraph.plot_graph(G, filename=out_file, colored_nodes=maximum_iset)
Example #8
0
def get_is(G, gs_set, k):
    cnt = 0
    for x in gs_set:
        for y in gs_set:
            if G.has_edge(x, y) == True:
                cnt += 1
                G.remove_edge(x, y)
    if cnt > k:
        raise Exception('The the number of K is too small!')

    for x in gs_set:
        neighbors = list(G.neighbors(x))
        for y in neighbors:
            if G.has_node(y):
                G.remove_node(y)
    return approximation.maximum_independent_set(G), k - cnt
Example #9
0
def solveIt(inputData):
    # Modify this code to run your optimization algorithm
    # parse the input
    lines = inputData.split('\n')

    firstLine = lines[0].split()
    nodeCount = int(firstLine[0])
    edgeCount = int(firstLine[1])

    edges = []
    for i in range(1, edgeCount + 1):
        line = lines[i]
        parts = line.split()
        edges.append((int(parts[0]), int(parts[1])))
    # build a trivial solution
    # every node has its own color
        #items = len(values)
        #define n constraints fir each possible color:
    g=nx.Graph()
    g.add_edges_from(edges)
    solution=[-1]*len(g.nodes())
    i=0
    while(len(g.nodes())>0):
        maxDegVert=g.degree().keys()[g.degree().values().index(max(g.degree().values()))]
        # print(maxDegVert)
        indSet=maximum_independent_set(g)
        # indSet=maximum(g,[maxDegVert])
        for node in indSet:
            g.remove_node(node)
            solution[node]=i
        i=i+1
    # print(solution)
    # prepare the solution in the specified output format
    outputData = str(i) + ' ' + str(0) + '\n'
    outputData += ' '.join(map(lambda x:str(int(x)), solution))
    return outputData
def test_independent_set():
    # smoke test
    G = nx.Graph()
    assert_equal(len(a.maximum_independent_set(G)),0)
def test_independent_set():
    # smoke test
    G = nx.Graph()
    assert_equal(len(a.maximum_independent_set(G)),0)
def find_maximal_independent_set(filename, sub_filename):
    with open(filename) as file:
        lines = file.readlines()

    graph = nx.DiGraph()
    for line in lines:
        if 'v' in line:
            rg.add_nodes_from(graph, [(line.split()[1], {
                "type": line.split()[2]
            })])
        elif 'e' in line:
            rg.add_edges_from(graph, [(line.split()[1], line.split()[2])])

    with open(sub_filename) as file:
        lines = file.readlines()

    graph_ind = -1
    graphs = []
    invalid_graphs = []
    for line in lines:
        if ':' in line:
            graph_ind += 1
            graphs.append(nx.DiGraph())
        elif 'v' in line:
            rg.add_nodes_from(graphs[graph_ind], [(line.split()[1], {
                "type": line.split()[2]
            })])
            if line.split()[2] == '0':
                invalid_graphs.append(graph_ind)
        elif 'e' in line:
            rg.add_edges_from(graphs[graph_ind],
                              [(line.split()[1], line.split()[2])])

    ret = {}

    for idx, pat_graph in enumerate(graphs):
        if idx in invalid_graphs:
            continue

        pattern = pat_graph

        test = isomorphism.GraphMatcher(graph, pattern, node_match=node_match)
        instances_gen = test.subgraph_isomorphisms_iter()

        instances = []
        for inst in instances_gen:
            instances.append(inst)

        newNodes = []
        newEdges = []
        for i, inst in enumerate(instances):
            # print(inst)
            newNodes.append(i)

            for k in inst:
                for z, temp_inst in enumerate(instances):
                    for s in temp_inst:
                        # breakpoint()
                        if k == s and not z == i:
                            if not ((z, i) in newEdges or
                                    ((i, z) in newEdges)):
                                newEdges.append((z, i))

        # print(newNodes)
        # print(newEdges)

        newGraph = nx.Graph()

        rg.add_nodes_from(newGraph, newNodes)
        rg.add_edges_from(newGraph, newEdges)

        res = nxaa.maximum_independent_set(newGraph)

        # print(res)
        print("Subgraph: ", idx)
        print("Size of Subgraph:" + str(len(pattern.nodes())))
        print("Num subgraphs occurences:" + str(len(newGraph.nodes())))
        print("Num overlapping subgraphs:" +
              str(len(newGraph.nodes()) - len(res)))
        print("Size max ind set:" + str(len(res)))
        print()

        # pos = nx.nx_agraph.graphviz_layout(graph, prog='dot')
        # nx.draw_networkx(graph, pos, with_labels=True)
        # plt.show()

        # color_map = []
        # for node in newGraph:
        #     if node in res:
        #         color_map.append('blue')
        #     else:
        #         color_map.append('green')
        # pos = nx.nx_agraph.graphviz_layout(newGraph, prog='dot')
        # nx.draw_networkx(newGraph, pos, node_color=color_map, with_labels=True)
        # plt.show()
        ret[idx] = (len(newGraph.nodes()), len(newGraph.nodes()) - len(res),
                    len(res))
    return ret
Example #13
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()
Example #14
0
def test_independent_set():
    # smoke test
    G = nx.Graph()
    assert len(a.maximum_independent_set(G)) == 0