API reference#

Reference for linopy’s public API. Most workflows start at ModelVariable, Constraint, and Objective are all built through Model.add_variables, Model.add_constraints, Model.add_objective, and accessed through the matching Model.variables, Model.constraints, and Model.objective accessors. The supporting classes below cover those types in detail.

Model#

Central container for an optimization problem. Most of linopy’s surface lives here.

model.Model([solver_dir, chunk, ...])

Linear optimization model.

Building a model#

model.Model.add_variables([lower, upper, ...])

Assign a new, possibly multi-dimensional array of variables to the model.

model.Model.add_constraints(lhs[, sign, ...])

Assign a new, possibly multi-dimensional array of constraints to the model.

model.Model.add_objective(expr[, overwrite, ...])

Add an objective function to the model.

model.Model.add_sos_constraints(variable, ...)

Add an sos1 or sos2 constraint for one dimension of a variable

model.Model.add_piecewise_formulation(*pairs)

Add piecewise linear constraints.

Inspecting a model#

model.Model.variables

Variables assigned to the model.

model.Model.constraints

Constraints assigned to the model.

model.Model.objective

Objective assigned to the model.

model.Model.sense

Sense of the objective function.

model.Model.type

Short string identifying the problem type.

model.Model.is_linear

Whether the objective is linear.

model.Model.is_quadratic

Whether the objective is quadratic.

Modifying a model#

model.Model.remove_variables(name)

Remove all variables stored under reference name name from the model.

model.Model.remove_constraints(name)

Remove all constraints stored under reference name 'name' from the model.

model.Model.remove_objective()

Remove the objective's linear expression from the model.

model.Model.remove_sos_constraints(variable)

Remove all sos constraints from a given variable.

model.Model.copy([include_solution, deep])

Return a copy of this model.

model.Model.apply_sos_reformulation()

Reformulate SOS constraints into binary + linear form, in place.

model.Model.undo_sos_reformulation()

Revert a previously applied SOS reformulation.

model.Model.reformulate_sos_constraints([prefix])

Reformulate SOS constraints as binary + linear constraints.

Solving#

model.Model.solve([solver_name, io_api, ...])

Solve the model with possibly different solvers.

Post-solve access#

model.Model.solution

Solution calculated by the optimization.

model.Model.dual

Dual values calculated by the optimization.

model.Model.status

Status of the model.

model.Model.termination_condition

Termination condition of the model.

Diagnostics#

model.Model.compute_infeasibilities()

Compute a set of infeasible constraints.

model.Model.format_infeasibilities([...])

Return a string representation of infeasible constraints.

IO#

model.Model.to_file(fn[, io_api, ...])

Write out a model to a lp or mps file.

model.Model.to_netcdf(*args, **kwargs)

Write out the model to a netcdf file.

io.read_netcdf(path, **kwargs)

Read in a model from a netcdf file.

Variable#

Subclass of xarray.DataArray carrying labels for a multi-dimensional decision variable.

variables.Variable(data, model, name[, ...])

Variable container for storing variable labels.

Attributes#

variables.Variable.lower

Get the lower bounds of the variables.

variables.Variable.upper

Get the upper bounds of the variables.

variables.Variable.type

Type of the variable.

variables.Variable.solution

Get the optimal values of the variable.

Modification#

variables.Variable.fix([value, decimals, ...])

Fix the variable to a given value by adding an equality constraint.

variables.Variable.unfix()

Remove the fix constraint for this variable.

variables.Variable.relax()

Relax the integrality of this variable.

variables.Variable.unrelax()

Restore the original integrality type of a relaxed variable.

Operations#

variables.Variable.sum([dim])

Sum the variables over all or a subset of dimensions.

variables.Variable.where(cond[, other])

Filter variables based on a condition.

Conversion#

variables.Variable.to_linexpr([coefficient])

Create a linear expression from the variables.

variables.Variable.to_polars()

Convert all variables to a single polars DataFrame.

Variables#

Container for the collection of variables on a model. Accessed via model.variables.

variables.Variables(data, model[, ...])

A variables container used for storing multiple variable arrays.

Attributes#

variables.Variables.lower

Get the lower bounds of all variables.

variables.Variables.upper

Get the upper bounds of all variables.

variables.Variables.solution

Get the solution of variables.

Modification#

variables.Variables.fix([value, decimals, ...])

Fix all variables in this container to their solution or a scalar value.

variables.Variables.unfix()

Unfix all variables in this container.

variables.Variables.relax()

Relax integrality of all integer/binary variables in this container.

variables.Variables.unrelax()

Restore integrality of all previously relaxed variables in this container.

Inventory#

variables.Variables.continuous

Get all continuous variables.

variables.Variables.binaries

Get all binary variables.

variables.Variables.integers

Get all integers variables.

variables.Variables.semi_continuous

Get all semi-continuous variables.

variables.Variables.sos

Get all variables involved in an sos constraint.

LinearExpression#

Linear combination of variables. Arithmetic on Variable / LinearExpression returns a LinearExpression.

expressions.LinearExpression(data, model)

A linear expression consisting of terms of coefficients and variables.

Post-solve access#

