1. Using lpSum
Welcome back! In this lesson we will learn about lpSum.
2. Moving from simple to complex
In a previous lesson we worked through a resource scheduling example at a bakery.
In that example there were two decision variables one for each product they sold. Bakeries often sell more than two products. What if the bakery sold 6 products?
Our code's decision variables may look like this. Think about it, what if they sold more?
3. Moving from simple to complex
Coding the objective function, or constraints, to sum the different variables together would be near impossible if your model contained hundreds or thousands of variables. We need a method that scales. In a later lesson we will show how to quickly define the decision variables at scale but for now we assume that they are defined and we want to sum many of them together.
4. Using lpSum()
The PuLP framework provides a function that does just that. LpSum, sums a list of linear expressions. It's only input is the list of expressions to sum.
Therefore, coding this objective function in PuLP using the addition symbol is equivalent to defining this objective function using lpSum.
5. lpSum with list comprehension
Often lpSum is used with Python's list comprehension. Going back to our working example. Imagine that we have defined a list of the different types of cakes at the bakery. In the code example shown here, the Python list is called cake_type. Additionally, in the example there are two dictionaries. One dictionary is for the amount of profit earned from each cake. The other dictionary contains the PuLP LpVariables defined earlier. Now with Python's list comprehension we create a list of Pulp LpVariables multiplied by the profit for each cake. Finally, we can sum all these values together to define the objective function by using lpSum. This structure makes it easy to scale the number of variables. To increase the number of types of cakes we would only need to extend our list and dictionary variables.
6. Summary
In summary, as our models become more complex we need a method of summing many variables.
The PuLP framework contains the lpSum function which does just that.
Using this function in combination with python's list comprehension creates a structure that scales. In upcoming lessons we will learn how to create PuLP LpVariables at scale which will allow us to work on larger problems.
7. Practice time!
Awesome, it is time for you to try using lpSum.