-
Notifications
You must be signed in to change notification settings - Fork 2
/
stats.go
82 lines (71 loc) · 1.79 KB
/
stats.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
package plot
import "math"
// Stats describes a data points.
type Stats struct {
Min Point
Center Point
Max Point
}
// nanStats is used for missing stats.
var nanStats = Stats{
Min: nanPoint,
Center: nanPoint,
Max: nanPoint,
}
// tryGetStats tries to calculate stats.
func tryGetStats(element Element) (Stats, bool) {
if dataset, ok := element.(Dataset); ok {
return dataset.Stats(), true
}
return nanStats, false
}
// maximalStats finds bounding stats from elements.
func maximalStats(els []Element) Stats {
finalstats := nanStats
for _, element := range els {
if element == nil {
continue
}
if elstats, ok := tryGetStats(element); ok {
if math.IsNaN(finalstats.Min.X) {
finalstats.Min.X = elstats.Min.X
} else if !math.IsNaN(elstats.Min.X) {
finalstats.Min.X = math.Min(finalstats.Min.X, elstats.Min.X)
}
if math.IsNaN(finalstats.Max.X) {
finalstats.Max.X = elstats.Max.X
} else if !math.IsNaN(elstats.Max.X) {
finalstats.Max.X = math.Max(finalstats.Max.X, elstats.Max.X)
}
if math.IsNaN(finalstats.Min.Y) {
finalstats.Min.Y = elstats.Min.Y
} else if !math.IsNaN(elstats.Min.Y) {
finalstats.Min.Y = math.Min(finalstats.Min.Y, elstats.Min.Y)
}
if math.IsNaN(finalstats.Max.Y) {
finalstats.Max.Y = elstats.Max.Y
} else if !math.IsNaN(elstats.Max.Y) {
finalstats.Max.Y = math.Max(finalstats.Max.Y, elstats.Max.Y)
}
}
}
return finalstats
}
// PointsStats calculates statistics of points.
func PointsStats(points []Point) Stats {
min, avg, max := nanPoint, Point{}, nanPoint
if len(points) > 0 {
min = points[0]
max = points[0]
}
for _, p := range points {
min = min.Min(p)
avg = avg.Add(p)
max = max.Max(p)
}
return Stats{
Min: min,
Center: avg.Scale(1 / float64(len(points))),
Max: max,
}
}