Count Binary Variables in JuMP Model

What is the proper way to count binary variables in my jump model?
I have been using:

MathOptInterface = MOI
    const_types = list_of_constraint_types(model)
    n_bin = 0
    n_lin = 0

    for i = 1:length(const_types)
        var = const_types[i][1]
        const_type = const_types[i][2]
        l = num_constraints(model, var, const_type)
        if const_type == MathOptInterface.ZeroOne
            n_bin += l
        else
            n_lin += l
        end
    end

And then we have number of binary variables is n_bin and number of real variables (Assuming there are only two types) is num_variables(model) - n_bin and number of constraints (all are linear) is n_lin. Does this seem right?

Probably just num_constraints(model, VariableRef, MOI.ZeroOne)?

Your count of the number of linear constraints includes things like variable bounds. Do instead:

n_bin, n_lin = 0, 0
for (F, S) in list_of_constraint_types(model)
    n = num_constraints(model, F, S)
    if S == MOI.ZeroOne
        n_bin += n
    end
    if F == AffExpr
        n_lin += n
    end
end
1 Like

Hi @odow, I have a follow-up (more like confirming if what I usually do is right or not):

Assuming the model has only continuous (both with bounds and unrestricted) and binary variables:

For continuous variables only: count(v -> !is_binary(v), all_variables(model))

For binary variables count(is_binary, all_variables(model))

For all constraints, including all bounds on variables:
num_constraints(model; count_variable_in_set_constraints = true)

Do these all look right? Thanks!

Yes, that’s one way to do this.

You could simplify to count(!is_binary, all_variables(model)).

1 Like

Thanks!