Beispiel #1
0
def solve(items,weights,values,capacities,tlimit):
    # Create solver
    solver = pywrapknapsack_solver.KnapsackSolver(pywrapknapsack_solver.KnapsackSolver.KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER,'problem')
    
    # Initialize solver
    solver.Init(values, weights, capacities)

    # Set time limit if given
    if tlimit > 0:
        solver.set_time_limit(tlimit)
    
    # Solve problem
    computed_value= solver.Solve()

    # Collect solution data
    packed_items= [x for x in range(0, len(weights[0]))
                if solver.BestSolutionContains(x)]
    packed_weights=[]
    for i in range(len(weights)):
        packed_weights.append(0)
    for i in packed_items:
        for j in range(len(weights)):
            packed_weights[j]+=weights[j][i]

    return computed_value,packed_items,packed_weights
Beispiel #2
0
    def get_ortool_value(self):
        # Create the solver.
        data = self.get_ortool_model()
        solver = pywrapknapsack_solver.KnapsackSolver(
            pywrapknapsack_solver.KnapsackSolver.
            KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, 'KnapsackExample')

        values = data['values']
        weights = data['weights']
        capacities = data['capacity']

        solver.Init(values, weights, capacities)
        computed_value = solver.Solve()

        packed_items = []
        packed_weights = []
        total_weight = 0
        print('Total value =', computed_value)
        for i in range(len(values)):
            if solver.BestSolutionContains(i):
                packed_items.append(i)
                packed_weights.append(weights[0][i])
                total_weight += weights[0][i]
        print('Total weight:', total_weight)
        print('Packed items:', packed_items)
        print('Packed_weights:', packed_weights)
        return computed_value
Beispiel #3
0
def solve_multi_knapsack(profits, weights, capacities, verbose=True):
    """Wrapper function for solving a multi-dimensional knapsack problem. Uses
    Google's ORtools library.

    Args:
        profits: list of N integers, indicating the profits associated with each
            of N items.
        weights: multi-dimensional list (M * N) of integers, where M is the
            number of weight dimensions to consider and N is the number of items
        capacities: list of M integers, indicating the max capacity along each of
            M dimensions
    Returns:
        list of integer indices of the chosen items
    """
    solver = pywrapknapsack_solver.KnapsackSolver(
        pywrapknapsack_solver.KnapsackSolver.
        # KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, 'MKP_Solve')
        KNAPSACK_MULTIDIMENSION_CBC_MIP_SOLVER,
        'MKP_Solve')
    solver.Init(profits, weights, capacities)
    computed_profit = solver.Solve()
    if verbose:
        print(('optimal profit = ' + str(computed_profit)))

    idx_chosen_items = []
    for i in range(len(profits)):
        if solver.BestSolutionContains(i):
            idx_chosen_items.append(i)
    return idx_chosen_items
    def get_allocation_rule(self, bids, weight_limit):
        """
        Selects highest bids using dynamic programming optimisation technique
        """
        values = []
        weights = [[]]
        capacities = [weight_limit]

        for bid in bids:
            values.append(bid.value)
            # appends to the inner list
            weights[0].append(bid.weight)

        # https://developers.google.com/optimization/bin/knapsack
        # https://developers.google.com/optimization/reference/python/algorithms/pywrapknapsack_solver
        solver = pywrapknapsack_solver.KnapsackSolver(
            pywrapknapsack_solver.KnapsackSolver.
            KNAPSACK_DYNAMIC_PROGRAMMING_SOLVER, 'KnapsackBids')

        solver.Init(values, weights, capacities)
        computed_value = solver.Solve()

        # # returns list of optimally packed indices
        selected_indices = [
            x for x in range(0, len(weights[0]))
            if solver.BestSolutionContains(x)
        ]

        # the indices are converted into their corresponding bids then returned
        return [bids[i] for i in selected_indices]
