This section includes source code for all of the Gurobi diet examples.The same source code can be found in theexamples directory of theGurobi distribution.
/* Copyright 2025, Gurobi Optimization, LLC *//* Solve the classic diet model, showing how to add constraints to an existing model. */#include<stdlib.h>#include<stdio.h>#include<math.h>#include"gurobi_c.h"intprintSolution(GRBmodel*model,intnCategories,intnFoods);intmain(intargc,char*argv[]){GRBenv*env=NULL;GRBmodel*model=NULL;interror=0;inti,j;int*cbeg,*cind,idx;double*cval,*rhs;char*sense;/* Nutrition guidelines, based on USDA Dietary Guidelines for Americans, 2005 http://www.health.gov/DietaryGuidelines/dga2005/ */constintnCategories=4;char*Categories[]={"calories","protein","fat","sodium"};doubleminNutrition[]={1800,91,0,0};doublemaxNutrition[]={2200,GRB_INFINITY,65,1779};/* Set of foods */constintnFoods=9;char*Foods[]={"hamburger","chicken","hot dog","fries","macaroni","pizza","salad","milk","ice cream"};doublecost[]={2.49,2.89,1.50,1.89,2.09,1.99,2.49,0.89,1.59};/* Nutrition values for the foods */doublenutritionValues[][4]={{410,24,26,730},{420,32,10,1190},{560,20,32,1800},{380,4,19,270},{320,12,10,930},{320,15,12,820},{320,31,12,1230},{100,8,2.5,125},{330,8,10,180}};/* Create environment */error=GRBloadenv(&env,"diet.log");if(error)gotoQUIT;/* Create initial model */error=GRBnewmodel(env,&model,"diet",nFoods+nCategories,NULL,NULL,NULL,NULL,NULL);if(error)gotoQUIT;/* Initialize decision variables for the foods to buy */for(j=0;j<nFoods;++j){error=GRBsetdblattrelement(model,"Obj",j,cost[j]);if(error)gotoQUIT;error=GRBsetstrattrelement(model,"VarName",j,Foods[j]);if(error)gotoQUIT;}/* Initialize decision variables for the nutrition information, which we limit via bounds */for(j=0;j<nCategories;++j){error=GRBsetdblattrelement(model,"LB",j+nFoods,minNutrition[j]);if(error)gotoQUIT;error=GRBsetdblattrelement(model,"UB",j+nFoods,maxNutrition[j]);if(error)gotoQUIT;error=GRBsetstrattrelement(model,"VarName",j+nFoods,Categories[j]);if(error)gotoQUIT;}/* The objective is to minimize the costs */error=GRBsetintattr(model,"ModelSense",GRB_MINIMIZE);if(error)gotoQUIT;/* Nutrition constraints */cbeg=malloc(sizeof(int)*nCategories);if(!cbeg)gotoQUIT;cind=malloc(sizeof(int)*nCategories*(nFoods+1));if(!cind)gotoQUIT;cval=malloc(sizeof(double)*nCategories*(nFoods+1));if(!cval)gotoQUIT;rhs=malloc(sizeof(double)*nCategories);if(!rhs)gotoQUIT;sense=malloc(sizeof(char)*nCategories);if(!sense)gotoQUIT;idx=0;for(i=0;i<nCategories;++i){cbeg[i]=idx;rhs[i]=0.0;sense[i]=GRB_EQUAL;for(j=0;j<nFoods;++j){cind[idx]=j;cval[idx++]=nutritionValues[j][i];}cind[idx]=nFoods+i;cval[idx++]=-1.0;}error=GRBaddconstrs(model,nCategories,idx,cbeg,cind,cval,sense,rhs,Categories);if(error)gotoQUIT;/* Solve */error=GRBoptimize(model);if(error)gotoQUIT;error=printSolution(model,nCategories,nFoods);if(error)gotoQUIT;printf("\nAdding constraint: at most 6 servings of dairy\n");cind[0]=7;cval[0]=1.0;cind[1]=8;cval[1]=1.0;error=GRBaddconstr(model,2,cind,cval,GRB_LESS_EQUAL,6.0,"limit_dairy");if(error)gotoQUIT;/* Solve */error=GRBoptimize(model);if(error)gotoQUIT;error=printSolution(model,nCategories,nFoods);if(error)gotoQUIT;QUIT:/* Error reporting */if(error){printf("ERROR: %s\n",GRBgeterrormsg(env));exit(1);}/* Free data */free(cbeg);free(cind);free(cval);free(rhs);free(sense);/* Free model */GRBfreemodel(model);/* Free environment */GRBfreeenv(env);return0;}intprintSolution(GRBmodel*model,intnCategories,intnFoods){interror,status,i,j;doubleobj,x;char*vname;error=GRBgetintattr(model,"Status",&status);if(error)returnerror;if(status==GRB_OPTIMAL){error=GRBgetdblattr(model,"ObjVal",&obj);if(error)returnerror;printf("\nCost: %f\n\nBuy:\n",obj);for(j=0;j<nFoods;++j){error=GRBgetdblattrelement(model,"X",j,&x);if(error)returnerror;if(x>0.0001){error=GRBgetstrattrelement(model,"VarName",j,&vname);if(error)returnerror;printf("%s %f\n",vname,x);}}printf("\nNutrition:\n");for(i=0;i<nCategories;++i){error=GRBgetdblattrelement(model,"X",i+nFoods,&x);if(error)returnerror;error=GRBgetstrattrelement(model,"VarName",i+nFoods,&vname);if(error)returnerror;printf("%s %f\n",vname,x);}}else{printf("No solution\n");}return0;}
/* Copyright 2025, Gurobi Optimization, LLC *//* Solve the classic diet model, showing how to add constraints to an existing model. */#include"gurobi_c++.h"usingnamespacestd;voidprintSolution(GRBModel&model,intnCategories,intnFoods,GRBVar*buy,GRBVar*nutrition);intmain(intargc,char*argv[]){GRBEnv*env=0;GRBVar*nutrition=0;GRBVar*buy=0;try{// Nutrition guidelines, based on// USDA Dietary Guidelines for Americans, 2005// http://www.health.gov/DietaryGuidelines/dga2005/constintnCategories=4;stringCategories[]={"calories","protein","fat","sodium"};doubleminNutrition[]={1800,91,0,0};doublemaxNutrition[]={2200,GRB_INFINITY,65,1779};// Set of foodsconstintnFoods=9;stringFoods[]={"hamburger","chicken","hot dog","fries","macaroni","pizza","salad","milk","ice cream"};doublecost[]={2.49,2.89,1.50,1.89,2.09,1.99,2.49,0.89,1.59};// Nutrition values for the foodsdoublenutritionValues[][nCategories]={{410,24,26,730},// hamburger{420,32,10,1190},// chicken{560,20,32,1800},// hot dog{380,4,19,270},// fries{320,12,10,930},// macaroni{320,15,12,820},// pizza{320,31,12,1230},// salad{100,8,2.5,125},// milk{330,8,10,180}// ice cream};// Modelenv=newGRBEnv();GRBModelmodel=GRBModel(*env);model.set(GRB_StringAttr_ModelName,"diet");// Create decision variables for the nutrition information,// which we limit via boundsnutrition=model.addVars(minNutrition,maxNutrition,0,0,Categories,nCategories);// Create decision variables for the foods to buy//// Note: For each decision variable we add the objective coefficient// with the creation of the variable.buy=model.addVars(0,0,cost,0,Foods,nFoods);// The objective is to minimize the costs//// Note: The objective coefficients are set during the creation of// the decision variables above.model.set(GRB_IntAttr_ModelSense,GRB_MINIMIZE);// Nutrition constraintsfor(inti=0;i<nCategories;++i){GRBLinExprntot=0;for(intj=0;j<nFoods;++j){ntot+=nutritionValues[j][i]*buy[j];}model.addConstr(ntot==nutrition[i],Categories[i]);}// Solvemodel.optimize();printSolution(model,nCategories,nFoods,buy,nutrition);cout<<"\nAdding constraint: at most 6 servings of dairy"<<endl;model.addConstr(buy[7]+buy[8]<=6.0,"limit_dairy");// Solvemodel.optimize();printSolution(model,nCategories,nFoods,buy,nutrition);}catch(GRBExceptione){cout<<"Error code = "<<e.getErrorCode()<<endl;cout<<e.getMessage()<<endl;}catch(...){cout<<"Exception during optimization"<<endl;}delete[]nutrition;delete[]buy;deleteenv;return0;}voidprintSolution(GRBModel&model,intnCategories,intnFoods,GRBVar*buy,GRBVar*nutrition){if(model.get(GRB_IntAttr_Status)==GRB_OPTIMAL){cout<<"\nCost: "<<model.get(GRB_DoubleAttr_ObjVal)<<endl;cout<<"\nBuy:"<<endl;for(intj=0;j<nFoods;++j){if(buy[j].get(GRB_DoubleAttr_X)>0.0001){cout<<buy[j].get(GRB_StringAttr_VarName)<<" "<<buy[j].get(GRB_DoubleAttr_X)<<endl;}}cout<<"\nNutrition:"<<endl;for(inti=0;i<nCategories;++i){cout<<nutrition[i].get(GRB_StringAttr_VarName)<<" "<<nutrition[i].get(GRB_DoubleAttr_X)<<endl;}}else{cout<<"No solution"<<endl;}}
/* Copyright 2025, Gurobi Optimization, LLC *//* Solve the classic diet model, showing how to add constraints to an existing model. */usingSystem;usingGurobi;classdiet_cs{staticvoidMain(){try{// Nutrition guidelines, based on// USDA Dietary Guidelines for Americans, 2005// http://www.health.gov/DietaryGuidelines/dga2005/string[]Categories=newstring[]{"calories","protein","fat","sodium"};intnCategories=Categories.Length;double[]minNutrition=newdouble[]{1800,91,0,0};double[]maxNutrition=newdouble[]{2200,GRB.INFINITY,65,1779};// Set of foodsstring[]Foods=newstring[]{"hamburger","chicken","hot dog","fries","macaroni","pizza","salad","milk","ice cream"};intnFoods=Foods.Length;double[]cost=newdouble[]{2.49,2.89,1.50,1.89,2.09,1.99,2.49,0.89,1.59};// Nutrition values for the foodsdouble[,]nutritionValues=newdouble[,]{{410,24,26,730},// hamburger{420,32,10,1190},// chicken{560,20,32,1800},// hot dog{380,4,19,270},// fries{320,12,10,930},// macaroni{320,15,12,820},// pizza{320,31,12,1230},// salad{100,8,2.5,125},// milk{330,8,10,180}// ice cream};// ModelGRBEnvenv=newGRBEnv();GRBModelmodel=newGRBModel(env);model.ModelName="diet";// Create decision variables for the nutrition information,// which we limit via boundsGRBVar[]nutrition=newGRBVar[nCategories];for(inti=0;i<nCategories;++i){nutrition[i]=model.AddVar(minNutrition[i],maxNutrition[i],0,GRB.CONTINUOUS,Categories[i]);}// Create decision variables for the foods to buy//// Note: For each decision variable we add the objective coefficient// with the creation of the variable.GRBVar[]buy=newGRBVar[nFoods];for(intj=0;j<nFoods;++j){buy[j]=model.AddVar(0,GRB.INFINITY,cost[j],GRB.CONTINUOUS,Foods[j]);}// The objective is to minimize the costs//// Note: The objective coefficients are set during the creation of// the decision variables above.model.ModelSense=GRB.MINIMIZE;// Nutrition constraintsfor(inti=0;i<nCategories;++i){GRBLinExprntot=0.0;for(intj=0;j<nFoods;++j)ntot.AddTerm(nutritionValues[j,i],buy[j]);model.AddConstr(ntot==nutrition[i],Categories[i]);}// Solvemodel.Optimize();PrintSolution(model,buy,nutrition);Console.WriteLine("\nAdding constraint: at most 6 servings of dairy");model.AddConstr(buy[7]+buy[8]<=6.0,"limit_dairy");// Solvemodel.Optimize();PrintSolution(model,buy,nutrition);// Dispose of model and envmodel.Dispose();env.Dispose();}catch(GRBExceptione){Console.WriteLine("Error code: "+e.ErrorCode+". "+e.Message);}}privatestaticvoidPrintSolution(GRBModelmodel,GRBVar[]buy,GRBVar[]nutrition){if(model.Status==GRB.Status.OPTIMAL){Console.WriteLine("\nCost: "+model.ObjVal);Console.WriteLine("\nBuy:");for(intj=0;j<buy.Length;++j){if(buy[j].X>0.0001){Console.WriteLine(buy[j].VarName+" "+buy[j].X);}}Console.WriteLine("\nNutrition:");for(inti=0;i<nutrition.Length;++i){Console.WriteLine(nutrition[i].VarName+" "+nutrition[i].X);}}else{Console.WriteLine("No solution");}}}
/* Copyright 2025, Gurobi Optimization, LLC *//* Solve the classic diet model, showing how to add constraints to an existing model. */importcom.gurobi.gurobi.*;publicclassDiet{publicstaticvoidmain(String[]args){try{// Nutrition guidelines, based on// USDA Dietary Guidelines for Americans, 2005// http://www.health.gov/DietaryGuidelines/dga2005/StringCategories[]=newString[]{"calories","protein","fat","sodium"};intnCategories=Categories.length;doubleminNutrition[]=newdouble[]{1800,91,0,0};doublemaxNutrition[]=newdouble[]{2200,GRB.INFINITY,65,1779};// Set of foodsStringFoods[]=newString[]{"hamburger","chicken","hot dog","fries","macaroni","pizza","salad","milk","ice cream"};intnFoods=Foods.length;doublecost[]=newdouble[]{2.49,2.89,1.50,1.89,2.09,1.99,2.49,0.89,1.59};// Nutrition values for the foodsdoublenutritionValues[][]=newdouble[][]{{410,24,26,730},// hamburger{420,32,10,1190},// chicken{560,20,32,1800},// hot dog{380,4,19,270},// fries{320,12,10,930},// macaroni{320,15,12,820},// pizza{320,31,12,1230},// salad{100,8,2.5,125},// milk{330,8,10,180}// ice cream};// ModelGRBEnvenv=newGRBEnv();GRBModelmodel=newGRBModel(env);model.set(GRB.StringAttr.ModelName,"diet");// Create decision variables for the nutrition information,// which we limit via boundsGRBVar[]nutrition=newGRBVar[nCategories];for(inti=0;i<nCategories;++i){nutrition[i]=model.addVar(minNutrition[i],maxNutrition[i],0,GRB.CONTINUOUS,Categories[i]);}// Create decision variables for the foods to buy//// Note: For each decision variable we add the objective coefficient// with the creation of the variable.GRBVar[]buy=newGRBVar[nFoods];for(intj=0;j<nFoods;++j){buy[j]=model.addVar(0,GRB.INFINITY,cost[j],GRB.CONTINUOUS,Foods[j]);}// The objective is to minimize the costs//// Note: The objective coefficients are set during the creation of// the decision variables above.model.set(GRB.IntAttr.ModelSense,GRB.MINIMIZE);// Nutrition constraintsfor(inti=0;i<nCategories;++i){GRBLinExprntot=newGRBLinExpr();for(intj=0;j<nFoods;++j){ntot.addTerm(nutritionValues[j][i],buy[j]);}model.addConstr(ntot,GRB.EQUAL,nutrition[i],Categories[i]);}// Solvemodel.optimize();printSolution(model,buy,nutrition);System.out.println("JSON solution:"+model.getJSONSolution());System.out.println("\nAdding constraint: at most 6 servings of dairy");GRBLinExprlhs=newGRBLinExpr();lhs.addTerm(1.0,buy[7]);lhs.addTerm(1.0,buy[8]);model.addConstr(lhs,GRB.LESS_EQUAL,6.0,"limit_dairy");// Solvemodel.optimize();printSolution(model,buy,nutrition);System.out.println("JSON solution:"+model.getJSONSolution());// Dispose of model and environmentmodel.dispose();env.dispose();}catch(GRBExceptione){System.out.println("Error code: "+e.getErrorCode()+". "+e.getMessage());}}privatestaticvoidprintSolution(GRBModelmodel,GRBVar[]buy,GRBVar[]nutrition)throwsGRBException{if(model.get(GRB.IntAttr.Status)==GRB.Status.OPTIMAL){System.out.println("\nCost: "+model.get(GRB.DoubleAttr.ObjVal));System.out.println("\nBuy:");for(intj=0;j<buy.length;++j){if(buy[j].get(GRB.DoubleAttr.X)>0.0001){System.out.println(buy[j].get(GRB.StringAttr.VarName)+" "+buy[j].get(GRB.DoubleAttr.X));}}System.out.println("\nNutrition:");for(inti=0;i<nutrition.length;++i){System.out.println(nutrition[i].get(GRB.StringAttr.VarName)+" "+nutrition[i].get(GRB.DoubleAttr.X));}}else{System.out.println("No solution");}}}
functiondiet()% Copyright 2025, Gurobi Optimization, LLC%% Solve the classic diet model% Nutrition guidelines, based on% USDA Dietary Guidelines for Americans, 2005% http://www.health.gov/DietaryGuidelines/dga2005/ncategories=4;categories={'calories';'protein';'fat';'sodium'};% minNutrition maxNutritioncategorynutrition=[18002200;% calories91inf;% protein065;% fat01779];% sodiumnfoods=9;foods={'hamburger';'chicken';'hot dog';'fries';'macaroni';'pizza';'salad';'milk';'ice cream'};foodcost=[2.49;% hamburger2.89;% chicken1.50;% hot dog1.89;% fries2.09;% macaroni1.99;% pizza2.49;% salad0.89;% milk1.59];% ice cream% calories protein fat sodiumnutritionValues=[4102426730;% hamburger42032101190;% chicken56020321800;% hot dog380419270;% fries3201210930;% macaroni3201512820;% pizza32031121230;% salad10082.5125;% milk330810180];% ice creamnutritionValues=sparse(nutritionValues);model.modelName='diet';% The variables are layed out as [ buy; nutrition]model.obj=[foodcost;zeros(ncategories,1)];model.lb=[zeros(nfoods,1);categorynutrition(:,1)];model.ub=[inf(nfoods,1);categorynutrition(:,2)];model.A=[nutritionValues'-speye(ncategories)];model.rhs=zeros(ncategories,1);model.sense=repmat('=',ncategories,1);functionprintSolution(result)ifstrcmp(result.status,'OPTIMAL')buy=result.x(1:nfoods);nutrition=result.x(nfoods+1:nfoods+ncategories);fprintf('\nCost: %f\n',result.objval);fprintf('\nBuy:\n')forf=1:nfoodsifbuy(f)>0.0001fprintf('%10s %g\n',foods{f},buy(f));endendfprintf('\nNutrition:\n')forc=1:ncategoriesfprintf('%10s %g\n',categories{c},nutrition(c));endelsefprintf('No solution\n');endend% Solveresults=gurobi(model);printSolution(results);fprintf('\nAdding constraint at most 6 servings of dairy\n')milk=find(strcmp('milk',foods));icecream=find(strcmp('ice cream',foods));model.A(end+1,:)=sparse([1;1],[milk;icecream],1,...1,nfoods+ncategories);model.rhs(end+1)=6;model.sense(end+1)='<';% Solveresults=gurobi(model);printSolution(results)end
#!/usr/bin/env python3# Copyright 2025, Gurobi Optimization, LLC# Solve the classic diet model, showing how to add constraints# to an existing model.importgurobipyasgpfromgurobipyimportGRB# Nutrition guidelines, based on# USDA Dietary Guidelines for Americans, 2005# http://www.health.gov/DietaryGuidelines/dga2005/categories,minNutrition,maxNutrition=gp.multidict({"calories":[1800,2200],"protein":[91,GRB.INFINITY],"fat":[0,65],"sodium":[0,1779],})foods,cost=gp.multidict({"hamburger":2.49,"chicken":2.89,"hot dog":1.50,"fries":1.89,"macaroni":2.09,"pizza":1.99,"salad":2.49,"milk":0.89,"ice cream":1.59,})# Nutrition values for the foodsnutritionValues={("hamburger","calories"):410,("hamburger","protein"):24,("hamburger","fat"):26,("hamburger","sodium"):730,("chicken","calories"):420,("chicken","protein"):32,("chicken","fat"):10,("chicken","sodium"):1190,("hot dog","calories"):560,("hot dog","protein"):20,("hot dog","fat"):32,("hot dog","sodium"):1800,("fries","calories"):380,("fries","protein"):4,("fries","fat"):19,("fries","sodium"):270,("macaroni","calories"):320,("macaroni","protein"):12,("macaroni","fat"):10,("macaroni","sodium"):930,("pizza","calories"):320,("pizza","protein"):15,("pizza","fat"):12,("pizza","sodium"):820,("salad","calories"):320,("salad","protein"):31,("salad","fat"):12,("salad","sodium"):1230,("milk","calories"):100,("milk","protein"):8,("milk","fat"):2.5,("milk","sodium"):125,("ice cream","calories"):330,("ice cream","protein"):8,("ice cream","fat"):10,("ice cream","sodium"):180,}# Modelm=gp.Model("diet")# Create decision variables for the foods to buybuy=m.addVars(foods,name="buy")# You could use Python looping constructs and m.addVar() to create# these decision variables instead. The following would be equivalent## buy = {}# for f in foods:# buy[f] = m.addVar(name=f)# The objective is to minimize the costsm.setObjective(buy.prod(cost),GRB.MINIMIZE)# Using looping constructs, the preceding statement would be:## m.setObjective(sum(buy[f]*cost[f] for f in foods), GRB.MINIMIZE)# Nutrition constraintsm.addConstrs((gp.quicksum(nutritionValues[f,c]*buy[f]forfinfoods)==[minNutrition[c],maxNutrition[c]]forcincategories),"_",)# Using looping constructs, the preceding statement would be:## for c in categories:# m.addRange(sum(nutritionValues[f, c] * buy[f] for f in foods),# minNutrition[c], maxNutrition[c], c)defprintSolution():ifm.status==GRB.OPTIMAL:print(f"\nCost:{m.ObjVal:g}")print("\nBuy:")forfinfoods:ifbuy[f].X>0.0001:print(f"{f}{buy[f].X:g}")else:print("No solution")# Solvem.optimize()printSolution()print("\nAdding constraint: at most 6 servings of dairy")m.addConstr(buy.sum(["milk","ice cream"])<=6,"limit_dairy")# Solvem.optimize()printSolution()
# Copyright 2025, Gurobi Optimization, LLC## Solve the classic diet model, showing how to add constraints# to an existing model.library(Matrix)library(gurobi)# display resultsprintSolution<-function(model,res,nCategories,nFoods){if(res$status=='OPTIMAL'){cat('\nCost: ',res$objval,'\nBuy:\n')for(jinnCategories+1:nFoods){if(res$x[j]>1e-4){cat(format(model$varnames[j],justify='left',width=10),':',format(res$x[j],justify='right',width=10,nsmall=2),'\n')}}cat('\nNutrition:\n')for(jin1:nCategories){cat(format(model$varnames[j],justify='left',width=10),':',format(res$x[j],justify='right',width=10,nsmall=2),'\n')}}else{cat('No solution\n')}}# define primitive dataCategories<-c('calories','protein','fat','sodium')nCategories<-length(Categories)minNutrition<-c(1800,91,0,0)maxNutrition<-c(2200,Inf,65,1779)Foods<-c('hamburger','chicken','hot dog','fries','macaroni','pizza','salad','milk','ice cream')nFoods<-length(Foods)cost<-c(2.49,2.89,1.50,1.89,2.09,1.99,2.49,0.89,1.59)nutritionValues<-c(410,24,26,730,420,32,10,1190,560,20,32,1800,380,4,19,270,320,12,10,930,320,15,12,820,320,31,12,1230,100,8,2.5,125,330,8,10,180)# Build modelmodel<-list()model$A<-spMatrix(nCategories,nCategories+nFoods,i=c(mapply(rep,1:4,1+nFoods)),j=c(1,(nCategories+1):(nCategories+nFoods),2,(nCategories+1):(nCategories+nFoods),3,(nCategories+1):(nCategories+nFoods),4,(nCategories+1):(nCategories+nFoods)),x=c(-1.0,nutritionValues[1+nCategories*(0:(nFoods-1))],-1.0,nutritionValues[2+nCategories*(0:(nFoods-1))],-1.0,nutritionValues[3+nCategories*(0:(nFoods-1))],-1.0,nutritionValues[4+nCategories*(0:(nFoods-1))]))model$obj<-c(rep(0,nCategories),cost)model$lb<-c(minNutrition,rep(0,nFoods))model$ub<-c(maxNutrition,rep(Inf,nFoods))model$varnames<-c(Categories,Foods)model$rhs<-rep(0,nCategories)model$sense<-rep('=',nCategories)model$constrnames<-Categoriesmodel$modelname<-'diet'model$modelsense<-'min'# Optimizeres<-gurobi(model)printSolution(model,res,nCategories,nFoods)# Adding constraint: at most 6 servings of dairy# this is the matrix part of the constraintB<-spMatrix(1,nCategories+nFoods,i=rep(1,2),j=(nCategories+c(8,9)),x=rep(1,2))# append B to Amodel$A<-rbind(model$A,B)# extend row-related vectorsmodel$constrnames<-c(model$constrnames,'limit_dairy')model$rhs<-c(model$rhs,6)model$sense<-c(model$sense,'<')# Optimizeres<-gurobi(model)printSolution(model,res,nCategories,nFoods)# Clear spacerm(res,model)
' Copyright 2025, Gurobi Optimization, LLC' Solve the classic diet model, showing how to add constraints' to an existing model.ImportsSystemImportsGurobiClassdiet_vbSharedSubMain()Try' Nutrition guidelines, based on' USDA Dietary Guidelines for Americans, 2005' http://www.health.gov/DietaryGuidelines/dga2005/DimCategoriesAsString()=NewString(){"calories","protein","fat",_"sodium"}DimnCategoriesAsInteger=Categories.LengthDimminNutritionAsDouble()=NewDouble(){1800,91,0,0}DimmaxNutritionAsDouble()=NewDouble(){2200,GRB.INFINITY,65,1779}' Set of foodsDimFoodsAsString()=NewString(){"hamburger","chicken","hot dog",_"fries","macaroni","pizza",_"salad","milk","ice cream"}DimnFoodsAsInteger=Foods.LengthDimcostAsDouble()=NewDouble(){2.49,2.89,1.5R,1.89,2.09,1.99,_2.49,0.89,1.59}' Nutrition values for the foods' hamburger' chicken' hot dog' fries' macaroni' pizza' salad' milk' ice creamDimnutritionValuesAsDouble(,)=NewDouble(,){{410,24,26,730},_{420,32,10,1190},_{560,20,32,1800},_{380,4,19,270},_{320,12,10,930},_{320,15,12,820},_{320,31,12,1230},_{100,8,2.5,125},_{330,8,10,180}}' ModelDimenvAsNewGRBEnv()DimmodelAsNewGRBModel(env)model.ModelName="diet"' Create decision variables for the nutrition information,' which we limit via boundsDimnutritionAsGRBVar()=NewGRBVar(nCategories-1){}ForiAsInteger=0TonCategories-1nutrition(i)=model.AddVar(minNutrition(i),maxNutrition(i),0,_GRB.CONTINUOUS,Categories(i))Next' Create decision variables for the foods to buy'' Note: For each decision variable we add the objective coefficient' with the creation of the variable.DimbuyAsGRBVar()=NewGRBVar(nFoods-1){}ForjAsInteger=0TonFoods-1buy(j)=model.AddVar(0,GRB.INFINITY,cost(j),GRB.CONTINUOUS,_Foods(j))Next' The objective is to minimize the costs'' Note: The objective coefficients are set during the creation of' the decision variables above.model.ModelSense=GRB.MINIMIZE' Nutrition constraintsForiAsInteger=0TonCategories-1DimntotAsGRBLinExpr=0ForjAsInteger=0TonFoods-1ntot.AddTerm(nutritionValues(j,i),buy(j))Nextmodel.AddConstr(ntot=nutrition(i),Categories(i))Next' Solvemodel.Optimize()PrintSolution(model,buy,nutrition)Console.WriteLine(vbLf&"Adding constraint: at most 6 servings of dairy")model.AddConstr(buy(7)+buy(8)<=6,"limit_dairy")' Solvemodel.Optimize()PrintSolution(model,buy,nutrition)' Dispose of model and envmodel.Dispose()env.Dispose()CatcheAsGRBExceptionConsole.WriteLine("Error code: "&e.ErrorCode&". "&e.Message)EndTryEndSubPrivateSharedSubPrintSolution(ByValmodelAsGRBModel,ByValbuyAsGRBVar(),_ByValnutritionAsGRBVar())Ifmodel.Status=GRB.Status.OPTIMALThenConsole.WriteLine(vbLf&"Cost: "&model.ObjVal)Console.WriteLine(vbLf&"Buy:")ForjAsInteger=0Tobuy.Length-1Ifbuy(j).X>0.0001ThenConsole.WriteLine(buy(j).VarName&" "&buy(j).X)EndIfNextConsole.WriteLine(vbLf&"Nutrition:")ForiAsInteger=0Tonutrition.Length-1Console.WriteLine(nutrition(i).VarName&" "&nutrition(i).X)NextElseConsole.WriteLine("No solution")EndIfEndSubEndClass
#!/usr/bin/env python3# Copyright 2025, Gurobi Optimization, LLC# Separate the model (dietmodel.py) from the data file (diet2.py), so# that the model can be solved with different data files.## Nutrition guidelines, based on# USDA Dietary Guidelines for Americans, 2005# http://www.health.gov/DietaryGuidelines/dga2005/importdietmodelimportgurobipyasgpfromgurobipyimportGRBcategories,minNutrition,maxNutrition=gp.multidict({"calories":[1800,2200],"protein":[91,GRB.INFINITY],"fat":[0,65],"sodium":[0,1779],})foods,cost=gp.multidict({"hamburger":2.49,"chicken":2.89,"hot dog":1.50,"fries":1.89,"macaroni":2.09,"pizza":1.99,"salad":2.49,"milk":0.89,"ice cream":1.59,})# Nutrition values for the foodsnutritionValues={("hamburger","calories"):410,("hamburger","protein"):24,("hamburger","fat"):26,("hamburger","sodium"):730,("chicken","calories"):420,("chicken","protein"):32,("chicken","fat"):10,("chicken","sodium"):1190,("hot dog","calories"):560,("hot dog","protein"):20,("hot dog","fat"):32,("hot dog","sodium"):1800,("fries","calories"):380,("fries","protein"):4,("fries","fat"):19,("fries","sodium"):270,("macaroni","calories"):320,("macaroni","protein"):12,("macaroni","fat"):10,("macaroni","sodium"):930,("pizza","calories"):320,("pizza","protein"):15,("pizza","fat"):12,("pizza","sodium"):820,("salad","calories"):320,("salad","protein"):31,("salad","fat"):12,("salad","sodium"):1230,("milk","calories"):100,("milk","protein"):8,("milk","fat"):2.5,("milk","sodium"):125,("ice cream","calories"):330,("ice cream","protein"):8,("ice cream","fat"):10,("ice cream","sodium"):180,}dietmodel.solve(categories,minNutrition,maxNutrition,foods,cost,nutritionValues)
#!/usr/bin/env python3# Copyright 2025, Gurobi Optimization, LLC# Use a SQLite database with the diet model (dietmodel.py). The database# (diet.db) can be recreated using the included SQL script (diet.sql).## Note that this example reads an external data file (..\data\diet.db).# As a result, it must be run from the Gurobi examples/python directory.importosimportsqlite3importdietmodelimportgurobipyasgpcon=sqlite3.connect(os.path.join("..","data","diet.db"))cur=con.cursor()cur.execute("select category,minnutrition,maxnutrition from categories")result=cur.fetchall()categories,minNutrition,maxNutrition=gp.multidict((cat,[minv,maxv])forcat,minv,maxvinresult)cur.execute("select food,cost from foods")result=cur.fetchall()foods,cost=gp.multidict(result)cur.execute("select food,category,value from nutrition")result=cur.fetchall()nutritionValues=dict(((f,c),v)forf,c,vinresult)con.close()dietmodel.solve(categories,minNutrition,maxNutrition,foods,cost,nutritionValues)
#!/usr/bin/env python3# Copyright 2025, Gurobi Optimization, LLC# Read diet model data from an Excel spreadsheet (diet.xlsx).# Pass the imported data into the diet model (dietmodel.py).## Note that this example reads an external data file (..\data\diet.xlsx).# As a result, it must be run from the Gurobi examples/python directory.## This example uses Python package 'openpyxl', which isn't included# in most Python distributions. You can install it with# 'pip install openpyxl'.importosimportopenpyxlimportdietmodel# Open 'diet.xlsx'book=openpyxl.load_workbook(os.path.join("..","data","diet.xlsx"))# Read min/max nutrition info from 'Categories' sheetsheet=book["Categories"]categories=[]minNutrition={}maxNutrition={}forrowinsheet.iter_rows():category=row[0].valueifcategory!="Categories":categories.append(category)minNutrition[category]=row[1].valuemaxNutrition[category]=row[2].value# Read food costs from 'Foods' sheetsheet=book["Foods"]foods=[]cost={}forrowinsheet.iter_rows():food=row[0].valueiffood!="Foods":foods.append(food)cost[food]=row[1].value# Read food nutrition info from 'Nutrition' sheetsheet=book["Nutrition"]nutritionValues={}forrowinsheet.iter_rows():ifrow[0].value==None:# column labels - categoriescats=[v.valueforvinrow]else:# nutrition valuesfood=row[0].valueforcolinrange(1,len(row)):nutritionValues[food,cats[col]]=row[col].valuedietmodel.solve(categories,minNutrition,maxNutrition,foods,cost,nutritionValues)
Help and Feedback