Code Monkey home page Code Monkey logo

cvxr's Introduction

CVXR

R-CMD-check CRAN_Status_Badge

CVXR provides an object-oriented modeling language for convex optimization, similar to CVX, CVXPY, YALMIP, and Convex.jl. It allows the user to formulate convex optimization problems in a natural mathematical syntax rather than the restrictive standard form required by most solvers. The user specifies an objective and set of constraints by combining constants, variables, and parameters using a library of functions with known mathematical properties. CVXR then applies signed disciplined convex programming (DCP) to verify the problem’s convexity. Once verified, the problem is converted into standard conic form using graph implementations and passed to a cone solver such as ECOS or SCS.

CVXR includes several open source solvers in addition to the default OSQP, ECOS and SCS. Recent (1.x+) versions also include support for commercial solvers such as MOSEK, GUROBI and CPLEX.

For details and examples, we refer you to Fu, Narasimhan, Boyd (2020). If you use CVXR in your work, please cite this reference. (The R command citation("CVXR", bibtex = TRUE) will also give you a bibtex-formatted entry.)

Installation

This package is now released on CRAN, so you can install the current released version as you would any other package for R, version 3.4 and higher. (CVXR is known to work with earlier versions of R too, but we don't check our releases against older versions of R.)

install.packages('CVXR', repos = "https://CRAN.R-project.org")

Development versions can be installed from the Github repository assuming you have the development tools for R available, including the C compilers etc. Execute:

library(devtools)
install_github("cvxgrp/CVXR")

Tutorial

A number of tutorial examples are available on the CVXR website along with links to our useR! 2019 short-course.

cvxr's People

Contributors

anqif avatar bnaras avatar dkang9503 avatar paulrosenfield avatar tvedebrink avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cvxr's Issues

Inconsistent error messages: DCP rules vs DGP rules

I have a problem, that is probably not convex, and so I wouldn't expect it to be solved by CVXR. However, the solve() call gives conflicting error messages if you run this:

#eg modified from https://cvxr.rbind.io/cvxr_examples/cvxr_gentle-intro/
library(CVXR)

# Variables minimized over
x <- Variable(1)
y <- Variable(1)
p <- Variable(1)
q <- Variable(1)

# Problem definition
objective <- Minimize((x - y)^2*q + (p - q)^2*y)
constraints <- list(x >= 0, y >= 0, p >= 0, q >= 0, 
                    x <= 67.314, y <= 78, p <= 76.11, q <= 86)
prob2.1 <- Problem(objective, constraints)

# Problem solution
solution2.1 <- solve(prob2.1)
solution2.1 <- solve(prob2.1, gp = TRUE)
solution2.1 <- solve(prob2.1, gp = FALSE)

Error messages:

> solution2.1 <- solve(prob2.1)
Error in construct_intermediate_chain(object, candidate_solvers, gp = gp) : 
  Problem does not follow DCP rules. However, the problem does follow DGP rules. Consider calling this function with gp = TRUE
> solution2.1 <- solve(prob2.1, gp = TRUE)
Error in construct_intermediate_chain(object, candidate_solvers, gp = gp) : 
  Problem does not follow DGP rules. However, the problem does follow DCP rules. Consider calling this function with gp = FALSE
> solution2.1 <- solve(prob2.1, gp = FALSE)
Error in construct_intermediate_chain(object, candidate_solvers, gp = gp) : 
  Problem does not follow DCP rules. However, the problem does follow DGP rules. Consider calling this function with gp = TRUE

many of the unit tests are failing

I am relying enough on this package (thank you so much for your work) that I would like to help. I have forked from master and was planning on working on these couple issues (#55 and #31) to eventually submit pull requests.

In the process, I wanted to run the unit tests to add my own tests, but also make sure that my
changes would not break current behaviors. Unfortunately, I see that a lot of the unit tests are failing (one example below) and I can't tell if it is because of my specific environment, or if it is indeed the case that the unit tests need some rework.

Also, I note that there are a few print() and calls to solver(..., verbose = TRUE) within the tests, which make running them in interactive mode particularly difficult to read.

I would hope that the master branch consistently pass all of its tests and create a clean output. Thank you if you can address.


Example output, after running devtools::test(filter = "g01-atoms")

Loading CVXR
Creating a generic function for ‘is.element’ from package ‘base’ in package ‘CVXR’
Creating a generic function for ‘nrow’ from package ‘base’ in package ‘CVXR’
Creating a generic function for ‘ncol’ from package ‘base’ in package ‘CVXR’
Creating a generic function for ‘%x%’ from package ‘base’ in package ‘CVXR’
Testing CVXR
✔ |  OK F W S | Context
✖ | 263 2   9 | g01-atoms [3.7 s]
────────────────────────────────────────────────────────────────────────────────
test-g01-atoms.R:291: error: test the vstack function
object of type 'S4' is not subsettable
1: .handleSimpleError(function (e) 
   {
       handled <<- TRUE
       test_error <<- e
       options(expressions = expressions_opt_new)
       on.exit(options(expressions = expressions_opt), add = TRUE)
       e$expectation_calls <- frame_calls(11, 2)
       test_error <<- e
       register_expectation(e)
       e$handled <- TRUE
       test_error <<- e
   }, "object of type 'S4' is not subsettable", quote(x[i, j])) at /Users/flodel/git/CVXR0/tests/testthat/test-g01-atoms.R:291
2: eval(code, test_env)

test-g01-atoms.R:449: error: test DCP properties of partial optimize
object of type 'S4' is not subsettable
1: Problem(Maximize(square(t[1])), list(-t <= x, x <= t)) at /Users/flodel/git/CVXR0/tests/testthat/test-g01-atoms.R:449
2: .Problem(objective = objective, constraints = constraints) at /Users/flodel/git/CVXR0/R/problem.R:304
3: new(structure("Problem", package = "CVXR"), ...)
4: initialize(value, ...)
5: initialize(value, ...)
6: .local(.Object, ...)
7: Maximize(square(t[1])) at /Users/flodel/git/CVXR0/R/problem.R:314
8: .Maximize(expr = expr) at /Users/flodel/git/CVXR0/R/problem.R:73
9: new(structure("Maximize", package = "CVXR"), ...)
10: initialize(value, ...)
11: initialize(value, ...)
12: .local(.Object, ...)
13: as.Constant(expr) at /Users/flodel/git/CVXR0/R/problem.R:20
14: is(expr, "Expression") at /Users/flodel/git/CVXR0/R/constant.R:104
15: square(t[1])
16: .Square(args = list(x)) at /Users/flodel/git/CVXR0/R/elementwise.R:1100
17: new(structure("Square", package = "CVXR"), ...)
18: initialize(value, ...)
19: initialize(value, ...)
20: .local(.Object, ...)
21: lapply(args, function(arg) {
       as.Constant(arg)
   }) at /Users/flodel/git/CVXR0/R/atoms.R:17

test-g01-atoms.R:455: skip: test the partial_optimize eval 1-norm
Reason: empty test

test-g01-atoms.R:490: skip: test partial_optimize min 1-norm
Reason: empty test

test-g01-atoms.R:506: skip: test partial_optimize simple problem
Reason: empty test

test-g01-atoms.R:522: skip: test partial_optimize special var
Reason: empty test

test-g01-atoms.R:538: skip: test partial_optimize special constr
Reason: empty test

test-g01-atoms.R:554: skip: test partial_optimize with parameters
Reason: empty test

test-g01-atoms.R:572: skip: test partial_optimize numeric function
Reason: empty test

test-g01-atoms.R:605: skip: test partial_optimize stacked
Reason: empty test

test-g01-atoms.R:622: skip: test the NonNegative Variable class
Reason: empty test
────────────────────────────────────────────────────────────────────────────────

══ Results ═════════════════════════════════════════════════════════════════════
Duration: 3.9 s

OK:       263
Failed:   2
Warnings: 0
Skipped:  9

If it is useful, here is my sessionInfo():

R version 3.4.1 (2017-06-30)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.6

Matrix products: default
BLAS: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] CVXR_0.99-6     testthat_2.2.1  devtools_1.12.0

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.2        xml2_1.1.1        magrittr_1.5      roxygen2_6.0.1   
 [5] bit_1.1-12        lattice_0.20-35   R6_2.2.2          rlang_0.4.0      
 [9] stringr_1.2.0     tools_3.4.1       grid_3.4.1        R.oo_1.22.0      
[13] cli_1.1.0         withr_2.1.2       scs_1.2-3         commonmark_1.2   
[17] assertthat_0.2.0  bit64_0.9-7       digest_0.6.12     crayon_1.3.4     
[21] Matrix_1.2-10     gmp_0.5-13.1      ECOSolveR_0.5.2   codetools_0.2-15 
[25] R.utils_2.9.0     memoise_1.1.0     stringi_1.1.5     compiler_3.4.1   
[29] Rmpfr_0.7-1       R.methodsS3_1.7.1

can anyone make Mosek solver multithreading??

set.seed(10)
n <- 1000
SAMPLES <- 100
mu <- matrix(abs(rnorm(n)), nrow = n)
Sigma <- matrix(rnorm(n^2), nrow = n, ncol = n)
Sigma <- t(Sigma) %*% Sigma

w <- Variable(n)
ret <- t(mu) %*% w
risk <- quad_form(w, Sigma)
constraints <- list(w >= 0, sum(w) == 1)

gammas <- 10^seq(-2, 3, length.out = SAMPLES)
ret_data <- rep(0, SAMPLES)
risk_data <- rep(0, SAMPLES)
w_data <- matrix(0, nrow = SAMPLES, ncol = n)

for(i in seq_along(gammas)) {
gamma <- gammas[i]
objective <- ret - gamma * risk
prob <- Problem(Maximize(objective), constraints)
result <- psolve(prob,solver = "MOSEK",mosek_params=list("msk_ipar_num_threads"=20))
risk_data[i] <- result$getValue(sqrt(risk))
ret_data[i] <- result$getValue(ret)
w_data[i,] <- result$getValue(w)
}

I set psolve(prob,solver = "MOSEK",mosek_params=list("msk_ipar_num_threads"=20))
and the multithreading just didn't work

sessionInfo()
R version 3.5.2 (2018-12-20)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 18.04.1 LTS

Matrix products: default
BLAS: /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.7.1
LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.7.1

locale:
[1] LC_CTYPE=en_US.utf8 LC_NUMERIC=C
[3] LC_TIME=en_US.utf8 LC_COLLATE=en_US.utf8
[5] LC_MONETARY=en_US.utf8 LC_MESSAGES=en_US.utf8
[7] LC_PAPER=en_US.utf8 LC_NAME=en_US.utf8
[9] LC_ADDRESS=en_US.utf8 LC_TELEPHONE=en_US.utf8
[11] LC_MEASUREMENT=en_US.utf8 LC_IDENTIFICATION=en_US.utf8

attached base packages:
[1] stats graphics grDevices utils datasets methods base

other attached packages:
[1] Tushare_0.1.3 forecast_8.5 forcats_0.4.0 dplyr_0.8.3
[5] purrr_0.3.3 readr_1.3.1 tidyr_0.8.3 tibble_2.0.1
[9] ggplot2_3.1.0 tidyverse_1.2.1 httr_1.4.0 CVXR_1.0-1
[13] xlsx_0.6.1 Rmosek_9.1.0 xts_0.11-2 zoo_1.8-4
[17] RMySQL_0.10.17 DBI_1.0.0 stringr_1.4.0 reshape2_1.4.3
[21] mltools_0.3.5 lightgbm_2.3.2 R6_2.4.1 data.table_1.12.8
[25] Matrix_1.2-15

loaded via a namespace (and not attached):
[1] tseries_0.10-46 bit64_0.9-7 jsonlite_1.6.1 ECOSolveR_0.5.3
[5] modelr_0.1.4 assertthat_0.2.0 TTR_0.23-6 xlsxjars_0.6.1
[9] cellranger_1.1.0 slam_0.1-47 pillar_1.3.1 backports_1.1.3
[13] lattice_0.20-38 glue_1.3.0 quadprog_1.5-8 rvest_0.3.3
[17] colorspace_1.4-0 plyr_1.8.4 timeDate_3043.102 pkgconfig_2.0.2
[21] broom_0.5.2 haven_2.1.0 scales_1.0.0 Rglpk_0.6-4
[25] gmp_0.6-0 generics_0.0.2 withr_2.1.2 urca_1.3-0
[29] nnet_7.3-12 lazyeval_0.2.1 Rmpfr_0.8-1 cli_2.0.0
[33] quantmod_0.4-13 magrittr_1.5 crayon_1.3.4 readxl_1.3.1
[37] fansi_0.4.0 nlme_3.1-137 xml2_1.2.0 tools_3.5.2
[41] hms_0.4.2 munsell_0.5.0 compiler_3.5.2 rlang_0.4.2
[45] grid_3.5.2 rstudioapi_0.9.0 gtable_0.2.0 fracdiff_1.4-2
[49] curl_3.3 lubridate_1.7.4 bit_1.1-15.2 rJava_0.9-11
[53] stringi_1.3.1 parallel_3.5.2 Rcpp_1.0.5 tidyselect_0.2.5
[57] lmtest_0.9-36

Poisson GLM

Hi,

Suppose that I'd like to fit a constrained Poisson GLM using CVXR, much like the logistic regression example in the documentation.
The program does not seem to optimize the function using either maximum likelihood formulation

    ## MWE
    library(CVXR)
    y <- rpois(n=100, lambda=50)
    X <- matrix(rnorm(100), ncol=1)
    betaHat <- Variable(1)
    obj <- sum(y* log(exp(X %*% betaHat)) - exp(X %*% betaHat))
    prob <- Problem(Maximize(obj))
    result <- CVXR::solve(prob)

or a Poisson loss formulation

    obj <- mean(exp(X %*% betaHat) - y * log(exp(X %*% betaHat)))
    prob <- Problem(Minimize(obj))
    result <- CVXR::solve(prob)

returning the error Error in construct_intermediate_chain(object, candidate_solvers, gp = gp) : Problem does not follow DCP rules. However, the problem does follow DGP rules. Consider calling this function with gp = TRUE. Setting gp=TRUE gives an opposite error.

Am I overlooking something?

How to solve a problem with a paarameter in it?

Hi,
In Python I could have the constraint depend on a parameter that is supplied later on.

param = cp.Parameter(nonneg=True)
prob = cp.Problem(cp.Minimize(y), [x == param])
param.value = 3
prob.solve()

How can I achieve this in R? I tried using the Parameter class and then setting the param value by calling value(param) <- 3 but solve didn't work.

Problem does not follow DCP rules

Describe the bug
Solver claims that my problem does not follow DCP rules. The small reproducible example provided below should be equivalent to an unconstrained Minimize(sum_entries(pos(errors_values))) where errors_values is a 3-by-3 matrix of randomly generated values. Which is obviously linear/convex.

To Reproduce

library(CVXR)
errors_values <- matrix(rnorm(3*3), 3, 3)
errors <- Variable(3, 3)
costs <- Variable(3, 3)
total_cost <- Variable(1)
objective <- Minimize(total_cost)
constraints <- list(
  errors == errors_values,
  costs == pos(errors),
  total_cost == sum_entries(costs)
)
problem <- Problem(objective = objective, constraints = constraints)
result <- solve(problem)

Expected behavior
For the solver to run and return with an optimal status and objective value equal to sum(pmax(errors_values, 0)).

Output
Error in construct_intermediate_chain(object, candidate_solvers, gp = gp) : Problem does not follow DCP rules. However, the problem does follow DGP rules. Consider calling this function with gp = TRUE

Version

R version 3.6.3 (2020-02-29)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Catalina 10.15.3

Matrix products: default
BLAS:   /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] CVXR_1.0-1