Beispiel #5
0
def main():
    # Create the solver.
    solver = pywrapknapsack_solver.KnapsackSolver(
        pywrapknapsack_solver.KnapsackSolver.
        KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, 'KnapsackExample')

    values = [
        360, 83, 59, 130, 431, 67, 230, 52, 93, 125, 670, 892, 600, 38, 48,
        147, 78, 256, 63, 17, 120, 164, 432, 35, 92, 110, 22, 42, 50, 323, 514,
        28, 87, 73, 78, 15, 26, 78, 210, 36, 85, 189, 274, 43, 33, 10, 19, 389,
        276, 312
    ]
    weights = [[
        7, 0, 30, 22, 80, 94, 11, 81, 70, 64, 59, 18, 0, 36, 3, 8, 15, 42, 9,
        0, 42, 47, 52, 32, 26, 48, 55, 6, 29, 84, 2, 4, 18, 56, 7, 29, 93, 44,
        71, 3, 86, 66, 31, 65, 0, 79, 20, 65, 52, 13
    ]]
    capacities = [850]

    solver.Init(values, weights, capacities)
    computed_value = solver.Solve()

    packed_items = []
    packed_weights = []
    total_weight = 0
    print('Total value =', computed_value)
    for i in range(len(values)):
        if solver.BestSolutionContains(i):
            packed_items.append(i)
            packed_weights.append(weights[0][i])
            total_weight += weights[0][i]
    print('Total weight:', total_weight)
    print('Packed items:', packed_items)
    print('Packed_weights:', packed_weights)
Beispiel #6
0
def Knapsackpackingsolution_single():
    data = {}
    data['Value'] = [
        360, 83, 59, 130, 431, 67, 230, 52, 93, 125, 670, 892, 600, 38, 48,
        147, 78, 256, 63, 17, 120, 164, 432, 35, 92, 110, 22, 42, 50, 323, 514,
        28, 87, 73, 78, 15, 26, 78, 210, 36, 85, 189, 274, 43, 33, 10, 19, 389,
        276, 312
    ]
    #a sequence
    data['Volumn'] = [[
        7, 0, 30, 22, 80, 94, 11, 81, 70, 64, 59, 18, 0, 36, 3, 8, 15, 42, 9,
        0, 42, 47, 52, 32, 26, 48, 55, 6, 29, 84, 2, 4, 18, 56, 7, 29, 93, 44,
        71, 3, 86, 66, 31, 65, 0, 79, 20, 65, 52, 13
    ]]
    data['limitation'] = [850]
    solver = pywrapknapsack_solver.KnapsackSolver(
        pywrapknapsack_solver.KnapsackSolver.
        KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, 'kNAPSACK')

    solver.Init(data['Value'], data['Volumn'], data['limitation'])
    computed_value = solver.Solve()
    packed_items = []
    packed_weights = []
    total_weight = 0
    print('Total value =', computed_value)
    for i in range(len(data['Value'])):
        if solver.BestSolutionContains(i):
            packed_items.append(i)
            packed_weights.append(data['Volumn'][0][i])
            total_weight += data['Volumn'][0][i]
    print('Total weight:', total_weight)
    print('Packed items:', packed_items)
    print('Packed_weights:', packed_weights)
Beispiel #7
0
def recommand():
    # Create the solver.
    solver = pywrapknapsack_solver.KnapsackSolver(
        pywrapknapsack_solver.KnapsackSolver.
        KNAPSACK_MULTIDIMENSION_SCIP_MIP_SOLVER, 'KnapsackExample')

    valid_players = DataPipeline().valid_players

    values = valid_players['SCR'].tolist()
    weights = [valid_players['RATING'].tolist()]
    capacities = [430]

    solver.Init(values, weights, capacities)
    computed_value = solver.Solve()

    packed_items = []
    packed_weights = []
    total_weight = 0
    # print('Total value =', computed_value)
    for i in range(len(values)):
        if solver.BestSolutionContains(i):
            packed_items.append(i)
            packed_weights.append(weights[0][i])
            total_weight += weights[0][i]
    print('Total weight:', total_weight)

    print('Total_Scores:', valid_players.iloc[packed_items]['SCR'].sum())
    print(valid_players.iloc[packed_items])
Beispiel #8
0
def ortoolopt(weights, values, cap):
    weights = [list(weights)]
    values = list(values)
    solver = pywrapknapsack_solver.KnapsackSolver(
        pywrapknapsack_solver.KnapsackSolver.KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER,
        "KnapsackExample",
    )
    solver.Init(values, weights, [cap])
    computed_value = solver.Solve()
    packed_items = []
    packed_weights = []
    total_weight = 0
