Guest User

Untitled

a guest
Dec 10th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. df <- cbind(expand.grid(shop=1:3,supply=1:2),distance=c(2.8,5.4,1.4,4.2,3.0,6.3))
  2.  
  3. df["Entry"] <- 1:dim(df)[[1]]
  4.  
  5. shop.mat <- table(df$shop,df$Entry)
  6. shop.mat
  7.  
  8. 1 2 3 4 5 6
  9. 1 1 0 0 1 0 0
  10. 2 0 1 0 0 1 0
  11. 3 0 0 1 0 0 1
  12.  
  13. supply.mat <- table(df$supply,df$Entry)
  14. supply.mat
  15.  
  16. 1 2 3 4 5 6
  17. 1 1 1 1 0 0 0
  18. 2 0 0 0 1 1 1
  19.  
  20. N_supply <- dim(supply.mat)[[1]]
  21. N_shop <- dim(shop.mat)[[1]]
  22. N_entry <- dim(df)[[1]]
  23.  
  24. constr.mat <- NULL
  25. dir <- NULL
  26. rhs <- NULL
  27.  
  28. constr.mat <- rbind(constr.mat,cbind(shop.mat,matrix(0,N_shop,N_supply)))
  29. dir <- c(dir,rep("==",N_shop))
  30. rhs <- c(rhs,rep(1,N_shop))
  31.  
  32. obj <- c(aggregate(distance~Entry,df,c)[["distance"]],rep(0,N_supply))
  33.  
  34. constr.mat <- rbind(constr.mat,cbind(supply.mat,-diag(table(df$supply))))
  35. dir <- c(dir,rep("<=",N_supply))
  36. rhs <- c(rhs,rep(0,N_supply))
  37.  
  38. constr.mat <- rbind(constr.mat,c(rep(0,N_entry),rep(1,N_supply)))
  39. dir <- c(dir,"<=")
  40. rhs <- c(rhs,2)
  41.  
  42. require(lpSolve)
  43. sol <- lp("min", obj, constr.mat, dir, rhs, all.bin = TRUE,num.bin.solns = 1, use.rw=FALSE, transpose.constr=TRUE)
  44.  
  45. sol$solution
  46. [1] 1 0 1 0 1 0 1 1
  47.  
  48. sol$objval
  49. [1] 7.2
  50.  
  51. selected_Entry <- dimnames(shop.mat)[[2]][as.logical(sol$solution[1:N_entry])]
  52. selected_Entry
  53. [1] "1" "3" "5"
  54.  
  55. df[df$Entry %in% selected_Entry,]
  56. shop supply distance Entry
  57. 1 1 1 2.8 1
  58. 3 3 1 1.4 3
  59. 5 2 2 3.0 5
  60.  
  61. constr.mat %*% sol$solution
  62. [,1]
  63. 1 1
  64. 2 1
  65. 3 1
  66. 1 -1
  67. 2 -2
  68. 2
  69.  
  70. constr.mat %*% c(1,1,1,0,0,0,1,1)
  71. [,1]
  72. 1 1
  73. 2 1
  74. 3 1
  75. 1 0
  76. 2 -3
  77. 2
  78.  
  79. constr.mat <- rbind(constr.mat,cbind(supply.mat,-diag(table(df$supply))),cbind(supply.mat,-diag(table(df$supply))))
  80. dir <- c(dir,rep("<=",N_supply),rep(">=",N_supply))
  81. rhs <- c(rhs,rep(0,N_supply),1-table(df$supply))
  82.  
  83. paste(t(unlist(constr.mat %*% sol$solution)),dir,rhs)
  84. [1] "1 == 1" "1 == 1" "1 == 1" "-1 <= 0"
  85. [5] "-2 <= 0" "2 <= 2" "-1 <= 0" "-2 <= 0"
  86. [9] "-1 >= -2" "-2 >= -2"
  87.  
  88. paste(t(unlist(constr.mat %*% c(1,1,1,0,0,0,1,1))),dir,rhs)
  89. [1] "1 == 1" "1 == 1" "1 == 1" "0 <= 0"
  90. [5] "-3 <= 0" "2 <= 2" "0 <= 0" "-3 <= 0"
  91. [9] "0 >= -2" "-3 >= -2"
Add Comment
Please, Sign In to add comment