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