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 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
|
package Algorithm::Numerical::Sample;
use 5.006;
use strict;
use warnings;
no warnings 'syntax';
use Exporter ();
our @ISA = qw /Exporter/;
our @EXPORT = qw //;
our @EXPORT_OK = qw /sample/;
our $VERSION = '2010011201';
my @PARAMS = qw /set sample_size/;
sub sample {
my %args = @_;
# Deal with - parameters.
foreach (@PARAMS) {
$args {$_} = $args {"-$_"} unless defined $args {$_};
}
# Check for set parameter.
die "sample requires the set parameter" unless $args {set};
my $set = $args {set};
# Set sample and set size.
my $sample_size = defined $args {sample_size} ? $args {sample_size} : 1;
my $set_size = @$set;
# Reservoir will be our sample.
my @reservoir = (undef) x $sample_size;
# Initialize counters.
my $sample_counter = 0;
my $set_counter = 0;
# Loop as long as the reservoir isn't filled.
while ($sample_counter < $sample_size) {
# Draw a random number.
my $U = rand ($set_size - $set_counter);
if ($U < $sample_size - $sample_counter) {
# Select the next element with probability
# $sample_size - $sample_counter
# ------------------------------
# $set_size - $set_counter
$reservoir [$sample_counter ++] = $set -> [$set_counter];
}
$set_counter ++;
}
wantarray ? @reservoir : \@reservoir;
}
package Algorithm::Numerical::Sample::Stream;
use strict;
sub new {
my $proto = shift;
my $class = ref $proto || $proto;
my %args = @_;
foreach (qw /sample_size/) {
$args {$_} = $args {"-$_"} unless defined $args {$_};
}
my $self = {};
$self -> {sample_size} = defined $args {sample_size} ? $args {sample_size}
: 1;
$self -> {seen} = 0;
$self -> {reservoir} = [(undef) x $self -> {sample_size}];
bless $self, $class;
}
sub data {
my $self = shift;
foreach my $sample (@_) {
if ($self -> {seen} < $self -> {sample_size}) {
# Initialize reservoir.
$self -> {reservoir} -> [$self -> {seen}] =
[$self -> {seen}, $sample];
}
else {
# Draw number.
my $U = int rand ($self -> {seen} + 1);
if ($U < $self -> {sample_size}) {
$self -> {reservoir} -> [$U] = [$self -> {seen}, $sample];
}
}
$self -> {seen} ++;
}
return;
}
sub extract {
my $self = shift;
my @result = map {$_ -> [1]}
sort {$a -> [0] <=> $b -> [0]} @{$self -> {reservoir}};
$self -> {seen} = 0;
$self -> {reservoir} = [(undef) x $self -> {sample_size}];
wantarray ? @result : $result [0];
}
__END__
=head1 NAME
Algorithm::Numerical::Sample - Draw samples from a set
=head1 SYNOPSIS
use Algorithm::Numerical::Sample qw /sample/;
@sample = sample (-set => [1 .. 10000],
-sample_size => 100);
$sampler = Algorithm::Numerical::Sample::Stream -> new;
while (<>) {$sampler -> data ($_)}
$random_line = $sampler -> extract;
=head1 DESCRIPTION
This package gives two methods to draw fair, random samples from a set.
There is a procedural interface for the case the entire set is known,
and an object oriented interface when the a set with unknown size has
to be processed.
=head2 B<A>: C<sample (set =E<gt> ARRAYREF [,sample_size =E<gt> EXPR])>
The C<sample> function takes a set and a sample size as arguments.
If the sample size is omitted, a sample of C<1> is taken. The keywords
C<set> and C<sample_size> may be preceeded with an optional C<->.
The function returns the sample list, or a reference to the sample
list, depending on the context.
=head2 B<B>: C<Algorithm::Numerical::Sample::Stream>
The class C<Algorithm::Numerical::Sample::Stream> has the following
methods:
=over
=item C<new>
This function returns an object of the
C<Algorithm::Numerical::Sample::Stream> class.
It will take an optional argument of the form
C<sample_size =E<gt> EXPR>, where C<EXPR> evaluates to the
sample size to be taken. If this argument is missing,
a sample of size C<1> will be taken.
The keyword C<sample_size> may be preceeded by an optional dash.
=item C<data (LIST)>
The method C<data> takes a list of parameters which are elements
of the set we are sampling. Any number of arguments can be given.
=item C<extract>
This method will extract the sample from the object, and reset it
to a fresh state, such that a sample of the same size but from a
different set, can be taken. C<extract> will return a list in list
context, or the first element of the sample in scalar context.
=back
=head1 CORRECTNESS PROOFS
=head2 Algorithm A.
Crucial to see that the C<sample> algorithm is correct is the
fact that when we sample C<n> elements from a set of size C<N>
that the C<t + 1>st element is choosen with probability
C<(n - m)/(N - t)>, when already C<m> elements have been
choosen. We can immediately see that we will never pick too
many elements (as the probability is 0 as soon as C<n == m>),
nor too few, as the probability will be 1 if we have C<k>
elements to choose from the remaining C<k> elements, for some
C<k>. For the proof that the sampling is unbiased, we refer to [3].
(Section 3.4.2, Exercise 3).
=head2 Algorithm B.
It is easy to see that the second algorithm returns the correct
number of elements. For a sample of size C<n>, the first C<n>
elements go into the reservoir, and after that, the reservoir
never grows or shrinks in size; elements only get replaced.
A detailed proof of the fairness of the algorithm appears in [3].
(Section 3.4.2, Exercise 7).
=head1 LITERATURE
Both algorithms are discussed by Knuth [3] (Section 3.4.2).
The first algoritm, I<Selection sampling technique>, was
discovered by Fan, Muller and Rezucha [1], and independently
by Jones [2]. The second algorithm, I<Reservoir sampling>,
is due to Waterman.
=head1 REFERENCES
=over
=item [1]
C. T. Fan, M. E. Muller and I. Rezucha, I<J. Amer. Stat. Assoc.>
B<57> (1962), pp 387 - 402.
=item [2]
T. G. Jones, I<CACM> B<5> (1962), pp 343.
=item [3]
D. E. Knuth: I<The Art of Computer Programming>, Volume 2, Third edition.
Reading: Addison-Wesley, 1997. ISBN: 0-201-89684-2.
=back
=head1 DEVELOPMENT
The current sources of this module are found on github,
L<< git://github.com/Abigail/algorithm--numerical--sample.git >>.
=head1 AUTHOR
This package was written by Abigail, L<< cpan@abigail.be >>.
=head1 COPYRIGHT and LICENSE
Copyright (C) 1998, 1999, 2009, Abigail.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
=cut
|