XplorGurobi¶
XplorGurobi ¶
Bases: XplorModel[Model, Var, LinExpr]
Xplor wrapper for the Gurobi solver.
This class provides a specialized wrapper for Gurobi, translating XplorModel's abstract operations into Gurobi-specific API calls for defining variables, constraints, optimizing, and extracting solutions.
Class Type Parameters:
| Name | Bound or Constraints | Description | Default |
|---|---|---|---|
ModelType
|
Model
|
The Gurobi model type. |
required |
ExpressionType
|
LinExpr
|
Stores objective terms as Gurobi LinExpr objects. |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
model |
Model
|
The instantiated Gurobi model object. |
Initialize the XplorGurobi model wrapper.
If no Gurobi model is provided, a new one is instantiated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Model | None
|
An optional, pre-existing Gurobi model instance. |
None
|
Source code in src/xplor/gurobi/model.py
Attributes¶
var
cached
property
¶
The entry point for creating custom expression objects (VarExpr) that represent variables or columns used within a composite Polars expression chain.
This proxy acts similarly to polars.col(), allowing you to reference
optimization variables (created via xmodel.add_vars()) or standard DataFrame columns
in a solver-compatible expression.
The resulting expression object can be combined with standard Polars expressions to form constraints or objective function components.
Examples:
Functions¶
add_vars ¶
add_vars(
name: str,
*,
lb: float | str | Expr = 0.0,
ub: float | str | Expr | None = None,
obj: float | str | Expr | None = None,
indices: Expr | list[str] | None = None,
vtype: VariableType = "CONTINUOUS",
priority: int | Expr = 0,
) -> Expr
Define and return a Var expression for optimization variables.
This method generates a Polars expression that, when consumed (e.g., via
.with_columns()), creates optimization variables for every row and adds
them to the underlying solver model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The base name for the variables (e.g., "production" or "flow"). This name is used to retrieve variable values after optimization. |
required |
lb
|
float | str | Expr
|
Lower bound for created variables. Can be a scalar, a column name (str), or a Polars expression. |
0.0
|
ub
|
float | str | Expr | None
|
Upper bound for created variables. If None, the solver default is used. |
None
|
obj
|
float | str | Expr | None
|
Objective function coefficient for created variables. Can be a scalar, a column name, or a Polars expression. |
None
|
indices
|
Expr | list[str] | None
|
Keys (column names) that uniquely identify each variable instance. Used to format the internal variable names (e.g., 'x[1,2]'). |
None
|
vtype
|
VariableType
|
The type of the variable (CONTINUOUS, INTEGER, or BINARY). |
'CONTINUOUS'
|
priority
|
int | Expr
|
Multi-objective optimization priority. Higher priority numbers are optimized FIRST (priority 2 before priority 1 before priority 0). All objectives with the same priority are combined into a single weighted sum. Currently only supported by the Gurobi backend. |
0
|
Returns:
| Type | Description |
|---|---|
Expr
|
A Polars expression ( |
Examples:
Assuming xmodel is an instance of a concrete class (XplorGurobi).
>>> # 1. Basic variable creation using columns for bounds:
>>> data = pl.DataFrame({"max_limit": [10.0, 5.0]})
>>> df = data.with_columns(
... xmodel.add_vars("x", lb=0.0, ub=pl.col("max_limit"), obj=1.0)
... )
>>> # df["x"] now contains gurobipy.Var or mathopt.Variable objects.
>>> # s2. Creating integer variables indexed by two columns:
>>> data = pl.DataFrame({"time": [1, 1, 2, 2], "resource": ["A", "B", "A", "B"]})
>>> df = data.with_columns(
... xmodel.add_vars(
... "sched",
... indices=["time", "resource"],
... vtype=VarType.INTEGER,
... )
... )
>>> # Variable names will look like 'sched[1,A]', 'sched[1,B]', etc.
Source code in src/xplor/model.py
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 | |
add_constrs ¶
add_constrs(
df: DataFrame,
*constr_exprs: ConstrExpr,
indices: Expr | list[str] | None = None,
**named_constr_exprs: ConstrExpr,
) -> DataFrame
Define and return a Constr expression for model constraints.
This method accepts a symbolic relational expression (e.g., x <= 5)
and generates a Polars expression that, when consumed (e.g., via .select()),
adds the constraints to the underlying solver model.
The constraint is added row-wise if the input expression is a Series of
expressions, or as a single constraint if the expression is aggregated
(e.g., using .sum()).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
The polars DataFrame used to create the constraints |
required |
constr_exprs
|
ConstrExpr
|
The constraints expression (e.g., a relational expression like
|
()
|
indices
|
Expr | list[str] | None
|
Keys (column names) that uniquely identify each constraint instance. Used to format the internal variable names (e.g., 'constr[1,2]'). |
None
|
named_constr_exprs
|
ConstrExpr
|
Other constraints expression |
{}
|
Returns:
| Type | Description |
|---|---|
Expr
|
A Polars expression ( |
.. warning::
|
All constraints provided within a single call to |
Examples:
Assuming df has been created and contains the variable Series df["x"].
>>> df.pipe(
... xmodel.add_constrs,
max_per_item = xplor.var("x") <= pl.col("capacity"),
min_per_item = xplor.var("x") >= pl.col("min_threshold"),
indices=["product"]
... )
Source code in src/xplor/model.py
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 | |
minimize ¶
Add minimization objectives to the model.
This method accepts named objective expressions and adds them to the model at the specified priority level. Multiple objectives at the same priority are combined into a single weighted sum.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
The polars DataFrame used to evaluate the objective expressions. |
required |
priority
|
int
|
Multi-objective optimization priority. Higher priority numbers are optimized FIRST (priority 2 before priority 1 before priority 0). All objectives with the same priority are combined into a single weighted sum. Currently only supported by the Gurobi backend. |
0
|
named_obj_exprs
|
Expr
|
Named objective expressions to minimize (e.g., |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The input DataFrame (unchanged), allowing for method chaining. |
Examples:
Assuming df has been created and contains the variable Series df["x"].
>>> df.pipe(
... xmodel.minimize,
... total_cost = (xplor.var("x") * pl.col("cost")).sum(),
... priority=1
... )
>>> # Multi-objective optimization
>>> df.pipe(
... xmodel.minimize,
... sum_x = xplor.var("x").sum(),
... sum_y = xplor.var("y").sum(),
... priority=2
... )
Source code in src/xplor/model.py
maximize ¶
Add maximization objectives to the model.
This method accepts named objective expressions and adds them to the model at the specified priority level. Multiple objectives at the same priority are combined into a single weighted sum. Internally, maximization is converted to minimization by negating the objective coefficients.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
The polars DataFrame used to evaluate the objective expressions. |
required |
priority
|
int
|
Multi-objective optimization priority. Higher priority numbers are optimized FIRST (priority 2 before priority 1 before priority 0). All objectives with the same priority are combined into a single weighted sum. Currently only supported by the Gurobi backend. |
0
|
named_obj_exprs
|
Expr
|
Named objective expressions to maximize (e.g., |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The input DataFrame (unchanged), allowing for method chaining. |
Examples:
Assuming df has been created and contains the variable Series df["x"].
>>> df.pipe(
... xmodel.maximize,
... total_revenue = (xplor.var("x") * pl.col("revenue")).sum(),
... priority=1
... )
>>> # Multi-objective optimization
>>> df.pipe(
... xmodel.maximize,
... sum_x = xplor.var("x").sum(),
... sum_y = xplor.var("y").sum(),
... priority=2
... )
Source code in src/xplor/model.py
optimize ¶
Solve the Gurobi model.
Before optimization, sets up multi-objective functions using setObjectiveN if multiple priority levels are defined. Higher priority values are optimized first (consistent with Gurobi's convention).
Source code in src/xplor/gurobi/model.py
get_objective_value ¶
Return the objective value from the solved Gurobi model.
Returns:
| Type | Description |
|---|---|
float
|
The value of the objective function. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the model has multiple objectives. Use get_multi_objective_values() instead. |
Source code in src/xplor/gurobi/model.py
get_multi_objective_values ¶
Return all objective values from a multi-objective Gurobi model.
Returns a dictionary mapping user priority levels to their objective values.
Returns:
| Type | Description |
|---|---|
dict[int, float]
|
Dictionary mapping priority level to objective value. Keys are user priority levels (higher priority = higher number). Values are the objective values for each priority. |
Examples:
>>> xmodel.optimize()
>>> obj_values = xmodel.get_multi_objective_values()
>>> print(obj_values)
{2: -150.0, 1: 50.0, 0: 10.0} # priority -> objective value
Source code in src/xplor/gurobi/model.py
read_values ¶
Read the value of an optimization variable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
Expr
|
Expression to evaluate. |
required |
Returns:
| Type | Description |
|---|---|
Expr
|
Values of the variable expression. |
Examples:
>>> xmodel: XplorModel
>>> df_with_solution = df.with_columns(xmodel.read_values(pl.selectors.object()))