R中的约束优化问题

Ric*_*rod 2 r

我正在尝试设置一个优化脚本,它将查看一组模型,拟合曲线到模型,然后根据一些参数进行优化.

从本质上讲,我的收入是成本的函数,功能递减,我有多个投资组合,比如4或5.作为输入,我有成本和收入数据,按设定的增量.我想要做的是将曲线拟合到Revenue = A*cost ^ B形式的投资组合,然后针对不同的投资组合进行优化,以找到每个投资组合之间针对设定预算的最佳成本分配.

下面的代码(我很抱歉它的优点,我确信有很多改进!)基本上读取我的数据,在这种情况下,模拟,创建必要的数据框架(这可能是我的不足之处进来),计算每个模拟曲线的必要变量,并生成图形以检查数据的拟合曲线.

我的问题是,现在我有5条曲线:

收入= A*成本^ B(每个功能的A,B和成本不同)

我想知道,鉴于5个变量,我应该如何在它们之间分摊成本,所以我想优化5条曲线的总和

成本<=预算

我知道我需要使用constrOptim,但我花了几个小时把头撞在桌子上(几个小时,不是真的敲我的脑袋......)我仍然无法弄清楚如何设置功能以便它最大化收入,受成本限制......

在这里的任何帮助将不胜感激,这已经困扰了我几个星期.

谢谢!

丰富

## clear all previous data

rm(list=ls())
detach()
objects()

library(base)
library(stats)

## read in data

sim<-read.table("input19072011.txt",header=TRUE)
sim2<-data.frame(sim$Wrevenue,sim$Cost)

## identify how many simulations there are - here you can change the 20 to the number of steps but all simulations must have the same number of steps

portfolios<-(length(sim2$sim.Cost)/20)

## create a matrix to input the variables into

a<-rep(1,portfolios)
b<-rep(2,portfolios)
matrix<-data.frame(a,b)

## create dummy vector to hold the revenue predictions

k<-1
j<-20

for(i in 1:portfolios){

test<-sim2[k:j,]

rev9<-test[,1]
cost9<-test[,2]

ds<-data.frame(rev9,cost9)

rhs<-function(cost, b0, b1){
b0 * cost^b1

m<- nls(rev9 ~ rhs(cost9, intercept, power), data = ds, start = list(intercept = 5,power = 1))

matrix[i,1]<-summary(m)$coefficients[1]
matrix[i,2]<-summary(m)$coefficients[2]

k<-k+20
j<-j+20

}

## now there exists a matrix of all of the variables for the curves to optimise

matrix
multiples<-matrix[,1]
powers<-matrix[,2]
coststarts<-rep(0,portfolios)

## check accuracy of curves

k<-1
j<-20

for(i in 1:portfolios){

dev.new()

plot(sim$Wrevenue[k:j])
lines(multiples[i]*(sim$Cost[k:j]^powers[i]))

k<-k+20
j<-j+20

}
Run Code Online (Sandbox Code Playgroud)

Vin*_*ynd 5

如果要查找 最大值 受限制 (和)的值cost[1],...,可以按如下方式对可行解决方案组进行参数化cost[5]revenue[1]+...+revenue[5]cost[1]+...+cost[5]<=budget0 <= cost[i] <= budget

cost[1] = s(x[1]) * budget
cost[2] = s(x[2]) * ( budget - cost[1] )
cost[3] = s(x[3]) * ( budget - cost[1] - cost[2])
cost[4] = s(x[4]) * ( budget - cost[1] - cost[2] - cost[3] )
cost[5] = budget - cost[1] - cost[2] - cost[3] - cost[4]
Run Code Online (Sandbox Code Playgroud)

where x[1],...,x[4]是要查找的参数(对它们没有约束),s是实线R和段(0,1)之间的任何双射.

# Sample data
a <- rlnorm(5)
b <- rlnorm(5)
budget <- rlnorm(1)

# Reparametrization
s <- function(x) exp(x) / ( 1 + exp(x) )
cost <- function(x) {
  cost <- rep(NA,5)
  cost[1] = s(x[1]) * budget
  cost[2] = s(x[2]) * ( budget - cost[1] )
  cost[3] = s(x[3]) * ( budget - cost[1] - cost[2])
  cost[4] = s(x[4]) * ( budget - cost[1] - cost[2] - cost[3] )
  cost[5] = budget - cost[1] - cost[2] - cost[3] - cost[4]
  cost  
}

# Function to maximize
f <- function(x) {
  result <- sum( a * cost(x) ^ b )
  cat( result, "\n" )
  result
}

# Optimization
r <- optim(c(0,0,0,0), f, control=list(fnscale=-1))
cost(r$par)
Run Code Online (Sandbox Code Playgroud)