0

I am trying to use lpsolve in R to solve the following lp program. I want to maximize the obj function. The constraints are that the variable weights sum up to 1, and the individual weights have to be either 0 or a minimum of 0.125, and a maximum of .5. I Was under the impression I can solve this by turning the variables into binary variables, but I seem to be running into issues when I try to solve this. Any help would be greatly appreciated!

library(lpsolveapi)

obj.coef <- c(3, 2, 5, 4)

lpmodelapi <- make.lp(0,length(obj.coef))
lp.control(lpmodelapi,sense='max')
set.objfn(lpmodelapi,obj.coef)
add.constraint(lpmodelapi, c(2, 1, 4, 3), ">=", 2)
add.constraint(lpmodelapi, c(1,1,1,1),"=", rhs =1)
add.constraint(lpmodelapi,c(1,0,0,0), ">=",.125)
add.constraint(lpmodelapi,c(0,1,0,0), ">=",.125)
add.constraint(lpmodelapi,c(0,0,1,0), ">=",.125)
add.constraint(lpmodelapi,c(0,0,0,1), ">=",.125)

add.constraint(lpmodelapi,c(1,0,0,0), "<=",.5)
add.constraint(lpmodelapi,c(0,1,0,0), "<=",.5)
add.constraint(lpmodelapi,c(0,0,1,0), "<=",.5)
add.constraint(lpmodelapi,c(0,0,0,1), "<=",.5)
set.type(lpmodelapi, 1:length(obj.coef), type = "binary")  


solve(lpmodelapi)
get.variables(lpmodelapi)
  • 1
    You are describing *semi-continuous variables* that are either zero or within a range. Try that for search term and this: https://stackoverflow.com/questions/40900940/linear-programming-with-conditional-constraints-in-r/40902869#40902869 – AirSquid Jul 14 '23 at 16:12
  • From the documentation of `lpsolveapi`, _if you don't need callbacks it is recommended to use ROI (https://cran.r-project.org/package=ROI, https://roi.r-forge.r-project.org/) instead_ – Reinderien Jul 15 '23 at 01:48
  • But what @AirSquid says is correct, and is natively supported: [set.semicont](https://www.rdocumentation.org/packages/lpSolveAPI/versions/5.5.2.0-17.9/topics/set.semicont) – Reinderien Jul 15 '23 at 01:50
  • Thank you so much. I think I am on the right track now. – akennedy12345 Jul 15 '23 at 13:59
  • I was able to get this to work, however it is insanely slow. I have approx 5000 decision variables. I am assuming I will need to use a more efficient solver for this? or is there an lpsolve solution that could possibly work? – akennedy12345 Jul 18 '23 at 16:07

0 Answers0