0

I have a working LPSolve Model that takes 4 binary decision variables, with the following working mechanisms: The sum of the count of the 4 different binary variables are subject to constraints (ie. count of Binary 1 < 20, count of Binary 2 < 10...). Each row must also only have 1 binary variable set to 1 (ie, in each row: Binary 1 + Binary 2 + Binary 3 + Binary 4 = 1)

Now, I need to maintain binary decision variables, but for the constraint where we count the occurrence of each binary variable, I need to provide weights to each row (i.e. let's say for Row 1, we use Binary 2. For that row, any of the binary variables has a weight of 0.5. Thus, this adds 0.5 to our count of Binary 2 variables. For row 2, we use Binary 3, and that row's weight is 0.6. Thus, we add 0.6 to our count of Binary 3) and so on and so forth. The sums of the binary variable's weights is subject to constraints.

I would define the weighting as follows:

# Set the seed for reproducibility
set.seed(123)

# Create random data frame
data <- data.frame(
  Weights = runif(5)*0.2,
  Column1 = runif(5),
  Column2 = runif(5),
  Column3 = runif(5),
  Column4 = runif(5)
)

Here is the R Code I am using to develop a solution to my binary linear model. Everything works as expected for my first part, but I can't seem to figure out how to add in row weights that only matter to the constraint that sums the count of each binary variable.

install.packages("lpSolve")
# Set the seed for reproducibility
set.seed(123)

# Create random data frame
data <- data.frame(
  Column1 = runif(5),
  Column2 = runif(5),
  Column3 = runif(5),
  Column4 = runif(5)
)

MAX_1 <- 3
MAX_2 <- 1
MAX_3 <- 2
MAX_4 <- 1000000 #no constraint but want to maintain in case of modifications in future


#Create a matrix of the figures
f.obj = data %>% 
  as.matrix()

#F.con is where we will prepare constraints.
f.con <- rbind(cbind(diag(nrow(f.obj)), diag(nrow(f.obj)), diag(nrow(f.obj)), diag(nrow(f.obj))),
               diag(4)[,rep(c(1,2,3,4), each=nrow(f.obj))])

#f.dir is the logical operator for constraints   
f.dir = c(rep("=", nrow(f.obj)),
          rep("<=", 4))

#f.rhs is the right hand side of our constraints. That is, what our actual constraints are. In this case:
# each row can only have 1 binary variable. We also are limiting the number of binary variables we use
f.rhs = c(rep(1,nrow(f.obj)),
          MAX_1, MAX_2, MAX_3, MAX_4)

#goal is to maximize
result <- lpSolve::lp("max", f.obj, f.con, f.dir, f.rhs, all.bin=T)


Par <- result$solution
P <- matrix(Par, nrow = nrow(f.obj))

data_output <- cbind(data, P)

Any help would be greatly appreciated!

Max Grove
  • 1
  • 1

0 Answers0