Ejemplo n.º 1
0
def read(path):
    (V,L) = loadWeightedGraph(path)
    G = [ Node() for i in range(V+1) ]
    for (x,y,c) in L:
        G[x].addEdge(y,c)
        G[y].addEdge(x,c)
    return G, set([i for i in range(1,V+1)])
Ejemplo n.º 2
0
def testStoerWagner(path):
    V, L, solution = dimacs.loadWeightedGraph(path)

    g = Graph(V, L)
    res = StoerWagnerAlgorithm(g)
    print("compare", res, solution)
    return res == solution
Ejemplo n.º 3
0
def solve(test):
    (V, E) = loadWeightedGraph(r"Laboratory\Lab_1\Tests" + "\\" + test)
    E.sort(key=lambda edge: edge[2])
    sys.setrecursionlimit(5000)
    solution = bin_search_solution(E, V, 1, 2)

    return solution
Ejemplo n.º 4
0
def loadGraph(name):
    (V,L) = loadWeightedGraph(name)
    G = [Node() for i in range(V+1)]

    for u, v, c in L:
        G[u].out.add(v)
        G[v].out.add(u)

    return G
Ejemplo n.º 5
0
def loadGraph(path):
    n, edges = renumber(*dimacs.loadWeightedGraph(path))
    vertices = [Node(vtx) for vtx in range(n)]

    for u, v, _ in edges:
        vertices[u].connect_to(v)
        vertices[v].connect_to(u)

    return vertices
Ejemplo n.º 6
0
def load_graph(file_path):
    (v_num, edges) = loadWeightedGraph(file_path)
    graph = [None] + [Node(i) for i in range(1, v_num + 1)
                      ]  # to index vertices by their number

    for (u, v, _) in edges:
        graph[u].connect_to(v)
        graph[v].connect_to(u)

    return graph
Ejemplo n.º 7
0
def run(name):
    (V, L) = loadWeightedGraph(name)

    G = [None] + [Node(i) for i in range(1, V + 1)]  # żeby móc indeksować numerem wierzchołka

    for (u, v, _) in L:
        G[u].connect_to(v)
        G[v].connect_to(u)

    return G, lex_bfs(G)
Ejemplo n.º 8
0
def find_union_method(name):
    Graph = loadWeightedGraph(name)
    Unia = union(Graph[0])
    Graph[1].sort(reverse=True, key=lambda x: x[2])
    result = None
    for i in Graph[1]:
        Unia.make_union(i[0], i[1])
        result = i[2]
        if Unia.find_set(1) == Unia.find_set(2):
            break
    return result
Ejemplo n.º 9
0
def check_graph_planarity(path):
    (v_num, edges) = loadWeightedGraph(path)

    graph = nx.Graph()

    nodes = [i for i in range(1, v_num+1)]
    graph.add_nodes_from(nodes)

    graph.add_weighted_edges_from(edges)

    print(1) if check_planarity(graph)[0] else print(0)
Ejemplo n.º 10
0
def articulation_points():
    v_len, edges = loadWeightedGraph("articulation/AT")

    graph = [[] for _ in range(v_len + 1)]

    for x, y, _ in edges:
        graph[x].append(y)
        graph[y].append(x)

    tremaux_tree, low = dfs(graph)

    print(tremaux_tree)
    for node in tremaux_tree:
        print(node.idx)
    print(low)
Ejemplo n.º 11
0
def solve(test_path):
    (V, L) = loadWeightedGraph(test_path)
    FU = [[i, 0] for i in range(V + 1)]

    s = 1
    t = 2
    L = sorted(L, key=lambda x: -x[2])
    res = L[0][2]

    for edge in L:
        union(edge[0], edge[1], FU)
        res = min(res, edge[2])
        if find(s, FU) == find(t, FU):
            break
    return res
Ejemplo n.º 12
0
def edge_connectivity(test):
    (V, _) = loadWeightedGraph(test)
    minimum = float("inf")

    for s in range(1, V):
        t = s + 1

        while t <= V:
            v = ford_fulkerson(test, s, t)

            if v < minimum:
                minimum = v

            t = t + 1

    return minimum
Ejemplo n.º 13
0
def main():
    graphs = os.listdir("maxclique")

    #graphs = ["game", "cycle3", "house"]
    #graphs = ["interval-rnd50"]
    graphs = [sys.argv[1]]

    print(len(graphs))
    for name in graphs:
        #print(name, file=sys.stderr)
        V, L = loadWeightedGraph("maxclique/" + name)

        print(V, len(L))

        for u, v, _ in L:
            print(u, v)
Ejemplo n.º 14
0
def tour(graph):

    # V - liczba wierzchołków, L - lista krawędzi postaci(x,y,weight)
    (V, L) = loadWeightedGraph(graph)

    # sortowanie krawędzi grafu malejąco - sortuję krotki po wadze
    L.sort(key=lambda tup: tup[2], reverse=True)

    nodes = [Node(i + 1) for i in range(V)]

    for x, y, weight in L:

        if find_set(nodes[x - 1]) != find_set(nodes[y - 1]):
            union(nodes[x - 1], find_set(nodes[y - 1]))

        # koniec algorytmu
        if find_set(nodes[0]) == find_set(nodes[1]):
            return weight
Ejemplo n.º 15
0
def solve(test):
    (V, E) = loadWeightedGraph(r"Laboratory\Lab_1\Tests" + "\\" + test)
    subsets = [Subset(u) for u in range(V + 1)]
    s, t = 1, 2

    graph = Graph(V, E)
    graph.sort_edges()

    for (u, v, w) in graph.edges:
        union(subsets, u, v)

        s_repr = find(subsets, s)
        t_repr = find(subsets, t)

        if s_repr == t_repr:
            return w

    return -1
Ejemplo n.º 16
0
def edge_connectivity(graph):

    (_, V, L) = loadWeightedGraph(graph)

    # wykorzystujemy słownik mapujący wierzchołki do których są krawędzie na ich wagi
    G = [{} for i in range(V + 1)]

    for u, v, c in L:
        G[u][v] = G[v][u] = c

    deleted = 0

    result = float("inf")

    while deleted != len(G) - 2:
        res, deleted = minimumCutPhase(G, deleted)
        result = min(result, res)

    return result
Ejemplo n.º 17
0
        for j in range(i + 1, n - 1):
            Ni = G[vs[i]].out
            Nj = G[vs[j]].out

            verts = [pi[v] for v in Nj - Ni if pi[v] < i]
            if verts:
                viable = [pi[v] for v in Ni - Nj]
                if not viable or min(verts) <= min(viable):
                    return False
    return True


grDir = "graphs/chordal"

for f in os.listdir(grDir):
    (V, L) = loadWeightedGraph(os.path.join(grDir, f))
    G = [None] + [Node(i) for i in range(1, V + 1)]
    for (u, v, _) in L:
        G[u].connect_to(v)
        G[v].connect_to(u)
    print("{}: {}".format(f, checkLexBFS(G, lexBFS(G, V))))
"""

(V, L) = loadWeightedGraph(os.path.join(grDir, "interval-rnd10"))
G = [None] + [Node(i) for i in range(1, V + 1)]
for (u, v, _) in L:
    G[u].connect_to(v)
    G[v].connect_to(u)
print(checkLexBFS(G, lexBFS(G, V)))

"""
Ejemplo n.º 18
0
""" main module of this laboratory"""

from FindUnionMethod import find_union_method
from dimacs import loadWeightedGraph
from Testing import testing
from BS_BFS_DFS import bs_dfs_method

from lab1.GraphFunctions import dfs_limited, edge_list_to_adjacency_list

if __name__ == "__main__":
    #print(dfs_limited(edge_list_to_adjacency_list(loadWeightedGraph("Graf/path10")), 11, 1, 2))
    print(bs_dfs_method(loadWeightedGraph("Graf/cloque5")))
Ejemplo n.º 19
0
                q.put(graph[curr_v][i][0])

    return False


def binary_search(v, edge_list,
                  search_algorithm):  # search algorithm: dfs, dfs_rec or bfs
    graph = make_adj_list(v, edge_list)
    edge_list.sort(key=lambda l: l[2])

    max_weight = edge_list[len(edge_list) - 1][2]
    min_weight = edge_list[0][2]

    curr_weight = (max_weight + min_weight) // 2
    while max_weight - min_weight > 1:
        if search_algorithm(graph, curr_weight):
            min_weight = curr_weight
        else:
            max_weight = curr_weight

        curr_weight = (max_weight + min_weight) // 2

    if search_algorithm(graph, min_weight + 1):
        print(min_weight + 1)
    else:
        print(min_weight)


(v_len, edges) = dimacs.loadWeightedGraph(sys.argv[1])  # reading graph
binary_search(v_len, edges, dfs)
Ejemplo n.º 20
0
    C = {fst_elem_key: G[fst_elem_key]}

    cut_weight = None
    while len(C) < len(G):
        u, cut_weight = max(tightness(G, C).items(), key=lambda item: item[1])
        C[u] = G[u]

    r_iter = reversed(G.keys())
    t = next(r_iter)
    s = next(r_iter)

    merge_vertices(G, s, t)

    return cut_weight


def minimum_cut(size, edge_list):
    edge_list = list(
        map(lambda edge: (edge[0] - 1, edge[1] - 1, edge[2]), edge_list))

    G = {i: Node() for i in range(size)}

    for u, v, w in edge_list:
        G[u].add_edge(v, w)
        G[v].add_edge(u, w)

    return min([minimum_cut_phase(G) for _ in range(size - 1)])


data = dimacs.loadWeightedGraph("graphs/clique200")
print(minimum_cut(*data))
Ejemplo n.º 21
0
        return (flow, path)
    else:
        return (0, [])


