def read(self): C = self.file.readline() print("Number of test cases is C:", C) lines = self.file.readlines() items_num_flag = True knapsack = Knapsack(0, 0) template_counter = 0 for line in lines: if line[0] == '\n': continue if len((line.rstrip()).split()) == 1 and items_num_flag: items_num_flag = False if knapsack.S != 0: self.knapsacks.append(knapsack) del knapsack knapsack = Knapsack(0, 0) knapsack.N = int(line.rstrip()) continue if len((line.rstrip()).split()) == 1 and not items_num_flag: items_num_flag = True knapsack.S = int(line.rstrip()) continue # Initialize knapsack items line.rstrip() weight, value = line.split(' ') item = Item(int(weight), int(value)) knapsack.items.append(item) self.knapsacks.append(knapsack)
def test_knapsack_empty(self): bag = () size = 50 ks = Knapsack(bag, size) result = ks.solve() self.assertEqual((), result)
def head(self, triangles): LIMIT = 180 knapsack = Knapsack(triangles, LIMIT) head = knapsack.main() for h in head: triangles.remove(h) head = self.sortHead(head) return [head, triangles]
def read_input(): print("Enter items knapsack volume and items number") volume, items_number = map(int, input().split()) costs = [] weights = [] print("Enter item weight and item cost") for i in range(0, items_number): item_weight, item_cost = map(int, input().split()) costs.append(item_cost) weights.append(item_weight) return Knapsack(volume, costs, weights), items_number
def rest(self, triangles): remainig = [] while True: ks = Knapsack(triangles, 180) seq = ks.main() for s in seq: triangles.remove(s) remainig.append(seq) if triangles == []: break return remainig
def read(self): C = int(input("Enter the number of test case: ")) # Loop through the test cases for i in range(C): print("Test case: " + str(i + 1)) N = int(input("Enter the number of items: ")) S = int(input("Enter the size of the knapsack: ")) print("Enter the item and its value in pairs: ") knapsack = Knapsack(N, S) item = Item(0, 0) for n in range(N): weight, value = input("Pair" + str(n + 1) + ":").split() item = Item(weight, value) knapsack.items.append(item) self.knapsacks.append(knapsack)
def optimize_values(data_frame, capacity, label): data_frame = data_frame.drop_duplicates(subset='Keyword') cost = data_frame.daily_cost_average.copy(deep=True) cost[cost == 0] = minimum / 10 values = (data_frame.daily_impressions_average + data_frame.daily_clicks_average) * (1 / cost) opt = Knapsack(items_names=data_frame.Keyword.to_list(), values=values.to_list(), capacity=capacity, weights=data_frame.daily_cost_average.tolist(), solve_type=5, name='Branch_n_bound_%s' % label) opt.get_results(print_it=True) df = data_frame[data_frame.Keyword.isin(opt.packed_items)] return df
def test_knapsack_values(self): bag = ( (10, 60), (20, 100), (30, 195), (40, 120), (50, 120), (5, 120), (60, 120), (10, 50), (10, 200), (20, 120), ) size = 50 ks = Knapsack(bag, size) result = ks.solve() self.assertEqual(((30, 195), (5, 120), (10, 200)), result)
def buildKnapsacks(commandSets): """ The buildKnapsacks function takes a 2d array of sets of commands to execute and runs through the array interpreting the commands. Args: commandSets A list of the sets of commands to execute for the problem. The builder first goes through the commands and splits them into spice and knapsack commands, it then makes them more easily interpreted, and finally it iterates through each set of commands and carries out their instructions. """ spiceCommands = [] knapsackCommands = [] commentCount = 0 spiceCount = 0 knapsackCount = 0 commandSet = [] spices = [] knapsacks = [] for commandSet in commandSets: for command in commandSet: if command[0] == '--': continue elif command[0] == 'spice': spiceCommands.append( ['spice', command[3][:-1], float(command[6][:-1]), float(command[9][:-1])]) elif command[0] == 'knapsack': knapsackCommands.append(['knapsack', float(command[3][:-1])]) print("Spice commands:", len(spiceCommands)) print("Knapsack commands:", len(knapsackCommands), '\n') for command in spiceCommands: if command[0] == 'spice': spices.append(Spice(command[1], command[2], command[3])) for command in knapsackCommands: if command[0] == 'knapsack': knapsacks.append(Knapsack(command[1])) spices.sort(key=lambda spice: spice.price, reverse=True) return spices, knapsacks
default='result.json', type=str, help='Set the output filename(json).') args = parser.parse_args() # Check argument by standard output print(args) # Set arguments to variables filename = args.filename crossover_prob = args.crossover_prob mutation_prob = args.mutation_prob popSize = args.population_size generation = args.generation # Dataset read and parsing knapsack = Knapsack(filename) knapsack.reader() gene_size = len(knapsack.dataset) # Generate each GA instance roulette = GeneticAlgorithm(gene_size, popSize, crossover_prob, mutation_prob) tournament = GeneticAlgorithm(gene_size, popSize, crossover_prob, mutation_prob) # Roulette Wheel selection GA Initialization print('Roulette', end=' ') roulette.initialization() roulette.calculateFitness(knapsack) # Tournament selection GA Initialization print('Tournament', end=' ')
from knapsack import Curve, Knapsack if __name__ == '__main__': # initializing solver (Knapsack class) instance with maximum money for all media budget = Knapsack(70874156) # maximal budget for every media maxb = 70 * 10**6 # initializing media as Curve instances # every Curve is some media like TV, OOH, etc. media1 = Curve(397650, 0.5085217, 0.92, 9.168728e-06 / 87.98509) media2 = Curve(1336580, 0.941772, 0.9964167, 7.202334e-07) media3 = Curve(5.509022, 5000, 0.99, 0.0002982394 / 219) media4 = Curve(3191.663, 10000, 0.75, 0.001353697 / 65) media5 = Curve(237349.3, 0.9954354, 0.7, 9.501362e-06 / 12.47645) media6 = Curve(2961.2209, 100, 0.5, 0.003669801 / 87.98509) media7 = Curve(664196.7, 0.662257, 0.92, 1.275716e-06 / 87.98509) # adding media to budget # in second argument we pass minimum and maximum allowed for media budget.add_curve(media1, 10600000, maxb) budget.add_curve(media2, 5700000, maxb) budget.add_curve(media3, 1923077, maxb) budget.add_curve(media4, 8307692, maxb) budget.add_curve(media5, 3246154, maxb) budget.add_curve(media6, 9791667, maxb) budget.add_curve(media7, 15786389, maxb) # call to optimize spends between media # last line represents optimal budget for every media, e.g. first number
def setUp(self): self.weight_available = 7 weight_per_item = [2, 3, 4, 5] value_per_item = [3, 4, 5, 5] self.input_data = ['7', '2 3 4 5', '3 4 5 5'] self.obj = Knapsack(self.weight_available, weight_per_item, value_per_item)
from knapsack import Knapsack from extract_objects import Objects if (__name__ == '__main__'): total_individual = 400 total_chromossomes = 20 total_generation = 800 mutation_rate = 0.1 crossover_rate = 0.9 elite = 20 pack_weight_limit = 400 objects = Objects() knapsack = Knapsack(total_individual, total_chromossomes, total_generation, mutation_rate, crossover_rate, elite, pack_weight_limit, objects) knapsack.start()
def main(): knapsack = Knapsack("./ks_1000.dat") # Hill-climbing best improvement iterations = [ (100, 64), (500, 32), (1_000, 16), (5_000, 8), (10_000, 4), (50_000, 2), (100_000, 1), ] average_score = [0] average_evaluations = [0] for iters, repeats in iterations: print( f"Testing hill-climbing best improvement {repeats} time(s) with {iters} iterations." ) total_score = 0 total_eval = 0 for _ in range(repeats): score, evaluations = hc_best(knapsack, iters) total_score += score total_eval += evaluations average_score.append(total_score / repeats) average_evaluations.append(total_eval / repeats) plt.plot(average_evaluations, average_score, label="Hill-climbing best improvement") # Hill-climbing first improvement iterations = [ (100, 64), (500, 32), (1_000, 16), (5_000, 8), (10_000, 4), (50_000, 2), (100_000, 1), ] average_score = [0] average_evaluations = [0] for iters, repeats in iterations: print( f"Testing hill-climbing first improvement {repeats} time(s) with {iters} iterations." ) total_score = 0 total_eval = 0 for _ in range(repeats): score, evaluations = hc_first(knapsack, iters) total_score += score total_eval += evaluations average_score.append(total_score / repeats) average_evaluations.append(total_eval / repeats) plt.plot(average_evaluations, average_score, label="Hill-climbing first improvement") # print(score, evals) # score, evals = recuit_simule(knapsack) # Evolution iterations = [(100, 50), (500, 10), (1_000, 5), (5_000, 1), (10_000, 1)] average_score = [0] average_evaluations = [0] for iters, repeats in iterations: print(f"Testing evolution {repeats} time(s) with {iters} iterations.") total_score = 0 total_eval = 0 for _ in range(repeats): pop = Population(10, knapsack) evaluations, score = pop.run(iters) total_score += score total_eval += evaluations average_score.append(total_score / repeats) average_evaluations.append(total_eval / repeats) plt.plot(average_evaluations, average_score, label="Evolution mu=10") plt.grid() plt.xlabel("Evaluations") plt.ylabel("Average performance") plt.figlegend() plt.show()
from knapsack import Knapsack import time import sys sys.setrecursionlimit(10000) knapsack = Knapsack() startTime = time.time() result = knapsack.findOptimum(knapsack.itemCount, knapsack.knapCapacity) print(time.strftime("%H:%M:%S", time.gmtime(time.time() - startTime))) print(result)
def test_knapsack(self): # Initial variables naive = 0 dynamic = 0 parallel = 0 bipercube = 0 hypercube2 = 0 hypercube4 = 0 hypercube6 = 0 hypercube8 = 0 # Problems to test problems = [ 'dynamic', 'hypercube2', 'hypercube4', 'hypercube6', 'hypercube8' ] # File out = open("out.csv", 'w') # csv output out.write("Capacidad" + "\t" + "Elementos" + "\t" + "Naive" + "\t" + "Programacion dinamica" + "\t" + "2 procesadores" + "\t" + "4 procesadores" + "\t" + "6 procesadores" + "\t" + "8 procesadores" + "\t" + "Peters and Rudolph" + "\t" + "\n") capacities = [100, 1000] elements = [100, 1000] for capacity in capacities: for element in elements: print print 'Capacity', capacity print 'Elements', element # Times naiveTime = '-' dynamicTime = '-' hypercube2Time = '-' hypercube4Time = '-' hypercube6Time = '-' hypercube8Time = '-' parallelTime = '-' # Variables values = [] weigths = [] # Construct the Knapsack for i in range(element): values.append(random.randint(1, int(element / 2))) weigths.append(random.randint(1, int(element / 2))) knap = Knapsack(capacity, weigths, values) # Resolve # Dynamic if 'dynamic' in problems: start = time.time() dynamic = knap.dynamic() end = time.time() dynamicTime = str(end - start) print "Dynamic time: " + str(end - start) # Naive if 'naive' in problems: start = time.time() naive = knap.naive() end = time.time() naiveTime = str(end - start) print "Naive time: " + str(end - start) # Parallel if 'parallel' in problems: start = time.time() parallel = knap.parallel() end = time.time() parallel = str(end - start) print "Parallel time: " + str(end - start) # Bipercube if 'bipercube' in problems: start = time.time() bipercube = knap.bipercube() end = time.time() print "Bipercube time: " + str(end - start) # Hypercube # 2 Processors if 'hypercube2' in problems: start = time.time() hypercube2 = knap.hypercube(2) end = time.time() hypercube2Time = str(end - start) print "Hypercube 2 time: " + str(end - start) # 4 Processors if 'hypercube4' in problems: start = time.time() hypercube4 = knap.hypercube(4) end = time.time() hypercube4Time = str(end - start) print "Hypercube 4 time: " + str(end - start) # 6 Processors if 'hypercube6' in problems: start = time.time() hypercube6 = knap.hypercube(6) end = time.time() hypercube6Time = str(end - start) print "Hypercube 6 time: " + str(end - start) # 8 Processors if 'hypercube8' in problems: start = time.time() hypercube8 = knap.hypercube(8) end = time.time() hypercube8Time = str(end - start) print "Hypercube 8 time: " + str(end - start) # File out.write( str(capacity) + "\t" + str(element) + "\t" + str(naiveTime) + "\t" + str(dynamicTime) + "\t" + str(hypercube2Time) + "\t" + str(hypercube4Time) + "\t" + str(hypercube6Time) + "\t" + str(hypercube8Time) + "\t" + str(parallelTime) + "\t") out.write("\n")
def __init__(self, knapsacks): self.knapsacks = [Knapsack(knapsack) for knapsack in knapsacks]
def test_knapsack(self): # Problems to test problems = [ 'dynamic', 'bipercube', 'hypercube2', 'hypercube4', 'hypercube6', 'hypercube8' ] naive = 0 dynamic = 0 parallel = 0 bipercube = 0 hypercube2 = 0 hypercube4 = 0 hypercube6 = 0 hypercube8 = 0 # Variables capacity = 100 elementCount = 100 profitsRange = 100 weigthsRange = 100 values = [] weigths = [] # Construct the Knapsack for i in range(elementCount): values.append(random.randint(1, profitsRange)) weigths.append(random.randint(1, weigthsRange)) knap = Knapsack(capacity, weigths, values) # Resolve # Dynamic start = time.time() dynamic = knap.dynamic() end = time.time() print "Dynamic time: " + str(end - start) # Naive if 'naive' in problems: start = time.time() naive = knap.naive() end = time.time() print "Naive time: " + str(end - start) # Parallel if 'parallel' in problems: start = time.time() parallel = knap.parallel() end = time.time() print "Parallel time: " + str(end - start) # Bipercube if 'bipercube' in problems: start = time.time() bipercube = knap.bipercube() end = time.time() print "Bipercube time: " + str(end - start) # Hypercube # 2 Processors if 'hypercube2' in problems: start = time.time() hypercube2 = knap.hypercube(2) end = time.time() print "Hypercube 2 time: " + str(end - start) # 4 Processors if 'hypercube4' in problems: start = time.time() hypercube4 = knap.hypercube(4) end = time.time() print "Hypercube 4 time: " + str(end - start) # 6 Processors if 'hypercube6' in problems: start = time.time() hypercube6 = knap.hypercube(6) end = time.time() print "Hypercube 6 time: " + str(end - start) # 8 Processors if 'hypercube8' in problems: start = time.time() hypercube8 = knap.hypercube(8) end = time.time() print "Hypercube 8 time: " + str(end - start) # Results # Naive if 'naive' in problems: self.assertEqual(naive, dynamic) # Parallel if 'parallel' in problems: self.assertEqual(parallel, dynamic) # Bipercube if 'bipercube' in problems: self.assertEqual(bipercube, dynamic) # 2 Processors if 'hypercube2' in problems: self.assertEqual(hypercube2, dynamic) # 4 Processors if 'hypercube4' in problems: self.assertEqual(hypercube4, dynamic) # 6 Processors if 'hypercube6' in problems: self.assertEqual(hypercube6, dynamic) # 8 Processors if 'hypercube8' in problems: self.assertEqual(hypercube8, dynamic)
@author: josep """ from Pair import Pair from knapsack import Knapsack as Knapsack pair1=Pair(4,1) pair2=Pair(7,7) pair3=Pair(1,22) pair4=Pair(2,23) pair5=Pair(3,6) items=[] items.extend([pair1,pair2,pair3,pair4,pair5]) knapsackObject=Knapsack(14,5,items) #print(knapsackObject.algorithm().fitness) filePath = "input_example.txt" f = open("result.txt", "a") with open(filePath, "r") as file: text = file.read() testCases = text.split("\n\n") start=1 while start <= int(testCases[0]): case = testCases[start].strip().split("\n")
#!/usr/bin/env python3 # coding=utf-8 from knapsack import Knapsack if __name__ == '__main__': weights = [2, 2, 4, 6, 3] max_weight = 9 k = Knapsack(weights, max_weight) k.put(0, 0) print("背包最大重量为: %d" % k.res_weight)