1. LpVariable dictionary function
In this lesson we will discuss the LpVariable dictionary function.
2. Moving from simple to complex
In a previous lesson we reviewed the complex bakery example which used the lpSum function to sum decision variables at scale. However, we haven't yet discussed how to create those variables at scale.
At the time we defined each LpVariable separately, typing the code for each one, and created a dictionary called var_dict to hold them. However, the LpVariable class has a method called dicts() that does just that.
3. Using LpVariable.dicts()
It creates a dictionary of LP variables saving us the need to type each LpVariable individually. The inputs for this method are similar to the original LpVariable.
The first is a prefix to the name of the variables.
The indexes parameter is a Python list of strings. This list will be used as the keys to the dictionary returned by the method.
The next two inputs set the lower and upper bounds of the variable.
Finally, the cat input, as before, categorizes the variable as either an integer, binary, or continuous.
4. LpVariable.dicts() with list comprehension
In Supply Chain LP problems often times we need to define a decision variable for every combination of an events. Using LpVariable-dot-dicts in combination with Python's list comprehension we can compactly create those combination of decision variables.
For example, we may need to define a decision variable for each combination of a list of customers and warehouses. In our code example, we use list comprehension to loop through every warehouse and every customer to create a larger list that contains tuples for each combination. The LpVariable.dicts function then takes this combined list and creates a LpVariable for each item in it with a lower limit of 0 and category type of Integer. LpVariable.dicts then outputs a dictionary containing all of the LpVariables.
We are now able to use this dictionary when defining the objective function. In this code example we again use list comprehension when defining the objective function to multiply the cost of shipping from a warehouse to a customer and summing all of those costs together with lpSum. This process allows us to create LpVariables at scale.
5. Summary
In this lesson we discussed the need for creating large number of variables for complex problems.
We can achieve this by using the dicts() method of the LpVariable class. The method returns a dictionary containing LP variables.
By using this method with list comprehension we have a structure that can scale easily. This complements what we discussed earlier with lpSum. With both of these elements we can now attempt more complex optimization problems.
6. Now you try it out
Alright, now you try it out.