We're sorry but this page doesn't work properly without JavaScript enabled. Please enable it to continue.
Feedback

How to improve your diet and save money with Python

00:00

Formal Metadata

Title
How to improve your diet and save money with Python
Title of Series
Part Number
35
Number of Parts
169
Author
License
CC Attribution - NonCommercial - ShareAlike 3.0 Unported:
You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal and non-commercial purpose as long as the work is attributed to the author in the manner specified by the author or licensor and the work or content is shared also in adapted form only under the conditions of this
Identifiers
Publisher
Release Date
Language
Production PlaceBilbao, Euskadi, Spain

Content Metadata

Subject Area
Genre
Abstract
Zuria Bauer/Daniel Domene López - How to improve your diet and save money with Python Optimization in Python (also known as mathematical programming) can be performed by minimization (or maximization) of an objective function within a model that can include discrete variables subject to a set of constrains. At this talk, chemical engineering students of the University of Alicante will introduce the audience to the possibilities of optimization, presenting Pyomo and showing real world examples such as how to improve your diet and save money at fast food restaurants. ----- Process optimization in industry has become essential in order to maximize the resources available and reduce energy consumption. Optimization problems become interesting when dealing with restrictions (linear or nonlinear) and integer variables (modeling the discrete decisions). Python ecosystem presents different libraries to solve optimization problems, some of them are CVXOpt, CVXPy, PulP, OpenOpt, or Pyomo. Among them, Pyomo results interesting because: - It can be used for Mathematical modeling in Python similarly to AMPL (and GAMS) - It communicates with the main solvers used in this field such as GLPK, Gurobi, CPLEX, CBC and PICO - It's free and open source Python library (BSD license), being developed by Sandia National Laboratories, USA. - It supports Python 3 and it is easy to install. The talk will be divided in three parts: 1. _Introduction to Mathematical Programming/Optimization (15 min):_ visual introduction to optimization concepts including restrictions and non linearties (linear Programming, Nonlinear Programming, ILP, MIP, MINLP). 2. _Introduction to the Pyomo sintax and a quick note for the installation (20 min):_ showing how to improve their diet and save money when ordering food in fast food restaurants. 3. _Optimization problems in engineering (10 min):_ showing more advanced optimization examples that include decision variables.
Keywords
11
52
79
TwitterUniform resource nameChi-squared distributionPersonal area networkSelf-organizationStudent's t-testMultilaterationProgrammer (hardware)WordInteractive televisionTwitterLaptopGUI widgetElement (mathematics)Lecture/Conference
TrailForm (programming)Arithmetic meanGraph (mathematics)1 (number)TangentCore dumpPoint (geometry)SpiralAreaCASE <Informatik>Functional (mathematics)Tracing (software)Medical imagingComputer fontType theoryTask (computing)Optimization problemStatuteVolume (thermodynamics)EvoluteList of unsolved problems in mathematicsConvex functionAuthorizationChemical equationConstraint (mathematics)Three-dimensional spaceLimit (category theory)DistanceObject (grammar)File formatInequality (mathematics)Convex setDimensional analysisSign (mathematics)DemosceneForm (programming)Maxima and minimaMoment (mathematics)VideoconferencingTheoryComputer programmingLine (geometry)Matching (graph theory)Domain nameIdeal (ethics)Mathematical morphologyInformationProduct (business)Physical systemRight angleComputer fileAdditionState of matterGUI widgetMathematical optimizationVertex (graph theory)Multiplication signSpacetimeCoefficientMultiplicationVariable (mathematics)Glattheit <Mathematik>SummierbarkeitDifferent (Kate Ryan album)Equaliser (mathematics)PlanningGame controllerRevision controlGradientLecture/Conference
SkewnessMetropolitan area networkLine (geometry)Special unitary groupExecution unitHand fanServer (computing)EmailCellular automatonCopyright infringementMereologyInformationNumberCASE <Informatik>Arithmetic meanVideo gameFood energyInstance (computer science)Link (knot theory)Constraint (mathematics)Set (mathematics)Sampling (statistics)Endliche ModelltheorieDigitizingMixed realityMaxima and minimaLinear programmingLine (geometry)Flow separationObject (grammar)Variable (mathematics)Dynamical systemComputer programmingRight angleInternetworkingPosition operatorComputerBit rateType theoryData structureSeries (mathematics)Multiplication signPhysical systemMathematical optimizationMathematicsProduct (business)Parameter (computer programming)Computer configurationImplementationFunctional (mathematics)Integrated development environmentList of unsolved problems in mathematicsOnline helpService (economics)Latin squareMathematical analysisNonlinear systemFigurate numberPlanningAutomatic differentiationInferenceRow (database)Different (Kate Ryan album)ResultantBinary codeoutputSimplex algorithmAlgebraCodeAlgorithmModeling languageOptimization problemScripting languageRoboticsProgramming languageCoefficientMenu (computing)Standard deviationLine codeDeterminantLinearizationDefault (computer science)ProteinDecision theoryThermal conductivityAxiom of choiceLecture/Conference
EmulationComa BerenicesProcess (computing)Mathematical optimizationMaxima and minimaArtificial neural networkArmConditional-access moduleInformation managementInterior (topology)Dimensional analysisDomain nameFood energyCASE <Informatik>Arithmetic meanRankingComputer programmingBitPopulation densityObject (grammar)Multiplication signComputer virusVideo gameEndliche ModelltheorieElement (mathematics)Type theoryObservational studyProduct (business)Water vaporMathematical optimizationPlanningSpacetimeMaxima and minimaCore dumpNichtlineares GleichungssystemMereologyNichtnewtonsche FlüssigkeitReal numberData structureDistanceExpressionNumberPoint (geometry)Integrated development environmentStaff (military)Office suiteSatelliteConstraint (mathematics)AutocovarianceData miningSkalarproduktraumNormal (geometry)Graph (mathematics)Self-organizationConjugate gradient methodUniverse (mathematics)Axiom of choiceHome pageStapeldateiCodeAnalytic continuationVariable (mathematics)Functional (mathematics)ExistenceLink (knot theory)ResultantComputer animation
3 (number)Type theorySampling (statistics)Object (grammar)Product (business)Functional (mathematics)Food energyConstraint (mathematics)Message passingArithmetic meanWater vaporInternetworkingCASE <Informatik>Level (video gaming)Theory of relativitySound effectBit rateMathematical optimizationDifferent (Kate Ryan album)Video gamePoint (geometry)Goodness of fitBitPareto distributionSpeech synthesisComputer animation
Transcript: English(auto-generated)
Welcome all. Here I have Daniel and Surya with me on how to improve your diet and save money with Python. Give them some applause. Hi everyone. My name is Surya, he is Daniel.
We are both students from the University of Alicante and we are both chemical engineering students. So we are not programmers. So if you see something in a code, feel free to send a pull request to GitHub. That's another thing. You can find word documentation and notebooks on GitHub, which I will post on Twitter later.
Something about us. We are both active members of Kachema, which is a non-profit organisation by a university. And, well, something maybe about your personalities.
He is in love with interactive widgets and he loves them. I actually don't like them so much. And, well, we are programmers since 2014, so we are beginners in this. And something about the talk.
We are chemical engineers and we love reactors and distillation columns. But I don't think you are much chemical engineer, so maybe this will not be interesting for you. So we were thinking, what is everything every one of us eats? And, well, every one of us wants to eat the most but pay the minimum of money.
So, but all of us have the objective, now it's summer, so we all want to fit and be healthy. So we are going to show you how you can optimise your food with a minimum cost, but having the nutritional concerns that you want to have.
And, well, now I'm going to let you with Daniel, who is going to tell you something more about the theory of this optimization problem.
Thank you. There are no interactive widgets here, so don't be afraid. Optimisation deals with finding a minimum or a maximum or zeros of a given function. And we are going to see some concepts using the diet problem.
This problem was announced in the early 40s when the US Army wanted to minimise the cost of food and give their shoulders a balanced diet. To understand this better, I give you an example.
Imagine we move the diet problem to the present time. At this date, it is common to go to a fast food establishment to treat. And we want a cheaper meat and of course we want a healthy meal.
So this is our problem. When you go to this establishment, you can choose some products like fries, like hamburgers. And this is our variable, naming as X in our mathematical problem.
You know, each product has a price and the total price is the multiplication of all coefficients by this variable. And the summation of all of them is our final cost.
What we want to do is minimise this cost, subject to our constraints and nutritional constraints. So this is our mathematical problem and we are going to optimise this using Python. But first, we have to see some concepts of optimisation.
I wish my professors showed me at the very beginning and I'm going to show you in 10 minutes. So first, what is a linear function and a non-linear function? As you can see here, this is a linear function, it's a line. And while this is a non-linear function, you see it's not a line.
You can perform this in three dimensions, this is a plane and a non-linear function looks like this in three dimensions.
Well, a smooth version known as smooth. If you have something like this, this is a function where you can calculate the tangent in all the points of its domain. So this means that this is a smooth function. Great!
And for example, in the vertex of this other function you cannot calculate the tangent, so this is a non-smooth function. This is important and later we will see it. And also in 3D, in three dimensions, this is a smooth function.
And as you can see, also a vertex, this is a non-smooth function. Many dimensioners use the gradient.avg function to solve the problem. And in more cases, this gradient is not given, so you have to calculate it numerically.
So if you have a noisy function, this is so complicated, you will not be sure that you don't have a mistake. So to automate, we prefer the green graph, the extra function, so non-noisy function.
If you have something like this, it's a convex function. When the tangent in a point is completely horizontal, you could have a minimum. In this case, you only have one point and it's the lowest point, so it's a global minimum.
And of course, if you have more than one point and have the horizontal tangent, you have more than one minimum. In this case, you have the lowest value for the function is the global minimum. And you have other minimums that are the local minimum. This is so important. And why is this important?
Well, when you are solving this type of problem, you don't actually know the value of all the points in your function. So it's like you are in a fog-covered mountain and you only have the information of the nearest region. So it could be possible that it's the fog going out.
Well, it could be that you are not in the global point, in the global optimum. Well, what is a convex and non-convex function? This is a convex function. Imagine if you choose any two points in the graph
and you trace a similar line between these two points, if the graph is always down the segment, you have a convex function. If not, you have a non-convex function. Yes, easy.
And also in three dimensions, convex and non-convex functions can be easy. So this is an important topic. What is a constraint? Well, a constraint is a function that limits your search space to find a minimum.
Imagine we have this function, this is the control of the function, and the lowest point is the black point, the global minimum. If we have not any constraint, our optimum point is the black point, the global minimum. So we can have different types of constraints.
Like this is a equality constraint, that means that the optimum point must be inside our restriction. So the solution for this problem is in the red point, this is the optimum. And as you can see, it's a clear point to the lower minimum inside this restriction.
You can have inequality constraints that allow you to search your optimum point over the restriction or under the restriction. In this case, you can search your optimum point over the inequality constraint, and
of course, the optimum point is the global minimum of the function, so it's fantastic. And you can have the other case. You are only allowed to search the optimum point under the constraint. So your solution is this red point.
You can ask me, well, it's a little far off the global minimum yet, but this is your problem and this is the better solution for this case. Because you are a constraint, and this is so important.
Of course, if you have more than one constraint, you can perform a little search space to find the minimum. And as you can see, the red point is another point. Of course, this region that you form with the constraint should be a convex region to be sure you are in a global optimum point.
Because if you have some like this, you never could be sure you are in a global optimum. You only can assure the solution is a local minimum or a local maximum, but not the best solution.
Well, most of the figures and the script from Guevara Sen and Saipi Lecture. Thank you, Guevara Coos. Well, attending to this determination problem can be divided by using these ideas.
If you pay attention of your editing function or your retention, you can ask. Well, it's a linear, it's a non-linear, or we have a decision variable. That means that you can do a choice.
For example, I only want a vegetarian menu. Or not. It's like one or zero. There are half my problem binary variable, yes or no. So, we can have linear programming program, mixed-interval linear programming program, non
-linear programming program, and the most difficult mixed-interval non-linear programming program. Each one of these type of problem have a main algorithm to solve it. For example, we use the simplex algorithm to solve linear programming.
Well, an optimization model can be defined mathematically as follows. This is our problem, the data problem. As you can see, there are only letters, but don't be afraid in payomo. This is not an abstract model because we put the coefficient and other parameters externally.
And this is a concrete model in payomo where you put explicitly the value of the parameters of other coefficients in the problem. So, now I'm going to change.
Well, the optimization problem could be solved through a solver.
A solver is the implementation of the main algorithm. Some of the solver could be that you saw here. For linear programming, we can use jlpk, pulp, cowix-ot. For example, for mixed-interval non-linear programming, we use baron and CPLEX.
CPLEX is fantastic. Really, really. Well, we can use this solver through algebraic modeling language that sees high-level computer languages that support formulation and analysis of large mathematical problems.
Some of them are Ampel, GAMS, AIMS and, of course, payomo. Payomo is interesting because it allows the formulation of algebraic models using Python. And this is great.
And it communicates with principal solvers, even Neocerber. Why payomo? Well, why not payomo? Payomo is an open source, has a solver integration, and has several advantages over custom.
Like, it's a robot language, has extensive documentation, a rich set of standard libraries, and more. So, why not payomo? It's a good option. So, for example, payomo, we have to thank Juan Luis Cano for his help building the conduct research for payomo.
Juan Luis is also in the conference. Thank you, Juan Luis. And, for example, you only have to type this line code. And you have to install the solver separately because they don't have implemented installation, but it's not a problem.
If you want to install glpki to solve any problems and mix the interval linear programming, type this. And, to solve non-linear programming, you can use epop, type in this other line.
And you can install some extra, like Neocerber, that is the free internet-based service for solving numerical optimization problems. And it's so interesting for more information. Click the link. And now I give the award, I don't know what to say, to Thuri, that is going to explain the program we perform.
We are sorry for that much of theory, but if we don't show you that, you will not understand what I'm going to show you now.
So, I'm now going to show you the practical part of this. So, now we're going to improve our diet. And, well, our problem is that, like Danny explained before, but we have two cases. The first case is, we set our menu from a fast food restaurant, you won't.
And we want to minimize the cost, but eat the healthiest way. So, we have a lot of constraints, we have to minimize our function option. And, well, all that has to be the optimum solution for us.
So, how I did this? I actually am not good with guideline daily amounts and this stuff, but I was searching on the internet. And, well, I find a lot of data about the input of daily nutrients you should eat a day.
What you can see here for different women, men, children that want to shoot you today. It's a little bit, I don't know if someone does that. But, well, using this, I have done the problem, I've solved it. First, we need to import Payama.
We say we are importing everything, but it's like, it's convention and Payama says he does this because it's like this. And then I got the data. I have to say the data, it's not totally real, so everything could be real, it's fiction.
And you will see here is my data and we have, I don't know if they will let me show you, but in this data, we have all menus, the costs and then on that, I will show you later if you want, we set or parameter what will be our constraint values.
It means, in this case, we have calories, sugar, proteins and some of this stuff and I've settled maximum and minimum values I want in my diet. So, solving this problem, first we need to input the model.
This type of problem is a linear problem and an abstract model. So, we set the sets, the sets is the data I use to get the model in and in this case, we have the products and the nutrients with their parameters, which are data which depends on the sets I have set before
and we have cost, nutrients and a maximum and minimum of each nutrients, which of course we've default zero and infinite. Then we have variables, will be in this case number of servings, what we're going to take. Our objective function is to minimize the cost of the food
and it's the normal structure of our object function. Our constraint is, I think, the most difficult part of the code because you have to look what you're going to do and later I will show you a more difficult problem like that.
This is very easy, we have maximum and minimum, nothing more and solving the problem, that's what Payamo gives you as a solution. You see, you have one solution, which is great. We have a function value, which means we have to minimize the cost of 369 euros and well, he finished everything done
and the solution he does for us is this. But it's not showing my solution, I don't know why. On the it, what you don't see, he gives you the answer. It makes, in this case we get, you can eat one Big Mac and you have optimized your diet.
You see, that's everything you can eat in one meal, of course, because you have, but only the hamburger, you can't eat the fries, only hamburger. You have to say, here, you see, that's a normal graph of what we've gone Big Mac.
You see, this black one is the daily amount in one meal you should eat but this type of food has a lot of salt, a lot of fat, so, well. If you want to eat healthy, you go there and eat a Big Mac. It won't be great.
Now I'm going to show you something very different, I like this problem a lot because I was thinking what can do more with the diet problem and I was thinking, well, now we're going to do the opposite. It means how much calories I can eat in one meal for only 5 euros
and it was like, wow, I go there and eat a lot. So, no, well, I do that, yeah. Let's eat. And, well, we did the same. We do the import of Payamu, we get the data
which you will not find that is a dead link McDonald's. I don't know what's happened. Well, and to solve that, it's an abstract model. We set our sets, our parameters but in this time you say it's not the nutrients we're going to set to maximum and minimum.
This time it's the cost, 0 and 5 euros in this case. Our variables are the same and our objective function now is the calories but we want the maximum. You see Payamu is very visual and very easy. You see there the sense. When you want to minimize, you put there minimize and when you put maximize, you don't have to do anything more.
And, well, our constraint now will be on the cost and our solution we got. You see you can eat a whole meal, 2690 kilocalories for 5 euros. So, you eat that what you should eat in one day
which I think is respectable for 5 euros. And the solution is this. You should eat 3 hamburgers for 1 euro, 29 and 1 package of grilled onion rings, which I've never seen.
Now, I'm sorry for it. We are chemical engineers and we love reactors and distillation companies, so now you're going to see the problem we solve normally. And, well, that's our problem or example. In this case, we solve chemical engineering, chemical industry problems.
So, we have to use a ways to get a product and to minimize our environmental impact because we deal with a lot of chemical products and something like that. So, to make it easy for you, we have products which we can do parts with the reactor
to a final product which will be beer in this case. And then we can separate water from the alcohol with distillation and we'll get whiskey and water. But we can't do it with 2 types. Reactors, we have batch, and continuous, we made a batch reactor.
It's what you do at home. You put your water in and stop the reaction, eat it and then put another boiling water on it. Continuous, it will be there how much time you want it. And distillation is the same. You have a batch reactor which is, I think it's on Simpson's capital.
Yeah, they explode that thing. But you can do it in short times or in long time for continuous. And, well, that's not what I'm going to show you. We have this superstructure. We have A, we want to get it to B and then to C.
And we have 2 ways to get it. We have a reactor, we have a lot of distillation columns. And, well, we get people to tell us what we can do with the minimum environmental impact. And, well, we have a lot of reactions. Everyone is interested and you can read them.
I didn't think he'd want that. Here we have an interesting fact. We have disjunctions. This is the first time you will see them. Disjunctions, you have to imagine it as like two situations. We have situation 1, which is when we have situation 1, the coast and every product will be this data.
But if this situation is not going to happen, we have the other. It means everything is zero, so this part is not existing anymore. And it's the hardest part to deal with it on Payamont. Which everyone is, if everyone is interested, you can come to me outside and I will explain you how to do it.
So, now we are going to introduce binary variables. Which is, everyone I think knows what a binary variable is. The 1 or 0, well, it exists or it doesn't exist. So, optimizing or final objection. You see, this time it's not a lovely linear problem.
This time we have a real expression with everything mapped stuff. And now I'm going to show you the results because the code is very very wrong. These are the results, what we should do. So, you see Payamont, you can use it for everything. To go to McDonald's or to make your own reactor at home.
And settle, I don't know, whiskey, beer, what you want. So, you can use everything of this for your own choice. And last but not least, I have to say it. I mean, I said before, we are both part of Kateme, which is a non-profit organization from the University of Alicante.
I would encourage chemical engineers to use programming, because we actually don't learn to program in our studies. And, well, we have to think, if we want to say that's the homepage. And we have to think a lot to our teachers, Fran Navarro and Ruwen Rufimena, which have helped us to do this.
And I hope you enjoyed to speak. I wanted to know if you know what are the methods for optimization that are used inside Piomo or any of the tools that you are calling from it.
Like, is it iterative way? Is it Newtonian? Is it conjugate gradient? What kind of method of optimization is done to arrive to the minimum? Normally, it's an iterative way, so he tries everything and he wants to choose how the solution will fit everything.
Normally, you have seen a very simple problem, but before I showed you, you have, I think, 29 equations. You have to optimize it, because the solution needs to fit every of them. So, sometimes it will be a good solution, what you get, but sometimes not. So, you have to play a little bit with that.
We normally use GAMS and you will see the code is on there too, that they give very similar, but not the same solution for you to the same problem, because every solver has his own stuff. I don't know if that's the answer to your question.
Thank you very much for the talk with the optimization of calories for 5 euros.
Did you have any constraints as in non-toxic level of salt or fat? So, can you survive those calories or did you have no constraints? I was looking at that and I saw on the internet that you should eat 2 grams of salt a day, which I think eats a lot more.
I was looking at it and I think if you eat that much of calories of salt a day, maybe you go to the hospital and the next. So, I don't think you can eat that much for one meal. It will be too much for you to get that.
Do we have those in one? No, the other, the 2600 calories, I mean. Yeah, the problem is that the food has a lot of salt and sugar and that's too much you should have in your body, so you will have problems later maybe.
I don't know, maybe not. You should try it. Please send me a message if you have tried, if you are okay. Hi, thank you for the talk. I have a question. Why can't you drink this water? It's whiskey water basically, drink and drive.
Why? There is water waste, don't drink that. It's whiskey water, right? I will buy it. Okay, that's because you have to study a little bit about the distillation.
You have a lot of types of different alcohol types in whiskey and you have to see there are some types you can't get blind from it. So that's what you are extracting and that's in the water. So maybe if you... It's water, right?
Yeah, it's water. There may be some molecules of water in it. Normally, everything what we got in the chemical engineering prediction, you don't should eat it or taste it. Well, I didn't recommend to drink.
So does that mean if you mix wastewater with whiskey, then you get beer out of it? No, no. It will be great, it will be great. Okay, my actual question, my actual question, is it possible to have the two objectives?
I think you implemented now the nutrition constraints as constraints. Yeah. But can there be two objectives which are somehow weighted that you can say... Well, that you can compromise between nutritional value and money spent. So it's fine if the nutrition value is not quite as high if you save two euro or something like that.
Yes, yes. Well, yes, you can perform a multi-objective exercise but not using this technique.
For example, if you are interested in optimizing the cost and the medical care, there are two objectives that are different. So you have to use Pareto on other techniques, not using these techniques. But yes, you could do it but using other things. This is only for one objective function.
Yeah, you can do it. If you want later, we can talk about it. What you can do will be easier if you want to do it like this. You can transform one of the function objectives in a constraint.
So if it is satisfied, you have two function objectives. You only have to do what are you dealing with. It's to know what you are doing, what normally we don't know. The speech should be 45 minutes but I was a little bit fast so I'm sorry for that.
No worries. Any more questions? So we can have our free meal. Thanks for coming.