Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 57 additions & 32 deletions pulp/apis/highs.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
from math import inf
from typing import TYPE_CHECKING, Any

import numpy as np

from .. import constants
from .core import (
LpSolver,
Expand Down Expand Up @@ -371,44 +373,67 @@ def buildSolverModel(self, lp):
exported_vars = lp.exported_variables()
id_to_col = {v.id: j for j, v in enumerate(exported_vars)}

# one addCols and one addRows call: per-column and per-row calls cost more
# than the solve itself on models that resolve in a few milliseconds, and the
# objective and constraint lookups are done once rather than once per column
cost = np.zeros(len(exported_vars))
for var, coefficient in lp.objective.items():
j = id_to_col.get(var.id)
if j is not None:
cost[j] = obj_mult * coefficient
lower = np.full(len(exported_vars), -inf)
upper = np.full(len(exported_vars), inf)
for j, var in enumerate(exported_vars):
lb = var.lowBound
ub = var.upBound
lp.solverModel.addCol(
obj_mult * lp.objective.get(var, 0.0),
-inf if lb is None else lb,
inf if ub is None else ub,
0,
[],
[],
)
if var.lowBound is not None:
lower[j] = var.lowBound
if var.upBound is not None:
upper[j] = var.upBound
empty = np.zeros(0, dtype=np.int32)
lp.solverModel.addCols(
len(exported_vars), cost, lower, upper, 0, empty, empty, np.zeros(0)
)

if var.cat == constants.LpInteger and self.mip:
lp.solverModel.changeColIntegrality(
j, highspy_mod.HighsVarType.kInteger
if self.mip:
integer = np.fromiter(
(
j
for j, var in enumerate(exported_vars)
if var.cat == constants.LpInteger
),
dtype=np.int32,
)
if len(integer):
lp.solverModel.changeColsIntegrality(
len(integer),
integer,
np.full(len(integer), highspy_mod.HighsVarType.kInteger),
)

for constraint in lp.constraints():
non_zero_constraint_items = [
(id_to_col[var.id], coefficient)
for var, coefficient in constraint.items()
if coefficient != 0
]

if len(non_zero_constraint_items) == 0:
indices, coefficients = [], []
else:
indices, coefficients = map(list, zip(*non_zero_constraint_items))

constraints = lp.constraints()
starts: list[int] = []
indices: list[int] = []
coefficients: list[float] = []
row_lower: list[float] = []
row_upper: list[float] = []
for constraint in constraints:
starts.append(len(indices))
for var, coefficient in constraint.items():
if coefficient != 0:
indices.append(id_to_col[var.id])
coefficients.append(coefficient)
lb = constraint.getLb()
ub = constraint.getUb()
lp.solverModel.addRow(
-inf if lb is None else lb,
inf if ub is None else ub,
len(indices),
indices,
coefficients,
)
row_lower.append(-inf if lb is None else lb)
row_upper.append(inf if ub is None else ub)
lp.solverModel.addRows(
len(constraints),
np.array(row_lower, dtype=np.float64),
np.array(row_upper, dtype=np.float64),
len(indices),
np.array(starts, dtype=np.int32),
np.array(indices, dtype=np.int32),
np.array(coefficients, dtype=np.float64),
)
if self.optionsDict.get("warmStart", False):
indices: list[int] = []
values: list[float] = []
Expand Down
34 changes: 34 additions & 0 deletions pulp/tests/test_highs.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from typing import ClassVar

import pulp.apis as solvers
from pulp import LpMaximize, LpProblem, const
from pulp.tests.bin_packing_problem import create_bin_packing_problem
from pulp.tests.solver_common import (
ALLOW_REPEATED_VAR_NAMES,
Expand All @@ -18,6 +19,39 @@ class HiGHS_PYTest(BaseSolverTest.PuLPTest):
"test_initial_value": PulpTestConfig(warm_start=True),
}

def test_model_arrays(self):
# the model HiGHS holds, column by column and row by row: a maximisation is
# negated, missing bounds are infinite and a zero coefficient is not an entry
import highspy

prob = LpProblem("arrays", LpMaximize)
x = prob.add_variable("x", 0, 4, cat=const.LpInteger)
y = prob.add_variable("y", None, None)
prob += 3 * x - 2 * y + 1, "obj"
prob += x + 0 * y <= 7, "c1"
prob += 2 * x - y >= -3, "c2"
prob += y == 5, "c3"
solver = solvers.HiGHS(msg=False)
prob.solverModel = highspy.Highs()
solver.buildSolverModel(prob)
lp = prob.solverModel.getLp()
inf = highspy.kHighsInf

self.assertEqual(lp.num_col_, 2)
self.assertEqual(lp.num_row_, 3)
self.assertEqual(list(lp.col_cost_), [-3, 2])
self.assertEqual(list(lp.col_lower_), [0, -inf])
self.assertEqual(list(lp.col_upper_), [4, inf])
self.assertEqual(
list(lp.integrality_),
[highspy.HighsVarType.kInteger, highspy.HighsVarType.kContinuous],
)
self.assertEqual(list(lp.row_lower_), [-inf, -3, 5])
self.assertEqual(list(lp.row_upper_), [7, inf, 5])
self.assertEqual(list(lp.a_matrix_.start_), [0, 1, 3, 4])
self.assertEqual(list(lp.a_matrix_.index_), [0, 0, 1, 1])
self.assertEqual(list(lp.a_matrix_.value_), [1, 2, -1, 1])

def test_callback(self):
prob = create_bin_packing_problem(bins=40, seed=99)

Expand Down
Loading