#     print("Total value =", computed_value)
    for i in range(len(values)):
        if solver.BestSolutionContains(i):
            packed_items.append(i)
            packed_weights.append(weights[0][i])
            total_weight += weights[0][i]
    #     print("Total weight:", total_weight)
    #     print("Packed items:", packed_items)
    #     print("Packed_weights:", packed_weights)
    selection = np.zeros(len(values))
    selection[packed_items] = 1
    return (
        selection.astype(int),
        total_weight,
        len(values),
        cap - total_weight,
    )
Beispiel #9
0
def main():
    # Create the solver.
    # [START solver]
    solver = pywrapknapsack_solver.KnapsackSolver(
        pywrapknapsack_solver.KnapsackSolver.
        KNAPSACK_DYNAMIC_PROGRAMMING_SOLVER, "test")
    # [END solver]

    # [START data]
    weights = [[
        565, 406, 194, 130, 435, 367, 230, 315, 393, 125, 670, 892, 600, 293,
        712, 147, 421, 255
    ]]
    capacities = [850]
    values = weights[0]
    # [END data]

    # [START solve]
    solver.Init(values, weights, capacities)
    computed_value = solver.Solve()
    # [END solve]

    # [START print_solution]
    packed_items = [
        x for x in range(0, len(weights[0])) if solver.BestSolutionContains(x)
    ]
    packed_weights = [weights[0][i] for i in packed_items]

    print("Packed items: ", packed_items)
    print("Packed weights: ", packed_weights)
    print("Total weight (same as total value): ", computed_value)
Beispiel #10
0
def exo1():
    # Create the solver.
    solver = pywrapknapsack_solver.KnapsackSolver(
        pywrapknapsack_solver.KnapsackSolver.
        KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, 'KnapsackExample')

    values = [40, 30, 25, 25, 10]
    weights = [[10, 4, 3, 2, 1]]
    capacities = [15]

    solver.Init(values, weights, capacities)
    computed_value = solver.Solve()

    packed_items = []
    packed_weights = []
    total_weight = 0
    print('Total value =', computed_value)
    for i in range(len(values)):
        if solver.BestSolutionContains(i):
            packed_items.append(i)
            packed_weights.append(weights[0][i])
            total_weight += weights[0][i]
    print('Total weight:', total_weight)
    print('Packed items:', packed_items)
    print('Packed_weights:', packed_weights)
Beispiel #11
0
def main():
    # Create the solver.
    solver = pywrapknapsack_solver.KnapsackSolver(
        pywrapknapsack_solver.KnapsackSolver.
        KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, 'KnapsackExample')

    weights = [[100, 26, 9, 11, 51, 231, 24, 79, 161]]
    values = [12, 10, 3, 4, 14, 45, 9, 4, 20]
    capacities = [500]

    solver.Init(values, weights, capacities)
    computed_value = solver.Solve()

    packed_items = []
    packed_weights = []
    total_weight = 0
    print('Total value =', computed_value)
    for i in range(len(values)):
        if solver.BestSolutionContains(i):
            packed_items.append(i)
            packed_weights.append(weights[0][i])
            total_weight += weights[0][i]
    print('Total weight:', total_weight)
    print('Packed items:', packed_items)
    print('Packed_weights:', packed_weights)
Beispiel #12
0
def solve_it_google(items,capacity):

    values = [item.value for item in items]
    print(values)
    weights = [[item.weight for item in items]]
    print(weights)
    #capacity

    solver = pywrapknapsack_solver.KnapsackSolver(
        pywrapknapsack_solver.
            KnapsackSolver.
            KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, 'KnapsackExample')

    solver.Init(values, weights, [capacity])

    value = solver.Solve()
    taken_items = []
    packed_weights = []
    total_weight = 0
    taken = [0] * len(items)
    print('Total value =', value)
    for i in range(len(values)):
        if solver.BestSolutionContains(i):
            taken_items.append(i)
            packed_weights.append(weights[0][i])
            total_weight += weights[0][i]
    for ind in taken_items:

        taken[items[ind].index] = 1

    output_data = str(int(value)) + ' ' + str(0) + '\n'
    output_data += ' '.join(map(str, taken))
    return output_data
