Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python optimization libraries find the inputs that minimize or maximize an objective, subject to constraints. A dedicated solver handles one class of problem, such as linear, quadratic, or conic programs, rather than an arbitrary function. These libraries let engineers and data scientists tune models, schedules, and designs toward the best result.
Popularity
SciPy has the most monthly downloads in this comparison, at 392.1M, a count that covers all its scientific computing.
from ortools.linear_solver import pywraplp
solver = pywraplp.Solver.CreateSolver("GLOP")
x = solver.NumVar(0.0, 3.0, "x")
solver.Add(x >= 1.0)
solver.Minimize(x)
status = solver.Solve()
if status == pywraplp.Solver.OPTIMAL:
print(x.solution_value())
def build_model(self, divergence, n_nonevent, n_event, trend_change):
# Parameters [D, V, pvalue_violation_indices,
min_diff_violation_indices] = model_data(
divergence, n_nonevent, n_event, self.max_pvalue,
self.max_pvalue_policy, self.min_event_rate_diff)
n = len(n_nonevent)
n_records = n_nonevent + n_event
# Initialize solver if self.mip_solver == "bop":
solver = pywraplp.Solver(
'BinningMIP', pywraplp.Solver.BOP_INTEGER_PROGRAMMING)
elif self.mip_solver == "cbc":
solver = pywraplp.Solver(
'BinningMIP', pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
# Decision variables x, y, t, d, u, bin_size_diff = self.decision_variables(solver, n)
# Objective function if self.gamma:
total_records = int(n_records.sum())
regularization = self.gamma / total_records
pmax = solver.IntVar(0, total_records, "pmax")
pmin = solver.IntVar(0, total_records, "pmin")
solver.Maximize(solver.Sum([(V[i][i] * x[i, i]) +
solver.Sum([(V[i][j] - V[i][j+1]) * x[i, j]
for j in range(i)])
for i in range(n)]) -
regularization * (pmax - pmin))
else:
solver.Maximize(solver.Sum([(V[i][i] * x[i, i]) +
solver.Sum([(V[i][j] - V[i][j+1]) * x[i, j]
for j in range(i)])
for i in range(n)]))
# Constraint: unique assignment self.add_constraint_unique_assignment(solver, n, x)
# Constraint: continuity self.add_constraint_continuity(solver, n, x)
# Constraint: min / max bins self.add_constraint_min_max_bins(solver, n, x, d)
# Constraint: min / max bin size self.add_constraint_min_max_bin_size(solver, n, x, u, n_records,
bin_size_diff)
# Constraint: min / max n_nonevent per bin if (self.min_bin_n_nonevent is not None or
self.max_bin_n_nonevent is not None):
for i in range(n):
bin_ne_size = solver.Sum([n_nonevent[j] * x[i, j]
for j in range(i + 1)])
if self.min_bin_n_nonevent is not None:
solver.Add(bin_ne_size >= self.min_bin_n_nonevent*x[i, i])
if self.max_bin_n_nonevent is not None:
solver.Add(bin_ne_size <= self.max_bin_n_nonevent*x[i, i])
# Constraint: min / max n_event per bin if (self.min_bin_n_event is not None or
self.max_bin_n_event is not None):
for i in range(n):
bin_e_size = solver.Sum([n_event[j] * x[i, j]
for j in range(i + 1)])
if self.min_bin_n_event is not None:
solver.Add(bin_e_size >= self.min_bin_n_event * x[i, i])
if self.max_bin_n_event is not None:
solver.Add(bin_e_size <= self.max_bin_n_event * x[i, i])
# Constraints: monotonicity if self.monotonic_trend == "ascending":
self.add_constraint_monotonic_ascending(solver, n, D, x)
elif self.monotonic_trend == "descending":
self.add_constraint_monotonic_descending(solver, n, D, x)
elif self.monotonic_trend == "concave":
self.add_constraint_monotonic_concave(solver, n, D, x)
elif self.monotonic_trend == "convex":
self.add_constraint_monotonic_convex(solver, n, D, x)
elif self.monotonic_trend in ("peak", "valley"):
for i in range(n):
solver.Add(t >= i - n * (1 - y[i]))
solver.Add(t <= i + n * y[i])
if self.monotonic_trend == "peak":
self.add_constraint_monotonic_peak(solver, n, D, x, y)
else:
self.add_constraint_monotonic_valley(solver, n, D, x, y)
elif self.monotonic_trend == "peak_heuristic":
self.add_constraint_monotonic_peak_heuristic(
solver, n, D, x, trend_change)
elif self.monotonic_trend == "valley_heuristic":
self.add_constraint_monotonic_valley_heuristic(
solver, n, D, x, trend_change)
# Constraint: reduction of dominating bins if self.gamma:
for i in range(n):
bin_size = solver.Sum([n_records[j] * x[i, j]
for j in range(i + 1)])
solver.Add(pmin <= total_records * (1 - x[i, i]) + bin_size)
solver.Add(pmax >= bin_size)
solver.Add(pmin <= pmax)
# Constraint: max-pvalue self.add_constraint_violation(solver, x, pvalue_violation_indices)
# Constraint: min diff self.add_constraint_violation(solver, x, min_diff_violation_indices)
# Constraint: fixed splits self.add_constraint_fixed_splits(solver, n, x)
self.solver_ = solver
self._n = n
self._x = x
def solve_via_data(
self, data, warm_start: bool, verbose: bool, solver_opts, solver_cache=None
):
"""Returns the result of the call to the solver.
minimize cx
subject to A x <= b
in HiGHS, the opt problem format is,
minimize cx
subject to lboundA <= A x <= uboundA
Parameters
---------- data : dict
Data used by the solver.
warm_start : bool
Whether to warm_start HiGHS.
verbose : bool
Should the solver print output?
solver_opts : dict
Additional arguments for the solver.
Returns
------- tuple
(status, optimal value, primal, equality dual, inequality dual)
"""
import highspy as hp
# setup problem data inf = hp.Highs().inf
dims = dims_to_solver_dict(data[s.DIMS])
c = data[s.C]
# A = sp.vstack([data[s.A], data[s.F]]).tocsc() A = data[s.A].tocsc()
data["Ax"] = A
leq_start = dims[s.EQ_DIM]
leq_end = dims[s.EQ_DIM] + dims[s.LEQ_DIM]
uboundA = data[s.B]
data["u"] = uboundA
lboundA = np.concatenate(
[data[s.B][:leq_start], -inf * np.ones(data[s.B][leq_start:leq_end].shape)]
)
data["l"] = lboundA
# setup highs model model = hp.HighsModel()
lp = model.lp_
lp.num_col_ = A.shape[1]
# assert data['n_var'] == A.shape[1] lp.num_row_ = A.shape[0]
# assert data['n_eq'] + data['n_ineq'] == A.shape[0] # offset already applied in invert() lp.offset_ = 0
lp.col_cost_ = c
lp.row_lower_ = lboundA
lp.row_upper_ = uboundA
assert A.format == "csc"
lp.a_matrix_.format_ = hp.MatrixFormat.kColwise
lp.a_matrix_.start_ = A.indptr
lp.a_matrix_.index_ = A.indices
lp.a_matrix_.value_ = A.data
# Define Variable bounds lb = data[s.LOWER_BOUNDS]
ub = data[s.UPPER_BOUNDS]
col_lower = np.full(lp.num_col_, -inf, dtype=c.dtype) if lb is None else lb.copy()
col_upper = np.full(lp.num_col_, inf, dtype=c.dtype) if ub is None else ub.copy()
# update col_lower and col_upper to account for boolean variables, # also set integrality_ for boolean or integers variables if data[s.BOOL_IDX] or data[s.INT_IDX]:
# note that integrality_ can only be assigned a list integrality = [hp.HighsVarType.kContinuous] * lp.num_col_
if data[s.BOOL_IDX]:
for ind in data[s.BOOL_IDX]:
integrality[ind] = hp.HighsVarType.kInteger
bool_mask = np.array(data[s.BOOL_IDX], dtype=int)
col_lower[bool_mask] = np.maximum(col_lower[bool_mask], 0)
col_upper[bool_mask] = np.minimum(col_upper[bool_mask], 1)
for ind in data[s.INT_IDX]:
integrality[ind] = hp.HighsVarType.kInteger
lp.integrality_ = integrality
lp.col_lower_ = col_lower
lp.col_upper_ = col_upper
solver = hp.Highs()
# setup options unpack_highs_options_inplace(solver_opts)
write_model_file = solver_opts.pop("write_model_file", None)
solver.setOptionValue("log_to_console", verbose)
for name, value in solver_opts.items():
# note that calling setOptionValue directly on the solver # allows one to pass advanced options that aren't available # on the HighOptions class (e.g., presolve_rule_off) if solver.setOptionValue(name, value) == hp.HighsStatus.kError:
raise ValueError(
f"HIGHS returned status kError for option (name, value): ({name}, {value})"
)
if write_model_file:
# TODO: Names can be collected upstream more systematically # (or in the parent class) to be used by all solvers. set_column_names_from_variables(lp, data[s.PARAM_PROB].variables)
solver.passModel(model)
if write_model_file:
solver.writeModel(write_model_file)
if warm_start and solver_cache is not None and self.name() in solver_cache:
old_solver, old_data, old_result = solver_cache[self.name()]
old_status = self.STATUS_MAP.get(old_result["model_status"], s.SOLVER_ERROR)
if old_status in s.SOLUTION_PRESENT:
solver.setSolution(old_result["solution"])
# initialize and solve problem try:
solver.run()
results = {
"solution": solver.getSolution(),
"basis": solver.getBasis(),
"info": solver.getInfo(),
"model_status": solver.getModelStatus().name,
"run_time": solver.getRunTime(),
}
if results["model_status"] == "kInfeasible":
results["dual_ray"] = solver.getDualRay()
except ValueError as e:
raise SolverError(e)
if solver_cache is not None:
solver_cache[self.name()] = (solver, data, results)
return results
OSQP
Solves quadratic programs with operator splitting.
def solve_via_data(self, data, warm_start: bool, verbose: bool, solver_opts,
solver_cache=None):
import osqp
is_pre_v1 = float(osqp.__version__.split('.')[0]) < 1
P = data[s.P]
q = data[s.Q]
A = sp.vstack([data[s.A], data[s.F]]).tocsc()
data['Ax'] = A
uA = np.concatenate((data[s.B], data[s.G]))
data['u'] = uA
lA = np.concatenate([data[s.B], -np.inf*np.ones(data[s.G].shape)])
data['l'] = lA
if P is not None:
P = sp.csc_matrix((P.data, P.indices, P.indptr), shape=P.shape)
if A is not None:
A = sp.csc_matrix((A.data, A.indices, A.indptr), shape=A.shape)
# Overwrite defaults eps_abs=eps_rel=1e-3, max_iter=4000 solver_opts['eps_abs'] = solver_opts.get('eps_abs', 1e-5)
solver_opts['eps_rel'] = solver_opts.get('eps_rel', 1e-5)
solver_opts['max_iter'] = solver_opts.get('max_iter', 10000)
# Use cached data if warm_start and solver_cache is not None and self.name() in solver_cache:
solver, old_data, results = solver_cache[self.name()]
new_args = {}
for key in ['q', 'l', 'u']:
if any(data[key] != old_data[key]):
new_args[key] = data[key]
factorizing = False
if P.data.shape != old_data[s.P].data.shape or any(
P.data != old_data[s.P].data):
P_triu = sp.csc_array(sp.triu(P, format='csc'))
new_args['Px'] = P_triu.data
factorizing = True
if A.data.shape != old_data['Ax'].data.shape or any(
A.data != old_data['Ax'].data):
new_args['Ax'] = A.data
factorizing = True
if new_args:
solver.update(**new_args)
# Map OSQP statuses back to CVXPY statuses status_map = self.STATUS_MAP_PRE_V1 if is_pre_v1 else self.STATUS_MAP
status = status_map.get(results.info.status_val, s.SOLVER_ERROR)
if status == s.OPTIMAL:
solver.warm_start(results.x, results.y)
# Polish if factorizing. polish_param = 'polish' if is_pre_v1 else 'polishing'
solver_opts[polish_param] = solver_opts.get(polish_param, factorizing)
solver.update_settings(verbose=verbose, **solver_opts)
else:
# Initialize and solve problem polish_param = 'polish' if is_pre_v1 else 'polishing'
solver_opts[polish_param] = solver_opts.get(polish_param, True)
solver = osqp.OSQP()
try:
solver.setup(P, q, A, lA, uA, verbose=verbose, **solver_opts)
except Exception as e:
raise SolverError(e)
results = solver.solve(raise_error=False)
if solver_cache is not None:
solver_cache[self.name()] = (solver, data, results)
return results
PuLP
Builds linear and mixed-integer models and sends them to selected solvers.
Downloads / mo
6.4M
Stars
2.5K
Last release
4.2.0
License
MIT
Strengths
Defines integer decisions.Set integer variable types when building a linear model.
Exports solver-ready models.Write LP or MPS files for external solver workflows.
Limitations
Solver binaries are installed separately.Install a solver extra or supply an accessible solver.
Native expressions stay linear.Use Pyomo for nonlinear objectives or constraints.
from pulp import LpProblem, LpMinimize, COIN_CMD, value
problem = LpProblem("demo", LpMinimize)
x = problem.add_variable("x", 0.0, 3.0)
problem += x
problem += x >= 1.0
stats = problem.solve(COIN_CMD(msg=False))
print(stats.status_str, value(x))
def solve_via_data(self, data, warm_start: bool, verbose: bool, solver_opts, solver_cache=None):
"""Returns the result of the call to the solver.
Parameters
---------- data : dict
Data generated via an apply call.
warm_start : Bool
Whether to warm_start Clarabel.
verbose : Bool
Control the verbosity.
solver_opts : dict
Clarabel-specific solver options.
Returns
------- The result returned by a call to clarabel.solve().
"""
import clarabel
A = data[s.A]
b = data[s.B]
q = data[s.C]
if s.P in data:
P = data[s.P]
else:
nvars = q.size
P = sp.csc_array((nvars, nvars))
P = sp.triu(P).tocsc()
cones = dims_to_solver_cones(data[ConicSolver.DIMS])
def new_solver():
_settings = self.parse_solver_opts(verbose, solver_opts)
_solver = clarabel.DefaultSolver(P, q, A, b, cones, _settings)
return _solver
def updated_solver():
if (not warm_start) or (solver_cache is None) or (self.name() not in solver_cache):
return None
_solver = solver_cache[self.name()]
if not hasattr(_solver, "update"):
return None
elif not _solver.is_data_update_allowed():
# disallow when presolve or chordal decomposition is used return None
else:
# current internal settings, to be updated if needed oldsettings = _solver.get_settings()
newsettings = self.parse_solver_opts(verbose, solver_opts, oldsettings)
# this overwrites all data in the solver but will not # reallocate internal memory. Could be faster if it # were known which terms (or partial terms) have changed. try:
_solver.update(P=P, q=q, A=A, b=b, settings=newsettings)
return _solver
except Exception:
# If sparsity pattern or dimensions changed, update() fails. # Return None to trigger a full new_solver() re-initialization. return None
# Try to get cached data solver = updated_solver()
if solver is None:
solver = new_solver()
results = solver.solve()
if solver_cache is not None:
solver_cache[self.name()] = solver
return results
def solve_via_data(self, data, warm_start: bool, verbose: bool, solver_opts, solver_cache=None):
"""Returns the result of the call to the solver.
Parameters
---------- data : dict
Data generated via an apply call.
warm_start : Bool
Whether to warm_start SCS.
verbose : Bool
Control the verbosity.
solver_opts : dict
SCS-specific solver options.
Returns
------- The result returned by a call to scs.solve().
"""
import scs
args = {"A": data[s.A], "b": data[s.B], "c": data[s.C]}
if s.P in data:
args["P"] = data[s.P]
if warm_start and solver_cache is not None and \
self.name() in solver_cache:
args["x"] = solver_cache[self.name()]["x"]
args["y"] = solver_cache[self.name()]["y"]
args["s"] = solver_cache[self.name()]["s"]
cones = dims_to_solver_dict(data[ConicSolver.DIMS])
def solve(_solver_opts):
_results = scs.solve(args, cones, verbose=verbose, **_solver_opts)
_status = self.STATUS_MAP[_results["info"]["status_val"]]
return _results, _status
solver_opts = SCS.parse_solver_options(solver_opts)
results, status = solve(solver_opts)
if solver_cache is not None and status == s.OPTIMAL:
solver_cache[self.name()] = results
return results
FAQ
SciPy suits general objective functions, least squares, and linear programs. OR-Tools suits scheduling, routing, and other discrete models. Optuna suits tuning hyperparameters and other black-box objectives.
Optuna optimizes black-box objectives through trials that sample float, integer, and categorical parameters. It prunes unpromising trials and supports custom samplers.
The scipy.optimize module in SciPy minimizes objective functions with local and global methods. It also handles nonlinear constraints, least squares, linear programming, and mixed-integer linear programming.
OSQP solves convex quadratic programs from sparse matrix inputs. It can update the problem data and solve again without repeating the setup.
For coding agents
Found your optimization library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.