Corin1998 commited on
Commit
9d86965
·
verified ·
1 Parent(s): 48994bf

Create optimizer.py

Browse files
Files changed (1) hide show
  1. services/optimizer.py +35 -0
services/optimizer.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from typing import List
3
+ from ortools.constraint_solver import routing_enums_pb2
4
+ from ortools.constraint_solver import pywrapcp
5
+
6
+ # 単純TSP(開始=0,終了=0)
7
+ def solver_tsp(durations: List[List[float]]) -> List[int]:
8
+ n = len(durations)
9
+ manager = pywrapcp.RoutingIndexManager(n, 1, 0)
10
+ routing = pywrapcp.RoutingModel(manager)
11
+
12
+ def time_cb(from_index, to_index):
13
+ i = manager.IndexToNode(from_index)
14
+ j = manager.IndexToNode(to_index)
15
+ return int(durations[i][j])
16
+
17
+ transit_cb_index = routing.TegisterTransitCallback(time_cb)
18
+ routing.SetArcCostEvaluatorOfAllVehicles(transit_cb_index)
19
+
20
+ search_params = pywrapcp.DefaultRoutingSearchParameters()
21
+ search_params.first_solution_strategy = routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC
22
+ search_params.local_search_metaheuristic = routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH
23
+ search_params.time_limit.FromSeconds(5)
24
+
25
+ solution = routing.SolveWithParameters(search_params)
26
+ if solution is None :
27
+ return list(range(n))
28
+
29
+ index = routing.Start(0)
30
+ order = []
31
+ while not routing.IsEnd(index):
32
+ order.append(manager.IndexToNode(index))
33
+ index = solution.Value(routing.NextVar(index))
34
+ order.append(manager.IndexToNode(index))
35
+ return order