1 # -------------------------------------------------------------------------
2 # Copyright (c) 2020 AT&T Intellectual Property
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
16 # -------------------------------------------------------------------------
19 from flask import Response
21 from osdf.operation.exceptions import BusinessException
22 from osdf.utils.data_conversion import decode_data
23 from runtime.model_api import get_model_data
24 from runtime.models.api.optim_request import OptimizationAPI
25 from runtime.solvers.mzn.mzn_solver import solve as mzn_solve
26 from runtime.solvers.py.py_solver import solve as py_solve
29 def is_valid_optim_request(request_json):
30 # Method to check whether the requestinfo/optimizer value is valid.
31 opt_info = request_json['optimInfo']
32 if not opt_info.get('modelId'):
33 if not opt_info.get('modelContent') or not opt_info.get('solver'):
34 raise BusinessException('modelContent and solver needs to be populated if model_id is not set')
35 if not opt_info.get('optData'):
36 raise BusinessException('optimInfo.optData needs to be populated to solve for a problem')
41 def validate_request(request_json):
42 OptimizationAPI(request_json).validate()
43 if not is_valid_optim_request(request_json):
44 raise BusinessException('Invalid optim request ')
48 def process_request(request_json):
49 response_code, response_message = run_optimizer(request_json)
50 response = Response(response_message, content_type='application/json; charset=utf-8')
51 response.headers.add('content-length', len(response_message))
52 response.status_code = response_code
56 def run_optimizer(request_json):
57 validate_request(request_json)
59 model_content, solver = get_model_content(request_json)
62 return mzn_solve(request_json, model_content)
64 return py_solve(request_json, model_content)
65 raise BusinessException('Unsupported optimization solver requested {} '.format(solver))
68 def get_model_content(request_json):
69 model_id = request_json['optimInfo'].get('modelId')
71 status, data = get_model_data(model_id)
73 model_content = decode_data(data[1])
76 raise BusinessException('model_id [{}] not found in the model database'.format(model_id))
78 model_content = request_json['optimInfo']['modelContent']
79 solver = request_json['optimInfo']['solver']
80 return model_content, solver