Self-Hosted Service Client API Reference#

Client#

Service Client#

class cuopt_sh_client.CuOptServiceSelfHostClient(
ip: str = '0.0.0.0',
port: str = '5000',
use_https: bool = False,
self_signed_cert='',
polling_interval=1,
request_excess_timeout=None,
only_validate=False,
polling_timeout=600,
timeout_exception=True,
result_type=mime_type.MSGPACK,
)#

This version of the CuOptServiceClient is an interface with a self hosted version of the cuOpt core service. This client allows users to make calls to a self hosted instance of the cuOpt service at a specific ip and port.

It closely emulates the interface of the managed service client, however it does not implement most of the managed service-specific features required for interaction with NVIDIA Cloud Functions.

Parameters:
  • ip (str) – The IP address of the cuOpt service. Defaults to 0.0.0.0

  • port (str) – The port of the cuOpt service. Defaults to 5000.

  • use_https (boolean) – Use HTTPS to communicate with server in secured way.

  • self_signed_cert (str) – A complete path to self signed certificate. If it’s a standard certificate, then no need to provide anything.

  • polling_interval (int) – The duration in seconds between consecutive polling attempts. Defaults to 1.

  • request_excess_timeout (int) – Note: Deprecated, Use polling_timeout instead

  • only_validate (boolean) – Only validates input. Defaults to False.

  • polling_timeout (int) – The time in seconds that the client will poll for a result before exiting and returning a request id. The request id may be polled again in a call to repoll(). If set to None, the client will never timeout and will poll indefinitely. Defaults to 600.

  • timeout_exception (boolean) – If True, the client returns a TimeoutError exception if polling_timeout seconds passes before a solution is returned. The value of the exception contains JSON giving the request id so that repoll() may be called to poll again for a result. If False, the client returns a dictionary containing the repoll information with no exception. Defaults to True.

  • result_type (enum) – Supported result mime_types are mime_type.JSON, mime_type.MSGPACK, mime_type.ZLIB and mime_type.WILDCARD. If a wildcard is used, the result mime_type will be set to the content_type mime_type of the original request. If not provided, result_type defaults to mime_type.MSGPACK

delete(
id,
running=None,
queued=None,
cached=None,
)#

Delete a cached entry by id or abort a job by id.

Parameters:
  • id (str) – A uuid identifying the cached entry or job to be deleted. The wildcard id ‘*’ will match all uuids (filtered by ‘running’, ‘queued’, and ‘cached’).

  • running (bool) – If set to True, the request will be aborted if ‘id’ is a currently running job. Defaults to True if ‘id’ is a specific uuid and both ‘queued’ and ‘cached’ are unspecified, otherwise False.

  • queued (bool) – If set to True, the request will be aborted if ‘id’ is a currently queued job. Defaults to True if ‘id’ is a specific uuid and both ‘running’ and ‘cached’ are unspecified, otherwise False.

  • cached (bool) – If set to True, the request will be aborted if ‘id’ is a cached data entry. Defaults to True if ‘id’ is a specific uuid and both ‘running’ and ‘queued’ are unspecified, otherwise False.

delete_solution(id)#

Delete a solution by id.

Parameters:

id (str) – A uuid identifying the solution to be deleted.

get_LP_solve(
cuopt_data_models,
solver_config=<solver_settings.solver_settings.SolverSettings object>,
cache=False,
response_type='obj',
filepath=False,
output='',
delete_solution=True,
warmstart_id=None,
incumbent_callback=None,
logging_callback=None,
)#

Get linear programming solution for a given problem.

Parameters:
  • cuopt_data_models

    Note - Batch mode is only supported in LP and not in MILP

    File path to mps or json/dict/DataModel returned by cuopt_mps_parser/list[mps file paths]/list[dict]/list[DataModel].

    For single problem, input should be either a path to mps/json file, /DataModel returned by cuopt_mps_parser/ path to json file/ dictionary.

    For batch problem, input should be either a list of paths to mps files/ a list of DataModel returned by cuopt_mps_parser/ a list of dictionaries.

    To use a cached cuopt problem data, input should be a uuid identifying the reqId of the cached data.

  • solver_config (SolverSettings object or Dict) – Contains solver settings including tolerance values. See the LP documentation for details on solver settings.

  • response_type (str) – Choose “dict” if response should be returned as a dictionary or “obj” for Solution object. Defaults to “obj”

  • filepath (boolean) – Indicates that cuopt_problem_json_data is the relative path of a cuopt data file under the server’s data directory. The data directory is specified when the server is started (see the server documentation for more detail). Defaults to False.

  • output (str) – Optional name of the result file. If the server has been configured to write results to files and the size of the result is greater than the configured limit, the server will write the result to a file with this name under the server’s result directory (see the server documentation for more detail). Defaults to a name based on the path if ‘filepath’ is True, or a uuid if ‘filepath’ is False.

  • delete_solution (boolean) – Delete the solution when it is returned. Defaults to True.

  • incumbent_callback (callable) –

    # Note : Only applicable to MIP

    A callback that will be invoked as incumbent_callback(solution, cost) to # noqa receive incumbent solutions from the MIP solver where solution is a list of floats and cost is a float. The callback will be invoked each time the solver produces an incumbent solution. The LP solver will not return any incumbent solutions. Default is None.

  • logging_callback (callable) –

    # Note : Only applicable to MIP

    A callback that will be invoked as logging_callback(solution) to receive log lines from the MIP solver. Solution will be a list of strings. The LP solver will not return any incumbent solutions. Default is None.

  • Returns (dict or Solution object.)