Beispiel #13
0
def main():
    # Create the solver.
    # [START solver]
    solver = pywrapknapsack_solver.KnapsackSolver(
        pywrapknapsack_solver.KnapsackSolver.
        KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, 'KnapsackExample')
    # [END solver]

    # [START data]
    values = [
        360, 83, 59, 130, 431, 67, 230, 52, 93, 125, 670, 892, 600, 38, 48,
        147, 78, 256, 63, 17, 120, 164, 432, 35, 92, 110, 22, 42, 50, 323, 514,
        28, 87, 73, 78, 15, 26, 78, 210, 36, 85, 189, 274, 43, 33, 10, 19, 389,
        276, 312
    ]
    weights = [[
        7, 0, 30, 22, 80, 94, 11, 81, 70, 64, 59, 18, 0, 36, 3, 8, 15, 42, 9,
        0, 42, 47, 52, 32, 26, 48, 55, 6, 29, 84, 2, 4, 18, 56, 7, 29, 93, 44,
        71, 3, 86, 66, 31, 65, 0, 79, 20, 65, 52, 13
    ]]
    capacities = [850]
    # [END data]

    # [START solve]
    solver.Init(values, weights, capacities)
    computed_profit = solver.Solve()
    # [END solve]

    # [START print_solution]
    print('optimal profit =', computed_profit)
Beispiel #14
0
def main():
    # Create the solver.
    solver = pywrapknapsack_solver.KnapsackSolver(
        pywrapknapsack_solver.KnapsackSolver.
        KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, 'test')
    values = [
        360, 83, 59, 130, 431, 67, 230, 52, 93, 125, 670, 892, 600, 38, 48,
        147, 78, 256, 63, 17, 120, 164, 432, 35, 92, 110, 22, 42, 50, 323, 514,
        28, 87, 73, 78, 15, 26, 78, 210, 36, 85, 189, 274, 43, 33, 10, 19, 389,
        276, 312
    ]

    weights = [[
        7, 0, 30, 22, 80, 94, 11, 81, 70, 64, 59, 18, 0, 36, 3, 8, 15, 42, 9,
        0, 42, 47, 52, 32, 26, 48, 55, 6, 29, 84, 2, 4, 18, 56, 7, 29, 93, 44,
        71, 3, 86, 66, 31, 65, 0, 79, 20, 65, 52, 13
    ]]

    capacities = [850]

    solver.Init(values, weights, capacities)
    computed_value = solver.Solve()

    packed_items = [
        x for x in range(0, len(weights[0])) if solver.BestSolutionContains(x)
    ]
    packed_weights = [weights[0][i] for i in packed_items]
    total_weight = sum(packed_weights)
    print("Packed items: ", packed_items)
    print("Packed weights: ", packed_weights)
    print("Total value: ", computed_value)
    print("Total weight: ", total_weight)
Beispiel #15
0
    def run_algorithm(self):

        from ortools.algorithms import pywrapknapsack_solver
        solver = pywrapknapsack_solver.KnapsackSolver(\
                    pywrapknapsack_solver.KnapsackSolver.KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER,\
                    'solver')
        # Scaling Items
        epsilon = 0.3
        print("Scaling items for {0}-epsilon approximation".format(epsilon))
        # Randomly select a group of non-conflict items to do knapsack on:
        print("Randomly select a group of items that have no conflicts")
        items = self.compatible_items_random(self.N)

        # Preprocess Data
        print("Preprocess Data")
        weights = list()
        values = list()
        capacities = list()
        map_indicies_to_item = dict()

        item_costs = list()
        item_weights = list()

        max_profit = max([x.profit for x in self.items])
        scaling_factor = self.N / epsilon / max_profit
        print("Scaling factor: {0}".format(scaling_factor))

        for i, item in enumerate(items):
            values.append(min(item.profit * scaling_factor, 0))
            item_weights.append(item.weight)
            item_costs.append(item.cost)
            map_indicies_to_item[i] = item

        # Form Knapsack problem
        print("Creating Knapsack problem")

        weights.append(item_costs)
        capacities.append(self.M)

        weights.append(item_weights)
        capacities.append(self.P)

        # Initialize Solver
        solver.Init(values, weights, capacities)

        # Solve
        print("Solving...")
        picked = solver.Solve()
        print("Done!")

        # Retrieve solution
        print("Converting solution to items...")

        packed_items_indices = [x for x in range(0, len(weights[0])) if solver.BestSolutionContains(x)]
        packed_items = [map_indicies_to_item[x] for x in packed_items_indices]

        print("Success!")
        return packed_items