loaded via a namespace (and not attached):
 [1] bit_4.0.4       compiler_3.6.3  R6_2.4.1        Matrix_1.2-18  
 [5] tools_3.6.3     gmp_0.6-0       Rcpp_1.0.4      bit64_4.0.2    
 [9] grid_3.6.3      Rmpfr_0.8-1     lattice_0.20-38

Additional context
Running the solver with gp = TRUE as suggested by the error message above returns an opposite error, claiming the problem now does follow DCP rules, which I believe is true.

I also tested adding nonneg = TRUE to the Variable() definition of costs and total_costs. It does not help.

This small reproducible example was inspired from a much more complex production process, which was running fine in a previous version of R and CVXR.

Thanks if you can have a look and provide feedback soon.

Consider supporting SDPT3 solver

SDPT3 is one of the classical solvers for the MATLAB toolbox CVX.
This convex solver is now available as R package 'sdpt3r' on CRAN.
It would be nice if this solver could be integrated with CVXR, too.

CVXR with new mosek problem

To slove the quadratic minimizatiom problem, I tested a example from stackoverflow and also I found this problem in the issues #40 . But I came cross a new different error. After running the last command result <- solve(prob,solver='MOSEK', verbose=TRUE), the errors showed that:

Interior-point solution summary
Problem status : PRIMAL_AND_DUAL_FEASIBLE
Solution status : OPTIMAL
Primal. obj: 2.9027224916e-01 nrm: 1e+00 Viol. con: 1e-08 var: 0e+00 cones: 0e+00
Dual. obj: 2.9027225465e-01 nrm: 1e+01 Viol. con: 0e+00 var: 2e-08 cones: 0e+00
Error in py_call_impl(callable, dots$args, dots$keywords) :
AttributeError: type object 'solsta' has no attribute 'near_optimal'

Detailed traceback:
File "/scratch/work/dais2/R/CVXR/python/mosekglue.py", line 138, in mosek_intf
return format_results(task, data)
File "/scratch/work/dais2/R/CVXR/python/mosekglue.py", line 207, in format_results
mosek.solsta.near_optimal: s.OPTIMAL_INACCURATE,

It seems that I can obtain the the optimal value. But it still shows the error. So, I think this might be a new bug and I am very sure. The detailed version information are as follows.

sessionInfo()
R version 3.5.0 (2018-04-23)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: CentOS Linux 7 (Core)

Matrix products: default
BLAS/LAPACK: /share/apps/spack/software/openblas/0.3.2/7rbfsnk/lib/libopenblasp-r0.3.2.so

