Pyomo: Access Solution From Python Code

后端 未结 3 1476
[愿得一人]
[愿得一人] 2020-12-29 14:58

I have a linear integer programme I want to solve. I installed solver glpk (thanks to this answer) and pyomo. I wrote code like this:

from pyomo.environ impo         


        
3条回答
  •  孤独总比滥情好
    2020-12-29 15:44

    Here's a modified version of your script that illustrates two different ways of printing variable values: (1) by explicitly referencing each variable and (2) by iterating over all variables in the model.

    # Pyomo v4.4.1
    # Python 2.7
    from pyomo.environ import *
    from pyomo.opt import SolverFactory
    
    a = 370
    b = 420
    c = 4
    
    model             = ConcreteModel()
    model.x           = Var([1,2], domain=Binary)
    model.y           = Var([1,2], domain=Binary)
    model.Objective   = Objective(expr = a * model.x[1] + b * model.x[2] + (a-b)*model.y[1] + (a+b)*model.y[2], sense=maximize)
    model.Constraint1 = Constraint(expr = model.x[1] + model.x[2] + model.y[1] + model.y[2] <= c)
    
    opt = SolverFactory('glpk')
    
    results = opt.solve(model)
    
    #
    # Print values for each variable explicitly
    #
    print("Print values for each variable explicitly")
    for i in model.x:
      print str(model.x[i]), model.x[i].value
    for i in model.y:
      print str(model.y[i]), model.y[i].value
    print("")
    
    #
    # Print values for all variables
    #
    print("Print values for all variables")
    for v in model.component_data_objects(Var):
      print str(v), v.value
    

    Here's the output generated:

    Print values for each variable explicitly
    x[1] 1.0
    x[2] 1.0
    y[1] 0.0
    y[2] 1.0
    
    Print values for all variables
    x[1] 1.0
    x[2] 1.0
    y[1] 0.0
    y[2] 1.0
    

提交回复
热议问题