Reputation: 6366
I have the following constraint:
sum of (between p = 0 to p = 2) of X_sap <= A_sa
My classes are:
# s
site_classes = [1, 2]
# a
age_classes = [1, 2, 3]
# p
period_classes = [0, 1, 2]
age_areas = {1: {'age_range': '0to10', 1: 3000, 2: 8000},
2: {'age_range': '11to20', 1: 6000, 2: 4000},
3: {'age_range': '21to30', 1: 9000, 2: 7000}}
My sap is defined as follow:
sap = []
for s in site_classes:
for a in age_classes:
for p in period_classes:
sap.append(f'{s}_{a}_{p}')
Here's how I'm creating my X_sap:
x_vars = lp.LpVariable.dicts("X", sap, lowBound=0, cat='Continuous')
Here's how I'm creating my area constraints
area_c_dict = {}
for s in site_classes:
for a in age_classes:
for p in period_classes:
area_c_dict[f'{s}_{a}_{p}'] = age_areas[a][s]
I'm struggling to generate my constraints to output in this way
X110 + X111 + X112 <= 3,000
X120 + X121 + X122 <= 6,000
X130 + X131 + X132 <= 9,000
X210 + X211 + X212 <= 8,000
X220 + X221 + X222 <= 4,000
X230 + X231 + X232 <= 7,000
My outputted variables are
area_c_dict = {'1_1_0': 3000, '1_1_1': 3000, '1_1_2': 3000, '1_2_0': 6000, '1_2_1': 6000, '1_2_2': 6000, '1_3_0': 9000, '1_3_1': 9000, '1_3_2': 9000, '2_1_0': 8000, '2_1_1': 8000, '2_1_2': 8000, '2_2_0': 4000, '2_2_1': 4000, '2_2_2': 4000, '2_3_0': 7000, '2_3_1': 7000, '2_3_2': 7000}
x_vars = {'1_1_0': X_1_1_0, '1_1_1': X_1_1_1, '1_1_2': X_1_1_2, '1_2_0': X_1_2_0, '1_2_1': X_1_2_1, '1_2_2': X_1_2_2, '1_3_0': X_1_3_0, '1_3_1': X_1_3_1, '1_3_2': X_1_3_2, '2_1_0': X_2_1_0, '2_1_1': X_2_1_1, '2_1_2': X_2_1_2, '2_2_0': X_2_2_0, '2_2_1': X_2_2_1, '2_2_2': X_2_2_2, '2_3_0': X_2_3_0, '2_3_1': X_2_3_1, '2_3_2': X_2_3_2}
Any help would be greatly appreciated on how I can achieve that. I'm not sure how to loop through my x_vars without breaking it
Upvotes: 2
Views: 1123
Reputation: 116
First, create your decision variables like this:
x_vars = lp.LpVariable.dicts("X", [(s,a,p) for s in site_classes for a in age_classes for p in period_classes] , lowBound=0, cat='Continuous')
Then use the lpSum
function from the pulp library to make your constraints:
for s in site_classes:
for a in age_classes:
prob += lp.lpSum(x_vars[(s,a,p)] for p in period_classes) <= age_areas[a][s]
The prob
variable is an instance of the LpProblem
class
Demonstration on how to define a decision variable for the sum of variables to be used in other constraints
define a free variable
sum_var = lp.LpVariable.dicts("sum_of_variables", [(s,a) for s in site_classes for a in age_classes] , cat='Continuous')
now add a definition to your free variable.
for s in site_classes:
for a in age_classes:
prob += lp.lpSum(x_vars[(s,a,p)] for p in period_classes) == sum_var[(s,a)]
Now you can use your free variable in a constraint
for s in site_classes:
for a in age_classes:
prob += sum_var[(s,a)] <= age_areas[a][s]
This approach can improve the readability of you linear program and makes it easier to add complexity to the model
Upvotes: 2