Trying to save MPS from raw solver and problems with MOI.RawSolver()

I am having problems with JuMP.write_to_file which calls MOI.write_to_file. I had some problems using Model with no solver attached (because this calls the MOI function mentioned above and, at the moment, it seems a little memory-hungry and limited, not supporting .rew and the like), so I wanted to try having a solver attached (CPLEX or Gurobi), and using it to write the MPS and started writing an alternative to JuMP.write_to_file that tried to be native if possible, however I am hitting some problems.

My code is here, the highlighted line emphasizes my current problem. Independently of the the model being a direct_model or a Model, I hit a ERROR: OptimizeNotCalled() for trying to get the MOI.RawSolver() from the model object to call the specific solver saving/writing method. I tried MOI.attach_optimizer when it is a Model (and has a CachingOptimizer underlying) but this had no effect.

I guess you need something like:

native_write(model::Model) = native_write(backend(model))
function native_write(model::MOI.Utilities.CachingOptimizer)
    MOI.Utilities.attach_optimizer(model)
    return native_write(model.optimizer)
end
native_write(model::MOI.Bridges.LazyBridgeOptimizer) = native_write(model.model)

function native_write(model::Gurobi.Optimizer)
    # ...
end
function native_write(model::CPLEX.Optimizer)
    # ...
end
1 Like

Thank you very much odow, I thought about pinging you, but it is easter and I did not want to be a bother.

1 Like

Worked like a charm. I kept my old logic to be able to fallback to JuMP.write_to_file if the solver is not recognized by the module (i.e., nobody extended the right functions), so I used your idea to be able to get the raw solver from a Model or direct_model in lines 22–33 of this file.

Now I just need to check if JuMP.read_from_file is able to parse back the native MPS files, XD.

Do you think JuMP/MOI may want to have this functionality in the future? I did not open a issua/PR because I had no time to go through the approval process this time, but in the future I can port this feature to JuMP/MOI.