API Reference

Bipartite Matching

The following mods can be imported from gurobi_optimods.bipartite_matching:

maximum_bipartite_matching(graph, nodes1, nodes2, *, verbose=True, logfile=None, solver_params=None)

Solve a maximum cardinality bipartite matching problem on the given graph.

Parameters
graphspmatrix or Graph or DataFrame

A graph, specified either as a scipy.sparse adjacency matrix, networkx graph, or pandas dataframe.

nodes1ndarray or str

Nodes in the first bipartite set. If graph is a scipy sparse matrix, nodes1 must be a numpy array. If graph is a pandas dataframe, nodes1 must be a column name. If graph is a networkx graph, nodes1 must be a list.

nodes2ndarray or str

Nodes in the first bipartite set. If graph is a scipy sparse matrix, nodes2 must be a numpy array. If graph is a pandas dataframe, nodes2 must be a column name. If graph is a networkx graph, nodes2 must be a list.

verbosebool, optional

verbose=False suppresses all console output

logfilestr, optional

Write all mod output to the given file path

solver_paramsdict, optional

Gurobi parameters to be passed to the solver

Returns
spmatrix or Graph or DataFrame

A subgraph of the original graph (with the same data type) specifying the maximum matching

Minimum Cost Flow

The following mods can be imported from gurobi_optimods.min_cost_flow:

min_cost_flow_networkx(G, *, verbose=True, logfile=None, solver_params=None)

Solve the minimum cost flow problem for a given graph.

Parameters
GDiGraph

Graph with edge attributes capacity and cost, as well as node attributes demand.

verbosebool, optional

verbose=False suppresses all console output

logfilestr, optional

Write all mod output to the given file path

solver_paramsdict, optional

Gurobi parameters to be passed to the solver

Returns
tuple

Cost of the minimum cost flow (float), dictionary indexed by edges with non-zero flow in the solution (dict)

min_cost_flow_pandas(arc_data, demand_data, *, verbose=True, logfile=None, solver_params=None)

Solve the minimum cost flow problem for a given graph.

The inputs adhere to the following structure:

arc_data = pd.DataFrame(
    [
        {"from": 0, "to": 1, "capacity": 16, "cost": 0}, {"from": 1,
        "to": 2, "capacity": 10, "cost": 0},
    ]
).set_index(["from", "to"])

demand_data = pd.DataFrame(
    [{"node": 0, "demand": -1}, {"node": 2, "demand": 1}]
).set_index("node")
Parameters
arc_dataDataFrame

DataFrame with graph and respective attributes. These must include "from", "to" nodes used as index, "capacity", and "cost".

demand_dataDataFrame

DataFrame with node demand information. These must include indexed by “node”, and include the “demand”. This value can be positive (requesting flow) or negative (supplying flow).

verbosebool, optional

verbose=False suppresses all console output

logfilestr, optional

Write all mod output to the given file path

solver_paramsdict, optional

Gurobi parameters to be passed to the solver

Returns
tuple

Cost of the minimum cost flow (float), dictionary indexed by edges with non-zero flow in the solution (Series)

min_cost_flow_scipy(G, capacities, costs, demands, *, verbose=True, logfile=None, solver_params=None)

Solve the minimum cost flow problem for a given graph.

Parameters
Gspmatrix

Adjacency matrix of the graph.

capacitiesspmatrix

Matrix containing capacities for each edge.

costsspmatrix

Matrix containing costs for each edge.

demandsndarray

Array containing the demand for each node.

verbosebool, optional

verbose=False suppresses all console output

logfilestr, optional

Write all mod output to the given file path

solver_paramsdict, optional

Gurobi parameters to be passed to the solver

Returns
tuple

Cost of the minimum cost flow (float), dictionary indexed by edges with non-zero flow in the solution (spmatrix)

Maximum Weighted Independent Set

The following mods can be imported from gurobi_optimods.mwis:

maximum_weighted_independent_set(adjacency_matrix, weights, *, verbose=True, logfile=None, solver_params=None)

Find a set of mutually non-adjacent vertices with maximum weighted sum.

Parameters
adjacency_matrixspmatrix

The upper triangular adjacency matrix.

weightsndarray

Vertex weight array.

verbosebool, optional

verbose=False suppresses all console output

logfilestr, optional

Write all mod output to the given file path

solver_paramsdict, optional

Gurobi parameters to be passed to the solver

Returns
ndarray

The maximum weighted independent set array.

Mean-Variance Portfolio

The following mods can be imported from gurobi_optimods.portfolio:

class MeanVariancePortfolio(mu, cov_matrix=None, cov_factors=None)

Optimal mean-variance portfolio solver.

Instantiate an object of MeanVariancePortfolio for given covariance matrix and return vector. Use MeanVariancePortfolio.efficient_portfolio() to solve for efficient portfolios with given parameters.

Parameters
mu1-d ndarray

Vector of expected returns for each asset

cov_matrix2-d ndarray

Covariance matrix \(\Sigma\)

cov_factorstuple of ndarray

Covariance factors that constitute \(\Sigma = B K B^T + diag(d)\).

  • cov_factors[0]: (n, k) ndarray \(B\)

  • cov_factors[1]: (k, k) ndarray \(K\), SPD

  • cov_factors[2]: (n,) ndarray \(d\), nonnegative

Raises
LinAlgError

If the matrix K is not positive definite

efficient_portfolio(gamma, max_trades=None, max_positions=None, fees_buy=None, fees_sell=None, costs_buy=None, costs_sell=None, min_long=None, min_short=None, max_total_short=0.0, initial_holdings=None, rf_return=None, *, verbose=True, logfile=None, solver_params=None)

