【问题标题】:lpsolve with constraints in rlpsolve 与 r 中的约束
【发布时间】:2021-08-12 04:16:08
【问题描述】:

我想使用 R 解决优化问题,使用 lpSolve 可以执行类似于 excel 中的求解器插件的过程。下面是一个简单的案例,我想专门使用 lpSolve 最大化 npv 值。

df<-structure(list(id = c(1, 2, 3, 4, 5, 6, 7, 8), Revenue = c(109, 
111, 122, 139, 156, 140, 137, 167)), row.names = c(NA, 8L), class = "data.frame")

dcf <- function(x, r, t0=FALSE){
  # calculates discounted cash flows (DCF) given cash flow and discount rate
  #
  # x - cash flows vector
  # r - vector or discount rates, in decimals. Single values will be recycled
  # t0 - cash flow starts in year 0, default is FALSE, i.e. discount rate in first period is zero.
  if(length(r)==1){
    r <- rep(r, length(x))
    if(t0==TRUE){r[1]<-0}
  }
  x/cumprod(1+r)
}

npv <- function(x, r, t0=FALSE){
  # calculates net present value (NPV) given cash flow and discount rate
  #
  # x - cash flows vector
  # r - discount rate, in decimals
  # t0 - cash flow starts in year 0, default is FALSE
  sum(dcf(x, r, t0))
}
npv(df$Revenue,.2)
#Non optimized npv yields a value of 492.
#How can i use lpSolve to optimize my table? Said another way how can I rearrange the table to maximize npv using lpSolve?


更复杂的问题涉及具有以下规则的惩罚列: Id 代表项目。

  1. 如果 ID 项目不是开始期间(第 1 行)。检查先前的 Id 是否在 2 的增量内(从其他先前行中减去行 Id 的绝对值。如果为真,则将收入惩罚 20%。我认为这个问题仍然涉及解决正确的顺序。我该如何优化这个功能?
#Randomize order to give base npv. Now i need to optimize the order to find max value
df<- df%>%mutate(random_sort= sample(nrow(df)))

x=function(i){
  df_fcn<- i
  df_fcn<- df_fcn%>%mutate(Penalty= if_else(abs(random_sort-lag(random_sort))>2,1,.8))%>%mutate(Penalty=ifelse(is.na(Penalty),1,Penalty))
  df_fcn<- df_fcn%>%mutate(Revenue_Penalized= Revenue*Penalty)
  
  npv(df_fcn$Revenue_Penalized,.2)
  }

【问题讨论】:

  • npv(sort(df$Revenue, decreasing = TRUE), 0.2)。我不明白你想用 lpSolve 做什么。
  • 只选择 NPV 最大的项目并不是真正的优化。如果您可以选择不同的项目并有一些预算(每个时期),它会变得更有趣。
  • 我的实际问题涉及根据价值和与其他数据的距离来安排一系列地理空间数据。我只是想了解 lpSolve 的工作原理,以便我可以在我的实际数据上实现。如果需要,我可以分享一个实际示例
  • 第二个问题更能代表我的数据。上一个问题可能对您了解我为什么需要 lpSolve 有用。 stackoverflow.com/questions/68744583/…

标签: r optimization linear-programming lpsolve


【解决方案1】:

我想出的最好办法是随机重新排列数据并找到最大值。

schedule_function=function(i){
  i<- i%>%mutate(random_sort=sample(random_sort))
  df_fcn<- i%>%mutate(Penalty= if_else(abs(random_sort-lag(random_sort))>2,1,.8))%>%mutate(Penalty=ifelse(is.na(Penalty),1,Penalty))
  df_fcn<- df_fcn%>%mutate(Revenue_Penalized= Revenue*Penalty)
  final_df<-print(df_fcn)
  npv(df_fcn$Revenue_Penalized,.2)
}


n <- 1:10000
MAX = -Inf    ## initialize maximum
for (i in 1:length(n)) {
  x <- schedule_function(df)
  if (x > MAX) MAX <- x

  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    相关资源
    最近更新 更多