Skip to content

Commit

Permalink
Improve performance for large models (#750)
Browse files Browse the repository at this point in the history
* Avoid allocating an additional LpAffineExpression when creating a LpConstraint comparing against an int or float

* LpConstraint no longer inherits from LpAffineExpression to avoid unnecessary copying of LpAffineExpression's contents

* Avoid creating tempory lists when not needed

* cplex_api: Avoid creating temporary lists in buildSolverModel

* Format with black

* Avoid allocating an extra list in LpAffineExpression.sorted_keys

* Add missing asCplexLpAffineExpression function to LpConstraint

* Add missing isAtomic and atom functions to LpConstraint

* Fix formatting with black

* fixed type of self.constraints

---------

Co-authored-by: pchtsp <pchtsp@gmail.com>
  • Loading branch information
MBradbury and pchtsp authored Feb 19, 2025
1 parent c06fe08 commit 5e5ca19
Show file tree
Hide file tree
Showing 2 changed files with 179 additions and 93 deletions.
14 changes: 8 additions & 6 deletions pulp/apis/cplex_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,8 @@ def buildSolverModel(self, lp):
lp.solverModel.objective.set_sense(
lp.solverModel.objective.sense.maximize
)
if lp.objective is None:
raise PulpSolverError("No objective set")
obj = [float(lp.objective.get(var, 0.0)) for var in model_variables]

def cplex_var_lb(var):
Expand Down Expand Up @@ -372,15 +374,16 @@ def cplex_var_types(var):
rows = []
senses = []
rhs = []
rownames = []
for name, constraint in lp.constraints.items():
rownames = list(lp.constraints.keys())
for constraint in lp.constraints.values():
# build the expression
expr = [(var.name, float(coeff)) for var, coeff in constraint.items()]
if not expr:
if len(constraint) == 0:
# if the constraint is empty
rows.append(([], []))
else:
rows.append(list(zip(*expr)))
expr1 = [var.name for var in constraint.keys()]
expr2 = [float(coeff) for coeff in constraint.values()]
rows.append((expr1, expr2))
if constraint.sense == constants.LpConstraintLE:
senses.append("L")
elif constraint.sense == constants.LpConstraintGE:
Expand All @@ -389,7 +392,6 @@ def cplex_var_types(var):
senses.append("E")
else:
raise PulpSolverError("Detected an invalid constraint type")
rownames.append(name)
rhs.append(float(-constraint.constant))
lp.solverModel.linear_constraints.add(
lin_expr=rows, senses=senses, rhs=rhs, names=rownames
Expand Down
Loading

0 comments on commit 5e5ca19

Please sign in to comment.