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:
- ipstr
The IP address of the cuOpt service. Defaults to 0.0.0.0
- portstr
The port of the cuOpt service. Set to empty string or None to omit the port from cupot urls (this is useful with exported services in kubernetes for example). Defaults to 5000.
- use_httpsboolean
Use HTTPS to communicate with server in secured way.
- self_signed_certstr
A complete path to self signed certificate. If it’s a standard certificate, then no need to provide anything.
- polling_intervalint
The duration in seconds between consecutive polling attempts. Defaults to 1.
- request_excess_timeoutint
Note: Deprecated, Use polling_timeout instead
- only_validateboolean
Only validates input. Defaults to False.
- polling_timeoutint
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_exceptionboolean
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_typeenum
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
Methods
delete
(id[, running, queued, cached])Delete a cached entry by id or abort a job by id.
delete_solution
(id)Delete a solution by id.
get_LP_solve
(cuopt_data_models[, ...])Get linear programming solution for a given problem.
get_optimized_routes
(cuopt_problem_json_data)Get optimized routing solution for a given problem.
repoll
(data[, response_type, delete_solution])Poll for a result when a previous command resulted in a timeout.
status
(id)Return the status of a cuOpt server request.
upload_solution
(solution)Store a solution on the server and return a request id.
- delete(
- id,
- running=None,
- queued=None,
- cached=None,
Delete a cached entry by id or abort a job by id.
- Parameters:
- idstr
A uuid identifying the cached entry or job to be deleted. The wildcard id ‘*’ will match all uuids (filtered by ‘running’, ‘queued’, and ‘cached’).
- runningbool
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.
- queuedbool
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:
- idstr
A uuid identifying the solution to be deleted.
- get_LP_solve(
- cuopt_data_models,
- solver_config=<cuopt_sh_client.thin_client_solver_settings.ThinClientSolverSettings 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_configSolverSettings object or Dict
Contains solver settings including tolerance values. See the LP documentation for details on solver settings.
- response_typestr
Choose “dict” if response should be returned as a dictionary or “obj” for Solution object. Defaults to “obj”
- filepathboolean
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.
- outputstr
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_callbackcallable
# 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_datadict 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.
- filepathboolean
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.
- outputstr
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:
- datastr
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 cuopt_sh_client.PDLPSolverMode(*values)#
Enum representing different solver modes to use in the SolverSettings.set_pdlp_solver_mode function.
Notes
Default mode is Stable2.
Attributes
Stable2
Best overall mode from experiments; balances speed and convergence success. If you want to use the legacy version, use Stable1.
Methodical1
Takes slower individual steps, but fewer are needed to converge.
Fast1
Fastest mode, but with less success in convergence.
Methods
as_integer_ratio
(/)Return a pair of integers, whose ratio is equal to the original int.
bit_count
(/)Number of ones in the binary representation of the absolute value of self.
bit_length
(/)Number of bits necessary to represent self in binary.
conjugate
Returns self, the complex conjugate of any int.
from_bytes
(/, bytes[, byteorder, signed])Return the integer represented by the given array of bytes.
is_integer
(/)Returns True.
to_bytes
(/[, length, byteorder, signed])Return an array of bytes representing an integer.
- Fast1 = 3#
- Methodical1 = 2#
- Stable1 = 0#
- Stable2 = 1#
- class cuopt_sh_client.SolverMethod(*values)#
Enum representing different methods to use for solving linear programs.
Attributes
denominator
the denominator of a rational number in lowest terms
imag
the imaginary part of a complex number
numerator
the numerator of a rational number in lowest terms
real
the real part of a complex number
Methods
as_integer_ratio
(/)Return a pair of integers, whose ratio is equal to the original int.
bit_count
(/)Number of ones in the binary representation of the absolute value of self.
bit_length
(/)Number of bits necessary to represent self in binary.
conjugate
Returns self, the complex conjugate of any int.
from_bytes
(/, bytes[, byteorder, signed])Return the integer represented by the given array of bytes.
is_integer
(/)Returns True.
to_bytes
(/[, length, byteorder, signed])Return an array of bytes representing an integer.
- Concurrent = 0#
- DualSimplex = 2#
- PDLP = 1#
- class solution.solution.PDLPWarmStartData(
- current_primal_solution,
- current_dual_solution,
- initial_primal_average,
- initial_dual_average,
- current_ATY,
- sum_primal_solutions,
- sum_dual_solutions,
- last_restart_duality_gap_primal_solution,
- last_restart_duality_gap_dual_solution,
- initial_primal_weight,
- initial_step_size,
- total_pdlp_iterations,
- total_pdhg_iterations,
- last_candidate_kkt_score,
- last_restart_kkt_score,
- sum_solution_weight,
- iterations_since_last_restart,
- class data_model.DataModel#
Initialize a DataModel which represents a Linear Program.
A linear programming optimization problem is defined as follows: 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 >>> >>> # 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)
Methods
Get the type of each row (constraint) converted to a numpy.array with int8 type (ascii value).
Get the constraint bounds (b / right-hand side) as numpy.array with float64 type.
Get the constraints lower bounds as numpy.array with float64 type.
Get the indices of the CSR representation of the constraint matrix as numpy.array with int type.
Get the indices of the CSR representation of the constraint matrix as numpy.array with int type.
Get the values of the CSR representation of the constraint matrix as numpy.array with float64 type.
Get the constraints upper bounds as numpy.array with float64 type.
NOTE: Not supported for MILP.
Get the initial primal solution as numpy.array with float64 type.
Get the objective_coefficients (c) as numpy.array with float64 type.
Get the offset of the objective function as a float64.
Get the scaling factor of the objective function as a float64.
Get the row names as numpy.array with string type.
Get the type of each row (constraint) as numpy.array with char8 type.
Get the sense of optimization as a bool.
Get the variables (x) lower bounds as numpy.array with float64 type.
Get the variable names as numpy.array with string type.
Get the variable types as numpy.array with char type.
Get the variables (x) upper bounds as numpy.array with float64 type.
Set the constraint bounds (b / right-hand side) array.
Set the constraints lower bounds.
Set the constraints upper bounds.
set_csr_constraint_matrix
(A_values, ...)Set the constraint matrix (A) in CSR format.
set_initial_dual_solution
(initial_dual_solution)NOTE: Not supported for MILP.
Set the initial primal solution.
set_maximize
(maximize)Set the sense of optimization to maximize.
Set the objective coefficients (c) array.
set_objective_offset
(objective_offset)Set the offset of the objective function (objective_offset + objective_value).
Set the scaling factor of the objective function (scaling_factor * objective_value).
set_row_names
(row_names)Set the row names.
set_row_types
(row_types)Set the type of each row (constraint).
set_variable_lower_bounds
(variable_lower_bounds)Set the variables (x) lower bounds.
set_variable_names
(variables_names)Set the variables names.
set_variable_types
(variable_types)Set the variable types.
set_variable_upper_bounds
(variable_upper_bounds)Set the variables (x) 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:
- bnp.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_boundsnp.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_boundsnp.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
- Parameters:
- A_valuesnp.array dtype - float64
Values of the CSR representation of the constraint matrix as a device floating point array.
- A_indicesnp.array dtype - int32
Indices of the CSR representation of the constraint matrix as a device integer array.
- A_offsetsnp.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_solutionnp.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_solutionnp.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:
- maximizebool
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:
- cnp.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_offsetfloat64
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_factorfloat64
The scaling factor to apply.
Notes
Setting before calling the solver is optional.
- set_row_names(row_names)#
Set the row names.
- Parameters:
- row_namesnp.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_typesnp.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_boundsnp.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_namesnp.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_typesnp.array dtype - unicode string (<U1)
Host character array.
- set_variable_upper_bounds(variable_upper_bounds)#
Set the variables (x) upper bounds.
- Parameters:
- variable_upper_boundsnp.array dtype - float64
Device floating point array.
Notes
Setting before calling the solver is optional, default value for all is +infinity.
- class cuopt_sh_client.ThinClientSolverSettings#
Methods
get_parameter
(name)Get a parameter for the solver.
set_optimality_tolerance
(eps_optimal)NOTE: Not supported for MILP, absolute is fixed to 1e-4,
set_parameter
(name, value)Set a parameter for the solver.
toDict
- get_parameter(name)#
Get a parameter for the solver.
- Parameters:
- namestr
The name of the parameter to get.
- Returns:
- object
The value of the parameter.
Notes
For a list of available parameters, see the settings.rst file in the cuOpt documentation.
- set_optimality_tolerance(eps_optimal)#
NOTE: Not supported for MILP, absolute is fixed to 1e-4,
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_optimalfloat64
Tolerance to optimality
- Notes
- —–
- Default value is 1e-4.
- To set each absolute and relative tolerance, use the provided setters.
- set_parameter(name, value)#
Set a parameter for the solver.
- Parameters:
- namestr
The name of the parameter to set.
- valueobject
The value to set the parameter to.
Notes
For a list of available parameters, see the settings.rst file in the cuOpt documentation.
- toDict()#
- 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_status=0,
- error_status=0,
- error_message='',
- primal_residual=0.0,
- dual_residual=0.0,
- primal_objective=0.0,
- dual_objective=0.0,
- gap=0.0,
- nb_iterations=0,
- solved_by_pdlp=None,
- 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,
- num_nodes=0,
- num_simplex_iterations=0,
A container of LP solver output
- Parameters:
- problem_categoryint
Whether it is a LP-0, MIP-1 or IP-2 solution
- varsDict[str, float64]
Dictionary mapping each variable (name) to its value.
- primal_solutionnumpy.array
Primal solution of the LP problem
- dual_solutionnumpy.array
Note: Applicable to only LP Dual solution of the LP problem
- reduced_costnumpy.array
Note: Applicable to only LP The reduced cost. It contains the dual multipliers for the linear constraints.
- termination_status: Integer
Termination status 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 seconds
- solved_by_pdlp: bool
Whether the problem was solved by PDLP or Dual Simplex
Methods
Note: Applicable to only LP Returns the dual objective as a float64.
Note: Applicable to only LP Returns the dual solution as numpy.array with float64 type.
Returns the error message as per ErrorMessage.
Returns the error status as per ErrorStatus.
Note: Applicable to only LP Returns the convergence statistics as a dictionary:
Note: Applicable to only MILP Returns the convergence statistics as a dictionary:
Note: Applicable to only LP
Returns the primal objective as a float64.
Returns the primal solution as numpy.array with float64 type.
Returns one of the problem category from ProblemCategory
Returns the reduced cost as numpy.array with float64 type.
Returns the engine solve time in seconds as a float64.
Returns whether the problem was solved by PDLP or Dual Simplex
Returns the termination reason as per TerminationReason.
Returns the termination status as per TerminationReason.
get_vars
()Returns the dictionnary mapping each variable (name) to its value.
raise_if_lp_solution
raise_if_milp_solution
- 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_error_message()#
Returns the error message as per ErrorMessage.
- get_error_status()#
Returns the error status as per ErrorStatus.
- 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).
- “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.
- num_nodes: int
Number of nodes explored during the MIP solve
- num_simplex_iterations: int
Number of simplex iterations performed during the MIP solve
- 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_reduced_cost()#
Returns the reduced cost as numpy.array with float64 type.
- get_solve_time()#
Returns the engine solve time in seconds as a float64.
- get_solved_by_pdlp()#
Returns whether the problem was solved by PDLP or Dual Simplex
- get_termination_reason()#
Returns the termination reason as per TerminationReason.
- get_termination_status()#
Returns the termination status 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)#
Self-Hosted Client CLI#
CLI provides an option for users to interact with the cuOpt on C level using mps files as input.
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. Set to empty string ('') to
97 omit the port number from the url (default 5000)
98 -s, --ssl Use https scheme (default is http)
99 -c SELF_SIGNED_CERT, --self-signed-cert SELF_SIGNED_CERT
100 Path to self signed certificates only, skip for
101 standard certificates
102 -l {critical,error,warning,info,debug}, --log-level {critical,error,warning,info,debug}
103 Log level
104 -ov, --only-validation
105 If set, only validates input
106 -v, --version Print client version and exit.
107 -sl [SOLVER_LOGS], --solver-logs [SOLVER_LOGS]
108 If set detailed MIP solver logs will be returned. If a
109 filename argument is given logs will be written to
110 that file. If no argument is given logs will be
111 written to stdout.
112 -il [INCUMBENT_LOGS], --incumbent-logs [INCUMBENT_LOGS]
113 If set MIP incumbent solutions will be returned. If a
114 filename argument is given incumbents will be written
115 to that file. If no argument is given incumbents will
116 be written to stdout.
117 -us, --upload-solution
118 Upload a solution to be cached on the server. The
119 reqId returned may be used as an initial solution for
120 VRP.