Docsity

ISYE 6501 Homework assignment 11, Assignments of Analytical Techniques

Toggle sidebar
bg1
Homework Assignment 11
Question1
1. Formulate an optimization model (a linear program) to find the cheapest diet that satisfies the maximum and
minimum daily nutrition constraints, and solve it using PuLP. Turn in your code and the solution. (The optimal
solution should be a diet of air-popped popcorn, poached eggs, oranges, raw iceberg lettuce, raw celery, and
frozen broccoli. UGH!)
Methodology + Code
1. Installed packages for linear programming solver + to read excel files and then imported data
#install packages
install.packages("readxl")
install.packages("lpSolve")
#run
library(readxl)
library(lpSolve)
diet <- read_excel("diet.xls")
2. Separated the rows with food and nutrient breakdown and the final row with min/max requirements
# Exclude bottom rows on requirements
food_data <- diet[!is.na(diet$Foods), ]
# Get the bottom rows to get your min and max requirements
req_data <- diet[diet$`Serving Size` %in% c("Minimum daily intake", "Maximum daily intake"), ]
3. Then set the nutrients columns, foods columns, and variables for cost/number of foods to be used to create a
matrix, as well as set the min and max values.
# Set Nutrient columns
nutrients <- c(
"Calories",
"Cholesterol mg",
"Total_Fat g",
"Sodium mg",
"Carbohydrates g",
"Dietary_Fiber g",
"Protein g",
"Vit_A IU",
"Vit_C IU",
"Calcium mg",
"Iron mg"
)
#Set food names and number of foods
foods <- food_data$Foods
pf3
pf4
pf5

Partial preview of the text

Download ISYE 6501 Homework assignment 11 and more Assignments Analytical Techniques in PDF only on Docsity!

Homework Assignment 11

Question

  1. Formulate an optimization model (a linear program) to find the cheapest diet that satisfies the maximum and minimum daily nutrition constraints, and solve it using PuLP. Turn in your code and the solution. (The optimal solution should be a diet of air-popped popcorn, poached eggs, oranges, raw iceberg lettuce, raw celery, and frozen broccoli. UGH!)

Methodology + Code

  1. Installed packages for linear programming solver + to read excel files and then imported data

#install packages install.packages("readxl") install.packages("lpSolve")

#run library(readxl) library(lpSolve)

diet <- read_excel("diet.xls")

  1. Separated the rows with food and nutrient breakdown and the final row with min/max requirements

Exclude bottom rows on requirements

food_data <- diet[!is.na(diet$Foods), ]

Get the bottom rows to get your min and max requirements

req_data <- diet[diet$Serving Size %in% c("Minimum daily intake", "Maximum daily intake"), ]

  1. Then set the nutrients columns, foods columns, and variables for cost/number of foods to be used to create a matrix, as well as set the min and max values.

Set Nutrient columns

nutrients <- c( "Calories", "Cholesterol mg", "Total_Fat g", "Sodium mg", "Carbohydrates g", "Dietary_Fiber g", "Protein g", "Vit_A IU", "Vit_C IU", "Calcium mg", "Iron mg" )

#Set food names and number of foods foods <- food_data$Foods

n_foods <- length(foods)

Set the cost value by row

cost <- food_data$Price/ Serving

Nutrient matrix of

A <- as.matrix(food_data[, nutrients])

Min and max requirement values by column

min_req <- as.numeric(req_data[req_data$Serving Size == "Minimum daily intake", nutrients]) max_req <- as.numeric(req_data[req_data$Serving Size == "Maximum daily intake", nutrients])

  1. Then we set the LP solver function values, obj is the cost of food which will be optimized, and then set a matrix for the minimum and maximum as an input into the function, we set a direction which matches to the matrix and optimizes for minimum and maximum logic. Finally the const.rhs part of the linear programing function which uses the values we set as minimum and maximum requirements.

Objective: minimize total cost

obj <- cost

Constraints:

For each nutrient j:

sum_i a_ij x_i >= min_j

sum_i a_ij x_i <= max_j

#To set the A matrix as transposed, and done twice because it requires min and max const.mat <- rbind(t(A), t(A))

