Add support to generic optimization structure
[optf/has.git] / conductor / conductor / solver / optimizer / greedy.py
1 #!/bin/python
2 #
3 # -------------------------------------------------------------------------
4 #   Copyright (c) 2015-2017 AT&T Intellectual Property
5 #   Copyright (C) 2020 Wipro Limited.
6 #
7 #   Licensed under the Apache License, Version 2.0 (the "License");
8 #   you may not use this file except in compliance with the License.
9 #   You may obtain a copy of the License at
10 #
11 #       http://www.apache.org/licenses/LICENSE-2.0
12 #
13 #   Unless required by applicable law or agreed to in writing, software
14 #   distributed under the License is distributed on an "AS IS" BASIS,
15 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 #   See the License for the specific language governing permissions and
17 #   limitations under the License.
18 #
19 # -------------------------------------------------------------------------
20 #
21
22
23 from oslo_log import log
24 import sys
25
26 from conductor.solver.optimizer import decision_path as dpath
27 from conductor.solver.optimizer import search
28
29 LOG = log.getLogger(__name__)
30
31
32 class Greedy(search.Search):
33
34     def __init__(self, conf):
35         search.Search.__init__(self, conf)
36
37     def search(self, _demand_list, _objective):
38         decision_path = dpath.DecisionPath()
39         decision_path.set_decisions({})
40
41         for demand in _demand_list:
42             LOG.debug("demand = {}".format(demand.name))
43
44             decision_path.current_demand = demand
45             candidate_list = self._solve_constraints(decision_path)
46
47             bound_value = 0.0
48             if _objective.goal == "min":
49                 bound_value = sys.float_info.max
50
51             best_resource = None
52             for candidate in candidate_list:
53                 decision_path.decisions[demand.name] = candidate
54                 _objective.compute(decision_path)
55                 if _objective.goal == "min":
56                     if decision_path.total_value < bound_value:
57                         bound_value = decision_path.total_value
58                         best_resource = candidate
59                 elif _objective.goal == "max":
60                     if decision_path.total_value > bound_value:
61                         bound_value = decision_path.total_value
62                         best_resource = candidate
63
64             if best_resource is not None:
65                 decision_path.decisions[demand.name] = best_resource
66                 decision_path.total_value = bound_value
67             else:
68                 return None
69
70         return decision_path