Skip to content

Commit 1d7952a

Browse files
committed
Type examples/ (coin-or#819)
* initial pass * black + isort * add ignores in pulp.py and pulp/__init__.py * start fixing mypy errors * fix some mypy * mypy passes * move Pattern class definition to be before use
1 parent f1cbfd2 commit 1d7952a

23 files changed

+153
-100
lines changed

examples/BeerDistributionProblem.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
]
3434

3535
# The cost data is made into a dictionary
36-
costs = makeDict([Warehouses, Bars], costs, 0)
36+
costs_dict = makeDict([Warehouses, Bars], costs, 0)
3737

3838
# Creates the 'prob' variable to contain the problem data
3939
prob = LpProblem("Beer Distribution Problem", LpMinimize)
@@ -46,7 +46,7 @@
4646

4747
# The objective function is added to 'prob' first
4848
prob += (
49-
lpSum([vars[w][b] * costs[w][b] for (w, b) in Routes]),
49+
lpSum([vars[w][b] * costs_dict[w][b] for (w, b) in Routes]),
5050
"Sum_of_Transporting_Costs",
5151
)
5252

examples/BeerDistributionProblemCompetitorExtension.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
]
3333

3434
# The cost data is made into a dictionary
35-
costs = makeDict([Warehouses, Bars], costs, 0)
35+
costs_dict = makeDict([Warehouses, Bars], costs, 0)
3636

3737
# Creates the 'prob' variable to contain the problem data
3838
prob = LpProblem("Beer Distribution Problem", LpMinimize)
@@ -45,7 +45,7 @@
4545

4646
# The objective function is added to 'prob' first
4747
prob += (
48-
lpSum([vars[w][b] * costs[w][b] for (w, b) in Routes]),
48+
lpSum([vars[w][b] * costs_dict[w][b] for (w, b) in Routes]),
4949
"Sum_of_Transporting_Costs",
5050
)
5151

examples/BeerDistributionProblemWarehouseExtension.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
]
2626

2727
# The cost data is made into a dictionary
28-
costs = makeDict([Warehouses, Bars], costs, 0)
28+
costs_dict = makeDict([Warehouses, Bars], costs, 0)
2929

3030
# Creates the 'prob' variable to contain the problem data
3131
prob = LpProblem("Beer Distribution Problem", LpMinimize)
@@ -38,7 +38,7 @@
3838

3939
# The objective function is added to 'prob' first
4040
prob += (
41-
lpSum([vars[w][b] * costs[w][b] for (w, b) in Routes]),
41+
lpSum([vars[w][b] * costs_dict[w][b] for (w, b) in Routes]),
4242
"Sum_of_Transporting_Costs",
4343
)
4444

examples/BeerDistributionProblem_resolve.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
]
3535

3636
# The cost data is made into a dictionary
37-
costs = makeDict([Warehouses, Bars], costs, 0)
37+
costs_dict = makeDict([Warehouses, Bars], costs, 0)
3838

3939
# Creates the 'prob' variable to contain the problem data
4040
prob = LpProblem("Beer Distribution Problem", LpMinimize)
@@ -47,7 +47,7 @@
4747

4848
# The objective function is added to 'prob' first
4949
prob += (
50-
lpSum([vars[w][b] * costs[w][b] for (w, b) in Routes]),
50+
lpSum([vars[w][b] * costs_dict[w][b] for (w, b) in Routes]),
5151
"Sum_of_Transporting_Costs",
5252
)
5353

@@ -68,10 +68,10 @@
6868

6969
# The problem data is written to an .lp file
7070
prob.writeLP("BeerDistributionProblem.lp")
71-
for demand in range(500, 601, 10):
71+
for demand_value in range(500, 601, 10):
7272
# reoptimise the problem by increasing demand at bar '1'
7373
# note the constant is stored as the LHS constant not the RHS of the constraint
74-
bar_demand_constraint["1"].constant = -demand
74+
bar_demand_constraint["1"].constant = -demand_value
7575
# or alternatively,
7676
# prob.constraints["Sum_of_Products_into_Bar_1"].constant = - demand
7777

