def display_submenu(G: Graph) -> None:
    """
    Submenu of main menu. Let user to go to convert handler or
    plot graph or print current graph or go back to main menu.
    """
    operations_choice = ''

    while operations_choice != 'q':
        print(50 * '-')
        print("[1] Convert")
        print("[2] Plot")
        print("[3] Print current graph")
        print("[b] Go back to menu")

        operations_choice = input("Pick the option:\n")

        if operations_choice == 'b':
            G.clear_grah()
            return

        if operations_choice == '1':
            handle_convert(G)
        elif operations_choice == '2':
            GraphPlotter.plot_graph(G)
        elif operations_choice == '3':
            print_graph(G)
def present_k_regular_graphs() -> None:
    """
    Finds k-regular graph for given k and vertices number.
    """
    vertices = int(input('\nNumber of vertices: '))
    k = int(input('Put k-parameter: '))
    randomizations = int(input("Put number of randomizations: "))

    G = Graph()
    G.create_k_regular_with_n_vertices(k, vertices)
    randomize(G, randomizations)
    
    GraphPlotter.plot_graph(G)
def present_graph_from_file(G: Graph) -> None:   
    operations_choice = ''
    v = len(G.repr)
    
    while operations_choice != 'b':
        display_submenu()
        operations_choice = input("Pick the option:\n")
    
        try:
            
            if operations_choice == '1':
                cycle = hamilton(G)
                if cycle == '[]':
                    print('Graph is not Hamiltonian')
                else:
                    print('Graph is Hamiltonian')
                    print(cycle)
            
            if operations_choice == '2':
                cycle = euler_cycle(G)
                if cycle == '[]':
                    print('Graph is not Eulerian')
                else:
                    print('Graph is Eulerian')
                    print(euler_cycle(G))
                
            if operations_choice == '3':
                G.to_adjacency_matrix()
                for k in range(1, v):
                    if G.is_k_regular(k):
                        print('Graph is ' + str(k) + '-regular')
                        break
                    if k == v - 1:
                        print('Graph is not k-regular')
            
            if operations_choice == '4':
                G.to_adjacency_matrix()
                randomizations = int(input('Number of randomizations: '))
                randomize(G, randomizations)
            
            if operations_choice == '5':
                G.to_adjacency_list()
                groups = get_components(G)
                print_sorted_components(G, groups)
                GraphPlotter.plot_graph(G, False, False, groups)
            
            if operations_choice == '6':
                GraphPlotter.plot_graph(G)
            
        except:
            print("Something went wrong. Try again!")
def present_graph_randomization() -> None:
    """
    Presents graph randomization for graph using graphical sequence
    and randomizations parameter.
    """
    print('\nLet\'s start with Your own graphical sequence.\n')
    sequence = present_graphical_sequence()

    if sequence != []:
        randomizations = int(input('Number of randomizations: '))
        G = Graph()
        G.load_data(sequence, RepresentationType.GRAPH_SEQUENCE)
        G.to_adjacency_matrix()
        randomize(G, randomizations)
        GraphPlotter.plot_graph(G)
def present_components_finding() -> None:
    """
    Presents finding graph components for graph
    generated by 'get_graph_with_probability'
    with parameters given by user.
    """
    vertices = int(input('\nNumber of vertices: '))
    probability = float(input("Put probability (0;1):\n"))

    G = Graph()
    G.load_data(get_graph_with_probability(vertices, probability), RepresentationType.ADJACENCY_MATRIX)
    G.to_adjacency_list()

    groups = get_components(G)
    print_sorted_components(G, groups)
    GraphPlotter.plot_graph(G, False, False, groups)
def present_eulerian_graphs() -> None:
    """
    Generates Eulerian Graph sequence and finds Eulerian Cycle.
    """
    randomizations = 100
    v = int(input('\nNumber of vertices: '))

    G = Graph()

    if generate_euler_graph_sequence(G, v):
        print('Graphical sequence of graph: ' + str(G))
        G.to_adjacency_matrix()
        randomize(G, randomizations)
        print('Euler Cycle: ' + euler_cycle(G))
        GraphPlotter.plot_graph(G)

    else:
        print("Error while generating euler graph sequence")
def present_hamiltonian_graphs() -> None:
    """
    Chceck if graph generated by 'get_graph_with_probability'
    with parameters given by user is Hamiltonian.
    """
    vertices = int(input('\nNumber of vertices: '))
    probability = float(input("Put probability (0;1):\n"))

    G = Graph()
    G.load_data(get_graph_with_probability(vertices, probability), RepresentationType.ADJACENCY_MATRIX)
    
    cycle = hamilton(G)
    if cycle == '[]':
        print("Graph is not hamiltonian")
    else:
        print("Graph is hamiltonian")
        print(cycle)
        
    GraphPlotter.plot_graph(G)
def present_graphical_sequence() -> list:
    """
    Presents graphical sequence inserting and checking [1].
    Returns sequence as a list if sequence is graphical.
    Otherwise - [] - empty list.
    """
    G = Graph()

    print('\nInsert sequence of integers')
    sequence = [int(x) for x in input('Your sequence: ').split()]

    if G.load_data(sequence, RepresentationType.GRAPH_SEQUENCE):
        print('Your sequence is graphical! Here is one of possible solutions\n')
        GraphPlotter.plot_graph(G)

    else:
        print('Sequence is not graphical\n')
        return []

    return sequence
예제 #9
0
def find_cycle(G: Graph, points: list) -> None:
    if G.repr_type == RepresentationType.EMPTY:
        print('\nGraph is empty! First try to create it.')
    else:
        print('\n[1] Closest Neighbour Algorithm')
        print('[2] Simulated Annealing Algorithm')
        print('[3] Combine two algorithms')

        option = input("\nChoose option\n")

        if option == '1':
            GraphPlotter.plot_points(points, closest_neighbour(G))

        if option == '2':
            print(
                '\nChoose how many times algorithms should be repeated (int)')
            repeat = int(input('Repeats: '))
            print('\nChoose starting temperature (int)')
            temp = int(input('Temperature: '))
            print('\nChoose number of iterations (int)')
            iter_max = int(input('ITER_MAX: '))
            path = simulated_annealing(G, temp, iter_max, repeat)
            if path != []:
                GraphPlotter.plot_points(points, path)

        if option == '3':
            print(
                '\nChoose how many times algorithms should be repeated (int)')
            repeat = int(input('Repeats: '))
            print('\nChoose starting temperature (int)')
            temp = int(input('Temperature: '))
            print('\nChoose number of iterations (int)')
            iter_max = int(input('ITER_MAX: '))
            path = simulated_annealing(G,
                                       temp,
                                       iter_max,
                                       repeat,
                                       path=closest_neighbour(G))
            if path != []:
                GraphPlotter.plot_points(points, path)
예제 #10
0
import os, sys
import numpy as np

currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)

from utils.Graph import Graph, RepresentationType
from utils.graph_plotter import GraphPlotter
from utils.graph_generators import randomize

if __name__ == "__main__":
    G = Graph()

    G.create_k_regular_with_n_vertices(k=2, vertices=7)
    randomize(G, 100)

    GraphPlotter.plot_graph(G)

예제 #11
0
import os, sys

currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)

from utils.graph_generators import get_directed_graph_with_probability
from utils.graph_plotter import GraphPlotter
from utils.DirectedGraph import DirectedGraph, RepresentationType

x = get_directed_graph_with_probability(10, 0.2, -5, 10)

g = DirectedGraph()
g.load_data(data=x, representation_type=RepresentationType.ADJACENCY_MATRIX)
GraphPlotter.plot_graph(g, draw_wages=True, draw_arrows=True)

g.to_incidence_matrix()
g.to_adjacency_matrix()
g.to_adjacency_list()
g.to_adjacency_matrix()

g.to_adjacency_list()
g.to_incidence_matrix()
g.to_adjacency_list()
g.to_adjacency_matrix()

GraphPlotter.plot_graph(g, draw_wages=True, draw_arrows=True)
import os, sys

currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)

from utils.Graph import Graph, RepresentationType
from utils.graph_plotter import GraphPlotter
from algorithms.components import get_components, print_sorted_components

if __name__ == '__main__':
    G = Graph()
    G.load_data([2, 2, 2, 1, 3, 1, 2, 1, 4, 2, 2, 1, 3, 1, 1],
                RepresentationType.GRAPH_SEQUENCE)
    G.to_adjacency_list()
    groups = get_components(G)

    print_sorted_components(G, groups)
    G.to_adjacency_matrix()
    GraphPlotter.plot_graph(G, False, False, groups)