get_optimized_routes(
cuopt_problem_json_data,
filepath=False,
cache=False,
output='',
delete_solution=True,
initial_ids=[],
)#

Get optimized routing solution for a given problem.

Parameters:
  • cuopt_problem_json_data (dict or str) – This is either the problem data as a dictionary or the path of a file containing the problem data as JSON or the reqId of a cached cuopt problem data. Please refer to the server doc for the structure of this dictionary.

  • filepath (boolean) – Indicates that cuopt_problem_json_data is the relative path of a cuopt data file under the server’s data directory. The data directory is specified when the server is started (see the server documentation for more detail). Defaults to False.

  • output (str) – Optional name of the result file. If the server has been configured to write results to files and the size of the result is greater than the configured limit, the server will write the result to a file with this name under the server’s result directory (see the server documentation for more detail). Defaults to a name based on the path if ‘filepath’ is True, or a uuid if ‘filepath’ is False.

  • delete_solution (boolean) – Delete the solution when it is returned. Defaults to True.

repoll(
data,
response_type='obj',
delete_solution=True,
)#

Poll for a result when a previous command resulted in a timeout. The request id is returned as JSON in the result of the original call.

Parameters:
  • data (str) – A uuid identifying the original request. For backward compatibility, data may also be a dictionary containing the key ‘reqId’ where the value is the uuid.

  • response_type (str) – For LP problem choose “dict” if response should be returned as a dictionary or “obj” for Solution object. Defaults to “obj”. For VRP problem, response_type is ignored and always returns a dict.

  • delete_solution (boolean) – Delete the solution when it is returned. Defaults to True.

status(id)#

Return the status of a cuOpt server request.

idstr

A uuid identifying the solution to be deleted.

upload_solution(solution)#

Store a solution on the server and return a request id. This can be used to upload a solution to use as an initial solution for a VRP problem (referenced by reqId).

Parameters:

solution – A solution in the cuOpt result format. May be a dictionary or a file.

LP Supporting Classes#

class data_model.DataModel(*args: Any, **kwargs: Any)#

Initialize a DataModel which represents a Linear Program.

Standard form representation follows the description from the wiki article here: https://en.wikipedia.org/wiki/Linear_programming#Standard_form. In other words, this structure stores all information used to represent the following LP equation: Minimize :

dot(c, x)

Subject to :

matmul(A, x) (= or >= or)<= b

Where :

x : Decision Variables

c : Objective Coefficients

A : Constraint Matrix

b : Constraint Bounds

With :

n = number of variables

m = number of constraints

x = n-dim vector

c = n-dim vector

A = mxn-dim sparse matrix

b = m-dim vector

Notes

By default, this assumes objective minimization. To solve a maximization problem, see set_maximization()

Objective value can be scaled and offseted accordingly: objective_scaling_factor * (dot(c, x) + objective_offset) please refer to to the set_objective_scaling_factor() and set_objective_offset() method.

Examples

Minimize:

cost = 0.2 * VAR1 + 0.1 * VAR2

Subject to

3 * VAR1 + 4 * VAR2 <= 5.4

2.7 * VAR1 + 10.1 * VAR2 <= 4.9

0 <= VAR1 <= 2

0 <= VAR2 <= inf

>>> from cuopt import linear_programming
>>>
>>> import numpy as np
>>>
>>> data_model = linear_programming.DataModel()
>>>
>>> # Set the CSR matrix representation, for more information about CSR
>>> # checkout:
>>> # https://docs.nvidia.com/cuda/cusparse/index.html#compressed-sparse-row-csr # noqa
>>>
>>> # Define the different np.array for the CSR representation
>>> # The 4 values of the constraint matrix (A)
>>> A_values = np.array([3.0, 4.0, 2.7, 10.1], dtype=np.float64)
>>>
>>> # The CSR index vector
>>> # Here we associate each value in the A_values to its variable index
>>> # First value correspond to the first variable
>>> # (3.0 -> variable[*0*], constraint[0])
>>> # Second value correspond to the second variable
>>> # (4.0 -> variable[*1*], constraint[0])
>>> # Third value correspond to the first variable
>>> # (2.7 -> variable[*0*], constraint[1])
>>> # Fourth value correspond to the second variable
>>> # (10.1 -> variable[*1*], constraint[1])
>>> A_indices = np.array([0, 1, 0, 1], dtype=np.int32)
>>>
>>> # The CSR offset vector
>>> # Here we specify the range of values for each constraint
>>> # [0, 2) corresponds to the range of values for the first constraints,
>>> # here [0:3.0, 1:4.0]
>>> # [2, 4) corresponds to the range of values for the second constraint,
>>> # here [1:2.7, 2:10.1]
>>> A_offsets = np.array([0, 2, 4], dtype=np.int32)
>>>
>>> data_model.set_csr_constraint_matrix(A_values, A_indices, A_offsets)
>>>
>>> # Set the constraint bounds (b / right-hand side) array
>>> b = np.array([5.4, 4.9], dtype=np.float64)
>>> data_model.set_constraint_bounds(b)
>>>
>>> # Set the objective coefficient (c) array.
>>> c = np.array([0.2, 0.1], dtype=np.float64)
>>> data_model.set_objective_coefficients(c)
>>>
>>> # Set the constraints/rows equalities, either using the row_type format
>>> # or by directly setting the bounds
>>>
>>> # Method 0: constraints/rows type
>>> # Set both constraints/rows to less-than (<=)
>>> row_types = np.array(['L', 'L'])
>>> data_model.set_row_types(row_types)
>>>
>>> # Method 1: directly set bounds
>>> # Set lower bounds to -infinity and upper bounds to b
>>> constraint_lower_bounds = np.array([np.NINF, np.NINF],
>>>                                       dtype=np.float64)
>>> constraint_upper_bounds = np.array(b, dtype=np.float64)
>>> data_model.set_constraint_lower_bounds(constraint_lower_bounds)
>>> data_model.set_constraint_upper_bounds(constraint_upper_bounds)
>>>
>>>
>>> # Set variable lower and upper bounds
>>> variable_lower_bounds = np.array([0.0, 0.0], dtype=np.float64)
>>> variable_upper_bounds = np.array([2.0, np.PINF], dtype=np.float64)
>>> data_model.set_variable_lower_bounds(variable_lower_bounds)
>>> data_model.set_variable_upper_bounds(variable_upper_bounds)
get_ascii_row_types()#

