|
| 1 | +package com.twitter.algebird.mutable |
| 2 | + |
| 3 | +import com.twitter.algebird.{Monoid, MonoidAggregator} |
| 4 | + |
| 5 | +import scala.collection.mutable |
| 6 | +import scala.util.Random |
| 7 | + |
| 8 | +/** |
| 9 | + * A reservoir of the currently sampled items. |
| 10 | + * |
| 11 | + * @param capacity |
| 12 | + * the reservoir capacity |
| 13 | + * @tparam T |
| 14 | + * the element type |
| 15 | + */ |
| 16 | +sealed class Reservoir[T](val capacity: Int) { |
| 17 | + var reservoir: mutable.ArrayBuffer[T] = new mutable.ArrayBuffer |
| 18 | + |
| 19 | + // When the reservoir is full, w is the threshold for accepting an element into the reservoir, and |
| 20 | + // the following invariant holds: The maximum score of the elements in the reservoir is w, |
| 21 | + // and the remaining elements are distributed as U[0, w]. |
| 22 | + // Scores are not kept explicitly, only their distribution is tracked and sampled from. |
| 23 | + // (w = 1 when the reservoir is not full.) |
| 24 | + var w: Double = 1 |
| 25 | + |
| 26 | + require(capacity > 0, "reservoir size must be positive") |
| 27 | + private val kInv: Double = 1d / capacity |
| 28 | + |
| 29 | + def size: Int = reservoir.size |
| 30 | + def isEmpty: Boolean = reservoir.isEmpty |
| 31 | + def isFull: Boolean = size == capacity |
| 32 | + |
| 33 | + /** |
| 34 | + * Add an element to the reservoir. If the reservoir is full then the element will replace a random element |
| 35 | + * in the reservoir, and the threshold <pre>w</pre> is updated. |
| 36 | + * |
| 37 | + * When adding multiple elements, [[append]] should be used to take advantage of exponential jumps. |
| 38 | + * |
| 39 | + * @param x |
| 40 | + * the element to add |
| 41 | + * @param rng |
| 42 | + * the random source |
| 43 | + */ |
| 44 | + def accept(x: T, rng: Random): Unit = { |
| 45 | + if (isFull) { |
| 46 | + reservoir(rng.nextInt(capacity)) = x |
| 47 | + } else { |
| 48 | + reservoir.append(x) |
| 49 | + } |
| 50 | + if (isFull) { |
| 51 | + w *= Math.pow(rng.nextDouble, kInv) |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + // The number of items to skip before accepting the next item is geometrically distributed |
| 56 | + // with probability of success w / prior. The prior will be 1 when adding to a single reservoir, |
| 57 | + // but when merging reservoirs it will be the threshold of the reservoir being pulled from, |
| 58 | + // and in this case we require that w < prior. |
| 59 | + private def nextAcceptTime(rng: Random, prior: Double = 1.0): Int = |
| 60 | + (-rng.self.nextExponential / Math.log1p(-w / prior)).toInt |
| 61 | + |
| 62 | + /** |
| 63 | + * Add multiple elements to the reservoir. |
| 64 | + * @param xs |
| 65 | + * the elements to add |
| 66 | + * @param rng |
| 67 | + * the random source |
| 68 | + * @param prior |
| 69 | + * the threshold of the elements being added, such that the added element's value is distributed as |
| 70 | + * <pre>U[0, prior]</pre> |
| 71 | + * @return |
| 72 | + * this reservoir |
| 73 | + */ |
| 74 | + def append(xs: TraversableOnce[T], rng: Random): Reservoir[T] = { |
| 75 | + var skip = if (isFull) nextAcceptTime(rng) else 0 |
| 76 | + for (x <- xs) { |
| 77 | + if (!isFull) { |
| 78 | + // keep adding while reservoir is not full |
| 79 | + accept(x, rng) |
| 80 | + if (isFull) { |
| 81 | + skip = nextAcceptTime(rng) |
| 82 | + } |
| 83 | + } else if (skip > 0) { |
| 84 | + skip -= 1 |
| 85 | + } else { |
| 86 | + accept(x, rng) |
| 87 | + skip = nextAcceptTime(rng) |
| 88 | + } |
| 89 | + } |
| 90 | + this |
| 91 | + } |
| 92 | + |
| 93 | + /** |
| 94 | + * Add multiple elements to the reservoir. This overload is optimized for indexed sequences, where we can |
| 95 | + * skip over multiple indexes without accessing the elements. |
| 96 | + * |
| 97 | + * @param xs |
| 98 | + * the elements to add |
| 99 | + * @param rng |
| 100 | + * the random source |
| 101 | + * @param prior |
| 102 | + * the threshold of the elements being added, such that the added element's value is distributed as |
| 103 | + * <pre>U[0, prior]</pre> |
| 104 | + * @return |
| 105 | + * this reservoir |
| 106 | + */ |
| 107 | + def append(xs: IndexedSeq[T], rng: Random, prior: Double): Reservoir[T] = { |
| 108 | + var i = xs.size.min(capacity - size) |
| 109 | + for (j <- 0 until i) { |
| 110 | + accept(xs(j), rng) |
| 111 | + } |
| 112 | + assert(isFull) |
| 113 | + |
| 114 | + val end = xs.size |
| 115 | + while (i >= 0 && i < end) { |
| 116 | + i += nextAcceptTime(rng, prior) |
| 117 | + // the addition can overflow, in which case i < 0 |
| 118 | + if (i >= 0 && i < end) { |
| 119 | + // element enters the reservoir |
| 120 | + reservoir(rng.nextInt(capacity)) = xs(i) |
| 121 | + w *= Math.pow(rng.nextDouble, kInv) |
| 122 | + i += 1 |
| 123 | + } |
| 124 | + } |
| 125 | + this |
| 126 | + } |
| 127 | + |
| 128 | + override def toString: String = s"Reservoir($capacity, $w, ${reservoir.toList})" |
| 129 | +} |
| 130 | + |
| 131 | +object Reservoir { |
| 132 | + implicit def monoid[T](implicit randomSupplier: () => Random): Monoid[Reservoir[T]] = |
| 133 | + new ReservoirMonoid()(randomSupplier) |
| 134 | +} |
| 135 | + |
| 136 | +/** |
| 137 | + * This is the "Algorithm L" reservoir sampling algorithm [1], with modifications to act as a monoid by |
| 138 | + * merging reservoirs. |
| 139 | + * |
| 140 | + * [1] Kim-Hung Li, "Reservoir-Sampling Algorithms of Time Complexity O(n(1+log(N/n)))", 1994 |
| 141 | + * |
| 142 | + * @tparam T |
| 143 | + * the item type |
| 144 | + */ |
| 145 | +class ReservoirMonoid[T](implicit val randomSupplier: () => Random) extends Monoid[Reservoir[T]] { |
| 146 | + |
| 147 | + /** |
| 148 | + * Builds a reservoir with a single item. |
| 149 | + * |
| 150 | + * @param k |
| 151 | + * the reservoir capacity |
| 152 | + * @param x |
| 153 | + * the item to add |
| 154 | + * @return |
| 155 | + */ |
| 156 | + def build(k: Int, x: T): Reservoir[T] = { |
| 157 | + val r = new Reservoir[T](k) |
| 158 | + r.accept(x, randomSupplier()) |
| 159 | + r |
| 160 | + } |
| 161 | + |
| 162 | + override def zero: Reservoir[T] = new Reservoir(1) |
| 163 | + def zero(k: Int): Reservoir[T] = new Reservoir(k) |
| 164 | + override def isNonZero(r: Reservoir[T]): Boolean = !r.isEmpty |
| 165 | + |
| 166 | + /** |
| 167 | + * Merge two reservoirs. NOTE: This mutates one or both of the reservoirs. They should not be used after |
| 168 | + * this operation, except as the return value for further aggregation. |
| 169 | + */ |
| 170 | + override def plus(left: Reservoir[T], right: Reservoir[T]): Reservoir[T] = |
| 171 | + if (left.isEmpty) right |
| 172 | + else if (left.size + right.size <= left.capacity) { |
| 173 | + // the sum of the sizes is less than the reservoir size, so we can just merge |
| 174 | + left.append(right.reservoir, randomSupplier()) |
| 175 | + } else { |
| 176 | + val (s1, s2) = if (left.w < right.w) (left, right) else (right, left) |
| 177 | + val rng = randomSupplier() |
| 178 | + if (s2.isFull) { |
| 179 | + // The highest score in s2 is w, and the other scores are distributed as U[0, w]. |
| 180 | + // Since s1.w < s2.w, we have to drop the single (sampled) element with the highest score |
| 181 | + // unconditionally. The other elements enter the reservoir with probability s1.w / s2.w. |
| 182 | + val i = rng.nextInt(s2.size) |
| 183 | + s2.reservoir(i) = s2.reservoir.head |
| 184 | + s1.append(s2.reservoir.drop(1), rng, s2.w) |
| 185 | + } else { |
| 186 | + s1.append(s2.reservoir, rng, 1.0) |
| 187 | + } |
| 188 | + } |
| 189 | +} |
| 190 | + |
| 191 | +/** |
| 192 | + * An aggregator that uses reservoir sampling to sample k elements from a stream of items. Because the |
| 193 | + * reservoir is mutable, it is a good idea to copy the result to an immutable view before using it, as is done |
| 194 | + * by [[ReservoirSamplingToListAggregator]]. |
| 195 | + * |
| 196 | + * The aggregator defines operations for [[IndexedSeq]]s that allow for more efficient aggregation, however |
| 197 | + * care must be taken with methods such as [[composePrepare()]] which return a regular [[MonoidAggregator]] |
| 198 | + * that loses this optimized behavior. |
| 199 | + * |
| 200 | + * @param k |
| 201 | + * the number of elements to sample |
| 202 | + * @param randomSupplier |
| 203 | + * the random generator |
| 204 | + * @tparam T |
| 205 | + * the item type |
| 206 | + * @tparam C |
| 207 | + * the result type |
| 208 | + */ |
| 209 | +abstract class ReservoirSamplingAggregator[T, +C](k: Int)(implicit val randomSupplier: () => Random) |
| 210 | + extends MonoidAggregator[T, Reservoir[T], C] { |
| 211 | + override val monoid: ReservoirMonoid[T] = new ReservoirMonoid |
| 212 | + override def prepare(x: T): Reservoir[T] = monoid.build(k, x) |
| 213 | + |
| 214 | + override def apply(xs: TraversableOnce[T]): C = present(agg(xs)) |
| 215 | + def apply(xs: IndexedSeq[T]): C = present(agg(xs)) |
| 216 | + |
| 217 | + override def applyOption(inputs: TraversableOnce[T]): Option[C] = |
| 218 | + if (inputs.isEmpty) None else Some(apply(inputs)) |
| 219 | + |
| 220 | + override def append(r: Reservoir[T], t: T): Reservoir[T] = r.append(Seq(t), randomSupplier()) |
| 221 | + |
| 222 | + override def appendAll(r: Reservoir[T], xs: TraversableOnce[T]): Reservoir[T] = |
| 223 | + r.append(xs, randomSupplier()) |
| 224 | + def appendAll(r: Reservoir[T], xs: IndexedSeq[T]): Reservoir[T] = |
| 225 | + r.append(xs, randomSupplier(), 1.0) |
| 226 | + |
| 227 | + override def appendAll(xs: TraversableOnce[T]): Reservoir[T] = agg(xs) |
| 228 | + def appendAll(xs: IndexedSeq[T]): Reservoir[T] = agg(xs) |
| 229 | + |
| 230 | + private def agg(xs: TraversableOnce[T]): Reservoir[T] = |
| 231 | + appendAll(monoid.zero(k), xs) |
| 232 | + private def agg(xs: IndexedSeq[T]): Reservoir[T] = |
| 233 | + appendAll(monoid.zero(k), xs) |
| 234 | +} |
| 235 | + |
| 236 | +class ReservoirSamplingToListAggregator[T](k: Int)(implicit randomSupplier: () => Random) |
| 237 | + extends ReservoirSamplingAggregator[T, List[T]](k)(randomSupplier) { |
| 238 | + override def present(r: Reservoir[T]): List[T] = |
| 239 | + randomSupplier().shuffle(r.reservoir).toList |
| 240 | + |
| 241 | + override def andThenPresent[D](f: List[T] => D): MonoidAggregator[T, Reservoir[T], D] = |
| 242 | + new AndThenPresent(this, f) |
| 243 | +} |
| 244 | + |
| 245 | +/** |
| 246 | + * Monoid that implements [[andThenPresent]] without ruining the optimized behavior of the aggregator. |
| 247 | + */ |
| 248 | +protected class AndThenPresent[-A, B, C, +D](val agg: MonoidAggregator[A, B, C], f: C => D) |
| 249 | + extends MonoidAggregator[A, B, D] { |
| 250 | + override val monoid: Monoid[B] = agg.monoid |
| 251 | + override def prepare(a: A): B = agg.prepare(a) |
| 252 | + override def present(b: B): D = f(agg.present(b)) |
| 253 | + |
| 254 | + override def apply(xs: TraversableOnce[A]): D = f(agg(xs)) |
| 255 | + override def applyOption(xs: TraversableOnce[A]): Option[D] = agg.applyOption(xs).map(f) |
| 256 | + override def append(b: B, a: A): B = agg.append(b, a) |
| 257 | + override def appendAll(b: B, as: TraversableOnce[A]): B = agg.appendAll(b, as) |
| 258 | + override def appendAll(as: TraversableOnce[A]): B = agg.appendAll(as) |
| 259 | +} |
0 commit comments