Filtering variables on model copy

I am looking to take a model model_1 and “duplicate” it into model_2 (using copy_model) while only keeping a specific part of the original model. I know

  • that I can use filter_constraints to mask out constraints that I do not want to keep
  • that filtering variables is not that easy, because it could be that I’m keeping a constraint, that contains a variable, that I’m dropping (and there is no “right” way to decide what should happen)

But, let’s say I have a list of constraints that I want to keep. What is the most efficient way to create a copy, that contains these constraints, as well as all variables in these constraints?

Obviously I could just copy the whole model, with filter_constraints, and then remove all variables that are not part of these constraints. But that could be an extreme overhead if those constraints only contain a small portion of all variables …

I don’t think there’s an easy way. You’d need to first loop over the constraints and build a set of variables to keep.

We copy the variables first, and the constraints second, so there’s no way to know when copying the variables if they’re later going to appear in a constraint that you will keep.

I would actually have that. I don’t know if that could make sense (in the future), but a “filter_variables” parameter could then be used during the “copy the variables first” step? (again with the problem that this could lead to problems when copying the constraints if the relevant variables do not exist; but that would be a “user error”).

Whats the use case for this? We generally recommend against copying models. The filter was mainly added to access the IIS.

The use case would be doing “general” decomposition on some JuMP model. E.g. Benders, or ADMM. I start from a predefined model, with some guidance on “where” to decompose and therefore need one (or many) copies of the original problem, but with a reduced set of variables or constraints.

For the Benders example:

  1. Build the “normal” model
  2. Copy the model into a master model, keeping all constraints that are linked to master variables, as well as all master variables (and maybe their objective coefficients)
  3. Potentially modify the sub model, removing those constraints (may be faster to keep them, since they are then only related to fixed variables - the ones determined by the master - and could be eliminated during presolve anyways)

I opened a feature request. This first needs support in MOI: [Utilities] Add support for filtering variables in ModelFilter · Issue #2308 · jump-dev/MathOptInterface.jl · GitHub