-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathestimate.go
More file actions
137 lines (109 loc) · 3.42 KB
/
estimate.go
File metadata and controls
137 lines (109 loc) · 3.42 KB
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
// Copyright 2024 Aerospike, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package backup
import (
"bytes"
"fmt"
"io"
"log/slog"
"math"
)
// zScore represents the number of standard deviations a given value is from the mean of a distribution.
// For a 99% confidence interval, the zScore is approximately 2.576.
// This means that there is a 99% probability that the true population parameter
// lies within the calculated confidence interval.
const zScore = 2.576
// estimateStats contains the mean and variance of the data.
type estimateStats struct {
Mean float64
Variance float64
}
// getEstimate calculates the estimated backup file size.
func getEstimate(data []float64, total float64, logger *slog.Logger) float64 {
stats := calculateStats(data)
low, high := confidenceInterval(stats, len(data))
logger.Debug("predicted record size:",
slog.Float64("from", low),
slog.Float64("to", high))
avg := (low + high) / 2
logger.Debug("average record size:", slog.Float64("average", avg))
return total * avg
}
// calculateStats calculates the mean and variance of the data.
func calculateStats(data []float64) estimateStats {
n := len(data)
if n == 0 {
return estimateStats{}
}
var sum float64
for _, value := range data {
sum += value
}
mean := sum / float64(n)
// For n = 1, variance = 0
if n == 1 {
return estimateStats{
mean,
0.0,
}
}
var varianceSum float64
for _, value := range data {
varianceSum += (value - mean) * (value - mean)
}
variance := varianceSum / float64(n-1)
return estimateStats{
Mean: mean,
Variance: variance,
}
}
// confidenceInterval calculates the confidence interval of the data.
func confidenceInterval(stats estimateStats, sampleSize int) (low, high float64) {
if sampleSize == 0 {
return 0, 0
}
standardError := math.Sqrt(stats.Variance / float64(sampleSize))
marginOfError := zScore * standardError
low = stats.Mean - marginOfError
high = stats.Mean + marginOfError
return low, high
}
type nopWriteCloser struct{ io.Writer }
func (nopWriteCloser) Close() error { return nil }
// getCompressRatio calculates the compress ratio of the data.
func getCompressRatio(policy *CompressionPolicy, samplesData []byte) (float64, error) {
// Create an io.WriteCloser from samplesData to calculate the compress ratio.
var buf bytes.Buffer
wc := nopWriteCloser{Writer: &buf} // satisfies io.WriteCloser
// Create a compression writer similarly to the backup.
encodedWriter, err := newCompressionWriter(policy, wc)
if err != nil {
return 0, err
}
if _, err := encodedWriter.Write(samplesData); err != nil {
_ = encodedWriter.Close()
return 0, err
}
if err := encodedWriter.Close(); err != nil {
return 0, err
}
// Check buf.len for safety reasons.
if buf.Len() == 0 {
if len(samplesData) > 0 {
return 0, fmt.Errorf("output length is zero, but samples data is not empty")
}
return 1, nil
}
return float64(len(samplesData)) / float64(buf.Len()), nil
}