#This tells the solver that the first 11 rows above are min, and second max const.dir <- c(rep(">=", length(nutrients)), rep("<=", length(nutrients)))

#setting the constraints for the function const.rhs <- c(min_req, max_req)

  1. Final part was to run the main lp() function from the library, which sets the direction to what the function is looking to optimize for, the objective to optimize for cost, and then using the input matrices, directions, and requirements that we provided above. I then printed the results from the solution to give me food and servings.

Run the lpsolver function

solution1 <- lp( direction = "min", objective.in = obj, const.mat = const.mat, const.dir = const.dir, const.rhs = const.rhs )

Print results

selected_lps <- data.frame( Food = foods, Servings = solution1$solution )

selected_lps <- selected1[selected1$Servings, ] print(selected_lps)

nutrition_lower <- cbind(t(A), matrix(0, nrow = length(nutrients), ncol = n_foods)) nutrition_upper <- cbind(t(A), matrix(0, nrow = length(nutrients), ncol = n_foods))

  1. Set the constraints that if a food is selected then it has to be at least 0.1g of servings.

Constraint that if food is selected, then at least 0.1 serving

x_i >= 0.1 y_i

Also need - x_i <= M y_i so that x_i = 0 when y_i = 0

link_lower <- cbind(diag(n_foods), -0.1 * diag(n_foods)) # x_i - 0.1 y_i >= 0 link_upper <- cbind(diag(n_foods), -1000 * diag(n_foods)) # x_i - 1000 y_i <= 0

  1. Set the part of the function that says both celery and broccoli cannot both be selected

Celery and broccoli constraint -> y_celery + y_broccoli <= 1 the mathematical formula for at most one and not both.

#returns the row position of the food list celery_idx <- which(foods == "Celery, Raw") broccoli_idx <- which(foods == "Frozen Broccoli")

#This part sets the y_i value to 1 if selected celery_broccoli <- rep(0, n_vars) celery_broccoli[n_foods + celery_idx] <- 1 celery_broccoli[n_foods + broccoli_idx] <- 1

  1. Set the function regarding what classifies as meat/poultry and making sure that for the objective function atleast 3 different foods are selected from this category.

At least 3 meat/poultry/fish/egg foods constraint

#Set the values that are protein protein_foods <- c( "Roasted Chicken", "Poached Eggs", "Scrambled Eggs", "Bologna,Turkey", "Frankfurter, Beef", "Ham,Sliced,Extralean", "Kielbasa,Prk", "Pork", "Sardines in Oil", "White Tuna in Water" )

protein_idx <- which(foods %in% protein_foods)

#Gives value 1 to where protein meal is selected protein_constraint <- rep(0, n_vars) protein_constraint[n_foods + protein_idx] <- 1

Then LInk all the constraints together

#The constraint values const.mat <- rbind( nutrition_lower, nutrition_upper, link_lower, link_upper, celery_broccoli, protein_constraint )

#The constraint directions const.dir <- c( rep(">=", length(nutrients)), # nutrition minimums rep("<=", length(nutrients)), # nutrition maximums rep(">=", n_foods), # x_i - 0.1 y_i >= 0 rep("<=", n_foods), # x_i - M y_i <= 0 "<=", # celery + broccoli <= 1 ">=" # at least 3 protein foods )

#The constraint directions values const.rhs <- c( min_req, # nutrition minimums max_req, # nutrition maximums rep(0, n_foods), # x_i - 0.1 y_i >= 0 rep(0, n_foods), # x_i - M y_i <= 0 1, # celery + broccoli <= 1 3 # at least 3 protein foods )

And run the solver function and print results

Only second half of the values are binary

binary_positions <- (n_foods + 1):(2 * n_foods)

solution2 <- lp( direction = "min", objective.in = obj2, const.mat = const.mat, const.dir = const.dir, const.rhs = const.rhs, binary.vec = binary_positions )

Print results

#For servings x_sol <- solution2$solution[1:n_foods] #for binary choices y_sol <- solution2$solution[(n_foods + 1):(2 * n_foods)]