Get the type of each row (constraint) converted to a numpy.array with int8 type (ascii value).

get_constraint_bounds()#

Get the constraint bounds (b / right-hand side) as numpy.array with float64 type.

get_constraint_lower_bounds()#

Get the constraints lower bounds as numpy.array with float64 type.

get_constraint_matrix_indices()#

Get the indices of the CSR representation of the constraint matrix as numpy.array with int type.

get_constraint_matrix_offsets()#

Get the indices of the CSR representation of the constraint matrix as numpy.array with int type.

get_constraint_matrix_values()#

Get the values of the CSR representation of the constraint matrix as numpy.array with float64 type.

get_constraint_upper_bounds()#

Get the constraints upper bounds as numpy.array with float64 type.

get_initial_dual_solution()#

NOTE: Not supported for MILP.

Get the initial dual solution as numpy.array with float64 type.

get_initial_primal_solution()#

Get the initial primal solution as numpy.array with float64 type.

get_objective_coefficients()#

Get the objective_coefficients (c) as numpy.array with float64 type.

get_objective_offset()#

Get the offset of the objective function as a float64.

get_objective_scaling_factor()#

Get the scaling factor of the objective function as a float64.

get_row_names()#

Get the row names as numpy.array with string type.

get_row_types()#

Get the type of each row (constraint) as numpy.array with char8 type.

get_sense()#

Get the sense of optimization as a bool. True means maximize the objective function, false means minimize.

get_variable_lower_bounds()#

Get the variables (x) lower bounds as numpy.array with float64 type.

get_variable_names()#

Get the variable names as numpy.array with string type.

get_variable_types()#

Get the variable types as numpy.array with char type.

get_variable_upper_bounds()#

Get the variables (x) upper bounds as numpy.array with float64 type.

set_constraint_bounds(b)#

Set the constraint bounds (b / right-hand side) array.

Parameters:

b (np.array dtype - float64) – Device floating point array.

Notes

Setting before calling the solver is mandatory.

set_constraint_lower_bounds(constraint_lower_bounds)#

Set the constraints lower bounds.

Parameters:

constraint_lower_bounds (np.array dtype - float64) – Device floating point array.

Notes

Setting before calling the solver is optional if you set the row type, else it’s mandatory along with the upper bounds.

set_constraint_upper_bounds(constraint_upper_bounds)#

Set the constraints upper bounds.

Parameters:

constraint_upper_bounds (np.array dtype - float64) – Device floating point array.

Notes

Setting before calling the solver is optional if you set the row type, else it’s mandatory along with the lower bounds.

set_csr_constraint_matrix(A_values, A_indices, A_offsets)#

Set the constraint matrix (A) in CSR format. For more information about CSR checkout: https://docs.nvidia.com/cuda/cusparse/index.html#compressed-sparse-row-csr # noqa

Parameters:
  • A_values (np.array dtype - float64) – Values of the CSR representation of the constraint matrix as a device floating point array.

  • A_indices (np.array dtype - int32) – Indices of the CSR representation of the constraint matrix as a device integer array.

  • A_offsets (np.array dtype - int32) – Offsets of the CSR representation of the constraint matrix as a device integer array.

Notes

Setting before calling the solver is mandatory.

set_initial_dual_solution(initial_dual_solution)#

NOTE: Not supported for MILP.

Set the initial dual solution.

Parameters:

initial_dual_solution (np.array dtype - float64) – Device floating point array.

Notes

Setting before calling the solver is optional.

set_initial_primal_solution(initial_primal_solution)#

Set the initial primal solution.

Parameters:

initial_primal_solution (np.array dtype - float64) – Device floating point array.

Notes

Setting before calling the solver is optional.

set_maximize(maximize)#

Set the sense of optimization to maximize.

Parameters:

maximize (bool) – True means to maximize the objective function, else minimize.

Notes

