library(lpSolveAPI) #Linear program representation of transportation assignment model #in this model we're solving a problem of reassigning deputy patrol cars #between two different groups of positions. These reassignments are done #to minimize response times, and are calculated from historic call positions in #Maricopa County. We have a group of four cars we're reassigning, and we have #distances to each of the new positions #make.lp(number of constraints, number of decision variables, error reporting) lpmodel<-make.lp(9, 16, "full") #set objective function, this will be distance between previous position and #posible next position. The first row is car 1 distance to the four positions for the next hour #row two is car 2 distance to the those four points, and so forth. set.objfn(lpmodel, c(0.767,14.478,20.088, 24.415, 16.534,2.928,3.358,12.426, 22.115,18.007,18.431,2.657, 17.545,3.824,2.343,18.130)) #model, numeric vector with constraint coefficient, sign, rhs value of constraint #so we have first four variables represent distance from first position to the four #positions in the next shift. Since you can only occupy one of the positions, you'll #get something like 1,1,1,1,0,0,0... = 1, zeroing out the other three transfer positions #for the first constraint. #basically, these constraints mean that each former position will give up one car, and only #one car. add.constraint(lpmodel, c(1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), "=", 1) add.constraint(lpmodel, c(0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0), "=", 1) add.constraint(lpmodel, c(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0), "=", 1) add.constraint(lpmodel, c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1), "=", 1) #these constraints are necessary so that the positions that we're moving to #will each have one car moving to them, and only one car add.constraint(lpmodel, c(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0), "=", 1) add.constraint(lpmodel, c(0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0), "=", 1) add.constraint(lpmodel, c(0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0), "=", 1) add.constraint(lpmodel, c(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), "=", 1) #need a constraint to make sure model variables #don't go negative add.constraint(lpmodel, c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ">=", 0) #now we need to define all the variables as integer #since we can't chop up cars and sent the pieces around columns<-seq(1, 16) set.type(lpmodel, columns, type = c("integer")) #RowNames <- (cloud\$car_position) #ColNames <- (qoeload\$qoegroups) #dimnames(lpmodel) <- list(RowNames, ColNames) #now we'll solve our model solve(lpmodel) #take a look at our objective get.objective(lpmodel) #look at how our variables ended up get.variables(lpmodel) get.constraints(lpmodel) #this is the lp format of our problem write.lp(lpmodel,'model.lp',type='lp')