def solver(method: str, kp: Knapsack, items: List[Item], additionalArgs=None): if method == 'Heuristic': # Execute the heuristic method simple_heuristic = SimpleHeuristic(additionalArgs) return ConstructiveSolution(kp, items, simple_heuristic).getValue() elif method == 'SimulatedAnnealing': # Execute the Simulated Annealing metaheuristic return solveMetaheuristic(method, kp, items, additionalArgs) elif method == 'RandomSearch': # Execute the Random Search metaheuristic return solveMetaheuristic(method, kp, items, additionalArgs) elif method == 'HyperheuristicNaive': # Execute the Hyper-heuristic naive model hh = HyperheuristicNaive(additionalArgs) return ConstructiveSolution(kp, items, hh).getValue() elif method == 'Hyperheuristic': # Execute the Hyper-heuristic based on LSTM model return hyperheuristicSolver(kp, items, additionalArgs).getValue() elif method == 'Backtracking': # Execute the recursive backtracking method return kpBacktracking(kp.getCapacity(), items).getValue() elif method == 'DP': # Execute the dynamic programming method return kpDP(kp.getCapacity(), items).getValue() elif method == 'MILP': # Execute the mixed integer linear programming method return kpMILP(kp.getCapacity(), items).getValue() elif method in list(heuristicComparison.keys()): # Given the heuristic as method parameter, execute the constructive heuristic method simple_heuristic = SimpleHeuristic(method) return ConstructiveSolution(kp, items, simple_heuristic).getValue() else: return 0
def kpDP(W: int, items: List[Item]): n = len(items) A = np.zeros((n + 1, W + 1)) # Calculate the DP in the bottom-up fashion way for idx, item in enumerate(items, start=1): w, p = item.getWeight(), item.getProfit() for Wi in range(W + 1): if Wi == 0: continue elif idx == 0: A[idx, Wi] = p if w <= Wi else 0 elif w <= Wi: A[idx, Wi] = max(A[idx - 1, Wi], A[idx - 1, Wi - w] + p) else: A[idx, Wi] = A[idx - 1, Wi] # Find the items that get the best solution kp, idx = Knapsack(W), n while idx >= 1 and kp.getCapacity() > 0: if A[idx - 1, kp.getCapacity()] != A[idx, kp.getCapacity()]: kp.pack(items[idx - 1]) idx -= 1 return kp
def solveMetaheuristic(method: str, kp: Knapsack, items: List[Item], saveMetaheuristic=False, fileName='traindata.csv', overwrite=False): W = kp.getCapacity() items_copy = items.copy() # Execute the chosen method if method == 'SimulatedAnnealing': kp, mh = SimulatedAnnealing(kp, items) elif method == 'RandomSearch': kp, mh = RandomSearch(kp, items) else: return 0 # Save the sequence of heuristics if saveMetaheuristic: mh.saveMetaheuristic(W, items_copy, fileName, overwrite) return kp.getValue()