Skip to content

Instantly share code, notes, and snippets.

@globalpolicy
Last active June 5, 2025 19:39
Show Gist options
  • Select an option

  • Save globalpolicy/72b243259209ec5495aca3329214da63 to your computer and use it in GitHub Desktop.

Select an option

Save globalpolicy/72b243259209ec5495aca3329214da63 to your computer and use it in GitHub Desktop.
Water allocation problem via MILP
from pulp import *
problem=LpProblem(name='WaterAllocationProblem',sense=const.LpMaximize)
# for f(x) i.e. user1's reward function
user1_rewards_dict={
0:0,
1:5,
2:8,
3:9,
4:8,
5:5,
6:0
}
b1is=[]
user1_allocation=LpAffineExpression()
user1_reward=LpAffineExpression()
user1_constraint=LpAffineExpression()
for key in user1_rewards_dict:
b1i=LpVariable(name=f'b1{key}',cat=const.LpBinary)
user1_allocation+=key*b1i
user1_reward+=user1_rewards_dict[key]*b1i
user1_constraint+=b1i
b1is.append(b1i)
problem+=user1_constraint==1
# for g(x) i.e. user2's reward function
user2_rewards_dict={
0:0,
1:5,
2:6,
3:3,
4:-4,
5:-15,
6:-30
}
b2is=[]
user2_allocation=LpAffineExpression()
user2_reward=LpAffineExpression()
user2_constraint=LpAffineExpression()
for key in user2_rewards_dict:
b2i=LpVariable(name=f'b2{key}',cat=const.LpBinary)
user2_allocation+=key*b2i
user2_reward+=user2_rewards_dict[key]*b2i
user2_constraint+=b2i
b2is.append(b2i)
problem+=user2_constraint==1
# for h(x) i.e. user3's reward function
user3_rewards_dict={
0:0,
1:7,
2:12,
3:15,
4:16,
5:15,
6:12
}
b3is=[]
user3_allocation=LpAffineExpression()
user3_reward=LpAffineExpression()
user3_constraint=LpAffineExpression()
for key in user3_rewards_dict:
b3i=LpVariable(name=f'b3{key}',cat=const.LpBinary)
user3_allocation+=key*b3i
user3_reward+=user3_rewards_dict[key]*b3i
user3_constraint+=b3i
b3is.append(b3i)
problem+=user3_constraint==1
problem+=user1_allocation+user2_allocation+user3_allocation==6
problem+=user1_reward+user2_reward+user3_reward
problem.solve()
print([value(b1i) for b1i in b1is])
print([value(b2i) for b2i in b2is])
print([value(b3i) for b3i in b3is])
print(value(problem.objective))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment