MOI Count Repetitions of Integers

Given a vector of integers, is there a MOI constraint that will count the number of repetitions of each distinct integer in the vector?

You can use MOI.CountBelongs:

using JuMP, HiGHS
model = Model(HiGHS.Optimizer);
set_silent(model)
N = 3
l, u = 0, 3
@variable(model, l <= x[1:N] <= u, Int)
@variable(model, n[l:u], Int)
# n[i] is the count of how many `i` are in x
@constraint(model, [i=l:u], [n[i]; x] in MOI.CountBelongs(1+N, Set([i])))
optimize!(model)
value.(n), value.(x)
1 Like

Given your recent questions (MathOptInterface Documentation - #8 by odow), I’ll add a page to the JuMP documentation with a bunch of these short snippets.

Is there a way to first find the set S of distinct integers in the vector x, where S is a subset of l:u? If so, would this be more efficient? For example, what if the size of S were much smaller than the size of l:u (u-l+1)?
@variable(model, n[S], Int)
@constraint(model, [i=S], [n[i]; x] in MOI.CountBelongs(1+N, Set([i])))

Here’s the PR to improve the JuMP documentation: [docs] add tutorial on constraint programming by odow · Pull Request #3202 · jump-dev/JuMP.jl · GitHub

Is there a way to first find the set S of distinct integers in the vector x

You want to dynamically choose S and count them? I don’t think so. That seems like a hard problem.

@constraint(model, [i=l:u], [n[i]; x] in MOI.CountBelongs(1+N, Set([i])))

How would I find the set J = {j : n[j] = m} for a particular count m? Is it possible to sort J in increasing order?

The new docs of what you can do in JuMP are here: Constraint programming · JuMP

It’s not a fully fledged constraint programming system, so you’ll have to rewrite what you’re trying to do in terms of the available primitives. Things like sort, and nnz (from our emails) aren’t supported.