def raw_path_costs(cost_instance, path, edge_instance, heights=None):
    """
    Compute raw angles, edge costs, pylon heights and normal costs
    (without weighting)
    Arguments:
        List or array of path coordinates
    """
    path_costs = np.array([cost_instance[:, p[0], p[1]] for p in path])
    # raw angle costs
    ang_costs = CostUtils.compute_raw_angles(path)
    # raw edge costs
    if edge_instance is None:
        edge_instance = cost_instance
    edge_costs = CostUtils.compute_edge_costs(path, edge_instance)
    # pylon heights
    if heights is not None:
        heights = np.expand_dims(heights, 1)
    else:
        heights = np.zeros((len(edge_costs), 1))
    # concatenate
    all_costs = np.concatenate(
        (
            np.expand_dims(ang_costs, 1), path_costs,
            np.expand_dims(edge_costs, 1), heights
        ), 1
    )
    # names = self.cost_classes + ["edge_costs", "heigths"]
    # assert all_costs.shape[1] == len(names)
    return all_costs
def logging(ID, graph, path, path_costs, cfg, time_pipeline, comp_path=None):
    if comp_path is None:
        max_eucl = 0
        mean_eucl = 0
    else:
        # compute path distances and multiply with resolution to get meters
        max_eucl = (KspUtils.path_distance(path, comp_path, mode="eucl_max") *
                    cfg.scale * 10)
        mean_eucl = (
            KspUtils.path_distance(path, comp_path, mode="eucl_mean") *
            cfg.scale * 10)
    # SAVE timing test
    angle_cost = round(np.sum(CostUtils.compute_angle_costs(path)), 2)
    n_categories = len(cfg.class_weights)
    path_costs = np.asarray(path_costs)
    summed_costs = np.around(np.sum(path_costs[:, -n_categories:], axis=0), 2)
    weighted_sum = round(np.dot(summed_costs, cfg.class_weights), 2)
    n_pixels = np.sum(instance_corr > 0)

    # csv_header = ["ID", "instance", "resolution", "graph", "number pixels"
    # "space edges", "overall time",
    # "time vertex adding", "time edge adding",  "time shortest path",
    # "angle cost", "category costs", "sum of costs"]
    logs = [
        ID, INST, SCALE_PARAM * 10, n_pixels, graphtype, graph.n_nodes,
        graph.n_edges, time_pipeline, graph.time_logs["add_nodes"],
        graph.time_logs["add_all_edges"], graph.time_logs["shortest_path"],
        cfg.angle_weight, angle_cost, summed_costs, weighted_sum, mean_eucl,
        max_eucl
    ]
    with open(cfg.csv_times, 'a+', newline='') as write_obj:
        # Create a writer object from csv module
        csv_writer = writer(write_obj)
        # Add contents of list as last row in the csv file
        csv_writer.writerow(logs)
    def set_corridor(self,
                     dist_surface,
                     start_inds,
                     dest_inds,
                     sample_func="mean",
                     sample_method="simple",
                     factor_or_n_edges=1):
        # set new corridor
        corridor = (dist_surface > 0).astype(int)

        self.factor = factor_or_n_edges
        self.cost_rest = self.cost_instance * (self.hard_constraints >
                                               0).astype(int) * corridor
        # downsample
        tic = time.time()
        if self.factor > 1:
            self.cost_rest = CostUtils.downsample(self.cost_rest,
                                                  self.factor,
                                                  mode=sample_method,
                                                  func=sample_func)

        self.time_logs["downsample"] = round(time.time() - tic, 3)

        # repeat because edge artifacts
        self.cost_rest = self.cost_rest * (self.hard_constraints >
                                           0).astype(int) * corridor

        # add start and end TODO ugly
        self.cost_rest[:, dest_inds[0],
                       dest_inds[1]] = self.cost_instance[:, dest_inds[0],
                                                          dest_inds[1]]
        self.cost_rest[:, start_inds[0],
                       start_inds[1]] = self.cost_instance[:, start_inds[0],
                                                           start_inds[1]]