Setting before calling the solver is optional, default value if false (minimize).

set_objective_coefficients(c)#

Set the objective coefficients (c) array.

Parameters:

c (np.array dtype - float64) – Device floating point array.

Notes

Setting before calling the solver is mandatory.

set_objective_offset(objective_offset)#

Set the offset of the objective function (objective_offset + objective_value).

Parameters:

objective_offset (float64) – The constant objective_offset to add.

Notes

Setting before calling the solver is optional.

set_objective_scaling_factor(objective_scaling_factor)#

Set the scaling factor of the objective function (scaling_factor * objective_value).

Parameters:

objective_scaling_factor (float64) – The scaling factor to apply.

Notes

Setting before calling the solver is optional.

set_row_names(row_names)#

Set the row names.

Parameters:

row_names (np.array dtype - unicode string) – Host string array.

Notes

Setting before calling the solver is optional. Value is only used for file generation of the solution.

set_row_types(row_types)#

Set the type of each row (constraint). Possible values are: ‘E’ for equality ( = ): lower & upper constrains bound equal to b ‘L’ for less-than ( <= ): lower constrains bound equal to -infinity, upper constrains bound equal to b ‘G’ for greater-than ( >= ): lower constrains bound equal to b, upper constrains bound equal to +infinity

Parameters:

row_types (np.array dtype - unicode string (<U1)) – Host character array.

Notes

Setting before calling the solver is optional if you set the constraint lower and upper bounds, else it’s mandatory. If both are set, priority goes to set_constraint_lower/upper_bounds.

Examples

>>> row_types = np.array(['L', 'L'])
>>> data_model.set_row_types(row_types)
set_variable_lower_bounds(variable_lower_bounds)#

Set the variables (x) lower bounds.

Parameters:

variable_lower_bounds (np.array dtype - float64) – Device floating point array.

Notes

Setting before calling the solver is optional, default value for all is 0.

set_variable_names(variables_names)#

Set the variables names.

Parameters:

variables_names (np.array dtype - unicode string) – Host string array.

Notes

Setting before calling the solver is optional. Value is only used for file generation of the solution.

set_variable_types(variable_types)#

Set the variable types.

Parameters:

variables_types (np.array dtype - unicode string (<U1)) – Host character array.

set_variable_upper_bounds(variable_upper_bounds)#

Set the variables (x) upper bounds.

Parameters:

variable_upper_bounds (np.array dtype - float64) – Device floating point array.

Notes

Setting before calling the solver is optional, default value for all is +infinity.

class solver_settings.SolverSettings#
get_absolute_dual_tolerance()#

NOTE: Not supported for MILP. Default value is 1e-4.

Get the absolute dual tolerance. For more details on tolerance to optimality, see set_optimality_tolerance method.

Returns:

The absolute dual tolerance.

Return type:

float64

get_absolute_gap_tolerance()#

NOTE: Not supported for MILP. Default value is 1e-4.

Get the absolute gap tolerance. For more details on tolerance to gap, see set_optimality_tolerance method.

Returns:

The absolute gap tolerance.

Return type:

float64

get_absolute_primal_tolerance()#
NOTE: Default values

LP : 1e-4 and MILP : 1e-6.

Get the absolute primal tolerance. For more details on tolerance to optimality, see set_optimality_tolerance method.

Returns:

The absolute primal tolerance.

Return type:

float64

get_dual_infeasible_tolerance()#

NOTE: Not supported for MILP. Default value is 1e-8.

Get the dual infeasible tolerance.

Returns:

The dual infeasible tolerance.

Return type:

float64

get_infeasibility_detection()#

NOTE: Not supported for MILP.

Get the status of detecting infeasibility.

Returns:

Status of detecting infeasibility.

Return type:

bool

get_integrality_tolerance()#

NOTE: Supported for MILP only Default value is 1e-5.

Get integrality tolerance.

get_iteration_limit()#

NOTE: Not supported for MILP.

Get the iteration limit or None if none was set.

Returns:

The iteration limit.

Return type:

int or None

get_mip_heuristics_only()#

Get the heuristics only flag.

get_mip_incumbent_solution_callback()#

Return callback class object

get_mip_num_cpu_threads()#

Get the number of CPU threads to use for the branch and bound.

get_mip_scaling()#

Note: Only supported for MILP

Get whether or not MIP problem scaling is enabled.

Paramters#

enable_scalingbool

True to enable MIP scaling, False to disable.

Notes

The feasibility may not match between the scaled and unscaled problem on numerically challenging models. Default value is True.

get_pdlp_warm_start_data()#

TODO add more comments

Parameters:

pdlp_warm_start_data

Notes

get_primal_infeasible_tolerance()#

NOTE: Not supported for MILP. Default value is 1e-8.

Get the primal infeasible tolerance.

Returns:

The primal infeasible tolerance.

Return type:

float64

get_relative_dual_tolerance()#

NOTE: Not supported for MILP. Default value is 1e-4.

Get the relative dual tolerance. For more details on tolerance to optimality, see set_optimality_tolerance method.

Returns:

The relative dual tolerance.

Return type:

float64

get_relative_gap_tolerance()#

NOTE: Not supported for MILP. Default value is 1e-4.

Get the relative gap tolerance. For more details on tolerance to gap, see set_optimality_tolerance method.

