File size: 5,875 Bytes
acdc230
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
"""
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()