def findBestPath(G, s, t):
    graph = Graph(G[1], G[0])
    edges = G[1]
    edges = sorted(edges, key=lambda edge: edge[2])
    q = len(edges) - 1
    p = 0
    if BFS(graph, s, t, edges[q][2])[0] > 0:
        return edges[q][2]
    if BFS(graph, s, t, edges[p][2])[0] == 0:
        return 0
    while p < q - 1:
        half = int((p + q) / 2)
        flow = BFS(graph, s, t, edges[half][2])[0]
        if flow > 0:
            p = half
        elif flow == 0:
            q = half

    if BFS(graph, s, t, edges[q][2])[0] > 0:
        return edges[q][2]
    else:
        return edges[p][2]


print(findBestPath(dimacs.loadWeightedGraph(sys.argv[1]), 1, 2))
Ejemplo n.º 22
0
def testFindUnion(path):

    V,L,expected = dimacs.loadWeightedGraph(path)

    return przewodnikTurystycznyFindUnion(V,L) == expected
Ejemplo n.º 23
0
    def __init__(self, V, L):
        self.G = [Node() for i in range(V + 1)]
        self.V = V

        for (x, y, c) in L:
            self.G[x].addEdge(y, c)
            self.G[y].addEdge(x, c)

    def add_edge(self, u, v, weight):
        self.G[u].addEdge(v, weight)

    def delete_edge(self, u, v):
        self.G[u].delEdge(v)

    def print_graph(self):
        for (u, node) in enumerate(self.G):
            for v in range(1, self.V + 1):
                weight = node.edges.get(v, 0)

                if weight != 0:
                    print(f"From: {u}, to: {v}, weight: {weight}")


# def stoer_wagner(test):
test_dir = "Laboratory\\Lab_3\\tests\\connectivity"

(V, L) = loadWeightedGraph(test_dir + "\\simple")  # wczytaj graf
graph = Graph(V, L)

graph.print_graph()
Ejemplo n.º 24
0
        # print("aktualny",res, "best", best, "zostalo", x)

    # print("result:",min(res))
    return best


def testStoerWagner(path):
    V, L, solution = dimacs.loadWeightedGraph(path)

    g = Graph(V, L)
    res = StoerWagnerAlgorithm(g)
    print("compare", res, solution)
    return res == solution


V, L, res = dimacs.loadWeightedGraph("tests/grid5x5")

# for (x,y,c) in L:                        # przeglądaj krawędzie z listy
#   print( "krawedz miedzy", x, "i", y,"o wadze", c )   # wypisuj

import time
g = Graph(V, L)

g.print()
start = time.time()

print("powinno byc", res, "a jest", StoerWagnerAlgorithm(g))

print("time:", time.time() - start)

from runAllTests import run
Ejemplo n.º 25
0
def run(file):
    (V, E) = loadWeightedGraph(file)
    return stoerWagner(V, E)
Ejemplo n.º 26
0
def read_from_file(pathToFile):
    source, target, emf = dimacs.read_source(pathToFile)
    V, L = dimacs.loadWeightedGraph(pathToFile)
    L = list(map(lambda x: (x[0] - 1, x[1] - 1, x[2]), L))
    return Circuit(V, L, source, target, emf)
Ejemplo n.º 27
0
# https://faliszew.github.io/algograf/lab3


from dimacs import loadWeightedGraph
from queue import PriorityQueue
from flow_method import *
from utils import *
from stoer_wagner import *

(V,L) = loadWeightedGraph("graphs/clique200")
graph = nodesFromEdges(L, V)
print(stoerWagner(graph))
Ejemplo n.º 28
0
import networkx as nx
from dimacs import loadWeightedGraph
import matplotlib.pyplot as plt

G = nx.Graph()

filename = 'graphs-lab6/plnar/clique20'

(V, L) = loadWeightedGraph(filename)

v = [i for i in range(V + 1)]

G.add_nodes_from(v)

for a, b, w in L:
    G.add_edge(a, b)

from networkx.algorithms.planarity import check_planarity

print(check_planarity(G)[0])

pos = nx.spring_layout(G)

nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_edges(G, pos)
plt.show()
Ejemplo n.º 29
0
    y = find_set(y)

    if x.rank > y.rank:
        y.parent = x

    elif y.rank > x.rank:
        x.parent = y

    else:
        x.parent = y
        y.rank += 1


# wczytuje graf i wypisuje krawędzi

(V, L) = loadWeightedGraph("g1")  # wczytaj graf
for (x, y, c) in L:  # przeglądaj krawędzie z listy
    print("krawedz miedzy", x, "i", y, "o wadze", c)  # wypisuj
print()


def tour(graph):

    # V - liczba wierzchołków, L - lista krawędzi postaci(x,y,weight)
    (V, L) = loadWeightedGraph(graph)

    # sortowanie krawędzi grafu malejąco - sortuję krotki po wadze
    L.sort(key=lambda tup: tup[2], reverse=True)

    nodes = [Node(i + 1) for i in range(V)]