Beispiel #16
0
def knapsack_multidimensional_cbc(request,
                                  test_mode=False,
                                  muestreo=0,
                                  repeticiones=1):
    solver = pywrapknapsack_solver.KnapsackSolver(
        pywrapknapsack_solver.KnapsackSolver.
        KNAPSACK_MULTIDIMENSION_CBC_MIP_SOLVER, "Multi-dimensional solver")
    return knapsack_multidimensional(request, solver, test_mode, muestreo,
                                     repeticiones)
def solve_knapsack(method, objects_id, weights, every_trailer_axis,
                   objects_price):
    flat_list = []  # список весов
    for j in range(1):
        flat_list.append([])
        for i in range(len(weights)):
            flat_list[j].append(weights[i])  # Заполнение списка весов
    capacities = [every_trailer_axis]  # Максимальная вместимость
    if method == "Weight":  # Если оптимизация по весу
        leng = len(flat_list[0])
        values = []
        for i in range(leng):
            values.append(
                0)  # ценность не учитывается. У всех объектов одинаковая
        # Иннициализация алгоритма решения для загрузки максимальным весом
        solver = pywrapknapsack_solver.KnapsackSolver(
            pywrapknapsack_solver.KnapsackSolver.
            KNAPSACK_DYNAMIC_PROGRAMMING_SOLVER, 'test')
        solver.Init(values, flat_list, capacities)
        computed_value = solver.Solve()
        packed_items = [
            x for x in range(0, len(flat_list[0]))
            if solver.BestSolutionContains(x)
        ]
        packed_items_ids = []
        for i in packed_items:  # Получение id упакованных вещей
            packed_items_ids.append(objects_id[i])
    elif method == "Value":  # Если оптимизация по ценности
        # Инициализация алгоритма решения для загрузки максимально ценными вещами
        solver_2 = pywrapknapsack_solver.KnapsackSolver(
            pywrapknapsack_solver.KnapsackSolver.
            KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, 'test')
        capacities = [every_trailer_axis]
        solver_2.Init(objects_price, flat_list, capacities)
        packed_items = [
            x for x in range(0, len(flat_list[0]))
            if solver_2.BestSolutionContains(x)
        ]
        packed_items_ids = []  # Идентификаторы получаемых вещей
        for i in packed_items:  # Получение id упакованных вещей
            packed_items_ids.append(objects_id[i])
    return packed_items_ids
Beispiel #18
0
def knapsack_solver(self, capacity, values, weights):
    solver = pywrapknapsack_solver.KnapsackSolver(pywrapknapsack_solver.KnapsackSolver.KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER,'test')

    solver.Init(values, weights, capacity)
    computed_value = solver.Solve()
    packed_items = [x for x in range(0, len(weights[0]))
                    if solver.BestSolutionContains(x)]
    packed_weights = [weights[0][i] for i in packed_items]
    total_weight = sum(packed_weights)

    return packed_items, packed_weights, computed_value, total_weight
Beispiel #19
0
 def init_model(self, **kwargs):
     solver = pywrapknapsack_solver.KnapsackSolver(
         pywrapknapsack_solver.KnapsackSolver.
         KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, 'KnapsackExample')
     list_item = self.knapsack_model.list_items
     max_capacity = self.knapsack_model.max_capacity
     values = [item.value for item in list_item]
     weights = [[item.weight for item in list_item]]
     capacities = [max_capacity]
     solver.Init(values, weights, capacities)
     self.model = solver
Beispiel #20
0
def knapsolve(values,weights,budget):
    assert values.dtype==weights.dtype==int
    values = list(values)
    weights = [list(weights)]
    solver = pywrapknapsack_solver.KnapsackSolver(pywrapknapsack_solver.KnapsackSolver.KNAPSACK_DYNAMIC_PROGRAMMING_SOLVER,'globalpfrl')
    solver.Init(values,weights,[budget])
    total_importances = solver.Solve()
    best_items = [x for x in range(len(weights[0]))
                  if solver.BestSolutionContains(x)]
    best_values = [weights[0][i] for i in best_items]
    return best_items