expressions.LinearExpression.solution

Get the optimal values of the expression.

Operations#

expressions.LinearExpression.sum([dim, ...])

Sum the expression over all or a subset of dimensions.

expressions.LinearExpression.where(cond[, other])

Filter variables based on a condition.

expressions.LinearExpression.groupby(group)

Returns a LinearExpressionGroupBy object for performing grouped operations.

expressions.LinearExpression.rolling([dim, ...])

Rolling window object.

Structure#

expressions.LinearExpression.vars

Variable labels referenced by each term of the expression.

expressions.LinearExpression.coeffs

Coefficient applied to each term of the expression.

expressions.LinearExpression.const

Constant offset added to the expression.

expressions.LinearExpression.nterm

Get the number of terms in the linear expression.

Conversion#

expressions.LinearExpression.to_polars()

Convert the expression to a polars DataFrame.

Construction#

expressions.LinearExpression.from_tuples(*tuples)

Create a linear expression by using tuples of coefficients and variables.

expressions.merge(exprs, *add_exprs[, dim, ...])

Merge multiple expression together.

QuadraticExpression#

Quadratic combination of variables, returned when squared Variable / LinearExpression arithmetic is performed.

expressions.QuadraticExpression(data, model)

A quadratic expression consisting of terms of coefficients and variables.

Structure#

expressions.QuadraticExpression.vars

Variable labels referenced by each term of the expression.

expressions.QuadraticExpression.coeffs

Coefficient applied to each term of the expression.

expressions.QuadraticExpression.const

Constant offset added to the expression.

expressions.QuadraticExpression.nterm

Get the number of terms in the linear expression.

Conversion#

expressions.QuadraticExpression.to_matrix()

Return a sparse matrix representation of the expression only including quadratic terms.

expressions.QuadraticExpression.to_polars(...)

Convert the expression to a polars DataFrame.

Post-solve access#

expressions.QuadraticExpression.solution

Get the optimal values of the expression.

Constraint#

Subclass of xarray.DataArray carrying labels for a multi-dimensional constraint.

constraints.Constraint(data, model[, name, ...])

Constraint backed by an xarray Dataset.

Structure#

constraints.Constraint.lhs

Get the left-hand-side linear expression of the constraint.

constraints.Constraint.sign

Get the constraint sign DataArray.

constraints.Constraint.rhs

Get the RHS DataArray.

constraints.Constraint.coeffs

Get the LHS coefficients DataArray.

constraints.Constraint.vars

Get the LHS variable labels DataArray.

Post-solve access#

constraints.Constraint.dual

Get the dual values DataArray.

Conversion#

constraints.Constraint.to_polars()

Convert the constraint to a polars DataFrame.

CSRConstraint#

Memory-efficient, immutable constraint representation backed by a scipy CSR sparse matrix. Opt in via Model(freeze_constraints=True) or Model.add_constraints(..., freeze=True). See the Creating Constraints guide for usage.

constraints.CSRConstraint(csr, con_labels, ...)

Frozen constraint backed by a CSR sparse matrix.

Structure#

constraints.CSRConstraint.coeffs

Get coefficients DataArray, shape (*coord_dims, _term).

constraints.CSRConstraint.vars

Get variable labels DataArray, shape (*coord_dims, _term).

constraints.CSRConstraint.sign

Get sign DataArray.

constraints.CSRConstraint.rhs

Get RHS DataArray, shape (*coord_dims).

constraints.CSRConstraint.ncons

Get the number of active constraints (non-masked, with at least one valid variable).

constraints.CSRConstraint.nterm

Get the number of terms in the constraint.

Post-solve access#

constraints.CSRConstraint.dual

Get dual values DataArray, shape (*coord_dims).

Conversion#

constraints.CSRConstraint.to_polars()

Convert frozen constraint to polars DataFrame directly from CSR.

Constraints#

Container for the collection of constraints on a model. Accessed via model.constraints.

constraints.Constraints(data, model[, ...])

A constraint container used for storing multiple constraint arrays.

Inventory#

constraints.Constraints.inequalities

Get the subset of constraints which are purely inequalities.

constraints.Constraints.equalities

Get the subset of constraints which are purely equalities.

Aggregate access#

constraints.Constraints.coeffs

Get the coefficients of all constraints.

constraints.Constraints.vars

Get the variables of all constraints.

constraints.Constraints.sign

Get the signs of all constraints.

constraints.Constraints.rhs

Get the right-hand-side constants of all constraints.

constraints.Constraints.dual

Get the dual values of all constraints.

Conversion#

constraints.Constraints.to_matrix()

Construct a constraint matrix in sparse format by stacking per-constraint CSR matrices.

Objective#

Wraps the objective expression on a model. Accessed via model.objective.

objective.Objective(expression, model[, sense])

An objective expression containing all relevant information.

objective.Objective.expression

Returns the expression of the objective.

objective.Objective.sense

Returns the sense of the objective.

objective.Objective.value

Returns the value of the objective.

objective.Objective.is_linear

Whether the objective expression is linear.

objective.Objective.is_quadratic

Whether the objective expression is quadratic.

Piecewise#

