示例#1
0
    def plot_graph_base(self,
                        graph_base: graph_ltpl.data_objects.GraphBase.GraphBase,
                        cost_dep_color: bool = True,
                        plot_edges: bool = True) -> None:
        """
        Plot the major components stored in the graph_base object

        :param graph_base:       reference to the GraphBase object instance holding all graph relevant information
        :param cost_dep_color:   boolean flag, specifying, whether to plot edges with a variable color (depending on
                                 cost) or not (Note: cost dependent plotting is drastically slower)
        :param plot_edges:       boolean flag, specifying, whether the edges should be included in the plot

        """

        # refline
        plt_refline, = plt.plot(graph_base.refline[:, 0],
                                graph_base.refline[:, 1],
                                "k--", linewidth=1.4, label="Refline")

        # track bounds
        # bound1 = graph_base.refline + graph_base.normvec_normalized * graph_base.track_width[:, np.newaxis] / 2
        # bound2 = graph_base.refline - graph_base.normvec_normalized * graph_base.track_width[:, np.newaxis] / 2
        bound1 = graph_base.refline + graph_base.normvec_normalized * np.expand_dims(graph_base.track_width_right, 1)
        bound2 = graph_base.refline - graph_base.normvec_normalized * np.expand_dims(graph_base.track_width_left, 1)

        x = list(bound1[:, 0])
        y = list(bound1[:, 1])
        x.append(None)
        y.append(None)
        x.extend(list(bound2[:, 0]))
        y.extend(list(bound2[:, 1]))
        plt_bounds, = self.__main_ax.plot(x, y, "k-", linewidth=1.4, label="Bounds")

        # norm vecs
        x = []
        y = []
        for i in range(bound1.shape[0]):
            temp = np.vstack((bound1[i], bound2[i]))
            x.extend(temp[:, 0])
            y.extend(temp[:, 1])
            x.append(None)
            y.append(None)
        plt_normals, = plt.plot(x, y, color=TUM_colors['TUM_blue_dark'], linestyle="-", linewidth=0.7, label="Normals")

        # raceline points
        rlpt = graph_base.refline + graph_base.normvec_normalized * graph_base.alpha[:, np.newaxis]
        plt_raceline, = self.__main_ax.plot(rlpt[:, 0], rlpt[:, 1], color=TUM_colors['TUM_blue'], linestyle="-",
                                            linewidth=1.4, label="Raceline")

        # plot state poses
        nodes = graph_base.get_nodes()
        i = 0
        x = []
        y = []
        for node in nodes:
            tph.progressbar.progressbar(i, len(nodes) - 1, prefix="Plotting nodes   ")

            # Try to get node info (if filtered, i.e. online graph, this will fail)
            try:
                node_pos = graph_base.get_node_info(node[0], node[1])[0]
                x.append(node_pos[0])
                y.append(node_pos[1])
            except ValueError:
                pass
            i += 1
        plt_nodes, = self.__main_ax.plot(x, y, "x", color=TUM_colors['TUM_blue'], markersize=3, label="Nodes")

        if plot_edges:
            # plot edges
            edges = graph_base.get_edges()
            i = 0

            if not cost_dep_color:
                x = []
                y = []
                color_spline = TUM_colors['TUM_blue_light']  # (0, 1, 0)

                min_cost = None
                max_cost = None
            else:
                # get maximum and minimum cost in all provided edges
                min_cost = 9999.9
                max_cost = -9999.9
                for edge in edges:
                    try:
                        edge_cost = graph_base.get_edge(edge[0], edge[1], edge[2], edge[3])[2]
                        min_cost = min(min_cost, edge_cost)
                        max_cost = max(max_cost, edge_cost)
                    except ValueError:
                        pass

                color_spline = None
                plt_edges = None

            for edge in edges:
                tph.progressbar.progressbar(i, len(edges) - 1, prefix="Plotting edges   ")

                # Try to get edge (if filtered, i.e. online graph, this will fail)
                try:
                    spline = graph_base.get_edge(edge[0], edge[1], edge[2], edge[3])
                    spline_coords = spline[1][:, 0:2]
                    spline_cost = spline[2]

                    # cost dependent color
                    if cost_dep_color:
                        color_spline = (round(min(1, (spline_cost - min_cost) / (max_cost - min_cost)), 2),
                                        round(max(0, 1 - (spline_cost - min_cost) / (max_cost - min_cost)), 2), 0)
                        self.__main_ax.plot(spline_coords[:, 0], spline_coords[:, 1], "-",
                                            color=color_spline, linewidth=0.7)
                    else:
                        # Faster plot method (but for now, no individual color shading)
                        x.extend(spline_coords[:, 0])
                        x.append(None)
                        y.extend(spline_coords[:, 1])
                        y.append(None)
                except ValueError:
                    pass

                i += 1
                # plt.pause(0.000001) # Live plotting -> caution: slows down drastically!

            plt_edges = None
            if not cost_dep_color:
                plt_edges, = self.__main_ax.plot(x, y, "-", color=color_spline, linewidth=0.7, label="Edges")

        # properties
        leg = self.__main_ax.legend(loc='upper left')
        if plot_edges and not cost_dep_color:
            elements = [plt_refline, plt_bounds, plt_normals, plt_raceline, plt_nodes, plt_edges]
        else:
            elements = [plt_refline, plt_bounds, plt_normals, plt_raceline, plt_nodes]
        elementd = dict()
        # couple legend entry to real line
        for leg_element, orig_element in zip(leg.get_lines(), elements):
            leg_element.set_pickradius(10)  # 5 pts tolerance
            elementd[leg_element] = orig_element

        # line picking
        self.__fig.canvas.mpl_connect('pick_event', lambda event: self.__eh.onpick(event=event,
                                                                                   elementd=elementd))

        # detail information
        node_plot_marker, = self.__main_ax.plot([], [], 'o', color=TUM_colors['TUM_orange'])
        edge_plot_marker, = self.__main_ax.plot([], [], '-', color=TUM_colors['TUM_orange'])
        annotation = self.__main_ax.annotate('', xy=[0, 0], xytext=(0, 0), arrowprops={'arrowstyle': "->"})
        self.__eh.set_graph_markers(node_plot_marker=node_plot_marker,
                                    edge_plot_marker=edge_plot_marker,
                                    annotation=annotation)
        self.__fig.canvas.mpl_connect('motion_notify_event',
                                      lambda event: self.__eh.onhover(event=event,
                                                                      graph_base=graph_base))

        self.__text_display = self.__main_ax.text(0.02, 0.95, "", transform=plt.gcf().transFigure)
        self.__text_display2 = self.__main_ax.text(0.8, 0.9, "", transform=plt.gcf().transFigure)

        if type(self.__time_ax) is not str:
            self.__time_annotation = self.__time_ax.annotate("", xy=(0, 0), xytext=(0.05, 0.90),
                                                             textcoords='figure fraction',
                                                             bbox=dict(boxstyle="round", fc="w"),
                                                             arrowprops=dict(arrowstyle="->"))