Beispiel #21
0
def knapsack(capacity, sizes, values):

    sizes = [sizes]
    solver = pywrapknapsack_solver.KnapsackSolver(pywrapknapsack_solver.KnapsackSolver.KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, 'KnapsackExample')
    solver.Init(values, sizes, [capacity])
    computed_value = solver.Solve()

    items = []
    for i in range(len(values)):
        if solver.BestSolutionContains(i):
            items.append(i)

    return computed_value, items
def knapsack(items: List[Item], capacity: float) -> Tuple[float, List[int]]:
    """
    Knapsack Solver using OR-Tools
    https://developers.google.com/optimization/bin/knapsack#complete-programs

    Addition Details can be found here:
    https://google.github.io/or-tools/
    http://google.github.io/or-tools/python/ortools/algorithms/pywrapknapsack_solver.html
    """
    values = []
    weights = []
    capacities = []
    for item in items:
        values.append(item.value)

    temp_weights = []
    for item in items:
        temp_weights.append(item.weight)
    weights.append(temp_weights)

    capacities = [capacity]

    # print(f"Values: {values}")
    # print(f"Weights: {weights}")

    # http://google.github.io/or-tools/python/ortools/algorithms/pywrapknapsack_solver.html
    # Dynamic Programming Solver is also available through `KNAPSACK_DYNAMIC_PROGRAMMING_SOLVER`
    solver = pywrapknapsack_solver.KnapsackSolver(
        pywrapknapsack_solver.KnapsackSolver.
        KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, 'Knapsack')

    # You can also set a time limit here to make sure that the solution is terminated if it takes too long
    # Use `set_time_limit()` method for this

    solver.Init(values, weights, capacities)
    computed_value = solver.Solve()

    taken: List[int] = []

    for i in range(len(values)):
        if solver.BestSolutionContains(i):
            taken.append(1)
        else:
            taken.append(0)

    # print('Taken:', taken)
    # print('Total weight:', computed_value)

    return computed_value, taken
def solve_it(input_data):

    from ortools.algorithms import pywrapknapsack_solver

    # parse the input
    lines = input_data.split('\n')

    firstLine = lines[0].split()
    item_count = int(firstLine[0])
    capacity = int(firstLine[1])

    values = []
    weights = []
    capacities = [capacity]
    for i in range(1, item_count + 1):
        line = lines[i]
        parts = line.split()
        _value = int(parts[0])
        _weight = int(parts[1])
        values.append(_value)
        weights.append(_weight)
    weights = [weights]

    # Instanciate the solver
    str_solver = 'NItems_{}_Capacity_{}'.format(item_count, capacity)
    solver = pywrapknapsack_solver.KnapsackSolver(
        pywrapknapsack_solver.KnapsackSolver.
        KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, str_solver)

    solver.Init(values, weights, capacities)
    value = solver.Solve()

    packed_items = []
    packed_weights = []
    actual_cap = 0

    print('Total value =', value)
    for i in range(len(values)):
        if solver.BestSolutionContains(i):
            packed_items.append(i)
            packed_weights.append(weights[0][i])
            actual_cap += weights[0][i]

    # prepare the solution in the specified output format
    output_data = "Obj-value: {}, total weight: {} ({})\n".format(
        value, actual_cap, actual_cap / capacity)
    #output_data = str(value) + ' ' + str(0) + '\n'
    output_data += ' '.join(map(str, packed_items))
    return output_data
Beispiel #24
0
def solve_by_ortools(item_count, capacity, items):
    solver = pywrapknapsack_solver.KnapsackSolver(
        pywrapknapsack_solver.KnapsackSolver.
        KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, 'Solver')
    profits = []
    weights = []
    for item in items:
        profits.append(item.value)
        weights.append(item.weight)
    solver.set_time_limit(10)
    solver.Init(profits, [weights], [capacity])
    profit = solver.Solve()
    result_str = '{} 0\n'.format(profit)
    result_str += ' '.join(
        [str(int(solver.BestSolutionContains(i))) for i in range(item_count)])
    return result_str
Beispiel #25
0
def _solveKnapsack(values, weights, capacity):
    solver = pywrapknapsack_solver.KnapsackSolver(
        pywrapknapsack_solver.KnapsackSolver.
        KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, '')

    capacities = [capacity]

    solver.Init(values, [weights], capacities)
    computed_value = solver.Solve()

    packed_items = []
    packed_weights = []
    total_weight = 0
    for i in range(len(values)):
        if solver.BestSolutionContains(i):
            packed_items.append(i)
    return packed_items
