forked from fogleman/primitive
/
optimize.go
75 lines (70 loc) · 1.73 KB
/
optimize.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
package primitive
import (
"math"
"math/rand"
)
type Annealable interface {
Energy() float64
DoMove() interface{}
UndoMove(interface{})
Copy() Annealable
}
func HillClimb(state Annealable, maxAge int) Annealable {
state = state.Copy()
bestState := state.Copy()
bestEnergy := state.Energy()
step := 0
for age := 0; age < maxAge; age++ {
undo := state.DoMove()
energy := state.Energy()
if energy >= bestEnergy {
state.UndoMove(undo)
} else {
// fmt.Printf("step: %d, energy: %.6f\n", step, energy)
bestEnergy = energy
bestState = state.Copy()
age = -1
}
step++
}
return bestState
}
func PreAnneal(state Annealable, iterations int) float64 {
state = state.Copy()
previous := state.Energy()
var total float64
for i := 0; i < iterations; i++ {
state.DoMove()
energy := state.Energy()
total += math.Abs(energy - previous)
previous = energy
}
return total / float64(iterations)
}
func Anneal(state Annealable, maxTemp, minTemp float64, steps int) Annealable {
factor := -math.Log(maxTemp / minTemp)
state = state.Copy()
bestState := state.Copy()
bestEnergy := state.Energy()
previousEnergy := bestEnergy
for step := 0; step < steps; step++ {
pct := float64(step) / float64(steps-1)
temp := maxTemp * math.Exp(factor*pct)
undo := state.DoMove()
energy := state.Energy()
change := energy - previousEnergy
if change > 0 && math.Exp(-change/temp) < rand.Float64() {
state.UndoMove(undo)
} else {
previousEnergy = energy
if energy < bestEnergy {
// pct := float64(step*100) / float64(steps)
// fmt.Printf("step: %d of %d (%.1f%%), temp: %.3f, energy: %.6f\n",
// step, steps, pct, temp, energy)
bestEnergy = energy
bestState = state.Copy()
}
}
}
return bestState
}