メインコンテンツへスキップ

obtain variable values from a program inside a function

回答済み

コメント

4件のコメント

  • 正式なコメント
    Simranjit Kaur
    • Gurobi Staff
    This post is more than two years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum, or try Gurobot, our chatbot interface offering instant, expert-level support.
  • 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

投稿コメントは受け付けていません。