#Copyright (C) 2013-2015 Abdalkarim Awad #if the package is not yet installed, uncomment the following #line to install the nonlinear optimization package #install.packages("nloptr") library('nloptr') #use the library #objective function #It is the sum of all costs of all generators #let PA=x1, PB=x2 #f(x)=399.8+11.69*x[1]+0.00334*x[1]^2+616.9+11.83*x[2]+0.00149*x[2]^2 function_f <- function(x){ return(399.8+11.69*x[1]+0.00334*x[1]^2+616.9+11.83*x[2]+0.00149*x[2]^2 ) } # constraint function g(x), #x1+x2=600 ==> x1+x2-600=0 #the optimization method COBYLA supports equality constraints #by transforming them into two inequality constraints. #x1+x2-600=0 ==> x1+x2-600<=0 and x1+x2-600>=0 #==> x1+x2-600<=0 and -x1-x2+600<=0 const_g<- function( x) { return(rbind(c(x[1]+x[2]-600), -c(+x[1]+x[2]-600))) } # Solve using NLOPT_LN_COBYLA results <- nloptr( x0=c(100,100), #initial values eval_f=function_f, #min (f(x)) lb = c(0,0), #lower bound for x1 and x2 ub = c(Inf,Inf), #upper bound for x1 and x2 eval_g_ineq= const_g, #equality and inequality constraints opts = list("algorithm"="NLOPT_LN_COBYLA",xtol_rel = 1e-4)) #options print( results ) min_value=results$objective x=results$solution PA=x[1] PB=x[2] min_value PA PB