locale:
[1] LC_CTYPE=en_GB.UTF-8 LC_NUMERIC=C
[3] LC_TIME=en_GB.UTF-8 LC_COLLATE=en_GB.UTF-8
[5] LC_MONETARY=en_GB.UTF-8 LC_MESSAGES=en_GB.UTF-8
[7] LC_PAPER=en_GB.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats graphics grDevices utils datasets methods base

other attached packages:
[1] CVXR_0.99-5 reticulate_1.12

loaded via a namespace (and not attached):
[1] Rcpp_1.0.1 lattice_0.20-35 gmp_0.5-13.5
[4] MASS_7.3-49 R.methodsS3_1.7.1 grid_3.5.0
[7] R6_2.4.0 jsonlite_1.6 Rmpfr_0.7-2
[10] R.oo_1.22.0 R.utils_2.8.0 Matrix_1.2-14
[13] lpSolveAPI_5.5.2.0-17 tools_3.5.0 bit64_0.9-7
[16] bit_1.1-14 compiler_3.5.0 scs_1.2-3
[19] tcltk_3.5.0 ECOSolveR_0.5.2

installed_solvers()
[1] "ECOS" "ECOS_BB" "SCS" "MOSEK" "LPSOLVE" "GUROBI"

Diagonal Matrix

Hi,

First it is great to have CVX in R. I was having difficulties with matlab. However, in the Matlab version I was able to define a diagonal matrix using

variable X(n,n) diagonal

I could not find a similar functionality in the R package. I did not find any easy way to do this using constraints. Any ideas?

Thanks

Difficulties with DCP rules

Hi,

I am facing the following challenge for which I don't seem to find a solution:

Basically, I want to program some code for StoNED - Stochastic non-smooth envelopment of data. The mathematical problem is described as

Stoned Problem

I started with this:

# dim(G) is 35x15
# dim(X) is 5x15
# dim(y) is 5x1
# dim(h) is 15x1

# y is a vector of output, x a matrix of input, h a vector of zeros, G a matrix of constraint parameters, betaa shall be estimated

library(CVXR)
betaa <- Variable(15,1)
target <- cvxr_norm(log(y)-log(X%*%betaa))
obj <- Minimize(target)
constr <- list(G%*%betaa>=h)
prob <- Problem(obj,constr)
result <- solve(prob)
print(result$getValue(betaa))

Since this didn't work, I tried transforming the problem to this:

library(CVXR)
library(MASS)

#betaa <- Variable((15,1)
test <- Variable(5,1)
target <- cvxr_norm(log(y)-test)
obj <- Minimize(target)
constr <- list(G%*%(ginv(X)%*%exp(test))>=h)
prob <- Problem(obj,constr)
result <- solve(prob)
print(result$getValue(ginv(X)%*%exp(test)))

Through this I shifted the DCP error from the problem expression to the constraint expression. I really don't have a clue how to get around this. Does anyone have a proper solution? Thanks in advance!

DCP check is too slow

Hello, I am working on an optimization problem with a complex formulation and although the problem is easy to solve (<1 sec once Rglpk::Rglpk_solve_LP is called), the DCP check (CVXR::is_dcp) within CVXR::solve is very, very slow (minutes).

Here is a small reproducible example. Though unrelated to my optimization problem, it shows the kind of slow DCP check I am experiencing:

library(CVXR)
n <- 5L; m <- 3L
X <- Variable(n, m)
y <- runif(n)
cumX <- cumsum_axis(X, axis = 2) # %*% diag(m)
cumE <- sum_entries(cumX, axis = 1) - y
posE <- sum_entries(pos(cumE))
negE <- sum_entries(neg(cumE)) # * 1
objective <- Minimize(posE + negE)
problem <- Problem(objective)
system.time({ result <- is_dcp(problem) })
## user system elapsed
## 3.234 0.021 3.447

If you then run the same code but uncomment the * 1 multiplication, it runs in

## user system elapsed
## 12.278 0.104 14.546

If you then run the same code but uncomment the %*% diag(m), it runs in

## user system elapsed
## 52.452 0.646 69.411

I hope you will be able to find the problem and speed up is_dcp. If not or if it looks like it will take some time to implement, would you please consider making the ignore_dcp option skip completely the DCP check? Or provide a separate option?

Thank you.

Incompatible with conflicted package

Trying to add the conflicted package to my project; getting this error when trying to load CVXR while conflicted is loaded. Not really sure where it's coming from, but figured I'd raise it.

Registered S3 method overwritten by 'R.oo':
  method        from       
  throw.default R.methodsS3
Error: `fn` must be an R function, not a primitive function
Call `rlang::last_error()` to see a backtrace

> rlang::last_error()
<error>
message: `fn` must be an R function, not a primitive function
class:   `rlang_error`
backtrace:
 1. conflicted:::library(CVXR, warn.conflicts = FALSE)
 2. conflicted:::conflicts_register()
 3. conflicted::conflict_scout(pkgs)
 4. conflicted:::map2(names(conflicts), conflicts, superset_principle)
 5. base::mapply(.f, .x, .y, MoreArgs = list(...), SIMPLIFY = FALSE)
 7. conflicted:::is_superset(fun, non_base, base = base)
 8. rlang::fn_fmls(base_obj)
 9. rlang:::check_closure(fn)```

CVXR Mosek Setting

Hi, first thanks for the wonderful package.

I have already installed 3 times Mosek. It is working in python but CVXR (r package) function installed_solvers() is not able to find MOSEK.

installed_solvers()
[1] "ECOS" "ECOS_BB" "SCS" "LPSOLVE" "GLPK"

I'm working on a MACos Mojave. I installed Mosek via conda comand, got an academic license, create a folder in the home directory with the name mosek and put the license file in it. Then I tested in jupyter lab the following script https://docs.mosek.com/8.1/pythonapi/design.html#hello-world-in-mosek and getting the result
Solution x = 2.0 , so Mosek is working.
Then I installed reticulate, use the default directory, replace it by
use_python("/Users/apple/anaconda3")
and
use_python("/Users/apple/anaconda3/lib/python3.6")
In any of them, the function installed_solvers() has found mosek. My session info is the following

R version 3.4.3 (2017-11-30)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS 10.14.1

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats graphics grDevices utils datasets methods base

other attached packages:
[1] reticulate_1.10 Matrix_1.2-12 CVXR_0.99-2 e1071_1.6-8 rstudioapi_0.7 openxlsx_4.0.17

loaded via a namespace (and not attached):
[1] Rcpp_0.12.14 lpSolveAPI_5.5.2.0-17 bit_1.1-12 lattice_0.20-35
[5] R6_2.2.2 tools_3.4.3 grid_3.4.3 R.oo_1.21.0
[9] scs_1.1-1 class_7.3-14 bit64_0.9-7 gmp_0.5-13.1
[13] ECOSolveR_0.4 Rglpk_0.6-3 R.utils_2.6.0 slam_0.1-40
[17] compiler_3.4.3 Rmpfr_0.7-0 R.methodsS3_1.7.1 jsonlite_1.5

The documentation in https://cvxr.rbind.io/cvxr_examples/cvxr_using-other-solvers/ doesn't really say how to solve the problem. Could you help me? Thanks

Speed impact of ::get_problem_data

I know the package has just been updated with a lot of new changes especially to the internals of get_problem_data(). After updating my code and syntax, I am finding significant speed hits (evaluated using profvis, with upwards of ~10 times slower w.r.t. 0.99-7 in some iterative cases). Without getting too much into the technical implementation of my code; I was wondering if this was something known and if not let this be an early flag.

How to implement Mixed-integer quadratic program?

I am solving a MIP, which seems to fail in R like this:

 x <- Variable(3,integer=T) # 2 user choose best show_price
Error in Variable(3, integer = T) : unused argument (integer = T)
Error in exists(what, where, inherits = FALSE) : invalid first argument

However, I found a similar example from CVXPY:

# Construct a CVXPY problem
x = cp.Variable(n, integer=True)
objective = cp.Minimize(cp.sum_squares(A@x - b))
prob = cp.Problem(objective)
prob.solve()

`geo_mean` hangs for some values of `p`

Describe the bug
For some values of p, the geo_mean() function hangs, seemingly forever. In the example below, it has been using ~100% CPU for several minutes. When I press Ctrl-C to cancel, there is no stack trace.

To Reproduce

library(CVXR)
x = Variable(3)

p_bad = c(0.9, 0.8, 0.7)
m = geo_mean(x, p_bad)   # hangs forever

p_good = c(0.7, 0.8, 0.9)
m = geo_mean(x, p_good)  # runs

Expected behavior
I expected geo_mean to run identically in both cases.

Version

CVXR 1.0-1

Session info
R version 4.0.2 (2020-06-22)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 20.04.1 LTS

Matrix products: default
BLAS:   /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3
LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/liblapack.so.3

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] CVXR_1.0-1

loaded via a namespace (and not attached):
 [1] bit_4.0.4       compiler_4.0.2  R6_2.4.1        Matrix_1.2-18  
 [5] gmp_0.6-0       Rcpp_1.0.5      bit64_4.0.5     grid_4.0.2     
 [9] Rmpfr_0.8-1     lattice_0.20-41

Problem component 2 has no name

When calling result <- solve(problem) on a CVXR-defined problem, the structure of the result has an unnamed component that probably should be called result$solution or similar.

> result <- solve(problem)
> result
$status
[1] "optimal"

$value
[1] 97.84759

$`2`
             [,1]
 [1,] -3.91968871
 [2,] -3.01170409
 ...

$solver
[1] "ECOS"
...

The solution can be retrieved with result[[2]], but I assume that is not what was intended.

Not exactly spase solution of l1-penalized least-squares

I am trying to solve some least-squares problems regularized by convex non-smooth penalties (such as l1-matrix i.e LASSO, or nuclear norm). Although the LASSO solution of a least-squares problem is supposed to be exactly sparse, i.e the solution vector (or matrix in my case) entails components which are exactly zero, I noticed that the LASSO solution returned by the CVXR solver is not exactly sparse. In other words, some components of the solution are very small (~10^-15), but not exactly 0, and the relevant ones much bigger (~10^-1).

I noticed the issue with the generated data used for the tutorial on ElasticNet on CVRX website, where one can see that in the table1 (LASSO-path), the "almost zero components" of the solutions have been rounded to 3 digits.

Is there a way to get an exact sparse solution with CVXR ?

To get an exact sparse solution, I did as in the CVXR ElasticNet tutorial i.e I rounded the components of the returned solution to 2 or 3 digits. However, it is a pretty empirical approach isn't it ? In practice, it is not possible to know whether the true non-zero components of the solution are order 10^1, 10^0,... hence it is hard to threshold the digits of the true zero components of the solution (and not really in the spirit of LASSO-like problems).

NOTE
I know that I could solve the problem outside CVXR, with proximal methods, and the solution would result exactly sparse but for some convex penaIties it is hard for me to compute the proximal operators analytically. I would like to experiment different convex penalties quickly on my problem, and that's why I decided to learn to use CVXR.

Thanks !

Feature request: consistent iteration max arguments across solvers

Thanks for the really useful package! I've run across a couple of small small issues when trying to adjust the number of iterations.

  1. The names of the arguments to control the number of iterations is different for SCS and ECOS (and presumably the other solvers)
    • max_iters for SCS and MAXIT for ECOS
    • There's no warning if you set the wrong argument name – it just silently uses the default. Would it be possible to check that the provided ... arguments are control arguments the solver uses?
  2. Reaching a user-set maximum iteration count leads to a solver failure in ECOS, but solved_inaccurate in SCS. (In contrast, hitting the default ECOS iteration count gives solved_inaccurate)

small values for LASSO

I tried a test case with a loss of matrix Frobenius norm plus ($\lambda$ times) a penalty of l1 norm, like the normal LASSO case ($\min||X-A||_F+\lambda||X||_1$). I found the result, with a proper $\lambda$, the result has many small values (less than 1e-10) rather than zeros. (I also tried increase the $\lambda$, the values are getting smaller but never become exactly zeros). So it cannot get exactly sparse solution as the theoretical results asserts.

Is this a common problem in numerical optimization of l1 norm (even though theory says it is sparse, the numerical result only get very small number)? As I remembered, source code in package like glmnet also use a manually truncation step in the end of the code. So, do you suggest to truncate the results when it is extremely small, or try larger penalties? or is there any other solutions? (or I can be wrong in my simulation.)

Incompatible dimensions in building constraints

Hi! Thanks for your (and your team) amazing work in CVXR package. I use this package for some control purposes, and an Error appeared when I try to build constraints about state-space equations.

` library(CVXR)