Compute efficient portfolio for given parameters

Parameters
gammafloat >= 0

Risk aversion cofficient for balancing risk and return; the resulting objective functions is \(\mu^T x - 0.5 \gamma x^T \Sigma x\)

max_tradesint >= 0, optional

Upper limit on the number of trades

max_positionsint >= 0, optional

Upper limit on the number of open positions

fees_buyfloat or ndarray >= 0, optional

Fixed-charge fee for each buy transaction, relative to total portfolio value

fees_sellfloat or ndarray >= 0, optional

Fixed-charge fee for each sell transaction, relative to total portfolio value

costs_buyfloat or ndarray >= 0, optional

Variable transaction costs for each buy transaction, relative to trade value

costs_sellfloat or ndarray >= 0, optional

Variable transaction costs for each sell transaction, relative to trade value

min_longfloat >= 0, optional

Lower bound on the volume on a traded long position, relative to total portfolio value

min_shortfloat >= 0, optional

Lower bound on the volume on a traded short position, relative to total portfolio value

max_total_shortfloat >= 0, optional

Maximum total short positions, relative to total investment.

initial_holdings1-d ndarray, optional

Initial portfolio holdings (sum needs to be <= 1)

rf_returnfloat, optional

Include a risk-free asset having return rate rf_return.

verbosebool, optional

verbose=False suppresses all console output

logfilestr, optional

Write all mod output to the given file path

solver_paramsdict, optional

Gurobi parameters to be passed to the solver

Returns
mvp_resultPortfolioResult

A dataclass containing the efficient portfolio, along with auxiliary information:

  • mvp_result.x: The portfolio vector \(x\)

  • mvp_result.risk: The estimated risk \(x^T \Sigma x\) of the portfolio

  • mvp_result.return: The estimated return \(\mu^T x\) of the portfolio

  • mvp.x_rf relative investment in the risk-free asset. Present only if rf_return was non-None on input

Some combinations of requested portfolio features may rule out all possible portfolios. In this corner case the value None is returned.

Notes

Refer to Enforcing more portfolio features for a detailed discussion of all parameters.

class PortfolioResult(x, ret, risk, x_rf=None)

Data class representing computed portfolios.

Attributes
x1-d ndarray

The vector of relative investments into each asset

retfloat

The (estimated) return of the portfolio

riskfloat

The (estimated) risk of the portfolio

x_rffloat, optional

The relative investment into the risk-free asset. Equals to None if no risk-free return rate was specified upon input

Quadratic Unconstrained Binary Optimization (QUBO)

The following mods can be imported from gurobi_optimods.qubo:

class QuboResult(solution, objective_value)

Solution to a QUBO problem.

Attributes
solutionndarray

0/1 array of variable values in the solution

objective_valuefloat

The objective function value for this solution

solve_qubo(coeff_matrix, time_limit=1e+100, *, verbose=True, logfile=None, solver_params=None)

Solve a quadratic unconstrained binary optimization (QUBO) problem, i.e., minimize quadratic function \(x'Qx\) defined by coefficient matrix \(Q\) over a binary decision variable vector \(x\)

Parameters
coeff_matrixspmatrix

Quadratic coefficient matrix

time_limitfloat

Time limit in seconds (optional, default no limit)

verbosebool, optional

verbose=False suppresses all console output

logfilestr, optional

Write all mod output to the given file path

solver_paramsdict, optional

Gurobi parameters to be passed to the solver

Returns
QuboResult

A dataclass containing a 0/1 solution array and its objective value

Regression

The following mods can be imported from gurobi_optimods.regression:

class LADRegression

Least absolute deviations (L1-norm) regressor

fit(X_train, y_train, *, verbose=True, logfile=None, solver_params=None)

Fit the model to training data.

Parameters
X_trainndarray

Training set feature values

y_trainndarray

Training set output values

verbosebool, optional

verbose=False suppresses all console output

logfilestr, optional

Write all mod output to the given file path

solver_paramsdict, optional

Gurobi parameters to be passed to the solver

Workforce Scheduling

The following mods can be imported from gurobi_optimods.workforce:

solve_workforce_scheduling(availability, shift_requirements, worker_limits, preferences=None, rolling_limits=False, *, verbose=True, logfile=None, solver_params=None)

Solve a workforce scheduling model.

Parameters
availabilityDataFrame

Dataframe with columns ‘Worker’ and ‘Shift’ defining all allowable worker-shift combinations. The ‘Preference’ column optionally assigns a preference value to the given combination.

shift_requirementsDataFrame

Dataframe with columns ‘Shift’ and ‘Required’ specifying the number of staff required for every shift.

worker_limitsDataFrame

Dataframe with columns ‘Worker’, ‘MinShifts’, and ‘MaxShifts’ specifying the maximum and minimum number of shifts each worker may be assigned in the schedule.

preferencesstr, optional

The name of a column in the availability dataframe containing preference values. If provided, the mod returns a schedule which maximises the sum of preference values of assigned shifts.

rolling_limitsbool

Whether to enforce worker shift limits on a rolling window basis. If True, worker_limits must contain an additional ‘Window’ column specifying the rolling window for each worker.

verbosebool, optional

verbose=False suppresses all console output

logfilestr, optional

Write all mod output to the given file path

solver_paramsdict, optional

Gurobi parameters to be passed to the solver

Returns
DataFrame

Shift assignments as a subset of the availability dataframe

Raises
ValueError

If a feasible set of shift assignments cannot be constructed from the input data