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
- graph
spmatrixorGraphorDataFrame A graph, specified either as a scipy.sparse adjacency matrix, networkx graph, or pandas dataframe.
- nodes1
ndarrayorstr Nodes in the first bipartite set. If
graphis a scipy sparse matrix,nodes1must be a numpy array. Ifgraphis a pandas dataframe,nodes1must be a column name. Ifgraphis a networkx graph,nodes1must be a list.- nodes2
ndarrayorstr Nodes in the first bipartite set. If
graphis a scipy sparse matrix,nodes2must be a numpy array. Ifgraphis a pandas dataframe,nodes2must be a column name. Ifgraphis a networkx graph,nodes2must be a list.- verbosebool, optional
verbose=Falsesuppresses all console output- logfile
str, optional Write all mod output to the given file path
- solver_params
dict, optional Gurobi parameters to be passed to the solver
- graph
- Returns
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
- Returns
tupleCost 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_data
DataFrame DataFrame with graph and respective attributes. These must include
"from","to"nodes used as index,"capacity", and"cost".- demand_data
DataFrame 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=Falsesuppresses all console output- logfile
str, optional Write all mod output to the given file path
- solver_params
dict, optional Gurobi parameters to be passed to the solver
- arc_data
- Returns
tupleCost 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
- G
spmatrix Adjacency matrix of the graph.
- capacities
spmatrix Matrix containing capacities for each edge.
- costs
spmatrix Matrix containing costs for each edge.
- demands
ndarray Array containing the demand for each node.
- verbosebool, optional
verbose=Falsesuppresses all console output- logfile
str, optional Write all mod output to the given file path
- solver_params
dict, optional Gurobi parameters to be passed to the solver
- G
- Returns
tupleCost 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
- Returns
ndarrayThe 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
MeanVariancePortfoliofor given covariance matrix and return vector. UseMeanVariancePortfolio.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_factors
tupleofndarray 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\), SPDcov_factors[2]: (n,) ndarray \(d\), nonnegative
- mu1-d
- Raises
LinAlgErrorIf 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
- gamma
float>= 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_trades
int>= 0, optional Upper limit on the number of trades
- max_positions
int>= 0, optional Upper limit on the number of open positions
- fees_buy
floatorndarray>= 0, optional Fixed-charge fee for each buy transaction, relative to total portfolio value
- fees_sell
floatorndarray>= 0, optional Fixed-charge fee for each sell transaction, relative to total portfolio value
- costs_buy
floatorndarray>= 0, optional Variable transaction costs for each buy transaction, relative to trade value
- costs_sell
floatorndarray>= 0, optional Variable transaction costs for each sell transaction, relative to trade value
- min_long
float>= 0, optional Lower bound on the volume on a traded long position, relative to total portfolio value
- min_short
float>= 0, optional Lower bound on the volume on a traded short position, relative to total portfolio value
- max_total_short
float>= 0, optional Maximum total short positions, relative to total investment.
- initial_holdings1-d
ndarray, optional Initial portfolio holdings (sum needs to be <= 1)
- rf_return
float, optional Include a risk-free asset having return rate
rf_return.- verbosebool, optional
verbose=Falsesuppresses all console output- logfile
str, optional Write all mod output to the given file path
- solver_params
dict, optional Gurobi parameters to be passed to the solver
- gamma
- Returns
- mvp_result
PortfolioResult 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 portfoliomvp_result.return: The estimated return \(\mu^T x\) of the portfoliomvp.x_rfrelative investment in the risk-free asset. Present only ifrf_returnwas non-None on input
Some combinations of requested portfolio features may rule out all possible portfolios. In this corner case the value
Noneis returned.
- mvp_result
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
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.
- 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_matrix
spmatrix Quadratic coefficient matrix
- time_limit
float Time limit in seconds (optional, default no limit)
- verbosebool, optional
verbose=Falsesuppresses all console output- logfile
str, optional Write all mod output to the given file path
- solver_params
dict, optional Gurobi parameters to be passed to the solver
- coeff_matrix
- Returns
QuboResultA 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.
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
- availability
DataFrame 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_requirements
DataFrame Dataframe with columns ‘Shift’ and ‘Required’ specifying the number of staff required for every shift.
- worker_limits
DataFrame Dataframe with columns ‘Worker’, ‘MinShifts’, and ‘MaxShifts’ specifying the maximum and minimum number of shifts each worker may be assigned in the schedule.
- preferences
str, 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=Falsesuppresses all console output- logfile
str, optional Write all mod output to the given file path
- solver_params
dict, optional Gurobi parameters to be passed to the solver
- availability
- Returns
DataFrameShift assignments as a subset of the availability dataframe
- Raises
ValueErrorIf a feasible set of shift assignments cannot be constructed from the input data