/
ExponentiallyDecayingReservoir.cs
215 lines (186 loc) · 7.43 KB
/
ExponentiallyDecayingReservoir.cs
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
using System;
using System.Collections.Generic;
using System.Threading;
using Metrics.Utils;
namespace Metrics.Sampling
{
public sealed class ExponentiallyDecayingReservoir : Reservoir, IDisposable
{
private const int DefaultSize = 1028;
private const double DefaultAlpha = 0.015;
private static readonly TimeSpan RescaleInterval = TimeSpan.FromHours(1);
private class ReverseOrderDoubleComparer : IComparer<double>
{
public static readonly IComparer<double> Instance = new ReverseOrderDoubleComparer();
public int Compare(double x, double y)
{
return y.CompareTo(x);
}
}
private readonly SortedList<double, WeightedSample> values;
private SpinLock @lock = new SpinLock();
private readonly double alpha;
private readonly int size;
private AtomicLong count = new AtomicLong();
private AtomicLong startTime;
private readonly Clock clock;
private readonly Scheduler rescaleScheduler;
public ExponentiallyDecayingReservoir()
: this(DefaultSize, DefaultAlpha)
{ }
public ExponentiallyDecayingReservoir(int size, double alpha)
: this(size, alpha, Clock.Default, new ActionScheduler())
{ }
public ExponentiallyDecayingReservoir(Clock clock, Scheduler scheduler)
: this(DefaultSize, DefaultAlpha, clock, scheduler)
{ }
public ExponentiallyDecayingReservoir(int size, double alpha, Clock clock, Scheduler scheduler)
{
this.size = size;
this.alpha = alpha;
this.clock = clock;
this.values = new SortedList<double, WeightedSample>(size, ReverseOrderDoubleComparer.Instance);
this.rescaleScheduler = scheduler;
this.rescaleScheduler.Start(RescaleInterval, () => Rescale());
this.startTime = new AtomicLong(clock.Seconds);
}
public long Count { get { return this.count.Value; } }
public int Size { get { return Math.Min(this.size, (int)this.count.Value); } }
public Snapshot GetSnapshot(bool resetReservoir = false)
{
bool lockTaken = false;
try
{
this.@lock.Enter(ref lockTaken);
var snapshot = new WeightedSnapshot(this.count.Value, this.values.Values);
if (resetReservoir)
{
ResetReservoir();
}
return snapshot;
}
finally
{
if (lockTaken)
{
this.@lock.Exit();
}
}
}
public void Update(long value, string userValue = null)
{
Update(value, userValue, this.clock.Seconds);
}
public void Reset()
{
bool lockTaken = false;
try
{
this.@lock.Enter(ref lockTaken);
ResetReservoir();
}
finally
{
if (lockTaken)
{
this.@lock.Exit();
}
}
}
private void ResetReservoir()
{
this.values.Clear();
this.count.SetValue(0L);
this.startTime = new AtomicLong(this.clock.Seconds);
}
private void Update(long value, string userValue, long timestamp)
{
bool lockTaken = false;
try
{
this.@lock.Enter(ref lockTaken);
double itemWeight = Math.Exp(alpha * (timestamp - startTime.Value));
var sample = new WeightedSample(value, userValue, itemWeight);
double random = .0;
// Prevent division by 0
while (random.Equals(.0))
{
random = ThreadLocalRandom.NextDouble();
}
double priority = itemWeight / random;
long newCount = count.Increment();
if (newCount <= size)
{
this.values[priority] = sample;
}
else
{
var first = this.values.Keys[this.values.Count - 1];
if (first < priority)
{
this.values.Remove(first);
this.values[priority] = sample;
}
}
}
finally
{
if (lockTaken)
{
this.@lock.Exit();
}
}
}
public void Dispose()
{
using (this.rescaleScheduler) { }
}
///* "A common feature of the above techniques—indeed, the key technique that
// * allows us to track the decayed weights efficiently—is that they maintain
// * counts and other quantities based on g(ti − L), and only scale by g(t − L)
// * at query time. But while g(ti −L)/g(t−L) is guaranteed to lie between zero
// * and one, the intermediate values of g(ti − L) could become very large. For
// * polynomial functions, these values should not grow too large, and should be
// * effectively represented in practice by floating point values without loss of
// * precision. For exponential functions, these values could grow quite large as
// * new values of (ti − L) become large, and potentially exceed the capacity of
// * common floating point types. However, since the values stored by the
// * algorithms are linear combinations of g values (scaled sums), they can be
// * rescaled relative to a new landmark. That is, by the analysis of exponential
// * decay in Section III-A, the choice of L does not affect the final result. We
// * can therefore multiply each value based on L by a factor of exp(−α(L′ − L)),
// * and obtain the correct value as if we had instead computed relative to a new
// * landmark L′ (and then use this new L′ at query time). This can be done with
// * a linear pass over whatever data structure is being used."
// */
private void Rescale()
{
bool lockTaken = false;
try
{
this.@lock.Enter(ref lockTaken);
long oldStartTime = startTime.Value;
this.startTime.SetValue(this.clock.Seconds);
double scalingFactor = Math.Exp(-alpha * (startTime.Value - oldStartTime));
var keys = new List<double>(this.values.Keys);
foreach (var key in keys)
{
WeightedSample sample = this.values[key];
this.values.Remove(key);
double newKey = key * Math.Exp(-alpha * (startTime.Value - oldStartTime));
var newSample = new WeightedSample(sample.Value, sample.UserValue, sample.Weight * scalingFactor);
this.values[newKey] = newSample;
}
// make sure the counter is in sync with the number of stored samples.
this.count.SetValue(values.Count);
}
finally
{
if (lockTaken)
{
this.@lock.Exit();
}
}
}
}
}