-
Notifications
You must be signed in to change notification settings - Fork 5
/
stats.go
164 lines (145 loc) · 3.81 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
// SPDX-FileCopyrightText: 2022 Sascha Brawer <sascha@brawer.ch>
// SPDX-License-Identifier: MIT
package main
import (
"bufio"
"bytes"
"compress/gzip"
"encoding/json"
"fmt"
"io"
"math"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
type Sample []interface{} // [ID, Rank, Value]
type Stats struct {
Median int
Samples []Sample
}
func buildStats(date time.Time, qrankPath string, topN int, numSamples int, outDir string) (string, error) {
// To compute our stats, we do two passes over the QRank file.
// First, a pass to count the number of lines in the file;
// second, a pass that actually computes the stats.
qrankFile, err := os.Open(qrankPath)
if err != nil {
return "", err
}
defer qrankFile.Close()
qrankReader, err := gzip.NewReader(qrankFile)
if err != nil {
return "", err
}
numRanks, err := countLines(qrankReader)
if err != nil {
return "", err
}
numRanks -= 1 // Don’t count CSV header.
medianRank := numRanks/2 + 1
if _, err := qrankFile.Seek(0, os.SEEK_SET); err != nil {
return "", err
}
qrankReader, err = gzip.NewReader(qrankFile)
if err != nil {
return "", err
}
samplingDistanceSq := 4.0 * 4.0
var stats Stats
stats.Samples = make([]Sample, 0, numSamples)
var id string
var rank, value int64
var lastX, lastY, scaleY float64
scaleX := float64(numSamples) / float64(numRanks)
scanner := bufio.NewScanner(qrankReader)
scanner.Scan() // Skip CSV header.
for scanner.Scan() {
rank += 1
cols := strings.Split(scanner.Text(), ",")
if len(cols) < 2 {
return "", fmt.Errorf("%s:%d: less than 2 columns", qrankPath, rank-1)
}
id = cols[0]
value, err = strconv.ParseInt(cols[1], 10, 64)
if err != nil {
return "", err
}
if rank == 1 { // first item in file, this is the maximum value
scaleY = float64(numSamples) / math.Log10(float64(value))
}
x, y := float64(rank)*scaleX, math.Log10(float64(value))*scaleY
distance := (x-lastX)*(x-lastX) + (y-lastY)*(y-lastY)
near := distance < samplingDistanceSq
if rank == medianRank {
// If the median item is near the last, drop it.
// Unless the last is among the top N whose inclusion was requested by the caller.
// In production, the median of ~30M items is never going to be among the top 50,
// but in unit tests this does happen, and let’s be correct in all cases.
if near && len(stats.Samples) > topN {
stats.Samples = stats.Samples[:len(stats.Samples)-1]
}
stats.Median = len(stats.Samples)
}
if !near || rank <= int64(topN) || rank == medianRank {
stats.Samples = append(stats.Samples, Sample{id, rank, value})
lastX, lastY = x, y
}
}
// Make sure the last sample is the minimum value.
stats.Samples[len(stats.Samples)-1] = Sample{id, rank, value}
if err := scanner.Err(); err != nil {
return "", err
}
statsPath := filepath.Join(
outDir,
fmt.Sprintf("qrank-stats-%04d%02d%02d.json", date.Year(), date.Month(), date.Day()))
tmpStatsPath := statsPath + ".tmp"
j, err := json.Marshal(stats)
if err != nil {
return "", err
}
statsFile, err := os.Create(tmpStatsPath)
if err != nil {
return "", err
}
defer statsFile.Close()
if _, err := statsFile.Write(j); err != nil {
return "", err
}
if err := statsFile.Sync(); err != nil {
return "", err
}
if err := statsFile.Close(); err != nil {
return "", err
}
if err := os.Rename(tmpStatsPath, statsPath); err != nil {
return "", err
}
return statsPath, nil
}
// CountLines counts the number of lines in its input.
func countLines(r io.Reader) (int64, error) {
var count int64
buf := make([]byte, 64*1024)
for {
bufSize, err := r.Read(buf)
if err != nil && err != io.EOF {
return 0, err
}
var pos int
for {
i := bytes.IndexByte(buf[pos:], '\n')
if i == -1 || pos == bufSize {
break
}
pos += i + 1
count += 1
}
if err == io.EOF {
break
}
}
return count, nil
}