1
|
1 |
|
import numpy as np |
|
|
|
|
2
|
|
|
|
3
|
1 |
|
from grortir.main.pso.group_optimization_strategy import \ |
4
|
|
|
GroupOptimizationStrategy |
5
|
|
|
|
6
|
|
|
|
7
|
1 |
|
class CreditCallsGroupOptimizationStrategy(GroupOptimizationStrategy): |
8
|
|
|
"""Optimization with credits. |
9
|
|
|
Attributes: |
10
|
|
|
stages_in_group (list): stages in group |
11
|
|
|
process (AbstractProcess): optimized process |
12
|
|
|
max_calls_for_group (int): max calls which can be |
13
|
|
|
used for this group |
14
|
|
|
expected_quality (float): expected quality |
15
|
|
|
""" |
16
|
|
|
|
17
|
1 |
|
def __init__(self, stages_in_group, process): |
18
|
1 |
|
self.stages_in_group = stages_in_group |
19
|
1 |
|
self.process = process |
20
|
1 |
|
self.max_calls_for_group = 0 |
21
|
1 |
|
self.expected_quality = np.inf |
22
|
|
|
|
23
|
1 |
|
def initialize(self): |
|
|
|
|
24
|
|
|
""" |
25
|
|
|
Called once and set initial value of max_calls_for_group. |
26
|
|
|
""" |
27
|
1 |
|
if self._calculate_current_cost_in_group() != 0: |
28
|
1 |
|
raise ValueError( |
29
|
|
|
"Stages in group shouldn't started with initial cost.") |
30
|
1 |
|
all_initial_calls = 0 |
31
|
1 |
|
already_used_calls = 0 |
32
|
1 |
|
all_stages = self.process.nodes() |
33
|
1 |
|
for stage in all_stages: |
34
|
1 |
|
all_initial_calls += stage.get_maximal_acceptable_cost() |
35
|
1 |
|
for stage in all_stages: |
36
|
1 |
|
already_used_calls += stage.get_cost() |
37
|
1 |
|
self.max_calls_for_group = all_initial_calls - already_used_calls |
38
|
|
|
|
39
|
1 |
|
for stage in self.stages_in_group: |
40
|
1 |
|
if self.expected_quality > stage.maximum_acceptable_quality: |
41
|
1 |
|
self.expected_quality = stage.maximum_acceptable_quality |
42
|
|
|
|
43
|
1 |
|
def should_continue(self, best_particle): |
|
|
|
|
44
|
|
|
""" |
45
|
|
|
|
46
|
|
|
Args: |
47
|
|
|
best_particle Particle: best particle in swarm. |
48
|
|
|
|
49
|
|
|
Returns: |
50
|
|
|
bool: true if continuation is required. |
51
|
|
|
|
52
|
|
|
""" |
53
|
1 |
|
return self._is_safe_cost() and not self._is_enough_quality( |
54
|
|
|
best_particle) |
55
|
|
|
|
56
|
1 |
|
def _is_safe_cost(self): |
|
|
|
|
57
|
1 |
|
return ( |
58
|
|
|
self._calculate_current_cost_in_group() <= self.max_calls_for_group) |
59
|
|
|
|
60
|
1 |
|
def _is_enough_quality(self, best_particle): |
|
|
|
|
61
|
1 |
|
return best_particle.best_quality <= self.expected_quality |
62
|
|
|
|
63
|
1 |
|
def _calculate_current_cost_in_group(self): |
|
|
|
|
64
|
1 |
|
calls_used_in_group = 0 |
65
|
1 |
|
for stage in self.stages_in_group: |
66
|
1 |
|
calls_used_in_group += stage.get_cost() |
67
|
|
|
return calls_used_in_group |
68
|
|
|
|
The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:
If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.