Попытка решить модель, используя pyomo и bonmin.Модель не передана в решатель правильно - PullRequest
1 голос
/ 23 мая 2019

Я хочу использовать Pyomo и Bonmin на семинаре по исследованию операций, посвященном «Алгоритму расширенной поддержки гиперплоскости» от Kronqvist. Я хочу использовать bonmin для сравнения производительности алгоритма. Сначала я хочу проверить, правильно ли установлен Bonmin и работает ли он вместе с pyomo, поэтому я смоделировал пример из статьи, упомянутой выше. Это выпуклая проблема, поэтому bonmin должен быть в состоянии ее решить.

Моя ОС - Windows 7, поэтому я установил Bonmin с помощью Cygwin и добавил его в PATh. Я не заметил ни одного сообщения об ошибке во время установки. Для программирования я использую Anaconda с ноутбуком Jupyter.

В настоящее время я читаю документацию по pyomos, но пока мне не повезло.

from pyomo.environ import *
import numpy
import scipy

# Konkretes Optimierungsproblem

model = ConcreteModel(name = "Example 1")

model.x1 = Var(bounds=(1,20), within=Reals)
model.x2 = Var(bounds=(1,20), within=Integers)

model.obj = Objective(expr=(-1)*model.x1-model.x2)

model.g1 = Constraint(expr=0.15*((model.x1 - 8)**2)+0.1*((model.x2 - 6)**2)+0.025*exp(model.x1)*((model.x2)**(-2))-5<=0)
model.g2 = Constraint(expr=(model.x1)**(-1) + (model.x2)**(-1) - (model.x1)**(-0.5) * (model.x2) ** (-0.5)+4<=0)
model.l1 = Constraint(expr=2 * (model.x1) - 3 * (model.x2) -2<=0)

#Just some output to analze the generated model

print(model)
dir(model)
print(model.g2.expr)
model.x1 = 5
print(value(model.x1))

opt = SolverFactory('bonmin')
#opt.options['bonmin.algorithm'] = 'Bonmin'
print('using Bonmin')
# Set Options for solver.
opt.options['bonmin.solution_limit'] = '1'
opt.options['bonmin.time_limit'] = 1800
results = opt.solve(model)
results.write()

Вот результаты:

using Bonmin
WARNING: Loading a SolverResults object with a warning status into
    model=Example 1;
        message from solver=bonmin\x3a Infeasible problem
# ==========================================================
# = Solver Results                                         =
# ==========================================================
# ----------------------------------------------------------
#   Problem Information
# ----------------------------------------------------------
Problem: 
- Lower bound: -inf
  Upper bound: inf
  Number of objectives: 1
  Number of constraints: 0
  Number of variables: 0
  Sense: unknown
# ----------------------------------------------------------
#   Solver Information
# ----------------------------------------------------------
Solver: 
- Status: warning
  Message: bonmin\x3a Infeasible problem
  Termination condition: infeasible
  Id: 220
  Error rc: 0
  Time: 0.16000056266784668
# ----------------------------------------------------------
#   Solution Information
# ----------------------------------------------------------
Solution: 
- number of solutions: 0
  number of solutions displayed: 0

Как видите, модель не передана решателю правильно, поскольку, согласно решателю, проблема не имеет ни ограничений, ни переменных.

Может быть, проблема в том, что предупреждающие сообщения Солвера означают, что он установлен неправильно или это из-за невозможности решения проблемы?

Редактировать: как предложено Бетани Николсон в комментариях, я добавил опцию tee=tree в коде, что привело к следующему выводу

using Bonmin
Bonmin 1.8.7 using Cbc 2.10.0 and Ipopt 3.12.12
bonmin: bonmin.solution_limit=1
bonmin.time_limit=1800
bonmin.solution_limit=1
bonmin.time_limit=1800


******************************************************************************
This program contains Ipopt, a library for large-scale nonlinear optimization.
 Ipopt is released as open source code under the Eclipse Public License (EPL).
         For more information visit http://projects.coin-or.org/Ipopt
******************************************************************************

NLP0012I 
              Num      Status      Obj             It       time                 Location
NLP0014I             1      INFEAS 4.0986776       27 0.031
NLP0014I             2      INFEAS 4.0986776       27 0.015
Cbc0006I The LP relaxation is infeasible or too expensive

    "Finished"
WARNING: Loading a SolverResults object with a warning status into
    model=Example 1;
        message from solver=bonmin\x3a Infeasible problem
# ==========================================================
# = Solver Results                                         =
# ==========================================================
# ----------------------------------------------------------
#   Problem Information
# ----------------------------------------------------------
Problem: 
- Lower bound: -inf
  Upper bound: inf
  Number of objectives: 1
  Number of constraints: 0
  Number of variables: 0
  Sense: unknown
# ----------------------------------------------------------
#   Solver Information
# ----------------------------------------------------------
Solver: 
- Status: warning
  Message: bonmin\x3a Infeasible problem
  Termination condition: infeasible
  Id: 220
  Error rc: 0
  Time: 0.23000025749206543
