The Diet Problem with Rglpk

This relates to Coursera's “Linear and Integer Programming” course, September 2013.

Data Preparation

The files we need for GLPK command-line use were supplied by the course tutors in zip format.

Unfortunately, I haven't yet found any way to get Rglpk to accept separate model and data files. These can be concatenated (e.g. cat diet.model diet.data > diet.both), but it is also necessary to change the “end;” line below the model section to a “data;” line.

A lot of information in the MathProg files is ignored by Rglpk_read_file(), including row names.

I created a separate file “foods.lis” containing just these names.

Calculation

# Filename for model and data (and constraints)single file!)
MathProgFileName <- "diet.both"
# the more complex file 'dietSet.both' gives identical results: extra info
# in dietSet is ignored

# The R-CRAN package Rglpk must be installed on your system
require("Rglpk")
## Loading required package: Rglpk Loading required package: slam Using the
## GLPK callable library version 4.45

# Build the model from a MathProg file
x <- Rglpk_read_file(MathProgFileName, type = "MathProg")

# Run the solver
res <- Rglpk_solve_LP(x$objective, x$constraints[[1]], x$constraints[[2]], x$constraints[[3]], 
    x$bounds, x$types, x$maximum)

Results

# No row names are imported by Rglpk_read_file() so fetch these separately
foodnames <- t(read.delim("foods.lis", sep = "\n", header = FALSE))

amount <- res$solution
names(amount) <- foodnames
amount[amount != 0]
##        Carrots_Raw     Potatoes_Baked          Skim_Milk 
##             0.2358             3.5449             2.1678 
##      Peanut_Butter Popcorn_Air-Popped 
##             3.6008             4.8232

# Get the optimal objective value
optimalCost <- res$optimum
optimalCost  # in $ for the example given
## [1] 0.956