examples/CG.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
Authors: Antony Phillips, Dr Stuart Mitchell 2008
55
"""
66

7+
from typing import Dict, List, Optional, Tuple, Union
8+
79
# Import PuLP modeler functions
810
from pulp import *
911

@@ -18,20 +20,24 @@ class Pattern:
1820
totalRollLength = 20
1921
lenOpts = ["5", "7", "9"]
2022

21-
def __init__(self, name, lengths=None):
23+
def __init__(self, name: str, lengths: List[int]) -> None:
2224
self.name = name
2325
self.lengthsdict = dict(zip(self.lenOpts, lengths))
2426

25-
def __str__(self):
27+
def __str__(self) -> str:
2628
return self.name
2729

28-
def trim(self):
30+
def trim(self) -> int:
2931
return Pattern.totalRollLength - sum(
3032
[int(i) * int(self.lengthsdict[i]) for i in self.lengthsdict]
3133
)
3234

3335

34-
def masterSolve(Patterns, rollData, relax=True):
36+
def masterSolve(
37+
Patterns: List[Pattern],
38+
rollData: Dict[str, List[Union[float, int]]],
39+
relax: bool = True,
40+
) -> Union[Dict[str, float], Tuple[float, Dict[str, int]]]:
3541
# The rollData is made into separate dictionaries
3642
(rollDemand, surplusPrice) = splitDict(rollData)
3743

@@ -85,13 +91,15 @@ def masterSolve(Patterns, rollData, relax=True):
8591
varsdict[v.name] = v.varValue
8692

8793
# The number of rolls of each length in each pattern is printed
88-
for i in Patterns:
89-
print(i, " = %s" % [i.lengthsdict[j] for j in Pattern.lenOpts])
94+
for p in Patterns:
95+
print(p, " = %s" % [p.lengthsdict[j] for j in Pattern.lenOpts])
9096

9197
return value(prob.objective), varsdict
9298

9399

94-
def subSolve(Patterns, duals):
100+
def subSolve(
101+
Patterns: List[Pattern], duals: Dict[str, float]
102+
) -> Tuple[List[Pattern], bool]:
95103
# The variable 'prob' is created
96104
prob = LpProblem("SubProb", LpMinimize)
97105

examples/CGcolumnwise.py

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,11 @@
44
Authors: Antony Phillips, Dr Stuart Mitchell 2008
55
"""
66

7+
from typing import Any, Dict, List, Optional, Tuple, Union
8+
79
# Import PuLP modeler functions
810
from pulp import *
11+
from pulp.pulp import LpConstraintVar, LpProblem
912

1013

1114
class Pattern:
@@ -19,21 +22,21 @@ class Pattern:
1922
lenOpts = ["5", "7", "9"]
2023
numPatterns = 0
2124

22-
def __init__(self, name, lengths=None):
25+
def __init__(self, name: str, lengths: List[int]) -> None:
2326
self.name = name
2427
self.lengthsdict = dict(zip(self.lenOpts, lengths))
2528
Pattern.numPatterns += 1
2629

2730
def __str__(self):
2831
return self.name
2932

30-
def trim(self):
33+
def trim(self) -> int:
3134
return Pattern.totalRollLength - sum(
3235
[int(i) * int(self.lengthsdict[i]) for i in self.lengthsdict]
3336
)
3437

3538