예제 #13
0
    def run(self) -> None:
        self.console.print("[bold]Hello, user!")

        G = DirectedGraph()
        groups = None

        main_choice = ''

        try:
            while main_choice != 'q':
                self.newline()
                self.print_options()
                self.newline()

                main_choice = input("What would you like to do? ")

                if main_choice == 'q':
                    exit_program()

                elif main_choice == '1':
                    try:
                        groups = None
                        n_nodes = int(input("Number of nodes: "))
                        prob = float(input("Probability (0-1): "))
                        w_min = int(input("Lowest possible weight: "))
                        w_max = int(input("Highest possible weight: "))
                        result = get_directed_graph_with_probability(
                            num_of_nodes=n_nodes,
                            probability=prob,
                            lowest_weight=w_min,
                            highest_weight=w_max)

                        G.load_data(result,
                                    RepresentationType.ADJACENCY_MATRIX)
                        self.console.print(
                            "[bold green]Success:[/bold green] Graph generated."
                        )
                    except:
                        self.err("Something went wrong")
                    # GraphPlotter.plot_graph(G, draw_wages=True, draw_arrows=True)

                elif main_choice == '2':
                    groups = None
                    n_nodes = int(input("Number of nodes: "))
                    prob = float(input("Probability (0-1): "))
                    w_min = int(input("Lowest possible weight: "))
                    w_max = int(input("Highest possible weight: "))
                    try:
                        G = get_connected_digraph(num_of_nodes=n_nodes,
                                                  probability=prob,
                                                  lowest_weight=w_min,
                                                  highest_weight=w_max)
                        self.console.print(
                            "[bold green]Success:[/bold green] Graph generated."
                        )
                    except RuntimeError as e:
                        self.err(str(e))
                    except:
                        self.err("Couldn't crate graph")

                    # GraphPlotter.plot_graph(G, draw_wages=True, draw_arrows=True)

                elif main_choice == '3':
                    if not G.repr:
                        self.err("Graph not created. Generate it first")
                        continue
                    groups = kosaraju(G)
                    self.console.print(
                        "[bold green]Success:[/bold green] Groups successfully found."
                    )
                    GraphPlotter.plot_graph(G,
                                            draw_wages=False,
                                            draw_arrows=True,
                                            nodes_color_modes=groups)

                elif main_choice == '4':
                    if not G.repr:
                        self.err("Graph not created. Generate it first")
                        continue
                    start = int(input("Start from: "))
                    try:
                        print(f"\nShortest paths from node [{start}]:")
                        self.print_bellman_form_paths(bellman_ford(G, start))
                    except Exception as e:
                        self.err(str(e))

                elif main_choice == '5':
                    if not G.repr:
                        self.err("Graph not created. Generate it first")
                        continue
                    G.to_adjacency_matrix()
                    try:
                        dist_matrix = johnson_algorithm(G)
                        print("Distance matrix:")
                        self.print_dist_matrix(dist_matrix)
                    except Exception as e:
                        self.err(str(e))

                elif main_choice == 'p':
                    if not G.repr:
                        self.err("Graph not created. Generate it first")
                        continue
                    print_graph(G)

                elif main_choice == 't':
                    if not G.repr:
                        self.err("Graph not created. Generate it first")
                        continue
                    choice = self.select_plotting_type()
                    if choice == '1':
                        GraphPlotter.plot_graph(G,
                                                draw_wages=True,
                                                draw_arrows=True,
                                                nodes_color_modes=groups)
                    elif choice == '2':
                        GraphPlotter.plot_graph(G,
                                                draw_wages=True,
                                                draw_arrows=True,
                                                nodes_color_modes=None)

                    elif choice == '3':
                        GraphPlotter.plot_graph(G,
                                                draw_wages=False,
                                                draw_arrows=True,
                                                nodes_color_modes=groups)

                    elif choice == '4':
                        GraphPlotter.plot_graph(G,
                                                draw_wages=False,
                                                draw_arrows=True,
                                                nodes_color_modes=None)

                else:
                    self.err("Unrecognized option")
                    self.newline()
        except:
            self.err("Critical error. Exiting..")
            self.newline()
import os, sys

currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)

from utils.Graph import Graph, RepresentationType
from utils.graph_generators import gen_random_conn_graph_weighted
from utils.graph_plotter import GraphPlotter
from algorithms.dijkstra import find_shortest_path

if __name__ == "__main__":
    random_conn_graph = gen_random_conn_graph_weighted(10)

    G = Graph()
    G.load_data(
        data=random_conn_graph,
        representation_type=RepresentationType.ADJACENCY_MATRIX_WITH_WEIGHTS)
    print(G)
    GraphPlotter.plot_graph(G, draw_wages=True)

    s = 1
    print(50 * '-')
    print("START: s = {0}".format(s))

    print(
        find_shortest_path(G=G.get_weighted_adjacency_list(),
                           start=s,
                           verbose=True))

    # print(G.get_weighted_adjacency_list())
예제 #15
0
from random import random
from utils.graph_plotter import GraphPlotter
from utils.Graph import Graph, RepresentationType
from utils.graph_generators import get_graph_from_points
from algorithms.salesman import closest_neighbour, simulated_annealing

if __name__ == '__main__':
    G = Graph()
    points = list()

    for _ in range(100):
        points.append((2000 * random() - 1000, 2000 * random() - 1000))

    G.load_data(get_graph_from_points(points),
                RepresentationType.ADJACENCY_MATRIX)

    path = closest_neighbour(G)
    GraphPlotter.plot_points(points, path)
    path = simulated_annealing(G, 500, 100, 3)
    GraphPlotter.plot_points(points, path)

    points = np.loadtxt(os.path.dirname(__file__) + '/inputs/input59.dat',
                        usecols=(0, 1))
    G.load_data(get_graph_from_points(points),
                RepresentationType.ADJACENCY_MATRIX)

    path = closest_neighbour(G)
    GraphPlotter.plot_points(points, path)
    path = simulated_annealing(G, 500, 100, 10)
    GraphPlotter.plot_points(points, path)
예제 #16
0
import os, sys

currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)

from utils.DirectedGraph import DirectedGraph, RepresentationType
from utils.graph_plotter import GraphPlotter
from utils.graph_generators import get_directed_graph_with_probability
from algorithms.kosaraju import kosaraju

if __name__ == '__main__':
    G = DirectedGraph()

    G.load_data(get_directed_graph_with_probability(10, 0.2, 1, 1),
                RepresentationType.ADJACENCY_MATRIX)
    groups = kosaraju(G)
    GraphPlotter.plot_graph(G,
                            draw_wages=False,
                            draw_arrows=True,
                            nodes_color_modes=groups)