jump-dev / Convex.jl

A Julia package for disciplined convex programming
https://jump.dev/Convex.jl/stable/
Other
572 stars 123 forks source link

[Feature Request] Support Boolean Indexing for Constraints #707

Open RoyiAvital opened 4 days ago

RoyiAvital commented 4 days ago

It seems there is no support for using BitVector in constraints.

A simple (Stupid) example:

using Convex;
using ECOS;

numSamples = 100;
vY = rand(numSamples);

valThr = sort(vY, rev = true)[5];
vP = vY .>= valThr; #<! Set of boolean indices

vX = Variable(numSamples);
sConvProb = minimize( 0.5 * sumsquares(vX - vY), [vX[vP] == vY[vP]] ); #<! Will fail
solve!(sConvProb, ECOS.Optimizer; silent = true);

If one define vPi = findall(vP); then [vX[vPi] == vY[vPi]] will work.

odow commented 4 days ago

PRs accepted.

It's pretty much just this method, but for BitVector:

https://github.com/jump-dev/Convex.jl/blob/cc71b51d55109e8c9ca29cc91fe1b37176c229ac/src/atoms/IndexAtom.jl#L112-L118

RoyiAvital commented 4 days ago

I can add those with BitVector and BitMatrix.
I tried looking at the tests, should a specific test be added?

odow commented 4 days ago

Add a new function after:

https://github.com/jump-dev/Convex.jl/blob/cc71b51d55109e8c9ca29cc91fe1b37176c229ac/test/test_atoms.jl#L470-L544

I assume you want something like:

     target = """ 
     variables: x1, x2, x3 
     minobjective: [1.0 * x1, 1.0 * x3] 
     """ 
     _test_atom(target) do context 
         x = Variable(3)
         y = BitVector([true, false, true])
         return x[y] 
     end