""" Like multiple_noise.py, but unlike all the other scripts this script will probably not work inside blender. """ import os import json from dataclasses import dataclass import math from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from ortools.constraint_solver import routing_enums_pb2 from ortools.constraint_solver import pywrapcp import argparse @dataclass class BlenderCam: name: str location: tuple def main(): parser = argparse.ArgumentParser( prog='tsp_solver.py', description='Solves travelling salesman problem for the blender cameras', ) parser.add_argument('input_dir') parser.add_argument('output_file') parser.add_argument('-p', '--plot', action='store_true') args = parser.parse_args() data = create_data_model(args.input_dir) # Create the routing index manager. manager = pywrapcp.RoutingIndexManager( len(data["distance_matrix"]), data["num_vehicles"], data["depot"] ) # Create Routing Model. routing = pywrapcp.RoutingModel(manager) def distance_callback(from_index, to_index): """Returns the distance between the two nodes.""" # Convert from routing variable Index to distance matrix NodeIndex. from_node = manager.IndexToNode(from_index) to_node = manager.IndexToNode(to_index) return data["distance_matrix"][from_node][to_node] transit_callback_index = routing.RegisterTransitCallback(distance_callback) # Define cost of each arc. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index) # Setting first solution heuristic. search_parameters = pywrapcp.DefaultRoutingSearchParameters() search_parameters.first_solution_strategy = ( routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC ) # Solve the problem. solution = routing.SolveWithParameters(search_parameters) # Print solution on console. if solution: print_solution(manager, routing, solution) export_solution(data["blender_cams"], args.output_file, manager, routing, solution) if args.plot: plot_cams(data["blender_cams"], manager, routing, solution) def create_data_model(dir): data = {} data["blender_cams"] = load_cams(dir) data["distance_matrix"] = compute_distance_matrix(data["blender_cams"]) data["num_vehicles"] = 1 data["depot"] = 0 return data def compute_distance_matrix(blender_cams: list[BlenderCam]): distances = {} for from_counter, from_node in enumerate(blender_cams): distances[from_counter] = {} from_loc = blender_cams[from_counter].location for to_counter, to_node in enumerate(blender_cams): if from_counter == to_counter or to_counter == 0: distances[from_counter][to_counter] = 0 else: to_loc = blender_cams[to_counter].location dist = math.hypot( (from_loc[0] - to_loc[0]), (from_loc[1] - to_loc[1]), (from_loc[2] - to_loc[2]) ) * 1000 # round to nearest mm instead of nearest m # Euclidean distance distances[from_counter][to_counter] = int(dist) return distances def load_cams(dir): cam_fnames = os.listdir(dir) cam_fnames.sort() blender_cams = [] for name in cam_fnames: path = os.path.join(dir, name) with open(path) as fp: cam_data = json.load(fp) blender_cams.append(BlenderCam(cam_data["name"], cam_data["loc"])) return blender_cams def print_solution(manager, routing, solution): """Prints solution on console.""" print(f"Objective: {solution.ObjectiveValue()} miles") index = routing.Start(0) plan_output = "Route for vehicle 0:\n" route_distance = 0 while not routing.IsEnd(index): plan_output += f" {manager.IndexToNode(index)} ->" previous_index = index index = solution.Value(routing.NextVar(index)) route_distance += routing.GetArcCostForVehicle( previous_index, index, 0) plan_output += f" {manager.IndexToNode(index)}\n" plan_output += f"Route distance: {route_distance}miles\n" print(plan_output) def export_solution( blender_cams, output_file, manager, routing, solution ): with open(output_file, "w") as f: index = routing.Start(0) while not routing.IsEnd(index): cam = blender_cams[manager.IndexToNode(index)] f.write(cam.name + "\n") index = solution.Value(routing.NextVar(index)) def plot_cams( blender_cams: list[BlenderCam], manager, routing, solution ): xs = [cam.location[0] for cam in blender_cams] ys = [cam.location[1] for cam in blender_cams] zs = [cam.location[2] for cam in blender_cams] # Walk the route in visitation order route_indices = [] index = routing.Start(0) while not routing.IsEnd(index): route_indices.append(manager.IndexToNode(index)) index = solution.Value(routing.NextVar(index)) # skip the final node (return to depot) # route_indices.append(manager.IndexToNode(index)) route_xs = [xs[i] for i in route_indices] route_ys = [ys[i] for i in route_indices] route_zs = [zs[i] for i in route_indices] fig = plt.figure() ax: Axes3D = fig.add_subplot(projection='3d') ax.scatter(xs, ys, zs) # type: ignore[arg-type] # type: ignore[arg-type] ax.plot(route_xs, route_ys, route_zs, color='red') ax.set_xlabel("X (m)") ax.set_ylabel("Y (m)") ax.set_zlabel("Z (m)") # Optional: annotate visit order for order, i in enumerate(route_indices): ax.text(xs[i], ys[i], zs[i], str(order)) plt.show() if __name__ == "__main__": main()