39 endpoint: Optional[str] = _DEFAULT_ENDPOINT,
40 api_key: Optional[str] =
None,
41 deadline_sec: Optional[float] = _DEFAULT_DEADLINE_SEC,
44 """Solves a MathOpt model via HTTP request to the OR API.
47 model: The optimization model.
48 solver_type: The underlying solver to use.
49 params: Optional configuration of the underlying solver.
50 model_params: Optional configuration of the solver that is model specific.
51 endpoint: An URI identifying the service for remote solves.
52 api_key: Key to the OR API.
53 deadline_sec: The number of seconds before the request times out.
54 resources: Hints on resources requested for the solve.
57 A SolveResult containing the termination reason, solution(s) and stats.
58 A list of messages with the logs (if specified in the `params`).
61 OptimizationServiceError: if an HTTP error is returned while solving a
66 raise ValueError(
"api_key can't be None when solving remotely")
71 response = session.post(
78 http_error = json.loads(response.content)[
"error"]
79 raise OptimizationServiceError(
80 f
'status code {http_error["code"]}: {http_error["message"]}'
116 model: mathopt.Model,
122 """Builds a JSON payload.
125 model: The optimization model.
126 solver_type: The underlying solver to use.
127 params: Optional configuration of the underlying solver.
128 model_params: Optional configuration of the solver that is model specific.
129 resources: Hints on resources requested for the solve.
132 A JSON object with a MathOpt model and corresponding parameters.
135 SerializationError: If building the OR API proto is not successful or
136 deserializing to JSON fails.
142 request = rpc_pb2.SolveRequest(
143 model=model.export_model(),
144 solver_type=solver_type.value,
145 resources=resources.to_proto(),
146 parameters=params.to_proto(),
147 model_parameters=model_params.to_proto(),
149 api_request = proto_converter.convert_request(request)
150 except ValueError
as err:
151 raise ValueError
from err
153 return json.loads(json_format.MessageToJson(api_request))
159 """Parses a JSON representation of a response to a SolveResult object.
162 json_response: bytes representing the `SolveMathOptModelResponse` in JSON
164 model: The optimization model that was solved
167 A SolveResult of the model.
168 A list of messages with the logs.
171 SerializationError: If parsing the json response fails or if converting the
172 OR API response to the internal MathOpt response fails.
175 api_response = json_format.Parse(
176 json_response, optimization_pb2.SolveMathOptModelResponse()
178 except json_format.ParseError
as json_err:
180 "API response is not a valid SolveMathOptModelResponse JSON"
183 response = proto_converter.convert_response(api_response)
184 return mathopt.parse_solve_result(response.result, model), list(response.messages)