File: centroid.go

package info (click to toggle)
golang-github-influxdata-tdigest 0.0~git20180711.a7d76c6-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 140 kB
  • sloc: cpp: 509; sh: 9; makefile: 4
file content (59 lines) | stat: -rw-r--r-- 1,412 bytes parent folder | download
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
package tdigest

import (
	"fmt"
	"sort"
)

// ErrWeightLessThanZero is used when the weight is not able to be processed.
const ErrWeightLessThanZero = Error("centroid weight cannot be less than zero")

// Error is a domain error encountered while processing tdigests
type Error string

func (e Error) Error() string {
	return string(e)
}

// Centroid average position of all points in a shape
type Centroid struct {
	Mean   float64
	Weight float64
}

func (c *Centroid) String() string {
	return fmt.Sprintf("{mean: %f weight: %f}", c.Mean, c.Weight)
}

// Add averages the two centroids together and update this centroid
func (c *Centroid) Add(r Centroid) error {
	if r.Weight < 0 {
		return ErrWeightLessThanZero
	}
	if c.Weight != 0 {
		c.Weight += r.Weight
		c.Mean += r.Weight * (r.Mean - c.Mean) / c.Weight
	} else {
		c.Weight = r.Weight
		c.Mean = r.Mean
	}
	return nil
}

// CentroidList is sorted by the Mean of the centroid, ascending.
type CentroidList []Centroid

func (l *CentroidList) Clear() {
	*l = (*l)[0:0]
}

func (l CentroidList) Len() int           { return len(l) }
func (l CentroidList) Less(i, j int) bool { return l[i].Mean < l[j].Mean }
func (l CentroidList) Swap(i, j int)      { l[i], l[j] = l[j], l[i] }

// NewCentroidList creates a priority queue for the centroids
func NewCentroidList(centroids []Centroid) CentroidList {
	l := CentroidList(centroids)
	sort.Sort(l)
	return l
}