-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
103 lines (90 loc) · 2.27 KB
/
main.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package main
import (
"fmt"
"math/rand"
"quantilesketch/quantilesketch"
)
type Sketch interface {
RecordValue(value float64, count float64) error
GetValueAtQuantile(quantile float64) (float64, error)
}
func CreateSketches(numSketches int, relativeAccuracy float64) ([]Sketch, error) {
var sketches []Sketch
for i := 0; i < numSketches; i++ {
sketch, err := quantilesketch.New(relativeAccuracy)
if err != nil {
return nil, err
}
sketches = append(sketches, sketch)
}
return sketches, nil
}
func RecordValues(numValues int, countPerValue int, sketches []Sketch) ([]Sketch, error) {
for _, sketch := range sketches {
for i := 0; i < numValues; i++ {
if err := sketch.RecordValue(rand.NormFloat64(), float64(countPerValue)); err != nil {
return nil, err
}
}
}
return sketches, nil
}
func MergeSketches(sketches ...Sketch) (Sketch, error) {
if len(sketches) == 0 {
return nil, fmt.Errorf("must have at least 1 sketch")
}
merged := sketches[0]
for _, right := range sketches[1:] {
switch leftSketch := merged.(type) {
case *quantilesketch.QuantileSketch:
rightSketch, ok := right.(*quantilesketch.QuantileSketch)
if !ok {
return nil, fmt.Errorf("sketch types must match")
}
mergedSKetch, err := quantilesketch.Merge(leftSketch, rightSketch)
if err != nil {
return nil, err
}
merged = mergedSKetch
default:
return nil, fmt.Errorf("type not supported")
}
}
return merged, nil
}
func GetValuesAtQuantiles(sketch Sketch, quantiles ...float64) ([]float64, error) {
var values []float64
for _, quantile := range quantiles {
value, err := sketch.GetValueAtQuantile(quantile)
if err != nil {
return nil, err
}
values = append(values, value)
}
return values, nil
}
func main() {
relativeAccuracy := 0.001
numSketches := 100
sketches, err := CreateSketches(numSketches, relativeAccuracy)
if err != nil {
panic(err)
}
numValues := 1000
countPerValue := 10
sketches, err = RecordValues(numValues, countPerValue, sketches)
if err != nil {
panic(err)
}
merged, err := MergeSketches(sketches...)
if err != nil {
panic(err)
}
quantiles := []float64{0.5, 0.9, 0.95, 0.99}
values, err := GetValuesAtQuantiles(merged, quantiles...)
if err != nil {
panic(err)
}
fmt.Println(quantiles)
fmt.Println(values)
}