Exemplo n.º 1
0
    def generate(adjacency_type, graph: Graph, thread):
        """ Generates the file that will be used to visualize the graph. """

        file_output = ''
        output_filename = join(
            OUTPUT_FILES_DIRECTORY,
            rf"{datetime.now().strftime(date_format)}_{graph.graph_representation_type}_{len(graph.vertices)}_"
            rf"{graph.graph_type.replace(' ', '_')}.txt")

        if adjacency_type == "matrix":
            if hasattr(graph, 'mode'):
                if graph.mode == 'normal':
                    for i in range(len(graph.edges)):
                        if thread and thread.isStopped():
                            graph.reset_graph()
                            sys.exit(0)

                        for j in range(len(graph.edges)):
                            if graph.edges[i][j] == 1:
                                file_output += '1'
                            else:
                                file_output += '0'
                        file_output += '\n'
                else:
                    encoder = RunLengthEncoder()
                    for row in graph.edges:
                        if thread and thread.isStopped():
                            graph.reset_graph()
                            sys.exit(0)

                        row = ''.join([str(x) for x in row])

                        file_output += encoder.encode(row) + '\n'
            else:
                raise Exception("Graph without mode found.")

        else:
            for vertex, edges in graph.edges.items():
                if thread and thread.isStopped():
                    graph.reset_graph()
                    sys.exit(0)

                file_output += f"{vertex}:"
                if len(edges) > 0:
                    for node in graph.edges[vertex]:
                        file_output += f"{node},"

                    file_output = file_output[:-1]
                file_output += "\n"

        with open(output_filename, "w") as f:
            f.write(file_output)

        del file_output