Returns:

The relative gap tolerance.

Return type:

float64

get_relative_primal_tolerance()#
NOTE: Default values

LP : 1e-4 and MILP : 1e-6.

Get the relative primal tolerance. For more details on tolerance to optimality, see set_optimality_tolerance method.

Returns:

The relative primal tolerance.

Return type:

float64

get_solver_mode()#

NOTE: Not supported for MILP.

Get the solver mode. For more details on solver mode, see set_solver_mode method.

Returns:

The solver mode.

Return type:

Int

get_time_limit()#

Get the time limit in seconds or None if none was set.

Returns:

The time limit.

Return type:

float or None

set_absolute_dual_tolerance(absolute_dual_tolerance)#

NOTE: Not supported and not applicable for MILP.

Set the absolute dual tolerance.

Parameters:

absolute_dual_tolerance (float64) – Absolute dual tolerance

Notes

For more details on tolerance to optimality, see set_optimality_tolerance method. Default value is 1e-4.

set_absolute_gap_tolerance(absolute_gap_tolerance)#

NOTE: Not supported and not applicable for MILP. Default value is 1e-4.

Set the absolute gap tolerance.

Parameters:

absolute_gap_tolerance (float64) – Absolute gap tolerance

Notes

For more details on tolerance to gap, see set_optimality_tolerance method.

set_absolute_primal_tolerance(
absolute_primal_tolerance,
)#
NOTE: Default values

LP : 1e-4 and MILP : 1e-4.

Set the absolute primal tolerance.

Parameters:

absolute_primal_tolerance (float64) – Absolute primal tolerance

Notes

For more details on tolerance to optimality, see set_optimality_tolerance method.

set_dual_infeasible_tolerance(
dual_infeasible_tolerance,
)#

NOTE: Not supported for MILP. Default value is 1e-8.

Set the dual infeasible tolerance.

Parameters:

dual_infeasible_tolerance (float64) – Dual infeasible tolerance.

Notes

Higher values will detect infeasibility quicker but may trigger false positive.

set_infeasibility_detection(detect)#

NOTE: Not supported for MILP.

Solver will detect and leave if the problem is detected as infeasible.

Parameters:

detect (bool) – True to detect infeasibility, false to ignore it.

Notes

By default, the solver will not detect infeasibility. Some problems detected as infeasible may converge under a different tolerance factor. Detecting infeasibility consumes both runtime and memory. The added runtime is between 3% and 7%, added memory is between 10% and 20%.

set_integrality_tolerance(integrality_tolerance)#

NOTE: Supported for MILP only Default value is 1e-5.

Set integrality tolerance.

Parameters:

integrality_tolerance (float64) – Integrality tolerance

Notes

Default value is 1e-5.

set_iteration_limit(iteration_limit)#

NOTE: Not supported for MILP.

Set the iteration limit after which the solver will stop and return the current solution.

Parameters:

iteration_limit (int) – Iteration limit to set.

Notes

By default there is no iteration limit. For performance reasons, cuOpt’s does not constantly checks for iteration limit, thus, the solver might run a few extra iterations over the limit. If set along time limit, the first limit reached will exit.

set_mip_heuristics_only(heuristics_only)#

Set the heuristics only flag.

Parameters:

heuristics_only (bool) – True to run heuristics only, False to run heuristics and branch and bound.

Notes

By default, the solver runs both heuristics and branch and bound.

set_mip_incumbent_solution_callback(callback)#

Note: Only supported for MILP

Set the callback to receive incumbent solution.

Parameters:

callback (class for function callback) – Example is as shown below,

Examples

>>> class CustomLPIncumbentSolCallback(LPIncumbentSolCallback):
>>>
>>>     def __init__(self, sender, req_id):
>>>        super().__init__()
>>>        self.solution = None
>>>        self.solution_cost = None
>>>
>>>
>>>     def set_solution(self, solution, solution_cost):
>>>         # This is numba array
>>>         self.solution = solution.copy_to_host()
>>>         self.solution_cost = solution_cost
set_mip_num_cpu_threads(num_cpu_threads)#

Set the number of CPU threads to use for the branch and bound.

Parameters:

num_cpu_threads (int) – Number of CPU threads to use.

set_mip_scaling(mip_scaling)#

Note: Only supported for MILP

Get whether or not MIP problem scaling is enabled.

Paramters#

mip_scalingbool

True to enable MIP scaling, False to disable.

Notes

The feasibility may not match between the scaled and unscaled problem on numerically challenging models. Default value is True.

set_optimality_tolerance(eps_optimal)#
NOTE: Not supported for MILP, absolute is fixed to 1e-4,

relative is fixed for 1e-6 and integrality is fixed for 1e-4. Dual is not supported for MILP.

Set both absolute and relative tolerance on the primal feasibility, dual feasibility, and gap. Changing this value has a significant impact on accuracy and runtime.

Optimality is computed as follows:

dual_feasibility < absolute_dual_tolerance + relative_dual_tolerance
  • norm_objective_coefficient (l2_norm(c))

primal_feasibility < absolute_primal_tolerance
  • relative_primal_tolerance * norm_constraint_bounds (l2_norm(b))

duality_gap < absolute_gap_tolerance + relative_gap_tolerance
  • (abs(primal_objective) + abs(dual_objective))