Exemple #4
0
    def set_corridor(
        self, corridor, start_inds, dest_inds, sample_func="mean",
        sample_method="simple", factor_or_n_edges=1
    ):  # yapf: disable
        # assert factor_or_n_edges == 1, "pipeline not implemented yet"
        corridor = (corridor > 0).astype(int) * (self.hard_constraints >
                                                 0).astype(int)
        inf_corr = np.absolute(1 - corridor).astype(float)
        inf_corr[inf_corr > 0] = np.inf

        self.factor = factor_or_n_edges
        self.cost_rest = self.cost_instance + inf_corr
        # downsample
        tic = time.time()
        if self.factor > 1:
            self.cost_rest = CostUtils.inf_downsample(
                self.cost_rest, self.factor
            )

        self.time_logs["downsample"] = round(time.time() - tic, 3)

        # repeat because edge artifacts
        self.cost_rest = self.cost_rest + inf_corr

        # add start and end TODO ugly
        self.cost_rest[:, dest_inds[0], dest_inds[1]
                       ] = self.cost_instance[:, dest_inds[0], dest_inds[1]]
        self.cost_rest[:, start_inds[0], start_inds[1]
                       ] = self.cost_instance[:, start_inds[0], start_inds[1]]

        self.start_inds = start_inds
        self.dest_inds = dest_inds
Exemple #5
0
    def get_shortest_path(self, source, dest):
        """
        Compute shortest path and convert from line graph representation to
        coordinates
        """
        vertices_path = GeneralGraph.get_shortest_path(self, source, dest)
        out_path = []
        for v in vertices_path[1:-1]:
            start_node = int(v) // self.n_neighbors
            shift_ind = int(v) % self.n_neighbors
            start_pos = [start_node // self.y_len, start_node % self.y_len]
            out_path.append(start_pos)

        # append last on
        if len(out_path) > 0:
            out_path.append(list(np.array(start_pos) + self.shifts[shift_ind]))

        # compute costs: angle costs
        ang_costs = CostUtils.compute_angle_costs(out_path, self.max_angle_lg)
        out_costs = list()
        for k, (i, j) in enumerate(out_path):
            out_costs.append(
                [ang_costs[k]] + self.cost_instance[:, i, j].tolist()
            )
        # for i in range(len(vertices_path) - 1):
        #     edge = self.graph.edge(vertices_path[i], vertices_path[i + 1])
        #     out_costs.append([c[edge] for c in self.cost_props])

        weighted_sum = np.dot(
            self.cost_weights, np.sum(np.array(out_costs), axis=0)
        )
        return out_path, out_costs, weighted_sum
Exemple #6
0
 def transform_path(self, path):
     path_costs = np.array(
         [self.cost_instance[:, p[0], p[1]] for p in path]
     )
     # include angle costs
     ang_costs = CostUtils.compute_angle_costs(path, self.angle_norm_factor)
     # prevent that inf * 0 if zero edge weight
     edge_costs = 0
     if self.edge_weight != 0:
         edge_costs = CostUtils.compute_edge_costs(path, self.edge_inst)
     # print("unweighted edge costs", np.sum(edge_costs))
     path_costs = np.concatenate(
         (np.swapaxes(np.array([ang_costs]), 1, 0), path_costs), axis=1
     )
     cost_sum = np.dot(
         self.cost_weights, np.sum(np.array(path_costs), axis=0)
     ) + np.sum(edge_costs) * self.edge_weight
     # cost_sum = np.dot(
     #     self.class_weights, np.sum(np.array(path_costs), axis=0)
     # )  # scalar: weighted sum of the summed class costs
     return np.asarray(path
                       ).tolist(), path_costs.tolist(), cost_sum.tolist()
Exemple #7
0
        ID = f"{graph_names[g]}_{SCALE_PARAM}_{INST}_{angle_weight}"
        OUT_PATH = OUT_PATH_orig + ID

        # DEFINE GRAPH AND ALGORITHM
        graph = GRAPH_TYPE(instance, instance_corr, verbose=cfg.VERBOSE)
        tic = time.time()

        # PROCESS
        path, path_costs, cost_sum = graph.single_sp(**vars(cfg))

        time_pipeline = round(time.time() - tic, 3)
        print("FINISHED :", graph)
        print("----------------------------")

        # SAVE timing test
        angle_cost = round(np.sum(CostUtils.compute_angle_costs(path)), 3)
        n_categories = len(cfg.class_weights)
        path_costs = np.asarray(path_costs)
        summed_costs = np.around(np.sum(path_costs[:, -n_categories:], axis=0),
                                 3)
        weighted_sum = round(np.dot(summed_costs, cfg.class_weights), 3)
        n_pixels = np.sum(instance_corr > 0)

        # csv_header = ["ID", "instance", "resolution", "graph", "number pixels"
        # "space edges", "overall time",
        # "time vertex adding", "time edge adding",  "time shortest path",
        # "angle cost", "category costs", "sum of costs"]
        logs = [
            ID, INST, SCALE_PARAM * 10, n_pixels, graphtype, graph.n_nodes,
            graph.n_edges, time_pipeline, graph.time_logs["add_nodes"],
            graph.time_logs["add_all_edges"], graph.time_logs["shortest_path"],