简体   繁体   中英

PuLP: Stuck with objective function definition

I am a first time user of PuLP and I the last time I did linear programming, Python did not exist. I can solve this problem with LibreOffice's Solve extension (which does LP)

But I need to do it in code.

I want to optimise a stock picking problem. We need to pick a certain quantity of screws, say 98. Screws are packed in packs of 25 and 100. I name those pack sizes '25' and '100'. The cost of the pick needs to be minimised. There is a cost to pick each pack, and there is a cost to the excess quantity picked. The constraint is that the quantity picked >= target_qty

For example, if the cost to each unit of excess was 0.1 and the cost to pick the '25' pack was 1 and the cost to pack the '100' pack is 1.1., the cost of picking is 1 x 100 pack is

(100 - 98) *.1 + 0*1 + 1*1.1

This is cheaper than picking 4*'25' pack.

Assuming that there are dicts pack_cost{} and pack_capacity{} which both have the key pack_name, eg pack_cost = {'25':1,'100':1.1} and therefore list_of_pack_names = ['25','100']

I try this:

lp_prob = pulp.LpProblem('PackSizes', pulp.LpMinimize)
packs_used = pulp.LpVariable.dicts("Packs",list_of_pack_names,lowBound=0,cat="Integer")
pack_cost = [pack_costs[pack_name]*packs_used[pack_name] for pack_name in list_of_pack_names]
excess_cost = cost_per_unit * ( sum([pack_sizes[pack_name]*packs_used[pack_name] for pack_name in list_of_pack_names])- original_qty)

lp_prob += pulp.lpSum(pack_cost) + pulp.lpSum(excess_cost)  #objective function

# and constraint: total picked >= needed
lp_prob +=   pulp.lpSum(sum([pack_sizes[pack_name]*packs_used[pack_name] for pack_name in list_of_pack_names]) >= target_qty)

Results:

 print("Status:",pulp.LpStatus[lp_prob.status])

shows Optimal

lp_prob.objective is 10*Packs_10 + 15*Packs_15 + 30*Packs_30 - 16.5

but the solution is 0 of each pack size

You may check your problem with

print(lp_prob)

You do not add any essential constraint that prevents all vars from becoming zero. Probably, you misprinted in the constraint statement. This constraint makes the problem not trivial (check brackets):

lp_prob += pulp.lpSum(sum([pack_sizes[pack_name]*packs_used[pack_name] for pack_name in list_of_pack_names])) >= target_qty

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM