mirror of
https://github.com/ANL-CEEESA/MIPLearn.git
synced 2025-12-09 02:48:52 -06:00
Pyomo: implement build_maxcut_model; add support for quadratic objectives
This commit is contained in:
@@ -8,13 +8,14 @@ from typing import List, Union, Optional, Any
|
||||
import gurobipy as gp
|
||||
import networkx as nx
|
||||
import numpy as np
|
||||
from gurobipy import quicksum
|
||||
import pyomo.environ as pe
|
||||
from networkx import Graph
|
||||
from scipy.stats.distributions import rv_frozen
|
||||
|
||||
from miplearn.io import read_pkl_gz
|
||||
from miplearn.problems import _gurobipy_set_params
|
||||
from miplearn.problems import _gurobipy_set_params, _pyomo_set_params
|
||||
from miplearn.solvers.gurobi import GurobiModel
|
||||
from miplearn.solvers.pyomo import PyomoModel
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -99,7 +100,7 @@ def build_maxcut_model_gurobipy(
|
||||
|
||||
# Add the objective function
|
||||
model.setObjective(
|
||||
quicksum(
|
||||
gp.quicksum(
|
||||
-data.weights[i] * x[e[0]] * (1 - x[e[1]]) for (i, e) in enumerate(edges)
|
||||
)
|
||||
)
|
||||
@@ -108,6 +109,37 @@ def build_maxcut_model_gurobipy(
|
||||
return GurobiModel(model)
|
||||
|
||||
|
||||
def build_maxcut_model_pyomo(
|
||||
data: Union[str, MaxCutData],
|
||||
solver: str = "gurobi_persistent",
|
||||
params: Optional[dict[str, Any]] = None,
|
||||
) -> PyomoModel:
|
||||
# Initialize model
|
||||
model = pe.ConcreteModel()
|
||||
|
||||
# Read data
|
||||
data = _maxcut_read(data)
|
||||
nodes = pe.Set(initialize=list(data.graph.nodes))
|
||||
edges = list(data.graph.edges())
|
||||
|
||||
# Add decision variables
|
||||
model.x = pe.Var(nodes, domain=pe.Binary, name="x")
|
||||
|
||||
# Add the objective function
|
||||
model.obj = pe.Objective(
|
||||
expr=pe.quicksum(
|
||||
-data.weights[i] * model.x[e[0]]
|
||||
+ data.weights[i] * model.x[e[0]] * model.x[e[1]]
|
||||
for (i, e) in enumerate(edges)
|
||||
),
|
||||
sense=pe.minimize,
|
||||
)
|
||||
model.pprint()
|
||||
pm = PyomoModel(model, solver)
|
||||
_pyomo_set_params(model, params, solver)
|
||||
return pm
|
||||
|
||||
|
||||
def _maxcut_read(data: Union[str, MaxCutData]) -> MaxCutData:
|
||||
if isinstance(data, str):
|
||||
data = read_pkl_gz(data)
|
||||
|
||||
Reference in New Issue
Block a user