-
Notifications
You must be signed in to change notification settings - Fork 0
/
utility.go
53 lines (46 loc) · 1.02 KB
/
utility.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
package opt
import (
"math"
"sort"
)
// utilSlice is a generic sorting interface that preserves indices.
type utilSlice struct {
sort.Interface
perm []int
}
func (s utilSlice) Swap(i, j int) {
s.Interface.Swap(i, j)
s.perm[i], s.perm[j] = s.perm[j], s.perm[i]
}
// utilities computes rank normalized utilities given an arbitrary slice of scores.
func utilities(scores []float64) (u []float64) {
// Make the permutation slice
perm := make([]int, len(scores))
for i := range perm {
perm[i] = i
}
us := utilSlice{
Interface: sort.Float64Slice(scores),
perm: perm,
}
// Sort to get permutations
sort.Sort(sort.Reverse(us))
perm = us.perm
// Calculate utilities
s := float64(len(scores))
u = make([]float64, len(scores))
for i := range perm {
u[perm[i]] = float64(i) + 1.0 // whatever was in position perm[i] is rank i
}
for i := range u {
u[i] = math.Max(0, math.Log(s/2+1)-math.Log(u[i]))
}
uSum := 0.0
for i := range u {
uSum += u[i]
}
for i := range u {
u[i] = u[i]/uSum - 1/s
}
return u
}