# ----------------------------------------------------------
#   Solution Information
# ----------------------------------------------------------
Solution: 
- number of solutions: 0
  number of solutions displayed: 0

Редактировать 2: я пробовал другие простые проблемы. В то время как проблема решена корректно (x1 = 4, x2 = 2, minvalue = -10) Bonmin, его вывод утверждает, что задачи, переданные решателю, не имеют ограничений, когда он явно имеет пять (даже если четыре можно интерпретировать как границы). Кроме того, вывод все еще кажется мне немного странным. Почему указывается «количество решений = 0»? (Я еще не закончил с полной документацией по pyomo, возможно, мне просто нужно установить дополнительные параметры) Вот линейная задача:

from pyomo.environ import *
import numpy
import scipy

model = ConcreteModel(name = "Linear problem")

model.x1 = Var(domain = Reals)
model.x2 = Var(domain = Reals)

model.obj = Objective(expr=-1*(2*model.x1+model.x2))

model.l1 = Constraint(expr=model.x1>=0)
model.l2 = Constraint(expr=model.x2>=0)
model.l3 = Constraint(expr=model.x1<=4)
model.l4 = Constraint(expr=model.x2<=4)
model.l5 = Constraint(expr=model.x1+model.x2<=6)
model.pprint()
2 Var Declarations
    x1 : Size=1, Index=None
        Key  : Lower : Value : Upper : Fixed : Stale : Domain
        None :  None :  None :  None : False :  True :  Reals
    x2 : Size=1, Index=None
        Key  : Lower : Value : Upper : Fixed : Stale : Domain
        None :  None :  None :  None : False :  True :  Reals

1 Objective Declarations
    obj : Size=1, Index=None, Active=True
        Key  : Active : Sense    : Expression
        None :   True : minimize : - (2*x1 + x2)

5 Constraint Declarations
    l1 : Size=1, Index=None, Active=True
        Key  : Lower : Body : Upper : Active
        None :   0.0 :   x1 :  +Inf :   True
    l2 : Size=1, Index=None, Active=True
        Key  : Lower : Body : Upper : Active
        None :   0.0 :   x2 :  +Inf :   True
    l3 : Size=1, Index=None, Active=True
        Key  : Lower : Body : Upper : Active
        None :  -Inf :   x1 :   4.0 :   True
    l4 : Size=1, Index=None, Active=True
        Key  : Lower : Body : Upper : Active
        None :  -Inf :   x2 :   4.0 :   True
    l5 : Size=1, Index=None, Active=True
        Key  : Lower : Body    : Upper : Active
        None :  -Inf : x1 + x2 :   6.0 :   True

8 Declarations: x1 x2 obj l1 l2 l3 l4 l5

opt = SolverFactory('bonmin')
opt.options['bonmin.solution_limit'] = '1'
opt.options['bonmin.time_limit'] = 1800
results = opt.solve(model, tee = True)
results.write()

Bonmin 1.8.7 using Cbc 2.10.0 and Ipopt 3.12.12
bonmin: bonmin.solution_limit=1
bonmin.time_limit=1800
bonmin.solution_limit=1
bonmin.time_limit=1800

Cbc3007W No integer variables - nothing to do

******************************************************************************
This program contains Ipopt, a library for large-scale nonlinear optimization.
 Ipopt is released as open source code under the Eclipse Public License (EPL).
         For more information visit http://projects.coin-or.org/Ipopt
******************************************************************************

NLP0012I 
              Num      Status      Obj             It       time                 Location
NLP0014I             1         OPT -10        4 0
Cbc3007W No integer variables - nothing to do

    "Finished"
# ==========================================================
# = Solver Results                                         =
# ==========================================================
# ----------------------------------------------------------
#   Problem Information
# ----------------------------------------------------------
Problem: 
- Lower bound: -inf
  Upper bound: inf
  Number of objectives: 1
  Number of constraints: 0
  Number of variables: 2
  Sense: unknown
# ----------------------------------------------------------
#   Solver Information
# ----------------------------------------------------------
Solver: 
- Status: ok
  Message: bonmin\x3a Optimal
  Termination condition: optimal
  Id: 3
  Error rc: 0
  Time: 0.20000028610229492
# ----------------------------------------------------------
#   Solution Information
# ----------------------------------------------------------
Solution: 
- number of solutions: 0
  number of solutions displayed: 0

Прошу прощения, если я, кажется, спамить свой пост с кодом. Просто подумал, что это будет полезно, так как я думаю, что это указывает на то, что проблема заключается в решателе, а не в моделировании с pyomo.

1 Ответ

0 голосов
/ 29 мая 2019

У меня вчера была встреча с моим репетитором. Я на самом деле упустил из виду ошибку в модели, которая сделала ее невозможной. Bonmin решает проблему правильно, но результат все равно выглядит странно (например, модель не имеет ограничений). Он также понимает несколько странный вывод решателя, однако, он сказал, что я не должен больше этим заниматься.

Я глубоко извиняюсь за такую ​​глупую ошибку. Надеюсь, никто не потратил много времени на размышления по этому вопросу (кроме меня, конечно).

...