Pacotes
suppressPackageStartupMessages({
library(tidyverse)
library(glpkAPI)
})
Modelo em GNU MathProg
model_start <- 'set PONTOS;
param X{PONTOS};
param Y{PONTOS};
var u{PONTOS} >= 0;
var b0;
var b1;
minimize z:sum{i in PONTOS} u[i];
s.t. R1{i in PONTOS}: u[i] >= Y[i] - b0 - b1*X[i];
s.t. R2{i in PONTOS}: u[i] >= -(Y[i] - b0 - b1*X[i]);
solve;
data;
param : PONTOS : X Y := '
model_end <- ';
end;
'
Dados
#set.seed(12345)
n = 100
X = runif(n, 0, 10)
Y = 5*X + 10 + rnorm(n, 0, 10)
model_data <- paste("\t", 1:n, "\t", X[1:n], "\t", Y[1:n], "\n", collapse = "") #, "\b \b;\n"}
Escrevendo modelo em arquivo temporário
temp <- tempfile(fileext = ".mod")
write_lines(paste(model_start, model_data, model_end, sep = '\n'), temp)
Usando o pacote glpkAPI
mip <- initProbGLPK()
setProbNameGLPK(mip, "MAD")
mad <- mplAllocWkspGLPK()
result <- mplReadModelGLPK(mad, temp, skip=0)
result <- mplGenerateGLPK(mad)
result <- mplBuildProbGLPK(mad, mip)
# Solve
result <- solveSimplexGLPK(lp = mip)
numrows <- getNumRowsGLPK(mip)
numcols <- getNumColsGLPK(mip)
z = getRowPrimGLPK(mip, 1)
b0 = getColPrimGLPK(mip, numcols - 1)
b1 = getColPrimGLPK(mip, numcols)
glpkAPI::delProbGLPK(mip)
Erro
cat("Intercepto MAE: ", round(abs(b0 - 10), 3),
"\nIntercepto MQE: ", round(abs(coefficients["(Intercept)"] - 10), 3),
"\nInclinação MAE: ", round(abs(b1 - 5), 3),
"\nInclinação MQE: ", round(abs(coefficients["X"] - 5), 3))
## Intercepto MAE: 0.287
## Intercepto MQE: 1.742
## Inclinação MAE: 0.029
## Inclinação MQE: 0.313