If all three conditions hold, optimality is reached.

Parameters:

eps_optimal (float64) – Tolerance to optimality

Notes

Default value is 1e-4. To set each absolute and relative tolerance, use the provided setters.

set_pdlp_warm_start_data(pdlp_warm_start_data)#

Set the pdlp warm start data. This allows to restart PDLP with a previous solution context.

This should be used when you solve a new problem which is similar to the previous one.

Parameters:

pdlp_warm_start_data (PDLPWarmStartData) – PDLP warm start data.

Notes

For now, the problem must have the same number of variables and constraints as the one found in the previous solution.

Only supported solver modes are Stable1 and Fast1.

Examples

>>> solution = solver.Solve(first_problem, settings)
>>> settings.set_pdlp_warm_start_data(
>>>     solution.get_pdlp_warm_start_data()
>>> )
>>> solution = solver.Solve(second_problem, settings)
set_primal_infeasible_tolerance(
primal_infeasible_tolerance,
)#

NOTE: Not supported for MILP. Default value is 1e-8.

Set the primal infeasible tolerance.

Parameters:

primal_infeasible_tolerance (float64) – Primal infeasible tolerance.

Notes

Higher values will detect infeasibility quicker but may trigger false positive.

set_relative_dual_tolerance(relative_dual_tolerance)#

NOTE: Not supported and not applicable for MILP.

Set the relative dual tolerance.

Parameters:

relative_dual_tolerance (float64) – Relative dual tolerance

Notes

For more details on tolerance to optimality, see set_optimality_tolerance method. Default value is 1e-4.

set_relative_gap_tolerance(relative_gap_tolerance)#

NOTE: Not supported and not applicable for MILP. Default value is 1e-4.

Set the relative gap tolerance.

Parameters:

relative_gap_tolerance (float64) – Relative gap tolerance

Notes

For more details on tolerance to gap, see set_optimality_tolerance method.

set_relative_primal_tolerance(
relative_primal_tolerance,
)#
NOTE: Default values

LP : 1e-4 and MILP : 1e-6.

Set the relative primal tolerance.

Parameters:

relative_primal_tolerance (float64) – Relative primal tolerance

Notes

For more details on tolerance to optimality, see set_optimality_tolerance method.

set_solver_mode(solver_mode)#

NOTE: Not supported for MILP.

Set the mode under which the solver should operate. The mode will change the way the solver internally optimizes the problem. The mode choice can drastically impact how fast a specific problem will be solved. Users are encouraged to test different modes to see which one fits the best their problem. By default, the solver uses SolverMode.Stable1, the best overall mode from our experiments. For now, only three modes are available : [Stable1, Methodical1, Fast1]

Parameters:

solver_mode (SolverMode) – Solver mode to set. Only possible values are: - SolverMode.Stable1 - SolverMode.Methodical1 - SolverMode.Fast1

Notes

For now, we don’t offer any mechanism to know upfront which solver mode will be the best for one specific problem. Mode description: Stable1: Best compromise between success at converging and speed (corresponds to the former solver_mode 0) Methodical1: Usually leads to slower individual steps but less are needed to converge (corresponds to the former solver_mode 1). It uses from 1.3x up to 1.7x times more memory Fast1: Less convergence success but usually yields the highest speed (new mode, replacing former solver_mode 2).

set_time_limit(time_limit)#

Set the time limit in seconds after which the solver will stop and return the current solution. If set along iteration limit, the first limit reached will exit.

LP: Solver runs until optimality is reached within the time limit. If it does, it will return and will not wait for the entire duration of the time limit.

MILP: Solver runs the entire duration of the time limit to search for a better solution.

Parameters:

time_limit (float64) – Time limit to set in seconds.

Notes

By default there is no time limit. For performance reasons, cuOpt’s does not constantly checks for time limit, thus, the solver might run a few milliseconds over the limit.

class solution.Solution(
problem_category,
vars,
solve_time=0.0,
primal_solution=None,
dual_solution=None,
reduced_cost=None,
current_primal_solution=None,
current_dual_solution=None,
initial_primal_average=None,
initial_dual_average=None,
current_ATY=None,
sum_primal_solutions=None,
sum_dual_solutions=None,
last_restart_duality_gap_primal_solution=None,
last_restart_duality_gap_dual_solution=None,
initial_primal_weight=0.0,
initial_step_size=0.0,
total_pdlp_iterations=0,
total_pdhg_iterations=0,
last_candidate_kkt_score=0.0,
last_restart_kkt_score=0.0,
sum_solution_weight=0.0,
iterations_since_last_restart=0,
termination_reason=0,
primal_residual=0.0,
dual_residual=0.0,
primal_objective=0.0,
dual_objective=0.0,
gap=0.0,
nb_iterations=0,
mip_gap=0.0,
solution_bound=0.0,
presolve_time=0.0,
max_constraint_violation=0.0,
max_int_violation=0.0,
max_variable_bound_violation=0.0,
)#

A container of LP solver output

