-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoptimizer_aggregator.go
84 lines (70 loc) · 2.66 KB
/
optimizer_aggregator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package genetic_algorithm
import ()
type OptimizerAggregator struct {
optimizer OptimizerInterface
statisticsAggregatorConstructor StatisticsAggregatorConstructor
statisticsOptions StatisticsOptionsInterface
iterations int
}
func NewOptimizerAggregator() *OptimizerAggregator {
aggregator := new(OptimizerAggregator)
aggregator.statisticsAggregatorConstructor = NewStatisticsDefaultAggregator
aggregator.statisticsOptions = NewStatisticsDefaultOptions()
return aggregator
}
func (aggregator *OptimizerAggregator) Optimizer(optimizer OptimizerInterface) *OptimizerAggregator {
aggregator.optimizer = optimizer
return aggregator
}
func (aggregator *OptimizerAggregator) StatisticsAggregatorConstructor(constr StatisticsAggregatorConstructor) *OptimizerAggregator {
aggregator.statisticsAggregatorConstructor = constr
return aggregator
}
func (aggregator *OptimizerAggregator) StatisticsOptions(statisticsOptions StatisticsOptionsInterface) *OptimizerAggregator {
aggregator.statisticsOptions = statisticsOptions
return aggregator
}
func (aggregator *OptimizerAggregator) Iterations(iterations int) *OptimizerAggregator {
aggregator.iterations = iterations
return aggregator
}
func (aggregator *OptimizerAggregator) check() {
if aggregator.optimizer == nil {
panic("Optimizer must be set")
}
if aggregator.statisticsAggregatorConstructor == nil {
panic("StatisticsAggregatorConstructor must be set")
}
if aggregator.statisticsOptions == nil {
panic("StatisticsOptions must be set")
}
if aggregator.iterations <= 0 {
panic("Iterations must be positive value")
}
}
func (aggregator *OptimizerAggregator) Optimize() (ChromosomeInterface, StatisticsDataInterface) {
aggregator.check()
statisticsAggregator := aggregator.statisticsAggregatorConstructor(aggregator.statisticsOptions)
aggregator.ensureOptimizerOptions(statisticsAggregator)
var bestChrom ChromosomeInterface
for i := 0; i < aggregator.iterations; i++ {
chrom, stats := aggregator.optimizer.Optimize()
if bestChrom == nil || bestChrom.Cost() > chrom.Cost() {
bestChrom = chrom
}
statisticsAggregator.Aggregate(stats)
}
return bestChrom, statisticsAggregator.Compute()
}
func (aggregator *OptimizerAggregator) ensureOptimizerOptions(statisticsAggregator StatisticsAggregatorInterface) {
optimizerWithStatisticsOptionsSetup, ok := aggregator.optimizer.(OptimizerWithStatisticsOptionsSetup)
if !ok {
return
}
statisticsAggregatorWithOptions, ok := statisticsAggregator.(StatisticsAggregatorWithOptions)
if !ok {
return
}
statisticsAggregatorWithOptions.Options().Ensure(
optimizerWithStatisticsOptionsSetup.SetupStatisticsOptions())
}