A <- matrix(c(2,-1,1,0.2),byrow = T,nrow = 2)
B <- matrix(c(1,0),byrow = T,nrow = 2)

N <- 7
Q <- diag(2)
R <- 2
N <- 7

x0 <- matrix(c(3,1),byrow = T)
u <- Variable(rows = 1, cols = N)
x <- Variable(rows = 2, cols = N)
objective <- Minimize(sum(Q %% x) + sum(R %% u))

constraints <- list(u >= -1,
u <= 1 ,
x >= -5,
x <= 5,
x[,1] == x0,
#x[,2:N] == A %% x[,1:(N-1)] + B %% u[,1:(N-1)]
x[,2] == A %% x[,1] + B %% u[,1]) `

Error in mul_shapes(size(object@args[[1]]), size(object@args[[2]])) : Incompatible dimensions.
If I use the second last lines ( #x[,2:N] == A %*% x[,1:(N-1)] + B %*% u[,1:(N-1)] ), the console proceed with an Error like above. I have to use the for loop to complete modeling (add constraints one by one). And the dimensions in the second last lines seem compatible.

By the way, I have another try on the building constraints for the one-dimension state-space equation in the way like x[2:N] == A %*% x[1:(N-1)] + B %*% u[1:(N-1)], it works. Therefore, I am not sure the problem lies in syntax or the matrix multiplication bug.

Thanks for your help!

`ignore_dcp` option is not working as intended

When calling solve with ignore_dcp = TRUE , the DCP check is still run. I can spot where this is happening in https://github.com/cvxgrp/CVXR/blob/master/R/problem.R, near line 473:

  if(!is_dcp(object)) {
    if(ignore_dcp)
      print("Problem does not follow DCP rules. Solving a convex relaxation.")
    else
      stop("Problem does not follow DCP rules.")
  }

I would suggest replacing with

  if (!ignore_dcp) {
    if(!is_dcp(object)) {
      stop("Problem does not follow DCP rules.")
    }
  }

mul_elemwise() deprecated?

A quick question: I'm getting the error
'mul_elemwise' is not an exported object from 'namespace:CVXR'

I can see that multiply() seems to do the same thing. mul_elemwise() only exists in documentation but not in the package anymore, from a cursory search. Is it deprecated?

Bug in Constant

A rounding error in constant.

> Constant((2/632)^2)
Constant(CONSTANT, POSITIVE, (1,1))> 
> Constant((2/633)^2)
Constant(CONSTANT, ZERO, (1,1))> 

MOSEK Support

It's so nice to see the latest version of CVXR support Mosek. I have Mosek installed on my PC and it works well with Rmosek in R. I am wondering how to import Mosek with CVXR. Thanks very much.


installed_solvers()
[1] "ECOS" "ECOS_BB" "SCS"
import_solver(MOSEK())
[1] FALSE


R version 3.4.4 (2018-03-15)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

Matrix products: default

locale:
[1] LC_COLLATE=English_Hong Kong SAR.1252 LC_CTYPE=English_Hong Kong SAR.1252 LC_MONETARY=English_Hong Kong SAR.1252
[4] LC_NUMERIC=C LC_TIME=English_Hong Kong SAR.1252

attached base packages:
[1] stats graphics grDevices utils datasets methods base

other attached packages:
[1] Rmosek_8.0.69 Matrix_1.2-14 CVXR_0.98-1

loaded via a namespace (and not attached):
[1] Rcpp_0.12.16 lattice_0.20-35 gmp_0.5-13.1 R.methodsS3_1.7.1 grid_3.4.4 R6_2.2.2 Rmpfr_0.7-0
[8] R.oo_1.22.0 R.utils_2.6.0 tools_3.4.4 bit64_0.9-7 bit_1.1-12 yaml_2.1.18 compiler_3.4.4
[15] scs_1.1-1 ECOSolveR_0.4

Matlab vs R version incompatibilty

I am solving the same problem in matlab and R but I get different results (the solutions are completely different for some variables not just a little here and there) although all the inputs are the .same for completeness here is the matlab code:

p=132; 
cvx_begin;
variables b(p);
minimize(norm(weight'*b, 1));
subject to;
    1<matrix*b;
    0<=b;                                   
cvx_end;

and the R code:

p=132
  b=Variable(p,name="b")
  objective <- norm1(t(weight) %*% b) 
  constrnt <-list(1 < matrix %*% b,0 <= b )
 prob <- Problem(Minimize(objective), constrnt)
results <- solve(prob)
lb_solution=results$getValue(b)

Any insights on why this might happen?

Package NEWS file

It would be nice if the CVXR package on CRAN has a NEWS (or: ChangeLog) file. Makes it easier for interested users to see what has changed, and for me as a maintainer of the Optimization Task View.

Relax R >= 3.4 Dependency to R >= 3.2

I'm able to build from source and run with R 3.2 if i modify the DESCRIPTION file

> session_info()
Session info ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 setting  value                       
 version  R version 3.2.4 (2016-03-10)
 system   x86_64, darwin13.4.0        
 ui       RStudio (1.1.423)           
 language (EN)                        
 collate  en_US.UTF-8                 
 tz       America/New_York            
 date     2018-03-02                  

Packages -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 package              * version    date       source        
 bit                    1.1-12     2014-04-09 CRAN (R 3.2.4)
 bit64                  0.9-7      2017-05-08 CRAN (R 3.2.5)
 CVXR                 * 0.95       2018-03-02 local         
 ECOSolveR              0.4        2018-02-18 CRAN (R 3.2.4)
 gmp                    0.5-13.1   2017-03-10 CRAN (R 3.2.5)
 Matrix                 1.2-4      2016-03-02 CRAN (R 3.2.4)
 R.methodsS3            1.7.1      2016-02-16 CRAN (R 3.2.3)
 R.oo                   1.21.0     2016-11-01 CRAN (R 3.2.5)
 R.utils                2.6.0      2017-11-05 CRAN (R 3.2.5)
 R6                     2.0.1      2014-10-29 CRAN (R 3.2.4)
 Rcpp                   0.12.15    2018-01-20 CRAN (R 3.2.4)
 RcppParallel           4.3.20     2016-08-16 CRAN (R 3.2.4)
 Rmpfr                  0.6-1      2016-11-15 CRAN (R 3.2.5)
 withr                  2.1.1      2017-12-19 CRAN (R 3.2.4)
 XML                    3.98-1.4   2016-03-01 CRAN (R 3.2.4)
 xts                  * 0.10-0     2017-07-07 CRAN (R 3.2.4)
 yaml                   2.1.13     2014-06-12 CRAN (R 3.2.0)
 zoo                  * 1.7-12     2015-03-16 CRAN (R 3.2.4)

Dual Variable Example

Can you please provide an example for retrieving optimal dual variables? I see a dual_value method was added, but I can't find any examples on its use and am having no luck interpreting the documentation.

Here is an example problem I'm trying to work through:
Q <- rbind(c(1, -1/2), c(-1/2, 2))
f <- cbind(-1, 0)
A <- rbind(c(1, 2), c(1, -4), c(5, 76))
b <- rbind(-2, -3, 1)

x <- Variable(2)
constraints <- list(A %% x <= b)
objective <- Minimize(quad_form(x, Q) + f %
% x)
problem <- Problem(objective, constraints)
solution <- solve(problem)

Thank you!

Elementwise multiplication of a matrix with a vector

Hello,
i am not sure if I have to ask this question here or on stack overflow, in case the topic does not belong here, please let me know.

I want to use CVXR to find the optimal values of a vector. In the objective function i need to multiply a matrix with this vector in an elementwise way:

b: Nx1 vector
X: Nxp matrix
result: Nxp matrix

Example:

/ # Set the dims
N <- 50
p <- 5
X <- matrix(rnorm(N*p), N, p)

/# to find the optimal values using optim() one could simply have a numeric object
/# say the optimal values are 0.1, -0.2, 0.3, -0.5, 0.6
b <- c(0.1, -0.2, 0.3, -0.5, 0.6)

/# Then we can have the Nxp matrix with the product
/# (where column i of X is multiplied by element i of b) is given by
X*b

b is the vector of coefficient to be optimised.

Using CVXR one must declare

b <- Variable(p)

as Variable object with uses the matrix form, therefore later we can't really multiply as in the previous case.

Also, we don't want to create a matrix of b: Nxp because we need to have one optimal value for all N observations of the i-th column (therefore the mul_elemwise(X, X*b) option wouldn't work as it would give different optimal values for different observations of N - if I am not mistaken).

thanks,

Base Apply and Elementwise Function

Is there a way to use base::apply and a CVXR elementwise function to apply an elementwise function to every column of a matrix? Assuming the length of the vector matches the number of rows of the matrix, I'd like to be able to make my objective function the following:

new_matrix <- apply(constant_matrix, 2, function(x) x * variable_vector)
objective <- sum_entries( max_entries( as.matrix(new_matrix), axis = 2 ) )

I get the following error when solving the problem:
Error in min(constant) : invalid 'type' (list) of argument

(In case my code is unclear, my goal is to multiply a variable vector by every column of a constant matrix, then get the max of each of those scaled columns, and then sum all of those maxes.)

Thanks!

CVXR using Mosek Quadratic minimization problem

Hi
I'm trying to solve a Quadratic optimization problem with linear constrains using the R package CVXR. Although the default solver is able to solve the optimization, Mosek solver is not. The reason I'm looking to use Mosek is because I need to solve a bigger problem with more than 250 constrains and the default solver gives an inaccurate solution, so I'm looking to solve the bigger problem with Mosek. Here's a simple example were Mosek is not working:

suppressMessages(suppressWarnings(library(CVXR)))

Problem data

set.seed(10)
n <- 10
SAMPLES <- 100
mu <- matrix(abs(rnorm(n)), nrow = n)
Sigma <- matrix(rnorm(n^2), nrow = n, ncol = n)
Sigma <- t(Sigma) %*% Sigma

Form problem

w <- Variable(n)
ret <- t(mu) %*% w
risk <- quad_form(w, Sigma)
constraints <- list(w >= 0, sum(w) == 1,ret==mean(mu))

Risk aversion parameters

prob <- Problem(Minimize(risk), constraints)
result <- solve(prob,solver='MOSEK')

It gives the following error.

Error in py_call_impl(callable, dots$args, dots$keywords) :
TypeError: 'int' object is not iterable
10.stop(structure(list(message = "TypeError: 'int' object is not iterable",
call = py_call_impl(callable, dots$args, dots$keywords),
cppstack = structure(list(file = "", line = -1L, stack = c("1 reticulate.so 0x000000010d278f9b _ZN4Rcpp9exceptionC2EPKcb + 219",
"2 reticulate.so 0x000000010d27fa35 _ZN4Rcpp4stopERKNSt3__112basic_stringIcNS0_11char_traitsIcEENS0_9allocatorIcEEEE + 53", ...
9.mosek_intf at mosekglue.py#51
8.get_mosekglue()$mosek_intf(reticulate::r_to_py(A), b, reticulate::r_to_py(G),
h, c, dims, offset, reticulate::dict(solver_opts), verbose)
7.Solver.solve(solver, objective, constraints, [email protected]_data,
warm_start, verbose, ...)
6.Solver.solve(solver, objective, constraints, [email protected]_data,
warm_start, verbose, ...)
5.CVXR::psolve(a, b, ...)
4.CVXR::psolve(a, b, ...)
3.solve.Problem(prob, solver = "MOSEK")
2.solve(prob, solver = "MOSEK")
1.solve(prob, solver = "MOSEK")

Somebody knows how to solve it, may be re expressing the problem?

My session info is the following:

R version 3.5.2 (2018-12-20)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Mojave 10.14.1

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats graphics grDevices utils datasets methods base

other attached packages:
[1] reticulate_1.10 Matrix_1.2-15 CVXR_0.99-2 e1071_1.7-0.1 rstudioapi_0.9.0
[6] openxlsx_4.1.0

loaded via a namespace (and not attached):
[1] Rcpp_1.0.0 lattice_0.20-38 class_7.3-14 gmp_0.5-13.2 R.methodsS3_1.7.1
[6] grid_3.5.2 R6_2.3.0 jsonlite_1.6 zip_1.0.0 Rmpfr_0.7-2
[11] R.oo_1.22.0 R.utils_2.7.0 tools_3.5.2 bit64_0.9-7 bit_1.1-14
[16] compiler_3.5.2 scs_1.1-1 ECOSolveR_0.4

View all results from CVXR

I am currently using CVXR to develop Lasso results. I am using the “SCS” solver and see that it goes through 5000 iterations. Is it possible to see the results of each of these iterations? I am hoping to develop a plot from the results.

Thanks

Status "unbounded" for a correct model?

For some benchmark tests I invoked the "catenary example" with N=1000 chain links and got the following status message:

N = 1000
L = 2; h = L/N
x = Variable(N+1)
y = Variable(N+1)
objective  = sum(y)
constraint = list(x[1] == 0, x[N+1] == 1,
                  y[1] == 1, y[N+1] == 1,
                  diff(x)^2 + diff(y)^2 <= h^2)
problem <- Problem(Minimize(objective), constraint)
result <- solve(problem)

result$getValue(x); result$getValue(y)
## [1] NA
## [1] NA
result$status
## [1] "unbounded"

The same code with N=100 returns the usual catenary line with status "optimal", and with N=500 NAs again and a status of "optimal_inaccurate".

I think, "optimal_inaccurate" is a correct message (the same we get with solver SCS, the result being far off the truth), but a status message "unbounded" for a model that works with a smaller numbers of variables does not seem right.

sum_squares doesn't work in R 3.5.2

Hi,
Thank you so much for building this package.

I am using R 3.5.2 64-bit with CVXR_0.99-3 on windows ten enterprise. CVXR_0.99-3. The sum_squares function in the objective function used for codes in the link lead me to in-feasibility, however, if I manually code the the sum of squares the problem is optimal.

For instance in 'simple examples' /Ordinary Least Squares section in the above link, if we use
objective <- Minimize(sum_squares(y - X %*% beta))
$status
[1] "infeasible_inaccurate"

$11
[1] NA

$value
[1] Inf

$solver
[1] "ECOS"

$solve_time
[1] 0.780979

$setup_time
[1] 0.01354082

$num_iters
[1] 100

$getValue
function (objet)
{
if (is(objet, "Variable") || is(objet, "Constraint")) {
return(result[[as.character(id(objet))]])
}
if (is_zero(objet)) {
size <- size(objet)
valResult <- matrix(0, nrow = size[1], ncol = size[2])
}
else {
arg_values <- list()
idx <- 1
for (arg in objet@args) {
arg_val <- if (is_constant(arg)) {
value(arg)
}
else {
getValue(arg)
}
if (is.null(arg_val) || (any(is.na(arg_val)) && !is_constant(objet)))
return(NA)
else {
arg_values[[idx]] <- arg_val
idx <- idx + 1
}
}
valResult <- to_numeric(objet, arg_values)
}
if (all(intf_size(valResult) == c(1, 1)))
intf_scalar_value(valResult)
else valResult
}
<bytecode: 0x0000000015286ea8>
<environment: 0x000000001525f250>

$getDualValue
function (objet)
{
if (!is(objet, "Constraint")) {
stop("getDualValue: argument should be a Constraint!")
}
getValue(objet)
}
<bytecode: 0x0000000015285b58>
<environment: 0x000000001525f250>

objective <- Minimize(sum((y - X %*% beta)^2))
$status
[1] "optimal"

$value
[1] 9946.64

$11
[,1]
[1,] 0.01490596
[2,] 0.74633566
[3,] -0.04689927
[4,] 1.06782714
[5,] 0.19997118
[6,] 0.03308453
[7,] 0.43790907
[8,] 1.08405414
[9,] 0.01644479
[10,] 0.67748525

$solver
[1] "ECOS"

$solve_time
[1] 0.656408

$setup_time
[1] 0.03219767

$num_iters
[1] 16

$getValue
function (objet)
{
if (is(objet, "Variable") || is(objet, "Constraint")) {
return(result[[as.character(id(objet))]])
}
if (is_zero(objet)) {
size <- size(objet)
valResult <- matrix(0, nrow = size[1], ncol = size[2])
}
else {
arg_values <- list()
idx <- 1
for (arg in objet@args) {
arg_val <- if (is_constant(arg)) {
value(arg)
}
else {
getValue(arg)
}
if (is.null(arg_val) || (any(is.na(arg_val)) && !is_constant(objet)))
return(NA)
else {
arg_values[[idx]] <- arg_val
idx <- idx + 1
}
}
valResult <- to_numeric(objet, arg_values)
}
if (all(intf_size(valResult) == c(1, 1)))
intf_scalar_value(valResult)
else valResult
}
<bytecode: 0x0000000015286ea8>
<environment: 0x000000002203dbb0>

$getDualValue
function (objet)
{
if (!is(objet, "Constraint")) {
stop("getDualValue: argument should be a Constraint!")
}
getValue(objet)
}
<bytecode: 0x0000000015285b58>
<environment: 0x000000002203dbb0>

$delta
Variable(10, 1)

(scs) verbose option does not work under standard R

But does work, in some sense, under Rstudio.

  1. the code
library("scs")	
library("CVXR")	


nCol =5
nRow = 50

AA = matrix(rnorm(nRow*nCol),ncol=nCol)
x = Variable( ncol( AA)) 
y = Variable( nrow( AA))

objective1   = Minimize(  sum(y) )
constraints  = list(  x<=10,x>= -10,
	                     AA %*% x <= y,
	                     AA %*% x >= -y,
	                     sum(x) > 10)

prob1 = Problem( objective1, constraints)	
	

solut2	=	psolve( prob1,verbose=TRUE,solver="SCS",max_iters=20000,warm_start=FALSE)	
  1. an R session with it. See how no print output comes, in spite of the computation going through.
R version 3.6.1 (2019-07-05) -- "Action of the Toes"
Copyright (C) 2019 The R Foundation for Statistical Computing
Platform: x86_64-w64-mingw32/x64 (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

> library("scs")
> library("CVXR")

Attaching package: ‘CVXR’

The following object is masked from ‘package:stats’:

    power

> 
> 
> nCol =5
> nRow = 50
> 
> AA = matrix(rnorm(nRow*nCol),ncol=nCol)
> x = Variable( ncol( AA)) 
> y = Variable( nrow( AA))
> 
> objective1   = Minimize(  sum(y) )
> constraints  = list(  x<=10,x>= -10,
+                      AA %*% x <= y,
+                      AA %*% x >= -y,
+                      sum(x) > 10)
> 
> prob1 = Problem( objective1, constraints)
> 
> 
> solut2=psolve( prob1,verbose=TRUE,solver="SCS",max_iters=20000,warm_start=FALSE)
> solut2=psolve( prob1,verbose=TRUE,solver="SCS",max_iters=20000,warm_start=FALSE)
> str(solut2)
List of 15
 $ status      : chr "optimal"
 $ value       : num 159
 $ 3           : num [1:50, 1] 6.44 4.42 1.28 7.22 2.57 ...
 $ 2           : num [1:5, 1] 1.38 1.82 2.06 2.52 2.21
 $ 5           : num [1:5, 1] 0 0 0 0 0
 $ 7           : num [1:5, 1] 0 0 0 0 0
 $ 9           : num [1:50, 1] 0 1 1 0 1 ...
 $ 11          : num [1:50, 1] 1 0 0 1 0 ...
 $ 13          : num 15.9
 $ solver      : chr "SCS"
 $ solve_time  : num 0.00681
 $ setup_time  : num 0.000145
 $ num_iters   : int 160
 $ getValue    :function (objet)  
 $ getDualValue:function (objet)  
> 
  1. session info
> sessionInfo()
R version 3.6.1 (2019-07-05)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)

Matrix products: default

locale:
[1] LC_COLLATE=French_France.1252  LC_CTYPE=French_France.1252    LC_MONETARY=French_France.1252 LC_NUMERIC=C                   LC_TIME=French_France.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] CVXR_0.99-7 scs_1.3-2  

loaded via a namespace (and not attached):
 [1] bit_1.1-14        compiler_3.6.1    R6_2.4.1          Matrix_1.2-17     gmp_0.5-13.5      Rcpp_1.0.3        bit64_0.9-7       R.methodsS3_1.7.1 grid_3.6.1        R.utils_2.9.0     ECOSolveR_0.5.3  
[12] Rmpfr_0.7-2       R.oo_1.23.0       lattice_0.20-38  
> 

  1. Rstudio Session, same code from within a notebook, shows the little trick to make it work: I need to call the solver three times, which then flushes the print buffer (my guess), and I do get all three printouts (not sure how practical that is with long computes…)
  • the buffer flush is also not complete...see at the very last lines.

R version 3.6.1 (2019-07-05) -- "Action of the Toes"
Copyright (C) 2019 The R Foundation for Statistical Computing
Platform: x86_64-w64-mingw32/x64 (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

> 
> 
> library("scs")	
> library("CVXR")	

Attaching package: ‘CVXR’

The following object is masked from ‘package:stats’:

    power

> 
> 
> nCol =5
> nRow = 50
> 
> AA = matrix(rnorm(nRow*nCol),ncol=nCol)
> x = Variable( ncol( AA)) 
> y = Variable( nrow( AA))
> 
> objective1   = Minimize(  sum(y) )
> constraints  = list(  x<=10,x>= -10,
+ 	                     AA %*% x <= y,
+ 	                     AA %*% x >= -y,
+ 	                     sum(x) > 10)
> 
> prob1 = Problem( objective1, constraints)	
> 	
> 
> solut2	=	psolve( prob1,verbose=TRUE,solver="SCS",max_iters=20000,warm_start=FALSE)	
> 
> solut2	=	psolve( prob1,verbose=TRUE,solver="SCS",max_iters=20000,warm_start=FALSE)	
> 
> solut2	=	psolve( prob1,verbose=TRUE,solver="SCS",max_iters=20000,warm_start=FALSE)	
----------------------------------------------------------------------------
	SCS v2.1.1 - Splitting Conic Solver
	(c) Brendan O'Donoghue, Stanford University, 2012
----------------------------------------------------------------------------
Lin-sys: sparse-direct, nnz in A = 615
eps = 1.00e-005, alpha = 1.50, max_iters = 20000, normalize = 1, scale = 1.00
acceleration_lookback = 10, rho_x = 1.00e-003
Variables n = 55, constraints m = 111
Cones:	linear vars: 111
Setup time: 2.10e-004s
----------------------------------------------------------------------------
 Iter | pri res | dua res | rel gap | pri obj | dua obj | kap/tau | time (s)
----------------------------------------------------------------------------
     0|6.18e+019 4.64e+019 1.00e+000 -6.10e+021 1.79e+021 1.35e+022 2.53e-005 
   100|3.83e-004 9.81e-004 9.35e-005 1.59e+002 1.59e+002 1.01e-014 4.39e-003 
   180|5.26e-007 2.18e-006 1.88e-007 1.59e+002 1.59e+002 9.29e-015 7.85e-003 
----------------------------------------------------------------------------
Status: Solved
Timing: Solve time: 7.85e-003s
	Lin-sys: nnz in L factor: 849, avg solve time: 1.55e-006s
	Cones: avg projection time: 9.50e-008s
	Acceleration: avg step time: 3.97e-005s
----------------------------------------------------------------------------
Error metrics:
dist(s, K) = 1.9277e-015, dist(y, K*) = 0.0000e+000, s'y/|s||y| = 4.3360e-017
primal res: |Ax + s - b|_2 / (1 + |b|_2) = 5.2574e-007
dual res:   |A'y + c|_2 / (1 + |c|_2) = 2.1761e-006
rel gap:    |c'x + b'y| / (1 + |c'x| + |b'y|) = 1.8843e-007
----------------------------------------------------------------------------
c'x = 158.9533, -b'y = 158.9534
============================================================================
----------------------------------------------------------------------------
	SCS v2.1.1 - Splitting Conic Solver
	(c) Brendan O'Donoghue, Stanford University, 2012
----------------------------------------------------------------------------
Lin-sys: sparse-direct, nnz in A = 615
eps = 1.00e-005, alpha = 1.50, max_iters = 20000, normalize = 1, scale = 1.00
acceleration_lookback = 10, rho_x = 1.00e-003
Variables n = 55, constraints m = 111
Cones:	linear vars: 111
Setup time: 1.32e-004s
----------------------------------------------------------------------------
 Iter | pri res | dua res | rel gap | pri obj | dua obj | kap/tau | time (s)
----------------------------------------------------------------------------
     0|6.18e+019 4.64e+019 1.00e+000 -6.10e+021 1.79e+021 1.35e+022 1.95e-005 
   100|3.83e-004 9.81e-004 9.35e-005 1.59e+002 1.59e+002 1.01e-014 5.17e-003 
   180|5.26e-007 2.18e-006 1.88e-007 1.59e+002 1.59e+002 9.29e-015 8.54e-003 
----------------------------------------------------------------------------
Status: Solved
Timing: Solve time: 8.55e-003s
	Lin-sys: nnz in L factor: 849, avg solve time: 1.78e-006s
	Cones: avg projection time: 1.24e-007s
	Acceleration: avg step time: 4.30e-005s
----------------------------------------------------------------------------
Error metrics:
dist(s, K) = 1.9277e-015, dist(y, K*) = 0.0000e+000, s'y/|s||y| = 4.3360e-017
primal res: |Ax + s - b|_2 / (1 + |b|_2) = 5.2574e-007
dual res:   |A'y + c|_2 / (1 + |c|_2) = 2.1761e-006
rel gap:    |c'x + b'y| / (1 + |c'x| + |b'y|) = 1.8843e-007
----------------------------------------------------------------------------
c'x = 158.9533, -b'y = 158.9534
============================================================================
----------------------------------------------------------------------------
	SCS v2.1.1 - Splitting Conic Solver
	(c) Brendan O'Donoghue, Stanford University, 2012
----------------------------------------------------------------------------
Lin-sys: sparse-direct, nnz in A = 615
eps = 1.00e-005, alpha = 1.50, max_iters = 20000, normalize = 1, scale = 1.00
acceleration_lookback = 10, rho_x = 1.00e-003
Variables n = 55, constraints m = 111
Cones:	linear vars: 111
Setup time: 1.21e-004s
----------------------------------------------------------------------------
 Iter | pri res | dua res | rel gap | pri obj> 
> 

> 


Last but not least, Thank You for these great packages!

Installation of package ‘CVXR’ had non-zero exit status

Hi, I tried to use install.packages('CVXR') to install the CVXR package on linux-gnu, but I was failed. The showed errors are as follows. The r verion I used is 3.4.1 (2017-06-30).

  • compilation aborted for RcppCVXcanon.cpp (code 2) make: *** [RcppCVXcanon.o] Error 2
    ERROR: compilation failed for package ‘CVXR’
  • removing ‘/scratch/work/XXXX/R/3.4.1/CVXR’
  • The downloaded source packages are in
    ‘/tmp/Rtmpbl4UzJ/downloaded_packages’
  • Warning message:
    In install.packages("CVXR", repos = "https://CRAN.R-project.org") :
    installation of package ‘CVXR’ had non-zero exit status

So, Could you give me some help or suggestions? Thanks in advance.

how can I configure the solver to run on multiple threads?

I managed to do this on one pc (pure luck) and I would like to repeat the configuration on another pc but I am not getting it. I did not use de parallel=TRUE argument. ECOS and SCS are running in multiple cores without my control. Any tips? It follows my session info with the packages that I used in the multi-threaded version:

`R version 3.6.2 (2019-12-12)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.6 LTS

