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 .model_api import get_model_data
23 from .models.api.optim_request import OptimizationAPI
24 from .solvers.mzn.mzn_solver import solve as mzn_solve
25 from .solvers.py.py_solver import solve as py_solve
28 def is_valid_optim_request(request_json):
29 # Method to check whether the requestinfo/optimizer value is valid.
30 opt_info = request_json['optimInfo']
31 if not opt_info.get('modelId'):
32 if not opt_info.get('modelContent') or not opt_info.get('solver'):
33 raise BusinessException('modelContent and solver needs to be populated if model_id is not set')
34 if not opt_info.get('optData'):
35 raise BusinessException('optimInfo.optData needs to be populated to solve for a problem')
40 def validate_request(request_json):
41 OptimizationAPI(request_json).validate()
42 if not is_valid_optim_request(request_json):
43 raise BusinessException('Invalid optim request ')
47 def process_request(request_json):
48 response_code, response_message = run_optimizer(request_json)
49 response = Response(response_message, content_type='application/json; charset=utf-8')
50 response.headers.add('content-length', len(response_message))
51 response.status_code = response_code
55 def run_optimizer(request_json):
56 validate_request(request_json)
58 model_content, solver = get_model_content(request_json)
61 return mzn_solve(request_json, model_content)
63 return py_solve(request_json, model_content)
64 raise BusinessException('Unsupported optimization solver requested {} '.format(solver))
67 def get_model_content(request_json):
68 model_id = request_json['optimInfo'].get('modelId')
70 status, data = get_model_data(model_id)
72 model_content = data[1]
75 raise BusinessException('model_id [{}] not found in the model database'.format(model_id))
77 model_content = request_json['optimInfo']['modelContent']
78 solver = request_json['optimInfo']['solver']
79 return model_content, solver