Construction helpers#

piecewise.breakpoints(values, *[, dim])

Create a breakpoint DataArray for piecewise linear constraints.

piecewise.segments(values, *[, dim])

Create a segmented breakpoint DataArray for disjunctive piecewise constraints.

piecewise.Slopes(values[, y0, align, dim])

Per-piece slopes + initial y-value, deferred until an x grid is known.

PiecewiseFormulation#

Returned by Model.add_piecewise_formulation().

piecewise.PiecewiseFormulation(name, method, ...)

Result of add_piecewise_formulation.

piecewise.PiecewiseFormulation.method

Resolved formulation method (see PWL_METHOD).

piecewise.PiecewiseFormulation.convexity

Shape of the piecewise curve when well-defined (see PWL_CONVEXITY), else None.

piecewise.PiecewiseFormulation.variables

View of the auxiliary variables in this formulation.

piecewise.PiecewiseFormulation.constraints

View of the auxiliary constraints in this formulation.

Low-level helper#

piecewise.tangent_lines(x, x_points, y_points)

Compute tangent-line (chord) expressions for a piecewise linear function.

Type aliases#

constants.PWL_METHOD

Allowed values for the method argument of Model.add_piecewise_formulation().

constants.PWL_METHODS

Set of valid PWL_METHOD values.

constants.PWL_CONVEXITY

Possible values for convexity.

constants.PWL_CONVEXITIES

Set of valid PWL_CONVEXITY values.

Solvers#

The stateful Solver instance owns the solver-side model and exposes a two-step from_name() / solve() workflow. Model.solve() is a thin wrapper around it.

solvers.Solver([model, io_api, options])

Abstract base class for solving a given linear problem.

Construction#

solvers.Solver.from_name(name, model[, ...])

Construct and build the solver subclass registered as name.

solvers.Solver.from_model(model[, io_api, ...])

Instantiate and build the solver against model.

Solving#

solvers.Solver.solve(**run_kwargs)

Run the prepared solver and return a Result.

solvers.Solver.update_solver_model(model, ...)

solvers.Solver.close()

Post-solve state#

Capabilities#

solvers.Solver.is_available()

Return True if this solver's package/binary is importable.

solvers.Solver.license_status()

Probe license/runtime availability.

solvers.Solver.supports(feature)

Check if this solver supports a given feature.

solvers.Solver.supported_features()

All features supported by this solver, static plus runtime.

solvers.Solver.runtime_features()

Features whose availability depends on the installed solver version or runtime environment.

Discovery#

solvers.available_solvers

Lazy sequence of installed solver names.

solvers.licensed_solvers

Installed solvers whose license_status() probe currently succeeds.

solvers.SolverFeature(value[, names, ...])

Enumeration of all solver capabilities tracked by linopy.

solvers.LicenseStatus(solver, ok[, message])

Result of Solver.license_status() — license/runtime probe outcome.

Implementations#

solvers.CBC([model, io_api, options])

Solver subclass for the CBC solver.

solvers.COPT([model, io_api, options])

Solver subclass for the COPT solver.

solvers.Cplex([model, io_api, options])

Solver subclass for the Cplex solver.

solvers.GLPK([model, io_api, options])

Solver subclass for the GLPK solver.

solvers.Gurobi([model, io_api, options])

Solver subclass for the gurobi solver.

solvers.Highs([model, io_api, options])

Solver subclass for the HiGHS solver.

solvers.Knitro([model, io_api, options])

Solver subclass for the Knitro solver.

solvers.MindOpt([model, io_api, options])

Solver subclass for the MindOpt solver.

solvers.Mosek([model, io_api, options])

Solver subclass for the Mosek solver.

solvers.SCIP([model, io_api, options])

Solver subclass for the SCIP solver.

solvers.Xpress([model, io_api, options])

Solver subclass for the xpress solver.

solvers.cuPDLPx([model, io_api, options])

Solver subclass for the cuPDLPx solver.

Remote solving#

remote.RemoteHandler(hostname[, port, ...])

Handler class for solving models on a remote machine via an SSH connection.

Solver status and result types#

Types returned by or compared against Model.status, Model.termination_condition, and Model.solution, plus SolverReport surfaced on Solver.report and Result.report.

constants.SolverStatus(value[, names, ...])

Solver status.

constants.TerminationCondition(value[, ...])

Termination condition of the solver.

constants.Status(status, termination_condition)

Status and termination condition of the solver.

constants.Solution([primal, dual, objective])

Solution returned by the solver.

constants.SolverReport([runtime, mip_gap, ...])

Solver-reported performance metrics.

constants.Result(status[, solution, ...])

Result of the optimization.

Utilities#

align(*objects[, join, copy, indexes, ...])

Given any number of Variables, Expressions, Dataset and/or DataArray objects, returns new objects with aligned indexes and dimension sizes.

options

Runtime configuration knobs (e.g. display widths).

Warnings#

These warning classes can be silenced or filtered via warnings.filterwarnings().

EvolvingAPIWarning

Signals a newly-added API whose details may evolve in minor releases.

PerformanceWarning

Warning raised when an operation triggers expensive Dataset reconstruction.