Matrix products: default
BLAS: /usr/lib/openblas-base/libblas.so.3
LAPACK: /usr/lib/libopenblasp-r0.2.18.so

locale:
[1] LC_CTYPE=pt_BR.UTF-8 LC_NUMERIC=C LC_TIME=pt_BR.UTF-8 LC_COLLATE=pt_BR.UTF-8
[5] LC_MONETARY=pt_BR.UTF-8 LC_MESSAGES=pt_BR.UTF-8 LC_PAPER=pt_BR.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C LC_MEASUREMENT=pt_BR.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats graphics grDevices utils datasets methods base

other attached packages:
[1] reticulate_1.14 zoo_1.8-7 CVXR_1.0

loaded via a namespace (and not attached):
[1] Rcpp_1.0.3 magrittr_1.5 MASS_7.3-51.5 bit_1.1-15.1
[5] lattice_0.20-38 R6_2.4.1 stringr_1.4.0 tools_3.6.2
[9] matrixcalc_1.0-3 grid_3.6.2 R.oo_1.23.0 audio_0.1-6
[13] R.matlab_3.6.2 SharpeR_1.2.0 bit64_0.9-7 Matrix_1.2-18
[17] gmp_0.5-13.5 beepr_1.3 R.utils_2.9.2 riskParityPortfolio_0.2.1
[21] stringi_1.4.5 compiler_3.6.2 Rmpfr_0.7-2 arrangements_1.1.8
[25] R.methodsS3_1.7.1 lubridate_1.7.4 expm_0.999-4 jsonlite_1.6 `

is_dcp has difference results on difference system (Mac, Linux and Windows)

Describe the bug
I ran a quadratic optimization by CVXR on Linux , Mac and Windows:

It's fine when i run code on windows and is_dcp(prob) returns true.

However, when I run the code on Linux and Mac. Some errors occured:

Error in construct_intermediate_chain(object, candidate_solvers, gp = gp) :
Problem does not follow DCP rules. However, the problem does follow DGP rules. Consider calling this function with gp = TRUE
Calls: byCVXR ... construct_intermediate_chain -> construct_intermediate_chain
Execution halted

To Reproduce
please load the R file and Rdata on https://uwmadison.box.com/s/eodz9ll2mrhqgq18do77dir6dekdx8xu.
(byCVXR.R cheak.RData)
and run : result <- byCVXR(summary.stat.study.F.sw,lambda_1 = len_lambda1[1] ,lambda_2 = len_lambda2[1],method='MetaMic')

CVXR Feasibility Problem

Hi,

Can CVXR solve feasibility problems like those found here: https://stanford.edu/class/ee363/notes/lmi-cvx.pdf

An example using CVX is:

cvx_begin sdp
 variable P(n,n) symmetric
 A'*P + P*A <= -eye(n)
 P >= eye(n)
cvx_end

As seen above, there is no minimization or maximization; just looking a P that satisfies the constraints.
If this is possibly using CVXR, which function could be used for it.
If no, can this functionality be added to the CVXR package?

Thank you

Need some help understanding how to vectorise constraint definition.

I'm using CVXR for the first time today, to perform a minimization of a max of a set of variables.

So i set my objective function as:

    O_j <- Variable(20)
    objective <- Minimize(max_entries(O_j))

So this should minimise the maximum of the 20 O_j values, as I understand it from the CVXR documentation.

Now in defining constraints, I am having issues in defining sets of constraints. Since I have 20 variables (and 2 more sets of 20 variables, which are mu_j and sigma_j), defining 20 constraints line by line is obviously tedious, and I am sure there is some way of aggregating this, for constraints that work by the universal quantifier/for all.

for example, one constraint is:

O[j] = 1-pnorm((C([j] -mu[j])/sigma[j])
for all j=1,2,3....20 (C is a constant vector of length 20)

I can replace the generic pnorm in R with p_norm in CVXR. But how will I aggregate all 20 constraints in one line of code? I'm new to using this package so I'm a bit confused.

Additionally, can functions like sqrt be used in constraints the same way or is there an equivalent for CVXR? I have a constraint which is:

`sigma[j] = sqrt(sum(P[i] * (1 - P[i]) * X[i,j] ) `

for all j = 1,2,3....20. Here, P is a constant vector of length 30. X is a variable defined as:

X_ij<-Int(30,20)
Now the sum here works like the excel function SUMPRODUCT(), that is,

P[1] * (1-P[1]) * X[1,j] + P[2] * (1-P[2]) * X[2,j] + ... + P[30] * (1-P[30]) * X[30,j]

I would normally do this using dplyr if I knew the values of X[ i , j ]. Will sum_entries work here?

The code works fine if I define each constraint line by line, but there must be a more efficient way to do this right? I know these doubts are pretty basic but I'm just starting to learn how to code with R/CVXR and any help would be appreciated. Thanks.

solver_error that shouldn't exist

When I try to execute the following example, I get a solver error. However, when I set the solver to the default ("ECOS"), it works. Obviously picking a solver isn't too cumbersome, but I wanted to bring this issue to attention as it appears to be a bug.

Thanks!

Example:

Set up data

n <- 7
r <- 1.05
m <- 200
V <- matrix(rep(0, m*n), m, n)
V[,1] <- r
V[,2] <- seq(.5, 2, (2-.5)/(m-1))
V[,3] <- pmax(0,(V[,2] - 1.1))
V[,4] <- pmax(0,(V[,2] - 1.2))
V[,5] <- pmax(0,(.8 - V[,2]))
V[,6] <- pmax(0,(.7 - V[,2]))
f <- .9
c<- 1.15
V[,7] <- pmin(pmax(V[,2]-1, f - 1), c - 1)
p <- rbind(1, 1, .06, .03, .02, .01)

CVXR Setup

p_collar <- Variable()
y <- Variable(m)
objective <- Maximize(p_collar)
constraints <- list(
y >= 0,
t(V) %*% y == rbind(p, p_collar)
)
problem <- Problem(objective, constraints)

solution <- solve(problem) #Solver returned with status solver_error

solution <- solve(problem, solver = 'ECOS') # Feasible Solution Found

unable to install on ubuntu bionic 18.04

Describe the bug
I am unable to install on Ubuntu. Package compiled successfully. Something went wrong afterwards.
The last few lines of error are shown below.

Output
installing to /home/s/R/x86_64-pc-linux-gnu-library/3.4/CVXR/libs
** R
** data
*** moving datasets to lazyload DB
** demo
** inst
** preparing package for lazy loading
Creating a generic function for ‘is.element’ from package ‘base’ in package ‘CVXR’
Creating a generic function for ‘nrow’ from package ‘base’ in package ‘CVXR’
Creating a generic function for ‘ncol’ from package ‘base’ in package ‘CVXR’
Error in attr(prototype, slotName) <- attr(pri, slotName) :
invalid first argument
Error : unable to load R code in package ‘CVXR’
ERROR: lazy loading failed for package ‘CVXR’

  • removing ‘/home/s/R/x86_64-pc-linux-gnu-library/3.4/CVXR’
    Warning in install.packages :
    installation of package ‘CVXR’ had non-zero exit status

The downloaded source packages are in
‘/tmp/RtmpIe6y6V/downloaded_packages’

library(CVXR)
Error in library(CVXR) : there is no package called ‘CVXR’

Version

sessionInfo()
R version 3.4.4 (2018-03-15)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 18.04.4 LTS

Matrix products: default
BLAS: /usr/lib/x86_64-linux-gnu/openblas/libblas.so.3
LAPACK: /usr/lib/x86_64-linux-gnu/libopenblasp-r0.2.20.so

locale:
[1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
[5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8 LC_PAPER=en_US.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats graphics grDevices utils datasets methods base

loaded via a namespace (and not attached):
[1] compiler_3.4.4 tools_3.4.4 grid_3.4.4 lattice_0.20-35

Constraint Problem

Hi,
I am porting an example of CVXPY using CVXR in R found here: https://groups.google.com/forum/#!topic/cvxpy/5hBSB9KVbuI

The Python Code:

import numpy as np
np.random.seed(1)
n = 8
m = 2
T = 50
alpha = 0.2
beta = 5
A = np.eye(n) + alpha*np.random.randn(n,n)
B = np.random.randn(n,m)
x_0 = beta*np.random.randn(n,1)

from cvxpy import *
x = Variable(n, T+1)
u = Variable(m, T)

states = []
for t in range(T):
    cost = sum_squares(x[:,t+1]) + sum_squares(u[:,t])
    constr = [x[:,t+1] == A*x[:,t] + B*u[:,t],
              norm(u[:,t], 'inf') <= 1]
    states.append( Problem(Minimize(cost), constr) )
# sums problem objectives and concatenates constraints.
prob = sum(states)
prob.constraints += [x[:,T] == 0, x[:,0] == x_0]
prob.solve()

This the R code:

n = 8
m = 2
T1 = 50
alpha = 0.2
beta = 5
A = pracma::eye(n) + alpha*pracma::randn(n,n)
B = pracma::randn(n,m)
x_0 = beta*pracma::randn(n,1)
x = Variable(n, T1+1)
u = Variable(m, T1)

states = c()
for (t in 1:T1) {
  cost = sum_squares(x[,t+1]) + sum_squares(u[,t])
constr = list(x[, t+1] == A*x[, t] + B*u[, t], pracma::Norm(u[,t], Inf) <= 1)
states = append(states, Problem(Minimize(cost), constr) )
}
prob = sum(states)
prob.constraints += [x[ ,T1] == 0, x[ ,0] == x_0]
prob.solve()

I am getting the following error:

Error in sum_shapes(lapply(object@args, function(arg) { :
Incompatible dimensions

I am suspecting it is from the following statement in the for loop because taking that line out shows a different case:

constr = list(x[, t+1] == Ax[, t] + Bu[, t], pracma::Norm(u[,t], Inf) <= 1)

Please could you look into this and suggest what could be possibly the cause for this error.

Thank you.

`power` doesn't handle `p` with length > 1

Describe the bug

Using power with a p argument that has length > 1 causes problems in several places.

To Reproduce

library(CVXR)
x = Variable(3)
p = c(1.1, 1.2, 1.3)
z = power(x, p)
#> Warning in if (p > 1) {: the condition has length > 1 and only the first element
#> will be used
#> Warning in if (p <= 1) stop("Must have p > 1"): the condition has length > 1 and
#> only the first element will be used
#> Warning in if (1/p == as.integer(1/p)) return(list(as.integer(1/p), c(p, : the
#> condition has length > 1 and only the first element will be used
#> Warning in if (p == 1) {: the condition has length > 1 and only the first
#> element will be used
#> Warning in if (p == 0) {: the condition has length > 1 and only the first
#> element will be used
prob = Problem(Minimize(sum(z)))
solve(prob)
#> Warning in if (object@p == 0) return(TRUE) else if (object@p == 1)
#> return(is_qpwa(object@args[[1]])) else if (object@p == : the condition has
#> length > 1 and only the first element will be used
#> Warning in if (object@p == 1) return(is_qpwa(object@args[[1]])) else if
#> (object@p == : the condition has length > 1 and only the first element will be
#> used
#> Warning in if (object@p == 2) return(is_pwl(object@args[[1]])) else
#> return(is_constant(object@args[[1]])): the condition has length > 1 and only the
#> first element will be used
#> Warning in if (p == 1) return(list(x, list())): the condition has length > 1 and
#> only the first element will be used
#> Warning in if (p == 0) return(list(ones, list())) else {: the condition has
#> length > 1 and only the first element will be used
#> Warning in if (p > 1) return(list(t, gm_constrs(x, list(t, ones), w))) else if
#> (p < : the condition has length > 1 and only the first element will be used
#> Error in all(valid_elems) && all.equal(sum(as.double(w)), 1): invalid 'y' type in 'x && y'

traceback()
#> 24: is_weight(p)
#> 23: gm_constrs(x, list(t, ones), w)
#> 22: object@canon_methods[[class(expr)]](expr, args)
#> 21: canonicalize_expr(object, expr, canon_args)
#> 20: canonicalize_expr(object, expr, canon_args)
#> 19: canonicalize_tree(object, arg)
#> 18: canonicalize_tree(object, arg)
#> 17: canonicalize_tree(object, arg)
#> 16: canonicalize_tree(object, arg)
#> 15: canonicalize_tree(object, problem@objective)
#> 14: canonicalize_tree(object, problem@objective)
#> 13: .nextMethod(object, problem)
#> 12: eval(call, callEnv)
#> 11: eval(call, callEnv)
#> 10: callNextMethod(object, problem)
#>  9: perform(r, problem)
#>  8: perform(r, problem)
#>  7: perform([email protected]_chain, object)
#>  6: perform([email protected]_chain, object)
#>  5: .construct_chains(object, solver = solver, gp = gp)
#>  4: psolve(a, solver = NA, ...)
#>  3: psolve(a, solver = NA, ...)
#>  2: solve(prob)
#>  1: solve(prob)

The error is the same if I use x ^ p instead of power(x, p).

Expected behavior

I expected the exponentiation to be applied element-wise to x. If that's not possible, it might be better to raise an error earlier when length(p) > 1. As the warnings say, the current code is only checking the first element of p for the various tests.

Output
See above.

Version
CVXR 1.0-1

Session info
R version 4.0.2 (2020-06-22)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 20.04.1 LTS

Matrix products: default
BLAS:   /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3
LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/liblapack.so.3

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] CVXR_1.0-1

loaded via a namespace (and not attached):
 [1] bit_4.0.4       compiler_4.0.2  R6_2.4.1        Matrix_1.2-18  
 [5] gmp_0.6-0       Rcpp_1.0.5      bit64_4.0.5     grid_4.0.2     
 [9] Rmpfr_0.8-1     lattice_0.20-41

Additional context
For background, my goal here was to solve a problem like the following, but with thousands of variables instead of two:

x = Variable(1)
y = Variable(1)
prob = Problem(Maximize(x^0.8 + y^0.9), list(x + y <= 1))
z = solve(prob)

Support CPLEX optimizer

Just noticede CVXR now supports Gurobi & Mosek - was wondering if it could also be made to support the CPLEX optimizer? (maybe using Rcplex or cplexAPI?)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.