36-
def createMaster():
39+
def createMaster() -> Tuple[LpProblem, LpConstraintVar, Dict[str, LpConstraintVar]]:
3740
rollData = { # Length Demand SalePrice
3841
"5": [150, 0.25],
3942
"7": [200, 0.33],
@@ -71,7 +74,11 @@ def createMaster():
7174
return prob, obj, constraints
7275

7376

74-
def addPatterns(obj, constraints, newPatterns):
77+
def addPatterns(
78+
obj: LpConstraintVar,
79+
constraints: Dict[str, LpConstraintVar],
80+
newPatterns: List[List[int]],
81+
) -> None:
7582
# A list called Patterns is created to contain all the Pattern class
7683
# objects created in this function call
7784
Patterns = []
@@ -82,7 +89,7 @@ def addPatterns(obj, constraints, newPatterns):
8289
for j, k in zip(i, Pattern.lenOpts):
8390
lsum += j * int(k)
8491
if lsum > Pattern.totalRollLength:
85-
raise ("Length Options too large for Roll")
92+
raise Exception("Length Options too large for Roll")
8693

8794
# The number of rolls of each length in each new pattern is printed
8895
print("P" + str(Pattern.numPatterns), "=", i)
@@ -92,20 +99,22 @@ def addPatterns(obj, constraints, newPatterns):
9299

93100
# The pattern variables are created
94101
pattVars = []
95-
for i in Patterns:
102+
for p in Patterns:
96103
pattVars += [
97104
LpVariable(
98-
"Pattern " + i.name,
105+
"Pattern " + p.name,
99106
0,
100107
None,
101108
LpContinuous,
102-
(i.cost - Pattern.trimValue * i.trim()) * obj
103-
+ lpSum([constraints[l] * i.lengthsdict[l] for l in Pattern.lenOpts]),
109+
(p.cost - Pattern.trimValue * p.trim()) * obj
110+
+ lpSum([constraints[l] * p.lengthsdict[l] for l in Pattern.lenOpts]),
104111
)
105112
]
106113

107114

108-
def masterSolve(prob, relax=True):
115+
def masterSolve(
116+
prob: LpProblem, relax: bool = True
117+
) -> Union[Tuple[float, Dict[str, int]], Dict[str, float]]:
109118
# Unrelaxes the Integer Constraint
110119
if not relax:
111120
for v in prob.variables():
@@ -130,7 +139,7 @@ def masterSolve(prob, relax=True):
130139
return value(prob.objective), varsdict
131140

132141

133-
def subSolve(duals):
142+
def subSolve(duals: Dict[str, float]) -> List[Union[Any, List[int]]]:
134143
# The variable 'prob' is created
135144
prob = LpProblem("SubProb", LpMinimize)
136145

examples/ComputerPlantProblem.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@
4646
(supply, fixedCost) = splitDict(supplyData)
4747

4848
# The cost data is made into a dictionary
49-
costs = makeDict([Plants, Stores], costs, 0)
49+
costs_dict = makeDict([Plants, Stores], costs, 0)
5050

5151
# Creates the problem variables of the Flow on the Arcs
5252
flow = LpVariable.dicts("Route", (Plants, Stores), 0, None, LpInteger)
@@ -59,7 +59,7 @@
5959

6060
# The objective function is added to prob - The sum of the transportation costs and the building fixed costs
6161
prob += (
62-
lpSum([flow[p][s] * costs[p][s] for (p, s) in Routes])
62+
lpSum([flow[p][s] * costs_dict[p][s] for (p, s) in Routes])
6363
+ lpSum([fixedCost[p] * build[p] for p in Plants]),
6464
"Total Costs",
6565
)

examples/SpongeRollProblem1.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
cost = 1
2424

2525
# The pattern data is made into a dictionary
26-
patterns = makeDict([LenOpts, PatternNames], patterns, 0)
26+
patterns_dict = makeDict([LenOpts, PatternNames], patterns, 0)
2727

2828
# The problem variables of the number of each pattern to make are created
2929
vars = LpVariable.dicts("Patt", PatternNames, 0, None, LpInteger)
@@ -37,7 +37,7 @@
3737
# The demand minimum constraint is entered
3838
for i in LenOpts:
3939
prob += (
40-
lpSum([vars[j] * patterns[i][j] for j in PatternNames]) >= rollDemand[i],
40+
lpSum([vars[j] * patterns_dict[i][j] for j in PatternNames]) >= rollDemand[i],
4141
f"Ensuring enough {i} cm rolls",
4242
)
4343

examples/SpongeRollProblem2.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
(rollDemand, surplusPrice) = splitDict(rollData)
3636

3737
# The pattern data is made into a dictionary
38-
patterns = makeDict([LenOpts, PatternNames], patterns, 0)
38+
patterns_dict = makeDict([LenOpts, PatternNames], patterns, 0)
3939

4040
# The problem variables of the number of each pattern to make are created
4141
pattVars = LpVariable.dicts("Patt", PatternNames, 0, None, LpInteger)
@@ -58,7 +58,8 @@
5858
# The demand minimum constraint is entered
5959
for i in LenOpts:
6060
prob += (
61-
lpSum([pattVars[j] * patterns[i][j] for j in PatternNames]) - surplusVars[i]
61+
lpSum([pattVars[j] * patterns_dict[i][j] for j in PatternNames])
62+
- surplusVars[i]
6263
>= rollDemand[i],
6364
f"Ensuring enough {i} cm rolls",
6465
)

examples/SpongeRollProblem3.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,12 @@
44
Authors: Antony Phillips, Dr Stuart Mitchell 2007
55
"""
66

7+
from typing import Any, Dict, List, Tuple, Union
78

8-
def calculatePatterns(totalRollLength, lenOpts, head):
9+
10+
def calculatePatterns(
11+
totalRollLength: int, lenOpts: List[Union[Any, int]], head: List[Union[Any, int]]
12+
) -> List[List[int]]:
913
"""
1014
Recursively calculates the list of options lists for a cutting stock problem. The input
1115
'tlist' is a pointer, and will be the output of the function call.
@@ -36,7 +40,9 @@ def calculatePatterns(totalRollLength, lenOpts, head):
3640
return patterns
3741

3842

39-
def makePatterns(totalRollLength, lenOpts):
43+
def makePatterns(
44+
totalRollLength: int, lenOpts: List[int]
45+
) -> Tuple[List[str], List[List[int]], Dict[str, int]]:
4046
"""
4147
Makes the different cutting patterns for a cutting stock problem.
4248
@@ -105,7 +111,7 @@ def makePatterns(totalRollLength, lenOpts):
105111

106112
# The pattern data is made into a dictionary so it can be called by patterns["7"]["P3"] for example.
107113
# This will return the number of rolls of length "7" in pattern "P3"
108-
patterns = makeDict([PatternNames, LenOpts], patterns, 0)
114+
patterns_dict = makeDict([PatternNames, LenOpts], patterns, 0)
109115

110116
# The variable 'prob' is created
111117
prob = LpProblem("Cutting Stock Problem", LpMinimize)
@@ -127,7 +133,8 @@ def makePatterns(totalRollLength, lenOpts):
127133
# The demand minimum constraint is entered
128134
for j in LenOpts:
129135
prob += (
130-
lpSum([pattVars[i] * patterns[i][j] for i in PatternNames]) - surplusVars[j]
136+
lpSum([pattVars[i] * patterns_dict[i][j] for i in PatternNames])
137+
- surplusVars[j]
131138
>= rollDemand[j],
132139
f"Ensuring enough {j} cm rolls",
133140
)

0 commit comments

Comments
 (0)