Parameters:
  • problem_category (int) – Whether it is a LP-0, MIP-1 or IP-2 solution

  • vars (Dict[str, float64]) – Dictionary mapping each variable (name) to its value.

  • primal_solution (numpy.array) – Primal solution of the LP problem

  • dual_solution (numpy.array) – Note: Applicable to only LP Dual solution of the LP problem

  • reduced_cost (numpy.array) – Note: Applicable to only LP The reduced cost. It contains the dual multipliers for the linear constraints.

  • termination_reason (Integer) – Termination reason value.

  • primal_residual (Float64) – L2 norm of the primal residual: measurement of the primal infeasibility

  • dual_residual (Float64) – Note: Applicable to only LP L2 norm of the dual residual: measurement of the dual infeasibility

  • primal_objective (Float64) – Value of the primal objective

  • dual_objective (Float64) – Note: Applicable to only LP Value of the dual objective

  • gap (Float64) – Difference between the primal and dual objective

  • nb_iterations (Int) – Number of iterations the LP solver did before converging

  • mip_gap (float64) – Note: Applicable to only MILP The relative difference between the best integer objective value found so far and the objective bound. A value of 0.01 means the solution is guaranteed to be within 1% of optimal.

  • solution_bound (float64) – Note: Applicable to only MILP The best known bound on the optimal objective value. For minimization problems, this is a lower bound on the optimal value. For maximization problems, this is an upper bound.

  • max_constraint_violation (float64) – Note: Applicable to only MILP The maximum amount by which any constraint is violated in the current solution. Should be close to zero for a feasible solution.

  • max_int_violation (float64) – Note: Applicable to only MILP The maximum amount by which any integer variable deviates from being an integer. A value of 0 means all integer variables have integral values.

  • max_variable_bound_violation (float64) – Note: Applicable to only MILP The maximum amount by which any variable violates its upper or lower bounds in the current solution. Should be zero for a feasible solution.

  • presolve_time (float64) – Note: Applicable to only MILP Time used for pre-solve

  • solve_time (Float64) – Solve time in milliseconds

get_dual_objective()#

Note: Applicable to only LP Returns the dual objective as a float64.

get_dual_solution()#

Note: Applicable to only LP Returns the dual solution as numpy.array with float64 type.

get_lp_stats()#

Note: Applicable to only LP Returns the convergence statistics as a dictionary:

“primal_residual”: float64

Measurement of the primal infeasibility. This quantity is being reduced until primal tolerance is met (see SolverSettings primal_tolerance).

“dual_residual”: float64,

Measurement of the dual infeasibility. This quantity is being reduced until dual tolerance is met (see SolverSettings dual_tolerance).

“gap”: float64

Difference between the primal and dual objective. This quantity is being reduced until gap tolerance is met (see SolverSettings gap_tolerance).

“reduced_cost”: np.array float64

Reduced cost containing the dual multipliers for the linear constraints.

  • “nb_iterations”: int

    Number of iterations the LP solver did before converging.

get_milp_stats()#

Note: Applicable to only MILP Returns the convergence statistics as a dictionary:

mip_gap: float64

The relative difference between the best integer objective value found so far and the objective bound. A value of 0.01 means the solution is guaranteed to be within 1% of optimal.

presolve_time: float64

Time took for pre-solve

max_constraint_violation: float64

The maximum amount by which any constraint is violated in the current solution. Should be close to zero for a feasible solution .

max_int_violation: float64

The maximum amount by which any integer variable deviates from being an integer. A value of 0 means all integer variables have integral values.

max_variable_bound_violation: float64

The maximum amount by which any variable violates its upper or lower bounds in the current solution. Should be zero for a feasible solution.

solution_bound: float64

The best known bound on the optimal objective value. For minimization problems, this is a lower bound on the optimal value. For maximization problems, this is an upper bound.

get_pdlp_warm_start_data()#

Note: Applicable to only LP

Allows to retrieve the warm start data from the PDLP solver.

See SolverSettings.set_pdlp_warm_start_data for more details.

get_primal_objective()#

Returns the primal objective as a float64.

get_primal_solution()#

Returns the primal solution as numpy.array with float64 type.

get_problem_category()#

Returns one of the problem category from ProblemCategory

LP - 0 MIP - 1 IP - 2

get_solve_time()#

Returns the engine solve time in milliseconds as a float64.

get_termination_reason()#

Returns the termination reason as per TerminationReason.

get_vars()#

Returns the dictionnary mapping each variable (name) to its value.

raise_if_lp_solution(function_name)#
raise_if_milp_solution(function_name)#