def prune_graph(graph_base: graph_ltpl.data_objects.GraphBase.GraphBase,
                closed: bool = True) -> None:
    """
    Prune graph - remove nodes and edges that are not reachable within the cyclic graph.

    :param graph_base:      reference to the GraphBase object instance holding all graph relevant information
    :param closed:          if false, an un-closed track is assumed, i.e. last layer nodes will not be pruned

    :Authors:
        * Tim Stahl <*****@*****.**>

    :Created on:
        28.09.2018

    """

    j = 0
    rmv_cnt_tot = 0
    nodes = graph_base.get_nodes()

    while True:
        rmv_cnt = 0
        for i, node in enumerate(nodes):
            tph.progressbar.progressbar(min(j * len(nodes) + i, len(nodes) * 10 - 2),
                                        len(nodes) * 10 - 1, prefix="Pruning graph    ")

            # if not closed, keep all nodes in start and end-layer
            if not closed and (node[0] == graph_base.num_layers - 1 or node[0] == 0):
                continue

            # get children and parents of node
            _, _, _, children, parents = graph_base.get_node_info(layer=node[0],
                                                                  node_number=node[1],
                                                                  return_child=True,
                                                                  return_parent=True)

            # remove edges (removing nodes may destroy indexing conventions)
            if not children or not parents:
                # if no children or no parents, remove all connecting edges
                if not children:
                    for parent in parents:
                        rmv_cnt += 1
                        graph_base.remove_edge(start_layer=parent[0],
                                               start_node=parent[1],
                                               end_layer=node[0],
                                               end_node=node[1])
                else:
                    for child in children:
                        rmv_cnt += 1
                        graph_base.remove_edge(start_layer=node[0],
                                               start_node=node[1],
                                               end_layer=child[0],
                                               end_node=child[1])

        if rmv_cnt == 0:
            break
        else:
            rmv_cnt_tot += rmv_cnt

        j += 1

    tph.progressbar.progressbar(100, 100, prefix="Pruning graph    ")

    if rmv_cnt_tot > 0:
        print("Removed %d edges, identified as dead ends!" % rmv_cnt_tot)