Skip to main content

obtain variable values from a program inside a function

Answered

Comments

3 comments

  • Riley Clement
    • Gurobi Staff

    Hi Iason,

    The solution values are stored in the X attribute of variables.  If you have a variable v, then you can use v.X.  If you would prefer to retrieve many values at once, for a collection of variables "vars", then you can use the getAttr method:

    sol_values = my_model.getAttr("X", vars)

    - Riley

    0
  • Iason Liagkas
    • Gurobi-versary
    • Detective
    • Thought Leader

    Thank you so much Riley

    0
  • Iason Liagkas
    • Gurobi-versary
    • Detective
    • Thought Leader

    Another way just for future reference is: where subproblem is the name of the model.

    # Define the prefix to match your variable naming pattern
    # This should match the variable name pattern used when adding variables to the model.
    # For example, if you named them like 'T[k,i][rs]', use that pattern here.
    prefix = "T_{k,i}^{rs}["  # This is a simplified prefix, adjust it to match your exact names

    # Assuming 'subproblem' is your Gurobi Model object and it's been optimized
    subproblem.optimize()

    # Check the optimization status before trying to access variable values
    if subproblem.status == GRB.OPTIMAL:

        # Get the list of all variable objects in the subproblem
        variables = subproblem.getVars()

        # Filter variables whose name starts with the specific pattern
        # Replace v.varName.startswith(prefix) with the appropriate pattern matching for your problem
        filtered_variables = [(v.varName, v.x) for v in variables if v.varName.startswith(prefix)]

        # Print the filtered variables
        for name, value in filtered_variables:
            print(f"Variable {name} has value {value}")


    0

Please sign in to leave a comment.