Service CLI#

  1usage: cuopt_sh [-h] [-id [INIT_IDS ...]] [-wid WARMSTART_ID] [-ca] [-f] [-d]
  2                [-r] [-q] [-ds] [-k] [-st] [-t TYPE] [-ss SOLVER_SETTINGS]
  3                [-o OUTPUT] [-pt POLL_TIMEOUT] [-rt {json,msgpack,zlib,*}]
  4                [-i IP] [-p PORT] [-s] [-c SELF_SIGNED_CERT]
  5                [-l {critical,error,warning,info,debug}] [-ov] [-v]
  6                [-sl [SOLVER_LOGS]] [-il [INCUMBENT_LOGS]] [-us]
  7                [data ...]
  8
  9Solve a cuOpt problem using a self-hosted service client.
 10
 11positional arguments:
 12  data                  Filename, or JSON string containing a request id. Data
 13                        may be a cuopt problem or a request id as displayed in
 14                        the output from a previous request which timed out. A
 15                        cuopt problem must be in a file, but a request id may
 16                        be passed in a file or as a JSON string. For VRP:A
 17                        single problem file is expected or file_name. For LP:
 18                        A single problem file in mps/json format or
 19                        file_name.Batch mode is supported in case of mps files
 20                        only for LP andnot for MILP, where a list of mpsfiles
 21                        can be shared to be solved in parallel.
 22
 23options:
 24  -h, --help            show this help message and exit
 25  -id [INIT_IDS ...], --init-ids [INIT_IDS ...]
 26                        reqId of a solution to use as an initial solution for
 27                        a VRP problem. There may be more than one, separated
 28                        by spaces. The list of ids will be terminated when the
 29                        next option flag is seen or there are no more
 30                        arguments.
 31  -wid WARMSTART_ID, --warmstart-id WARMSTART_ID
 32                        reqId of a solution to use as a warmstart data for a
 33                        single LP problem. This allows to restart PDLP with a
 34                        previous solution context. Not enabled for Batch LP
 35                        problem
 36  -ca, --cache          Indicates that the DATA needs to be cached. This does
 37                        not solve the problem but stores the problem data and
 38                        returns the reqId. The reqId can be used later to
 39                        solve the problem. This flag also may be used
 40                        alongside the delete argument to delete a cached
 41                        request.(see the server documentation for more
 42                        detail).
 43  -f, --filepath        Indicates that the DATA argument is the relative path
 44                        of a cuopt data file under the server's data
 45                        directory. The data directory is specified when the
 46                        server is started (see the server documentation for
 47                        more detail).
 48  -d, --delete          Deletes cached requests or aborts requests on the
 49                        cuOpt server. The DATA argument may be the specific
 50                        reqId of a request or or it may be the wildcard '*'
 51                        which will match any request. If a specific reqId is
 52                        given and the -r, -q, and -ca flags are all
 53                        unspecified, the reqId will always be deleted if it
 54                        exists. If any of the -r, -q, or -ca flags are
 55                        specified, a specific reqId will only be deleted if it
 56                        matches the specified flags. If the wildard reqId '*'
 57                        is given, the -r, -q and/or -ca flags must always be
 58                        set explicitly. To flush the request queue, give '*'
 59                        as the reqId and specify the -q flag. To delete all
 60                        currently running requests, give '*' as the reqId and
 61                        specify the -r flag. To clear the request cache, give
 62                        '*' as the reqId and specify the -ca flag.
 63  -r, --running         Aborts a request only if it is running. Should be used
 64                        with -d argument
 65  -q, --queued          Aborts a request only if it is queued. Should be used
 66                        with -d argument
 67  -ds, --delete_solution
 68                        Deletes solutions on the cuOpt server. The DATA
 69                        argument is the specific reqId of a solution.
 70  -k, --keep            Do not delete a solution from the server when it is
 71                        retrieved. Default is to delete the solution when it
 72                        is retrieved.
 73  -st, --status         Report the status of a request (completed, aborted,
 74                        running, queued)
 75  -t TYPE, --type TYPE  The type of problem to solve. Supported options are
 76                        VRP and LP (defaults to VRP)
 77  -ss SOLVER_SETTINGS, --solver-settings SOLVER_SETTINGS
 78                        Filename or JSON string containing solver settings for
 79                        LP problem type
 80  -o OUTPUT, --output OUTPUT
 81                        Optional name of the result file. If the server has
 82                        been configured to write results to files and the size
 83                        of the result is greater than the configured limit,
 84                        the server will write the result to a file with this
 85                        name under the server's result directory (see the
 86                        server documentation for more detail). A default name
 87                        will be used if this is not specified.
 88  -pt POLL_TIMEOUT, --poll-timeout POLL_TIMEOUT
 89                        Number of seconds to poll for a result before timing
 90                        out and returning a request id to re-query (defaults
 91                        to 120)
 92  -rt {json,msgpack,zlib,*}, --result-type {json,msgpack,zlib,*}
 93                        Mime type of result in responseIf not provided it is
 94                        set to msgpack
 95  -i IP, --ip IP        Host address for the cuOpt server (default 0.0.0.0)
 96  -p PORT, --port PORT  Port for the cuOpt server (default 5000)
 97  -s, --ssl             Use https scheme (default is http)
 98  -c SELF_SIGNED_CERT, --self-signed-cert SELF_SIGNED_CERT
 99                        Path to self signed certificates only, skip for
100                        standard certificates
101  -l {critical,error,warning,info,debug}, --log-level {critical,error,warning,info,debug}
102                        Log level
103  -ov, --only-validation
104                        If set, only validates input
105  -v, --version         Print client version and exit.
106  -sl [SOLVER_LOGS], --solver-logs [SOLVER_LOGS]
107                        If set detailed MIP solver logs will be returned. If a
108                        filename argument is given logs will be written to
109                        that file. If no argument is given logs will be
110                        written to stdout.
111  -il [INCUMBENT_LOGS], --incumbent-logs [INCUMBENT_LOGS]
112                        If set MIP incumbent solutions will be returned. If a
113                        filename argument is given incumbents will be written
114                        to that file. If no argument is given incumbents will
115                        be written to stdout.
116  -us, --upload-solution
117                        Upload a solution to be cached on the server. The
118                        reqId returned may be used as an initial solution for
119                        VRP.