Beispiel #26
0
def solve_it(input_data):
    # Modify this code to run your optimization algorithm

    # parse the input
    lines = input_data.split('\n')

    firstLine = lines[0].split()
    item_count = int(firstLine[0])
    capacity = int(firstLine[1])

    solver = pywrapknapsack_solver.KnapsackSolver(
        pywrapknapsack_solver.KnapsackSolver.
        KNAPSACK_DYNAMIC_PROGRAMMING_SOLVER, 'test')

    values = []
    weights = []
    for line_idx in range(1, item_count + 1):
        line = lines[line_idx]
        parts = line.split()
        #val we
        values.append(int(parts[0]))
        weights.append(int(parts[1]))

    weights = [weights]

    solver.Init(values, weights, [capacity])

    solver.Solve()

    packed_items = [
        x for x in range(0, len(weights[0])) if solver.BestSolutionContains(x)
    ]

    bool_items = []
    for i in range(item_count):
        if i in packed_items:
            bool_items.append(1)
        else:
            bool_items.append(0)

    packed_weights = [weights[0][i] for i in packed_items]

    # prepare the solution in the specified output format
    output_data = str(sum(packed_weights)) + ' ' + str(1) + '\n'
    output_data += ' '.join(map(str, bool_items))
    return output_data
Beispiel #27
0
def dySolve(knapsack, maxWeight):

    solver = pywrapknapsack_solver.KnapsackSolver(
        pywrapknapsack_solver.KnapsackSolver.
        KNAPSACK_DYNAMIC_PROGRAMMING_SOLVER, 'test')

    values = []
    weights = [[]]
    capacities = [maxWeight]

    for item in knapsack.items:
        values.append(item.value)
        weights[0].append(item.weight)

    solver.Init(values, weights, capacities)
    computed_value = solver.Solve()

    return computed_value
Beispiel #28
0
def knapsack_ortools(values, weights, items, capacity):
    """0-1 Knapsack problem solver"""
    osolver = pywrapknapsack_solver.KnapsackSolver(
        pywrapknapsack_solver.KnapsackSolver.KNAPSACK_DYNAMIC_PROGRAMMING_SOLVER,
        "SummarizationSegmentSelection")

    scale = 1000
    values = np.array(values)
    weights = np.array(weights)
    values = (values * scale).astype(np.int)
    weights = (weights).astype(np.int)
    capacity = capacity

    osolver.Init(values.tolist(), [weights.tolist()], [capacity])
    osolver.Solve()
    packed_items = [x for x in range(0, len(weights))
                    if osolver.BestSolutionContains(x)]

    return packed_items
Beispiel #29
0
    def post(self):
        data = request.get_json()
        profits = data['profits']
        weights = data['weights']
        capacities = data['capacities']

        solver = pywrapknapsack_solver.KnapsackSolver(
            pywrapknapsack_solver.KnapsackSolver.KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, "bpp_solver")
        solver.Init(profits, weights, capacities)
        computed_value = solver.Solve()
        packed_items = [x for x in range(0, len(weights[0])) if solver.BestSolutionContains(x)]
        packed_weights = [weights[0][i] for i in packed_items]
        total_weight = sum(packed_weights)

        return jsonify({
            'packed_items': packed_items,
            'total_profit': computed_value,
            'total_weight': total_weight
        })
Beispiel #30
0
def main():
    solver = pywrapknapsack_solver.KnapsackSolver(
        pywrapknapsack_solver.KnapsackSolver.
        KNAPSACK_DYNAMIC_PROGRAMMING_SOLVER, 'test')

    values = [16, 19, 23, 28]
    weights = [[2, 3, 4, 5]]
    capacity = [7]
    solver.Init(values, weights, capacity)
    computed_value = solver.Solve()

    packed_items = [
        x for x in range(0, len(weights[0])) if solver.BestSolutionContains(x)
    ]
    packed_weights = [weights[0][i] for i in packed_items]

    print("持ち出しアイテム:", packed_items)
    print("持ち出すアイテムの重さ: ", packed_weights)
    print("持ち出しアイテムの合計の価値:", computed_value)