def test_some_sequences(self): data = np.load('dp_solver.npy', allow_pickle=True)[:100] problem = load_problem(T=6) for i in data: d = i[0] seq = i[1:].astype(int) solver = solve_sequence(problem=problem, seq=seq) self.assertTrue(solver.result.feasible) self.assertAlmostEqual(d, solver.result.distance)
def repopulate_queue(Q, solutions): rand = np.random.permutation(len(solutions)) old_pop = [solutions[rand[i]] for i in range(10)] problem = load_problem() for s in old_pop: if s: solver = solve_sequence(problem, s[-1]) if solver.feasible: res = sliding_window(2, 1, solver, return_first=False, restrict_available=False) if res.feasible: Q.append(res)
def test_distance(self): # np random seed = 10 data = np.load('level_order_solver.npy', allow_pickle=True) problem = load_problem(T=6) truncation_args = {'limit': 1000, 'method': "distance"} optimizer = HeuristicTreeSolver(problem=problem, max_height=10, truncation_args=truncation_args) results = optimizer.solve() for i, j in enumerate(data): d = j[0] seq = j[1:][0] solver = results['solvers'][i] self.assertTrue(solver.result.feasible) self.assertAlmostEqual(d, solver.result.distance) self.assertEqual(seq, solver.result.seq)
res = solve(1, problem) else: S = transition(pop) if S is not None: res = solve(n_ships, problem, sampling=S) else: break results.append(res.opt.data["solver"][0]) _X, _F, pop = res.X, res.F[0], res.pop # prepare for the next iteration I, X, F = pop.get("feasible", "X", "F") if verbose: print(n_ships, _F, _X.tolist(), res.algorithm.n_gen, len(I)) if len(I) == 0: break pop = pop[I[:, 0]] n_ships += 1 return {"solvers": results} if __name__ == "__main__": np.random.seed(1) res = solve_level_ga(load_problem(6), verbose=True) print(res['solvers'])
Q, bd, bs = self._next(current=current, Q=Q, depth=depth) if bd <= best_distance: best_distance = bd best_solver = bs self.current_best = bs # ------------------------------------------------------------------------------------ result = {} result["results"] = self.best_distances result["solvers"] = self.best_solvers result["selected"] = selected return result if __name__ == "__main__": # Create sequence solver object P = load_problem(T=6) truncation_args = {'limit': 1000, 'method': "distance"} SeqSolver = HeuristicTreeSolver(problem=P, max_depth=10, truncation_args=truncation_args) # truncation_args = {'limit': 1000, 'method': "decomposition", 'w': 0.306} start = time.time() result = SeqSolver.solve() end = time.time() print(f"{end - start}")
def sliding_window(insert, remove, S, return_first=False, restrict_available=False): """ :param insert: Number of ships to expand by :param remove: Number of ships to remove :param S: DPSolver instance :return: """ success = 0 fail = 0 best_dist = 1e10 best_solver = None # Algorithm works on gaps between ships not ships themselves, hence remove += 1 remove += 1 problem = load_problem() if isinstance(S, list): _solver = solve_sequence(problem=problem, seq=S) elif isinstance(S, DPSolver): _solver = copy.copy(S) _solver.get_result() else: print("FAIL SLIDING WINDOW") return sequence, schedule, distances = _solver.seq[:], _solver.result.schedule[:], [min(s.distances) for s in _solver.states] for i in range(len(sequence) - remove): window = sequence[i+1:i + remove] start = min(S.states[i].schedule) # Minimum feasible available time from the ship states before the window end = problem.get_ship(window[-1]).times[1] # Maximum available time for the ship in WA following the window avail = problem.ships_in_working_area(start=start, end=end) avail = set(avail) - set(sequence[:i+1] + sequence[i + remove:]) if 0 in avail: avail.remove(0) sub_seq = list(itertools.permutations(avail, insert)) if restrict_available: sub_seq = [s for s in sub_seq if len(set(sequence[i + 1:i + remove]) - set(s)) == 0] candidates = [] # Candidate solutions for full evaluation for ship in sub_seq: solver = copy.copy(_solver) solver.get_result() # Update the solver to the correct transition point while len(solver.seq) != len(sequence[:i+1]): solver.pop_state() # Evaluate the transition with the new permutation skip = False for l, j in enumerate(ship): b = solver.next(j) new_sched = solver.states[-1].schedule new_dist = min(solver.states[-1].distances) if len(solver.states[-1].distances) else 1e6 # If the new schedule has less possible transitions or the new minimum distance is greate if len(new_sched) < len(schedule) or new_dist > distances[i+1+l]: skip = True break if skip: # Move to next permutation fail += 1 continue else: # Update candidate permutations based on distance success += 1 heapq.heappush(candidates, (min(solver.states[-1].distances), copy.copy(solver))) # Evaluate all candidate solutions for c in range(len(candidates)): d, sver = heapq.heappop(candidates) for s in sequence[i + remove:]: sver.next(s) result = sver.get_result() if result.feasible: if return_first: return sver if result.distance < best_dist: best_dist = result.distance best_solver = sver return best_solver
intermediate_results = sorted(intermediate_results, key=lambda x: x.dist) solvers[length] = intermediate_results[0] solver = solvers[length] if __name__ == "__main__": from dsp.Problem import Problem, load_problem from dsp.Solver import DPSolver from dsp.HTSolver import HeuristicTreeSolver import time import pprint as pp # Create sequence solver object P = load_problem() truncation_args = {'limit': 100, 'method': "distance"} # ALPHA = set(P.ships_in_working_area()) # SeqSolver = SequenceSolver(problem=P, height_limit=5) # result = SeqSolver.sequence_search(available=ALPHA, truncation_args=truncation_args) sol = solve_sequence(problem=P, seq=[0, 32, 30, 63, 12, 0]) # sol2 = solve_sequence(problem=P, seq=[0, 32, 30, 63, 12, 0]) sol2 = solve_sequence(problem=P, seq=[0, 8, 5, 30, 63, 12, 0]) # start = time.time() # result = old_sliding_window(1, 1, sol) # end = time.time() # print(f"Old Result 2 Time: {end-start}") # print(f"Old Result: {result}") # # start = time.time()