Skip to main content

Accessing the values of Mvars during optimization

Answered

Comments

3 comments

  • Quin Ackerman
    First Question
    First Comment

     Try using this:

    from gurobipy import Model, GRB
    import numpy as np

    # Create Gurobi model and define variables
    model = Model()
    mvars = model.addVars(n, vtype=GRB.CONTINUOUS, name="vars")

    # Define your PyCUTEst objective function
    def pycutest_objective_function(x):
        return np.sum(x**2)

    # Optimize the model and extract values
    model.optimize()
    if model.status == GRB.OPTIMAL:
        values = np.array(model.getAttr('X', mvars.values()))
        objective_value = pycutest_objective_function(values)
        print(f"Objective Value: {objective_value}")
    0
  • Harsh Gangwar
    First Question
    First Comment

    "'gurobipy.MVar' object has no attribute 'values'", I also checked Gurobi python API documentation the method values() is not listed there for the Mvars.

    0
  • Riley Clement
    Gurobi Staff Gurobi Staff

    Hi Harsh,

    I think it may be worthwhile familiarizing yourself with how models are formulated in our solver (and mixed integer programs more generally).

    Some quick examples can be found here: Functional Code Examples

    More thorough examples here: Resouce Center: Demos

    I need a method to extract the values of Gurobi decision variables (mvars) at any given instant to calculate the objective function...  Transfer the values of mvars to the PyCUTEst objective function during the optimization process.

    It is not possible to transfer values to an external function to be evaluated as the objective during the optimization.

    Alternatively, incorporate the PyCUTEst objective function directly into the Gurobi model.

    This is the right way to do it.  You need to examine what the PyCUTEst objective function is doing with the inputs and formulate it as an expression in Gurobi (before the optimization is run).

    - Riley

    0

Please sign in to leave a comment.