lpSolve
*1を使って線形計画法を解いてみた。理論は難しいから敬遠していたがソルバー使うと一瞬で解けて気持ち良い。
関数lp
に渡すパラメータは以下の通り。第一パラメータは"max"か"min"。詳しいことはrdocumentationなどを参照。
- f_obj : ベクトル。目的関数の係数を格納する。
- f_con : 行列。制約条件の係数を格納する。
- f_dir : ベクトル。不等号または等号を格納する。
- f_rhs : ベクトル。right hand side(右辺)、制約条件の右辺の係数(値)を格納する。
以下実例。
install and load library
install.packages('lpSolve') library(lpSolve)
その1*2
線型計画法
f_obj <- c(1,1) #目的関数の係数 f_con <- matrix(c(1,2,2,1),ncol=2) #制約条件を行列で f_dir <- c("<=","<=") #不等号? f_rhs <- c(4,4) # 不等号の右側
最適解を表示
lp("max",f_obj,f_con,f_dir,f_rhs)
最適解を取る時の引数
lp("max",f_obj,f_con,f_dir,f_rhs)$solution
整数計画法
lp("max",f_obj,f_con,f_dir,f_rhs,int.vec=1:2) #int.vecはintegerなvectorのindicesを与えていると思われる。 lp("max",f_obj,f_con,f_dir,f_rhs, int.vec=1:2)$solution
0-1 整数計画法
f_obj01 <- c(16,19,23,11) f_con01 <- matrix( c(2,3,4,5), ncol=4, nrow=1) f_dir01 <- c("<=") f_rhs01 <- c("6") lp("max",f_obj01,f_con01,f_dir01,f_rhs01,all.bin=T) lp("max",f_obj01,f_con01,f_dir01,f_rhs01,all.bin=T)$sol
その2*3
f_obj3 <- c(4,6) f_con3 <- matrix(c(1,3,0,2,0,4),nrow=3,ncol=2) f_dir3 <- rep("<=",3) f_rhs3 <- c(8,12,12) f_sol3 <- lp("max", f_obj3,f_con3,f_dir3,f_rhs3) f_sol3 f_sol3$sol
f_obj4 <- c(20,30) f_con4 <- matrix(c(1,3,3,2,4,1),nrow=3,ncol=2) f_dir4 <- rep("<=",3) f_rhs4 <- c(800,1800,1500) f_sol4 <- lp("max",f_obj4,f_con4,"<=",f_rhs4) f_sol4 f_sol4$sol
その3*4
f_obj5 <- c(1,1) f_con5 <- matrix(c(3,1,1,3),nrow=2,ncol=2) f_dir5 <- rep("<=",2) f_rhs5 <- c(9,6) f_sol5 <- lp("max",f_obj5,f_con5,f_dir5,f_rhs5) f_sol5 f_sol5$solution