blib/lib/Algorithm/RandomPointGenerator.pm

filter: Statementstmt 71.1% 257 / 361 Branchbran 48.3% 59 / 122 Conditioncond 68.2% 28 / 41 MC/DCmcdc 38.1% 8 / 21 Subroutinesub 80.6% 25 / 31 Podpod 57.8% 11 / 19 totaltotal 65.2% 388 / 595 CC 103 SCAR 29.3
CC
103
Cov
66%
plot_histogram_3d_surface
90.0
write_generated_points_to_a_file
42.0
display_hist_in_terminal_window
30.0
CRAP 18.6
↑ Summary
1 package Algorithm::RandomPointGenerator;
2  
3 #---------------------------------------------------------------------------
4 # Copyright (c) 2014 Avinash Kak. All rights reserved. This program is free
5 # software. You may modify and/or distribute it under the same terms as Perl itself.
6 # This copyright notice must remain attached to the file.
7 #
8 # Algorithm::RandomPointGenerator generates a set of random points in a 2D plane
9 # according to a user-specified probability distribution that is supplied as a
10 # 2D histogram.
11 # ---------------------------------------------------------------------------
12  
13 1 ▶use 5.10.0;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 1 ▶use List::Util qw/reduce/;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 1 ▶use Math::Random;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 1 ▶use constant PI => 4 * atan2( 1, 1 );
Subroutine BEGIN: called CC=1 SCAR=0.0
19 1 ▶use Math::Big qw/euler/;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 1 ▶use File::Basename;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 1 ▶use Graphics::GnuplotIF;
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 1 our $VERSION = '1.01';
24  
25 # from perl docs:
26 1 my $_num_regex = '^[+-]?\ *(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$';
27 # Useful for creating reproducible results:
28 1 random_seed_from_phrase('hellojello');
29  
30 # Constructor:
31 1 ▶sub new {
Subroutine new: called CC=11 SCAR=29.8
Pod documented
32 1 my ($class, %args) = @_;
33 1 my @params = keys %args;
34 1 ▶ croak "\nYou have used a wrong name for a keyword argument " .
Branch: 1 branch
BranchTrueFalseTotal
if check_for_illegal_params(@params) == 0 0 1 1
35 "--- perhaps a misspelling\n"
36 if check_for_illegal_params(@params) == 0;
37 bless {
38 _hist_file => $args{input_histogram_file} || croak("histogram file required"),
39 _bbox_file => $args{bounding_box_file} || croak("bounding box file required"),
40 _N => $args{number_of_points} || 2000,
41 _how_many_to_discard => $args{how_many_to_discard} || 500,
42 _debug => $args{debug} || 0,
43 _proposal_density_width => $args{proposal_density_width} || 0.1,
44 _y_axis_pos_direction => $args{y_axis_pos_direction} || "down",
45 _output_hist_bins_along_x => $args{output_hist_bins_along_x} || 40,
46 1 ▶ _command_line_mode => $args{command_line_mode} || 0,
Condition50%9/18
$args{'input_histogram_file'} || croak('histogram file required')
l!l
10
$args{'bounding_box_file'} || croak('bounding box file required')
l!l
10
$args{'number_of_points'} || 2000
l!l
10
$args{'how_many_to_discard'} || 500
l!l
10
$args{'debug'} || 0
l!l
01
$args{'proposal_density_width'} || 0.1
l!l
01
$args{'y_axis_pos_direction'} || 'down'
l!l
01
$args{'output_hist_bins_along_x'} || 40
l!l
01
$args{'command_line_mode'} || 0
l!l
01
MC/DC0%0/1
$args{'input_histogram_file'} || croak('histogram file required')
$args{'input_histogram_file'}
MC/DC0%0/1
$args{'bounding_box_file'} || croak('bounding box file required')
$args{'bounding_box_file'}
MC/DC0%0/1
$args{'number_of_points'} || 2000
$args{'number_of_points'}
MC/DC0%0/1
$args{'how_many_to_discard'} || 500
$args{'how_many_to_discard'}
MC/DC0%0/1
$args{'debug'} || 0
$args{'debug'}
MC/DC0%0/1
$args{'proposal_density_width'} || 0.1
$args{'proposal_density_width'}
MC/DC0%0/1
$args{'y_axis_pos_direction'} || 'down'
$args{'y_axis_pos_direction'}
MC/DC0%0/1
$args{'output_hist_bins_along_x'} || 40
$args{'output_hist_bins_along_x'}
MC/DC0%0/1
$args{'command_line_mode'} || 0
$args{'command_line_mode'}
Truth table50%1/2
A
A= $args{'input_histogram_file'}
Aresult
11
00
Truth table50%1/2
A
A= $args{'bounding_box_file'}
Aresult
11
00
Truth table50%1/2
A
A= $args{'number_of_points'}
Aresult
11
00
Truth table50%1/2
A
A= $args{'how_many_to_discard'}
Aresult
11
00
Truth table50%1/2
A
A= $args{'debug'}
Aresult
11
00
Truth table50%1/2
A
A= $args{'proposal_density_width'}
Aresult
11
00
Truth table50%1/2
A
A= $args{'y_axis_pos_direction'}
Aresult
11
00
Truth table50%1/2
A
A= $args{'output_hist_bins_along_x'}
Aresult
11
00
Truth table50%1/2
A
A= $args{'command_line_mode'}
Aresult
11
00
47 _x_delta => undef,
48 _y_delta => undef,
49 _input_histogram => undef,
50 _output_histogram => undef,
51 _bounding_box => undef,
52 _generated_points => undef,
53 _normalized_input_hist => undef,
54 _sigmax_for_proposal_density => undef,
55 _sigmay_for_proposal_density => undef,
56 _bin_width_for_output_hist => undef,
57 _bin_height_for_output_hist => undef,
58 }, $class;
59 }
60  
61 # The file that contains a 2D histogram of the desired probability distribution for
62 # the random points must either be in the CSV or the white-space-separated
63 # format. Since we are working with 2D densities, each line of this text file should
64 # show one row of the histogram. The subroutine creates an array of arrays from the
65 # information read from the file, which each inner row holding one row of the
66 # histogram.
67 1 ▶sub read_histogram_file_for_desired_density {
Subroutine read_histogram_file_for_desired_density: called CC=9 SCAR=24.6
Pod documented
68 1 my $self = shift;
69 1 my $filename = $self->{_hist_file};
70 1 ▶ open FILEIN, $filename
Branch: 1 branch
BranchTrueFalseTotal
open FILEIN, $filename or die "unable to open file: $!" 1 0 1
71 or die "unable to open file: $!";
72 1 my @hist;
73 1 ▶ while (<FILEIN>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline FILEIN)) 10 1 11
74 10 ▶ next if /^#/;
Branch: 1 branch
BranchTrueFalseTotal
if /^#/ 0 10 10
75 10 ▶ next if /^\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
if /^\s*$/ 0 10 10
76 10 chomp;
77 10 my @line;
78 10 ▶ if ($filename =~ /.csv$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($filename =~ /.csv$/) { } 10 0 10
79 10 @line = map {$_ =~ s/^\s*|\s*$//; $_} split /,/, $_;
80 } else {
81 0 @line = split;
82 }
83 10 push @hist, \@line;
84 }
85 1 close FILEIN;
86 1 ▶ if ($self->{_y_axis_pos_direction} eq "up") {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'_y_axis_pos_direction'} eq 'up') { } 0 1 1
elsif ($self->{'_y_axis_pos_direction'} eq 'down') { } 1 0 1
87 0 my @newhist;
88 0 foreach my $i (0..@hist-1) {
89 0 push @newhist, $hist[scalar(@hist)-$i-1];
90 }
91 0 $self->{_input_histogram} = \@newhist;
92 } elsif ($self->{_y_axis_pos_direction} eq "down") {
93 1 $self->{_input_histogram} = \@hist;
94 } else {
95 0 die "Something is wrong with your value for the construction option 'y_xis_pos_direction'";
96 }
97 }
98  
99  
100 # This subroutine is for reading from a text file the horizontal and the vertical
101 # limits of the bounding box in which the randomly generated points must reside. The
102 # file can either be in the CSV format or the white-space-separated format. Apart
103 # from any comment lines that begin with the hash mark, this must must contain
104 # exactly two lines, the first indicated the x-axis points that define the horizontal
105 # span of the bounding box and the second indicating the y-axis points that define
106 # the vertical span of the same.
107 1 ▶sub read_file_for_bounding_box {
Subroutine read_file_for_bounding_box: called CC=8 SCAR=21.3
Pod documented
108 1 my $self = shift;
109 1 my $histref = $self->{_input_histogram};
110 1 my $filename = $self->{_bbox_file};
111 1 ▶ open FILEIN, $filename
Branch: 1 branch
BranchTrueFalseTotal
open FILEIN, $filename or die "unable to open file: $!" 1 0 1
112 or die "unable to open file: $!";
113 1 my @bounding_box;
114 1 ▶ while (<FILEIN>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline FILEIN)) 2 1 3
115 2 ▶ next if /^#/;
Branch: 1 branch
BranchTrueFalseTotal
if /^#/ 0 2 2
116 2 ▶ next if /^\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
if /^\s*$/ 0 2 2
117 2 chomp;
118 2 my @line;
119 2 ▶ if ($filename =~ /.csv$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($filename =~ /.csv$/) { } 2 0 2
120 2 @line = map {$_ =~ s/^\s*|\s*$//; $_} split /,/, $_;
121 } else {
122 0 @line = split;
123 }
124 2 ▶ die "There must exist exactly two entries in each line of the bounding box file"
Branch: 1 branch
BranchTrueFalseTotal
if @line != 2 0 2 2
125 if @line != 2;
126 2 push @bounding_box, \@line;
127 }
128 1 ▶ die "There must exist only two lines in the bounding box file" if @bounding_box != 2;
Branch: 1 branch
BranchTrueFalseTotal
if @bounding_box != 2 0 1 1
129 1 close FILEIN;
130 1 $self->{_x_delta} = ($bounding_box[0][1] - $bounding_box[0][0]) / @{$histref->[0]};
131 1 $self->{_y_delta} = ($bounding_box[1][1] - $bounding_box[1][0]) / @$histref;
132 1 $self->{_bounding_box} = \@bounding_box;
133 }
134
135 # This is the heart of the module --- in the sense that this method implements the
136 # Metropolis-Hastings algorithm for generating the random points. This algorithm is
137 # the most popular algorithm today for what is known as the MCMC (Markov Chain Monte
138 # Carlo) sampling from a desired probability distribution.
139 1 ▶sub metropolis_hastings {
Subroutine metropolis_hastings: called CC=14 SCAR=26.8
Pod documented
140 1 $|++;
141 1 my $self = shift;
142 die "\nyou must first call read_file_for_bounding_box() before you can call\n" .
143 1 ▶ "metropolis_hastings()$!\n" unless $self->{_bounding_box};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_bounding_box"} 0 1 1
144 die "\nyou must first call normalize_input_histogram() before you can call\n" .
145 1 ▶ "metropolis_hastings()$!\n" unless $self->{_normalized_input_hist};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_normalized_input_hist"} 0 1 1
146 die "\nyou must first call set_sigmas_for_proposal_density() before you can call\n" .
147 1 ▶ "metropolis_hastings()$!\n" unless $self->{_sigmax_for_proposal_density};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_sigmax_for_proposal_density"} 0 1 1
148 1 my $box = $self->{_bounding_box};
149 1 my $N_discard = $self->{_how_many_to_discard};
150 1 my $N_iterations = $self->{_N} + $N_discard;
151 1 my $sample = [$box->[0][0] + ($box->[0][1] - $box->[0][0]) / 2.0,
152 $box->[1][0] + ($box->[1][1] - $box->[1][0]) / 2.0];
153 1 ▶ while ($self->desired_density($sample) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->desired_density($sample) == 0) 9 1 10
154 $sample = [$self->{_bounding_box}->[0][0] +
155 random_uniform() * ($self->{_bounding_box}->[0][1] - $self->{_bounding_box}->[0][0]),
156 $self->{_bounding_box}->[1][0] +
157 9 random_uniform() * ($self->{_bounding_box}->[1][1] - $self->{_bounding_box}->[1][0])]
158 }
159 1 ▶ print "\nstarting sample: @$sample\n" unless $self->{_command_line_mode};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_command_line_mode"} 1 0 1
160 1 ▶ if ($self->{_command_line_mode}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'_command_line_mode'}) { } 0 1 1
161 0 print "\nThe Metropolis-Hastings algorithm will be run over 2500 iterations.\n" .
162 "Of the 2500 points generated, the first 500 will be discarded.\n" .
163 "Each dot shown below stands for 50 iterations of the algorithm.\n\n";
164 } else {
165 1 print "\nThe Metropolis-Hastings algorithm will be run for $N_discard more iterations\n" .
166 "than the number of points you requested. The first $N_discard initial points thus\n" .
167 "generated will be discarded from the final output.\n\n";
168 }
169 1 my @arr;
170 1 foreach my $i (0..$N_iterations-1) {
171 100 ▶ unless ($self->{_command_line_mode}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"_command_line_mode"}) 100 0 100
172 100 ▶ print "\nIteration number: $i (out of $N_iterations)\n" if $i % ($N_iterations / 10) == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $i % ($N_iterations / 10) == 0 10 90 100
173 }
174 100 ▶ print ". " if $i % 50 == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $i % 50 == 0 2 98 100
175 # Get proposal probability q( $y | $x ).
176 100 my ($newsample, $prob) = $self->get_sample_using_proposal( $sample );
177 100 my $a1 = $self->desired_density( $newsample ) / $self->desired_density( $sample );
178 100 my $a2 = $self->proposal_density( $sample, $newsample ) / $prob;
179 100 my $a = $a1 * $a2;
180 100 my $u = random_uniform();
181 100 ▶ if ( $a >= 1 ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($a >= 1) { } 52 48 100
elsif ($u < $a) { } 8 40 48
182 52 $sample = $newsample;
183 52 push @arr, $sample;
184 } elsif ($u < $a) {
185 8 $sample = $newsample;
186 8 push @arr, $sample;
187 } else {
188 40 push @arr, $sample;
189 }
190 }
191 1 ▶ print "\nTotal number of iterations run: $N_iterations\n\n" unless $self->{_command_line_mode};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_command_line_mode"} 1 0 1
192 1 $self->{_generated_points} = \@arr;
193 }
194  
195 # From the standpoint of matching the input histogram, the quality of the random
196 # points generated by the Metropolis-Hastings algorithm is affected by what sort of a
197 # probability distribution is used for the proposal density function. This module
198 # uses a bivariate Gaussian density function for this purpose whose widths along x
199 # and y are controlled by constructor parameter "proposal_density_width" that
200 # defaults to 0.1. The function here sets the values for the sigmax and sigmay
201 # parameters of this bivariate density.
202 1 ▶sub set_sigmas_for_proposal_density {
Subroutine set_sigmas_for_proposal_density: called CC=2 SCAR=7.0
Pod documented
203 1 my $self = shift;
204 die "\nyou must call read_file_for_bounding_box() before you can call\n" .
205 1 ▶ "set_sigmas_for_proposal_density()$!\n" unless $self->{_bounding_box};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_bounding_box"} 0 1 1
206 1 my $param = $self->{_proposal_density_width};
207 1 my $box = $self->{_bounding_box};
208 1 $self->{_sigmax_for_proposal_density} = ($box->[0][1] - $box->[0][0]) * $param;
209 1 $self->{_sigmay_for_proposal_density} = ($box->[1][1] - $box->[1][0]) * $param;
210 }
211  
212 # This function is called by metropolis_hastings() for generating the next point in a
213 # random walk in the 2D plane:
214 100 ▶sub get_sample_using_proposal {
Subroutine get_sample_using_proposal: called CC=1 SCAR=0.0
Pod undocumented
215 100 my $self = shift;
216 100 my $x = shift;
217 100 my $mean = $x; # for proposal_prob($y|$x) = norm($x, $sigma ** 2)
218 100 my $sigmax = $self->{_sigmax_for_proposal_density};
219 100 my $sigmay = $self->{_sigmay_for_proposal_density};
220 100 my @SIGMA = ( [$sigmax**2, 0], [0, $sigmay**2] );
221 100 my $sample = Math::Random::random_multivariate_normal( 1, @$mean, @SIGMA );
222 100 my $gaussian_exponent = - 0.5 * ( (($sample->[0] - $mean->[0])**2 / $sigmax**2 ) +
223 (($sample->[1] - $mean->[1])**2 / $sigmay**2 ) ) ;
224 100 my $prob = ( 1.0 / (2 * PI * $sigmax * $sigmay ) ) * euler( $gaussian_exponent );
225 100 return ($sample, $prob);
226 }
227  
228 # This function returns the desired density at the candidate point produced by the by
229 # proposal density function. The desired density is calculated by applying bilinear
230 # interpolation to the bin counts to the four nearest four points in the normalized
231 # version of the input histogram.
232 210 ▶sub desired_density {
Subroutine desired_density: called CC=18 SCAR=29.4
Pod undocumented
233 210 my $self = shift;
234 210 my $sample = shift;
235 210 my $histref = $self->{_normalized_input_hist};
236 210 my $bbsize = $self->{_bounding_box};
237 210 my $horiz_delta = $self->{_x_delta};
238 210 my $vert_delta = $self->{_y_delta};
239 210 ▶ print "horiz_delta: $horiz_delta vert_delta: $vert_delta\n" if $self->{_debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_debug"} 0 210 210
240 210 ▶ return 0 if $sample->[0] < $bbsize->[0][0] || $sample->[0] > $bbsize->[0][1] ||
Branch: 1 branch
BranchTrueFalseTotal
if $sample->[0] < $bbsize->[0][0] or $sample->[0] > $bbsize->[0][1] or $sample->[1] < $bbsize->[1][0] or $sample->[1] > $bbsize->[1][1] 27 183 210
Condition77%7/9
$sample->[0] < $bbsize->[0][0] or $sample->[0] > $bbsize->[0][1] or $sample->[1] < $bbsize->[1][0] or $sample->[1] > $bbsize->[1][1]
l!l&&r!l&&!r
243183
$sample->[0] < $bbsize->[0][0] or $sample->[0] > $bbsize->[0][1] or $sample->[1] < $bbsize->[1][0]
l!l&&r!l&&!r
240186
$sample->[0] < $bbsize->[0][0] or $sample->[0] > $bbsize->[0][1]
l!l&&r!l&&!r
240186
MC/DC50%2/4
$sample->[0] < $bbsize->[0][0] or $sample->[0] > $bbsize->[0][1] or $sample->[1] < $bbsize->[1][0] or $sample->[1] > $bbsize->[1][1]
$sample->[0] < $bbsize->[0][0] $sample->[0] > $bbsize->[0][1] $sample->[1] < $bbsize->[1][0] $sample->[1] > $bbsize->[1][1]
Truth table60%3/5
A or B or C or D
A= $sample->[0] < $bbsize->[0][0]B= $sample->[0] > $bbsize->[0][1]C= $sample->[1] < $bbsize->[1][0]D= $sample->[1] > $bbsize->[1][1]
ABCDresult
1XXX1
01XX1
001X1
00011
00000
241 $sample->[1] < $bbsize->[1][0] || $sample->[1] > $bbsize->[1][1];
242 183 ▶ print "horizontal extent: $bbsize->[0][0] $bbsize->[0][1]\n" if $self->{_debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_debug"} 0 183 183
243 183 ▶ print "vertical extent: $bbsize->[1][0] $bbsize->[1][1]\n" if $self->{_debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_debug"} 0 183 183
244 183 my $bin_horiz = int( ($sample->[0] - $bbsize->[0][0]) / $horiz_delta );
245 183 my $bin_vert = int( ($sample->[1] - $bbsize->[1][0]) / $vert_delta );
246 print "bin 2D index: horiz: $bin_horiz vert: $bin_vert for sample value @$sample\n"
247 183 ▶ if $self->{_debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_debug"} 0 183 183
248 183 ▶ my $prob00 = $histref->[$bin_vert][$bin_horiz] || 0;
Condition100%2/2
$histref->[$bin_vert][$bin_horiz] || 0
l!l
17013
MC/DC100%1/1
$histref->[$bin_vert][$bin_horiz] || 0
$histref->[$bin_vert][$bin_horiz]
Truth table100%2/2
A
A= $histref->[$bin_vert][$bin_horiz]
Aresult
11
00
249 183 ▶ return $prob00 if (($bin_horiz + 1) >= @{$histref->[0]}) || (($bin_vert + 1) >= @{$histref});
Branch: 1 branch
BranchTrueFalseTotal
if $bin_horiz + 1 >= @{$histref->[0];} or $bin_vert + 1 >= @{$histref;} 12 171 183
Condition100%3/3
$bin_horiz + 1 >= @{$histref->[0];} or $bin_vert + 1 >= @{$histref;}
l!l&&r!l&&!r
111171
MC/DC100%2/2
$bin_horiz + 1 >= @{$histref->[0];} or $bin_vert + 1 >= @{$histref;}
$bin_horiz + 1 >= @{$histref->[0];} $bin_vert + 1 >= @{$histref;}
Truth table100%3/3
A or B
A= $bin_horiz + 1 >= @{$histref->[0];}B= $bin_vert + 1 >= @{$histref;}
ABresult
1X1
011
000
250 171 ▶ my $prob01 = $histref->[$bin_vert + 1][$bin_horiz] || 0;
Condition100%2/2
$$histref[$bin_vert + 1][$bin_horiz] || 0
l!l
16110
MC/DC100%1/1
$$histref[$bin_vert + 1][$bin_horiz] || 0
$$histref[$bin_vert + 1][$bin_horiz]
Truth table100%2/2
A
A= $$histref[$bin_vert + 1][$bin_horiz]
Aresult
11
00
251 171 ▶ my $prob10 = $histref->[$bin_vert][$bin_horiz+ 1] || 0;
Condition100%2/2
$histref->[$bin_vert][$bin_horiz + 1] || 0
l!l
12051
MC/DC100%1/1
$histref->[$bin_vert][$bin_horiz + 1] || 0
$histref->[$bin_vert][$bin_horiz + 1]
Truth table100%2/2
A
A= $histref->[$bin_vert][$bin_horiz + 1]
Aresult
11
00
252 171 ▶ my $prob11 = $histref->[$bin_vert + 1][$bin_horiz + 1] || 0;
Condition100%2/2
$$histref[$bin_vert + 1][$bin_horiz + 1] || 0
l!l
12051
MC/DC100%1/1
$$histref[$bin_vert + 1][$bin_horiz + 1] || 0
$$histref[$bin_vert + 1][$bin_horiz + 1]
Truth table100%2/2
A
A= $$histref[$bin_vert + 1][$bin_horiz + 1]
Aresult
11
00
253 171 ▶ print "The four probs: $prob00 $prob01 $prob10 $prob11\n" if $self->{_debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_debug"} 0 171 171
254 171 my $horiz_fractional = (($sample->[0] - $bbsize->[0][0]) / $horiz_delta) - $bin_horiz;
255 171 my $vert_fractional = (($sample->[1] - $bbsize->[1][0]) / $vert_delta) - $bin_vert;
256 171 ▶ print "horiz frac: $horiz_fractional vert frac: $vert_fractional\n" if $self->{_debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_debug"} 0 171 171
257 171 my $interpolated_prob = $prob00 * (1 - $horiz_fractional) * (1 - $vert_fractional) +
258 $prob10 * $horiz_fractional * (1 - $vert_fractional) +
259 $prob01 * (1 - $horiz_fractional) * $vert_fractional +
260 $prob11 * $horiz_fractional * $vert_fractional;
261 171 ▶ print "Interpolated prob: $interpolated_prob\n" if $self->{_debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_debug"} 0 171 171
262 171 return $interpolated_prob;
263 }
264  
265 100 ▶sub proposal_density {
Subroutine proposal_density: called CC=1 SCAR=0.0
Pod undocumented
266 100 my $self = shift;
267 100 my $sample = shift;
268 100 my $mean = shift;
269 100 my $sigmax = $self->{_sigmax_for_proposal_density};
270 100 my $sigmay = $self->{_sigmay_for_proposal_density};
271 100 my @SIGMA = ( [$sigmax, 0], [0, $sigmay] );
272 100 my $gaussian_exponent = - 0.5 * ( (($sample->[0] - $mean->[0])**2 / $sigmax**2 ) +
273 (($sample->[1] - $mean->[1])**2 / $sigmay**2 ) ) ;
274 100 my $prob = ( 1.0 / (2 * PI * $sigmax * $sigmay ) ) * euler( $gaussian_exponent );
275 100 return $prob;
276 }
277  
278 1 ▶sub normalize_input_histogram {
Subroutine normalize_input_histogram: called CC=4 SCAR=13.9
Pod documented
279 1 my $self = shift;
280 die "\nyou must first call read_histogram_file_for_desired_density() before you can call\n" .
281 1 ▶ "normalize_input_histogram()$!\n" unless $self->{_input_histogram};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_input_histogram"} 0 1 1
282 1 my $histref = deep_copy_AoA( $self->{_input_histogram} );
283 1 ▶ my $summation = reduce {$a + $b} map {@$_} @$histref;
Subroutine __ANON__: called CC=1 SCAR=0.0
284 1 foreach my $i (0..@$histref-1) {
285 10 foreach my $j (0..@{$histref->[0]}-1) {
286 100 $histref->[$i][$j] /= $summation;
287 }
288 }
289 1 $self->{_normalized_input_hist} = $histref;
290 }
291  
292 # Display a 2D histogram. Requires one argument which must be a reference to an
293 # array of arrays, which inner array holding one row of the histogram.
294 0 ▶sub display_hist_in_terminal_window {
Subroutine display_hist_in_terminal_window: not called CC=5 SCAR=34.0
Pod undocumented
295 0 my $self = shift;
296 die "\nyou must first call read_histogram_file_for_desired_density() before you can call\n" .
297 0 ▶ "display_hist_in_terminal_window()$!\n" unless $self->{_input_histogram};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_input_histogram"} 0 0 0
298 0 my $histref = $self->{_input_histogram};
299 0 foreach my $y (0..@$histref-1) {
300 0 foreach my $x (0..@{$histref->[0]}-1) {
301 0 ▶ if ($histref->[$y][$x] < 100) {
Branch: 1 branch
BranchTrueFalseTotal
if ($histref->[$y][$x] < 100) { } 0 0 0
302 0 printf "%d ", $histref->[$y][$x];
303 } else {
304 0 printf "%.3e ", $histref->[$y][$x];
305 }
306 }
307 0 print "\n";
308 }
309 0 print "\n";
310 }
311  
312 0 ▶sub write_generated_points_to_a_file {
Subroutine write_generated_points_to_a_file: not called CC=6 SCAR=37.4
Pod documented
313 0 my $self = shift;
314 die "\nyou must first call metropolis_hastings() before you can call\n" .
315 0 ▶ "write_generated_points_to_a_file()$!\n" unless $self->{_generated_points};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_generated_points"} 0 0 0
316 0 my $master_file_basename = basename($self->{_hist_file}, ('.csv', '.dat', '.txt'));
317 0 my $out_file = "random_points_generated_for_$master_file_basename.csv";
318 0 my @samples = @{$self->{_generated_points}};
319 0 my $N_discard = $self->{_how_many_to_discard};
320 0 my @truncated_sample_list = @samples[$N_discard..$#samples-1];
321 0 fisher_yates_shuffle(\@truncated_sample_list);
322 0 ▶ if (@truncated_sample_list) {
Branch: 1 branch
BranchTrueFalseTotal
if (@truncated_sample_list) 0 0 0
323 0 ▶ open( OUTFILE , ">$out_file") or
Branch: 1 branch
BranchTrueFalseTotal
open OUTFILE, ">$out_file" or die "Cannot open out.txt for write: $!" 0 0 0
324 die "Cannot open out.txt for write: $!";
325 0 foreach my $sample (@truncated_sample_list) {
326 0 printf OUTFILE "%.6f, %.6f\n", $sample->[0], $sample->[1];
327 }
328 0 close OUTFILE;
329 }
330 0 ▶ print "\nRandom points written out to $out_file\n" if $self->{_command_line_mode};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_command_line_mode"} 0 0 0
331 }
332  
333 0 ▶sub write_generated_points_to_standard_output {
Subroutine write_generated_points_to_standard_output: not called CC=3 SCAR=24.8
Pod undocumented
334 0 my $self = shift;
335 0 my @samples = @{$self->{_generated_points}};
336 0 my $N_discard = $self->{_how_many_to_discard};
337 0 my @truncated_sample_list = @samples[$N_discard..$#samples-1];
338 0 fisher_yates_shuffle(\@truncated_sample_list);
339 0 ▶ if (@truncated_sample_list) {
Branch: 1 branch
BranchTrueFalseTotal
if (@truncated_sample_list) 0 0 0
340 0 foreach my $sample (@truncated_sample_list) {
341 0 printf STDOUT "%.6f, %.6f\n", $sample->[0], $sample->[1];
342 }
343 }
344 }
345  
346 0 ▶sub display_output_histogram_in_terminal_window {
Subroutine display_output_histogram_in_terminal_window: not called CC=4 SCAR=30.0
Pod documented
347 0 my $self = shift;
348 die "\nyou must call make_output_histogram_for_generated_points()() before you can call\n" .
349 0 ▶ "display_output_histogram_in_terminal_window()$!\n" unless $self->{_output_histogram};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_output_histogram"} 0 0 0
350 0 my $output_hist = $self->{_output_histogram};
351 0 foreach my $row (@$output_hist) {
352 0 foreach my $sample (@$row) {
353 0 print "$sample ";
354 }
355 0 print "\n";
356 }
357 }
358  
359 1 ▶sub make_output_histogram_for_generated_points {
Subroutine make_output_histogram_for_generated_points: called CC=6 SCAR=18.0
Pod documented
360 1 my $self = shift;
361 1 my @data = @{$self->{_generated_points}};
362 1 my @horizonts = map {$_->[0]} @data;
363 1 my @verts = map {$_->[1]} @data;
364 1 my ($hmin, $hmax) = ($self->{_bounding_box}->[0][0], $self->{_bounding_box}->[0][1]);
365 1 my ($vmin, $vmax) = ($self->{_bounding_box}->[1][0], $self->{_bounding_box}->[1][1]);
366 1 my $aspect_ratio = ($vmax - $vmin) / ($hmax - $hmin);
367 1 my $num_bins_x = $self->{_output_hist_bins_along_x};
368 1 my $num_bins_y = int( $num_bins_x * $aspect_ratio );
369 1 my $hist;
370 1 foreach my $y (0..$num_bins_y-1) {
371 40 foreach my $x (0..$num_bins_x-1) {
372 1600 $hist->[$y][$x] = 0.0;
373 }
374 }
375 1 my $bin_width = ($hmax - $hmin) / $num_bins_x;
376 1 my $bin_height = ($vmax - $vmin) / $num_bins_y;
377 1 foreach my $sample (@data) {
378 100 my $hbin_index = int( ($sample->[0] - $hmin) / $bin_width );
379 100 my $vbin_index = int( ($sample->[1] - $vmin) / $bin_height );
380 100 ▶ $hist->[$vbin_index][$hbin_index]++
Branch: 1 branch
BranchTrueFalseTotal
if $hbin_index < $num_bins_x and $vbin_index < $num_bins_y 100 0 100
Condition33%1/3
$hbin_index < $num_bins_x and $vbin_index < $num_bins_y
!ll&&!rl&&r
00100
MC/DC0%0/2
$hbin_index < $num_bins_x and $vbin_index < $num_bins_y
$hbin_index < $num_bins_x $vbin_index < $num_bins_y
Truth table33%1/3
A and B
A= $hbin_index < $num_bins_xB= $vbin_index < $num_bins_y
ABresult
0X0
100
111
381 if ($hbin_index < $num_bins_x) && ($vbin_index < $num_bins_y);
382 }
383 1 $self->{_output_histogram} = $hist;
384 1 $self->{_bin_width_for_output_hist} = $bin_width;
385 1 $self->{_bin_height_for_output_hist} = $bin_height;
386 }
387  
388 # Plotting a 3D surface with Gnuplot requires that the input data be provided as a
389 # sequence of triples in a text file, with each triple in a separate line, and with
390 # each triple consisting of the x coordinate, followed by the y coordinate, which is
391 # then following by the height of the surface at that point. Additionally, and very
392 # importantly, this file must be separated into blocks, with the blocks separated by
393 # empty lines. Each block is for a single x coordinate and all the lines in a single
394 # block must be sorted with respected to the y coordinated. The blocks must be
395 # sorted with respect to the x coordinate.
396 0 ▶sub plot_histogram_3d_surface {
Subroutine plot_histogram_3d_surface: not called CC=9 SCAR=45.0
Pod documented
397 0 my $self = shift;
398 die "\nyou must call make_output_histogram_for_generated_points() before you can call\n" .
399 0 ▶ "plot_histogram_3d_surface()$!\n" unless $self->{_output_histogram};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_output_histogram"} 0 0 0
400 0 my $pause_time = shift;
401 0 my $hist = $self->{_output_histogram};
402 0 my @plot_points = ();
403 0 foreach my $y (0..@$hist-1) {
404 0 foreach my $x (0..@{$hist->[0]}-1) {
405 0 push @plot_points, [$x, $y, $hist->[$y][$x]];
406 0 push @plot_points, [$x+1, $y, $hist->[$y][$x]];
407 0 push @plot_points, [$x, $y+1, $hist->[$y][$x]];
408 0 push @plot_points, [$x+1, $y+1, $hist->[$y][$x]];
409 }
410 }
411 0 @plot_points = sort {$a->[0] <=> $b->[0]} @plot_points;
412 0 ▶ @plot_points = sort {$a->[1] <=> $b->[1] if $a->[0] == $b->[0]} @plot_points;
Branch: 1 branch
BranchTrueFalseTotal
if $Algorithm::RandomPointGenerator::a->[0] == $Algorithm::RandomPointGenerator::b->[0] 0 0 0
413 0 my $master_file_basename = basename($self->{_hist_file}, ('.csv', '.dat', '.txt'));
414 0 my $temp_file = "__temp_$master_file_basename.dat";
415 0 ▶ open(OUTFILE , ">$temp_file") or die "Cannot open temporary file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open OUTFILE, ">$temp_file" or die "Cannot open temporary file: $!" 0 0 0
416 0 my ($first, $oldfirst);
417 0 $oldfirst = $plot_points[0]->[0];
418 0 foreach my $sample (@plot_points) {
419 0 $first = $sample->[0];
420 0 ▶ if ($first == $oldfirst) {
Branch: 1 branch
BranchTrueFalseTotal
if ($first == $oldfirst) { } 0 0 0
421 0 my @out_sample;
422 $out_sample[0] = $self->{_bounding_box}->[0][0] + $sample->[0] *
423 0 $self->{_bin_width_for_output_hist};
424 $out_sample[1] = $self->{_bounding_box}->[1][0] + $sample->[1] *
425 0 $self->{_bin_height_for_output_hist};
426 0 $out_sample[2] = $sample->[2];
427 0 print OUTFILE "@out_sample\n";
428 } else {
429 0 print OUTFILE "\n";
430 }
431 0 $oldfirst = $first;
432 }
433 0 print OUTFILE "\n";
434 0 close OUTFILE;
435 0 my $x_left = $self->{_bounding_box}->[0][0];
436 0 my $x_right = $self->{_bounding_box}->[0][1];
437 0 my $y_lower = $self->{_bounding_box}->[1][0];
438 0 my $y_upper = $self->{_bounding_box}->[1][1];
439 0 my $argstring = <<"END";
440 set xrange [$x_left:$x_right]
441 set yrange [$y_lower:$y_upper]
442 set pm3d
443 splot "$temp_file" with pm3d
444 END
445 0 ▶ unless (defined $pause_time) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $pause_time) { } 0 0 0
446 0 my $hardcopy_name = "output_histogram_for_$master_file_basename.png";
447 0 my $plot1 = Graphics::GnuplotIF->new();
448 0 $plot1->gnuplot_cmd( 'set terminal png', "set output \"$hardcopy_name\"");
449 0 $plot1->gnuplot_cmd( $argstring );
450 0 my $plot2 = Graphics::GnuplotIF->new(persist => 1);
451 0 $plot2->gnuplot_cmd( $argstring );
452 } else {
453 0 my $plot = Graphics::GnuplotIF->new();
454 0 $plot->gnuplot_cmd( $argstring );
455 0 $plot->gnuplot_pause( $pause_time );
456 }
457 }
458  
459 1 ▶sub plot_histogram_lineplot {
Subroutine plot_histogram_lineplot: called CC=10 SCAR=23.1
Pod documented
460 1 my $self = shift;
461 1 my $pause_time = shift;
462 die "\nyou must call make_output_histogram_for_generated_points() before you can call\n" .
463 1 ▶ "plot_histogram_lineplot()$!\n" unless $self->{_output_histogram};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_output_histogram"} 0 1 1
464 1 my $hist = $self->{_output_histogram};
465 1 my @plot_points = ();
466 1 foreach my $y (0..@$hist-1) {
467 40 foreach my $x (0..@{$hist->[0]}-1) {
468 1600 push @plot_points, [$x, $y, $hist->[$y][$x]];
469 1600 push @plot_points, [$x+1, $y, $hist->[$y][$x]];
470 1600 push @plot_points, [$x, $y+1, $hist->[$y][$x]];
471 1600 push @plot_points, [$x+1, $y+1, $hist->[$y][$x]];
472 }
473 }
474 1 @plot_points = sort {$a->[0] <=> $b->[0]} @plot_points;
475 1 ▶ @plot_points = sort {$a->[1] <=> $b->[1] if $a->[0] == $b->[0]} @plot_points;
Branch: 1 branch
BranchTrueFalseTotal
if $Algorithm::RandomPointGenerator::a->[0] == $Algorithm::RandomPointGenerator::b->[0] 19409 1362 20771
476 1 my $master_file_basename = basename($self->{_hist_file}, ('.csv', '.dat', '.txt'));
477 1 my $temp_file = "__temp_$master_file_basename.dat";
478 1 ▶ open(OUTFILE , ">$temp_file") or die "Cannot open temporary file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open OUTFILE, ">$temp_file" or die "Cannot open temporary file: $!" 1 0 1
479 1 my ($first, $oldfirst);
480 1 $oldfirst = $plot_points[0]->[0];
481 1 foreach my $sample (@plot_points) {
482 6400 $first = $sample->[0];
483 6400 ▶ if ($first == $oldfirst) {
Branch: 1 branch
BranchTrueFalseTotal
if ($first == $oldfirst) { } 6360 40 6400
484 6360 my @out_sample;
485 $out_sample[0] = $self->{_bounding_box}->[0][0] + $sample->[0] *
486 6360 $self->{_bin_width_for_output_hist};
487 $out_sample[1] = $self->{_bounding_box}->[1][0] + $sample->[1] *
488 6360 $self->{_bin_height_for_output_hist};
489 6360 $out_sample[2] = $sample->[2];
490 6360 print OUTFILE "@out_sample\n";
491 } else {
492 40 print OUTFILE "\n";
493 }
494 6400 $oldfirst = $first;
495 }
496 1 print OUTFILE "\n";
497 1 close OUTFILE;
498 1 my $argstring = <<"END";
499 set hidden3d
500 splot "$temp_file" with lines
501 END
502 1 my $plot;
503 1 ▶ if (!defined $pause_time) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $pause_time) { } 0 1 1
504 0 $plot = Graphics::GnuplotIF->new( persist => 1 );
505 } else {
506 1 $plot = Graphics::GnuplotIF->new();
507 }
508 # my $plot = Graphics::GnuplotIF->new(persist => 1);
509 1 $plot->gnuplot_cmd( $argstring );
510 1 ▶ $plot->gnuplot_pause( $pause_time ) if defined $pause_time;
Branch: 1 branch
BranchTrueFalseTotal
if defined $pause_time 1 0 1
511 }
512  
513 1 ▶sub DESTROY {
Subroutine DESTROY: called CC=1 SCAR=0.0
514 1 my $self = shift;
515 1 my $master_file_basename = basename($self->{_hist_file}, ('.csv', '.dat', '.txt'));
516 1 ▶ unlink glob "__temp_$master_file_basename*";
Subroutine BEGIN: called CC=1 SCAR=0.0
517 }
518  
519 1 ▶sub deep_copy_AoA {
Subroutine deep_copy_AoA: called CC=3 SCAR=11.0
Pod undocumented
520 1 my $ref_in = shift;
521 1 my $ref_out;
522 1 foreach my $i (0..@{$ref_in}-1) {
523 10 foreach my $j (0..@{$ref_in->[$i]}-1) {
524 100 $ref_out->[$i]->[$j] = $ref_in->[$i]->[$j];
525 }
526 }
527 1 return $ref_out;
528 }
529  
530 # from perl docs:
531 0 ▶sub fisher_yates_shuffle {
Subroutine fisher_yates_shuffle: not called CC=2 SCAR=17.9
Pod undocumented
532 0 my $arr = shift;
533 0 my $i = @$arr;
534 0 ▶ while (--$i) {
Branch: 1 branch
BranchTrueFalseTotal
if (--$i) 0 0 0
535 0 my $j = int rand( $i + 1 );
536 0 @$arr[$i, $j] = @$arr[$j, $i];
537 }
538 }
539  
540 1 ▶sub check_for_illegal_params {
Subroutine check_for_illegal_params: called CC=5 SCAR=16.1
Pod undocumented
541 1 my @params = @_;
542 1 my @legal_params = qw / input_histogram_file
543 bounding_box_file
544 number_of_points
545 how_many_to_discard
546 proposal_density_width
547 y_axis_pos_direction
548 output_hist_bins_along_x
549 command_line_mode
550 debug
551 /;
552 1 my $found_match_flag;
553 1 foreach my $param (@params) {
554 4 foreach my $legal (@legal_params) {
555 10 $found_match_flag = 0;
556 10 ▶ if ($param eq $legal) {
Branch: 1 branch
BranchTrueFalseTotal
if ($param eq $legal) 4 6 10
557 4 $found_match_flag = 1;
558 4 last;
559 }
560 }
561 4 ▶ last if $found_match_flag == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $found_match_flag == 0 0 4 4
562 }
563 1 return $found_match_flag;
564 }
565  
566 1 1;
567  
568 =pod
569  
570 =head1 NAME
571  
572 Algorithm::RandomPointGenerator -- This module generates a set of random points in a
573 2D plane according to a user-specified probability distribution that is provided to
574 the module in the form of a 2D histogram.
575  
576  
577 =head1 SYNOPSIS
578  
579 # The quickest way to use the module is through the script genRand2D that you'll
580 # find in the examples subdirectory. You can move this script to any convenient
581 # location in your directory structure. Call this script as a command-line utility
582 # in the following manner:
583  
584 genRand2D --histfile your_histogram_file.csv --bbfile your_bounding_box_file.csv
585  
586 # where the '--histfile' option supplies the name of the file that contains a 2D
587 # histogram and the option '--bbfile' the name of the file that defines a bounding
588 # box in the XY-plane to which the histogram applies. The module uses the
589 # Metropolis-Hastings algorithm to draw random points from a probability density
590 # function that is approximated by the 2D histogram you supply through the
591 # '--histfile' option. You can also run the command
592  
593 genRand2D --help
594  
595 # for further information regarding these two command-line options. An invocation
596 # of genRand2D gives you 2000 random points that are deposited in a file whose
597 # name is printed out in the terminal window in which you invoke the genRand2D
598 # command.
599  
600  
601 # The rest of this Synopsis concerns using the module with greater control over
602 # the production and display of random points. Obviously, the very first thing
603 # you would need to do would be to import the module:
604  
605 use Algorithm::RandomPointGenerator;
606  
607 # Next, name the file that contains a 2D histogram for the desired density
608 # function for the generation of random points:
609  
610 my $input_histogram_file = "histogram.csv";
611  
612 # Then name the file that defines the bounding box for the random points:
613  
614 my $bounding_box_file = "bounding_box.csv";
615  
616 # Now construct an instance of RandomPointGenerator using a call that, assuming
617 # you wish to set all the constructor options, would look like:
618  
619 my $generator = Algorithm::RandomPointGenerator->new(
620 input_histogram_file => $input_histogram_file,
621 bounding_box_file => $bounding_box_file,
622 number_of_points => 2000,
623 how_many_to_discard => 500,
624 proposal_density_width => 0.1,
625 y_axis_pos_direction => 'down',
626 output_hist_bins_along_x => 40,
627 );
628  
629 # The role served by the different constructor options is explained later in this
630 # documentation. After constructing an instance of the module, you would need to
631 # call the following methods for generating the random points and for displaying
632 # their histogram:
633  
634 $generator->read_histogram_file_for_desired_density();
635 $generator->read_file_for_bounding_box();
636 $generator->normalize_input_histogram();
637 $generator->set_sigmas_for_proposal_density();
638 $generator->metropolis_hastings();
639 $generator->write_generated_points_to_a_file();
640 $generator->make_output_histogram_for_generated_points();
641 $generator->plot_histogram_3d_surface();
642  
643 # As to what is accomplished by each of the methods called above is described
644 # later in this documentation. Note that since several of the constructor
645 # parameters have defaults, a minimal call to the constructor may look as brief
646 # as:
647  
648 my $generator = Algorithm::RandomPointGenerator->new(
649 input_histogram_file => $input_histogram_file,
650 bounding_box_file => $bounding_box_file,
651 );
652
653 # In this case, the number of points to be generated is set to 2000. These will
654 # be the points after the first 500 that are discarded to get past the effects of
655 # the starting state of the generator.
656  
657  
658 =head1 CHANGES
659  
660 Version 1.01 downshifts the version of Perl that is required for this module. The
661 implementation code for the module is unchanged from Version 1.0.
662  
663  
664 =head1 DESCRIPTION
665  
666 Several testing protocols for "big data" research projects involving large geographic
667 areas require a random set of points that are distributed according to a
668 user-specified probability density function that exists in the form of a 2D
669 histogram. This module is an implementation of the Metropolis-Hastings algorithm for
670 generating such a set of points.
671  
672 =head1 METHODS
673  
674 The module provides the following methods:
675  
676 =over 4
677  
678 =item B<new():>
679  
680 A call to C<new()> constructs a new instance of the
681 C<Algorithm::RandomPointGenerator> class. If you wanted to set all the constructor
682 options, this call would look like:
683  
684 my $generator = Algorithm::RandomPointGenerator->new(
685 input_histogram_file => $input_histogram_file,
686 bounding_box_file => $bounding_box_file,
687 number_of_points => 2000,
688 how_many_to_discard => 500,
689 proposal_density_width => 0.1,
690 y_axis_pos_direction => 'down',
691 );
692  
693 where C<input_histogram_file> is the name of the file that contains a 2D histogram as
694 an approximation to the desired probability density function for the random points to
695 be generated. The data in the histogram file is expected to be in CSV format. Here
696 is a display of a very small portion of the contents of such a file for an actual
697 geographic region:
698  
699 0,211407,216387,211410,205621,199122,192870, ........
700 0,408221,427716,427716,427716,427716,427716,427716, ......
701 0,408221,427716,427716,427716,427716,427716,427716, ......
702 ....
703 ....
704 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,165,9282,11967,15143, .....
705 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,....
706  
707 The C<bounding_box_file> parameter of the constructor should delineate the portion of
708 the plane to which the input histogram corresponds. Here is an example of the
709 contents of an actual file supplied for this option:
710  
711 -71.772016, -70.431923
712 -34.254251, -33.203240
713  
714 Apart from any comment lines, there must exist exactly two lines in the bounding-box
715 file, with the first line indicating the left and the right limits of the horizontal
716 coordinates and the second line indicating the lower and the upper limits of the
717 vertical coordinates. (The values shown above are the longitude and the latitude
718 limits for a region in Chile, in case you are curious.)
719  
720 =back
721  
722 =head2 Constructor Parameters:
723  
724 =over 8
725  
726 =item C<input_histogram_file>:
727  
728 This required parameter supplies the name of the file that contains a 2D histogram as
729 the desired density function for the random points that the module will generate.
730 Each line record in this file must correspond to one row of the 2D histogram. The
731 left-to-right direction in the file will be considered to be positive direction for
732 the x-axis. As for the positive direction for the y-axis, it is common for that to
733 be from top to bottom when the histogram is written out to a text file as an array of
734 integers. It is important to bear in mind this orientation of the histogram in light
735 of the fact that a bounding box is specified typically with its y-axis going upwards
736 (whereas the x-axis continues to be positive from left to right). This inconsistency
737 between how a 2D histogram is typically stored in a text file and how a bounding box
738 is likely to be specified means that if the events occur more frequently in the upper
739 right hand corner of the bounding box, those high counts would show up in the lower
740 right hand corner of the histogram in a text file (or in a terminal display of the
741 contents of such a file). B<You can use the constructor option
742 C<y_axis_pos_direction> to reverse the positive sense of the y direction for the
743 histogram. If you set C<y_axis_pos_direction> to the string C<up>, then the
744 orientation of the y axis in both the histogram and the bounding box will be the
745 same.>
746  
747 =item C<bounding_box_file>:
748  
749 This required parameter supplies the name of the file that contains the bounding box
750 information. By bounding box is meant the part of the XY-plane that corresponds to
751 the histogram supplied through the C<input_histogram_file> option. Apart from any
752 comment lines, this file must contain exactly two lines and each line must contain
753 exactly two numeric entries. Additionally, the first entry in each of the two lines
754 must be smaller than the second entry in the same line. The two entries in the first
755 line define the lower and the upper bounds on the x-axis and the two entries in the
756 second line do the same for the y-axis.
757  
758 =item C<number_of_points>:
759  
760 This parameter specifies the number of random points that you want the module to
761 generate.
762  
763 =item C<how_many_to_discard>:
764  
765 The Metropolis-Hastings algorithm belongs to a category of algorithms known as
766 random-walk algorithms. Since the random walk carried out by such algorithms must be
767 initialized with user input, it is necessary to discard the points produced until the
768 effects the initial state have died out. This parameter specifies how many of the
769 generated points will be discarded. This parameter is optional in the sense that it
770 has a default value of 500.
771  
772 =item C<proposal_density_width>:
773  
774 Given the current point, the Metropolis-Hastings randomly chooses a candidate for the
775 next point. This random selection of a candidate point is carried out using what is
776 known as the "proposal density". The module uses a bivariate Gaussian for the
777 proposal density. The value supplied through this parameter controls the standard
778 deviations of the proposal Gaussian in the x and the y directions. The default value
779 for this parameter is 0.1. With that value for the parameter, the standard deviation
780 of the proposal density along the x direction will be set to 0.1 times the width of
781 the bounding box, and the standard deviation of the same along the y-direction to 0.1
782 times the height of the bounding box.
783  
784 =item C<y_axis_pos_direction>:
785  
786 See the explanation above for the constructor parameter C<input_histogram_file> for
787 why you may need to use the C<y_axis_pos_direction> parameter. The parameter takes
788 one of two values, C<up> and C<down>. The usual interpretation of a 2D histogram in
789 a text file --- with the positive direction of the y-axis pointing downwards ---
790 corresponds to the case when this parameter takes the default value of C<down>.
791  
792 =item C<output_hist_bins_along_x>:
793  
794 This parameter controls the resolution with which the histogram of the generated
795 random points will be displayed. The value you supply is for the number of bins
796 along the x-direction. The number of bins along the y-direction is set according to
797 the aspect ratio of the bounding box.
798  
799 =back
800  
801 =over
802  
803 =item B<read_histogram_file_for_desired_density():>
804  
805 $generator->read_histogram_file_for_desired_density();
806  
807 This is a required call after the constructor is invoked. As you would expect, this
808 call reads in the histogram data for the desired probability density function for
809 random point generation.
810  
811 =item B<read_file_for_bounding_box():>
812  
813 $generator->read_file_for_bounding_box();
814  
815 This is also a required call. This call reads in the left and the right limits on
816 the x-axis and the lower and the upper limits on the y-axis for the portion of the
817 XY-plane for which the random points are needed.
818  
819 =item B<normalize_input_histogram():>
820  
821 $generator->normalize_input_histogram();
822  
823 This normalizes the input histogram to turn it into an approximation to the desired
824 probability density function for the random points.
825  
826 =item B<set_sigmas_for_proposal_density():>
827  
828 $generator->set_sigmas_for_proposal_density();
829  
830 The Metropolis-Hastings algorithm is a random-walk algorithm that at each point first
831 creates a candidate for the next point and then makes a probabilistic decision
832 regarding the acceptance of the candidate point as the next point on the walk. The
833 candidate point is drawn from what is known as the proposal density function. This
834 module uses a bivariate Gaussian for the proposal density. You set the width of the
835 proposal density by calling this method.
836  
837 =item B<metropolis_hastings():>
838  
839 This is the workhorse of the module, as you would expect. As its name implies, it
840 uses the Metropolis-Hastings random-walk algorithm to generate a set of random points
841 whose probability distribution corresponds to the input histogram.
842  
843 =item B<write_generated_points_to_a_file():>
844  
845 $generator->write_generated_points_to_a_file();
846  
847 This method writes the generated points to a disk file whose name is keyed to the
848 name of the input histogram file. The two coordinates for each generated random point
849 are written out to a new line in this file.
850  
851 =item B<make_output_histogram_for_generated_points():>
852  
853 $generator->make_output_histogram_for_generated_points();
854  
855 The name of the method speaks for itself.
856  
857 =item B<plot_histogram_3d_surface():>
858  
859 $generator->plot_histogram_3d_surface();
860  
861 This method uses a Perl wrapper for Gnuplot, as provided by the module
862 Graphics::GnuplotIF, for creating a 3D surface plot of the histogram of the random
863 points generated by the module.
864  
865 =item B<plot_histogram_lineplot():>
866  
867 $generator->plot_histogram_lineplot();
868  
869 This creates a 3D line plot display of the histogram of the generated random points.
870  
871 =item B<display_output_histogram_in_terminal_window():>
872  
873 $generator->display_output_histogram_in_terminal_window();
874  
875 Useful for debugging purposes, it displays in the terminal window a two dimensional
876 array of numbers that is the histogram of the random points generated by the module.
877  
878 =back
879  
880 =head1 THE C<examples> DIRECTORY
881  
882 Probably the most useful item in the C<examples> directory is the command-line script
883 C<genRand2D> that can be called simply with two arguments for generating a set of
884 random points. A call to this script looks like
885  
886 genRand2D --histfile your_histogram_file.csv --bbfile your_bounding_box_file.csv
887  
888 where the C<--histfile> option supplies the name of the file that contains a 2D input
889 histogram and the C<--bbfile> option the name of the file that defines the bounding
890 box in the XY-plane. You can also execute the command line
891  
892 genRand2D --help
893  
894 for displaying information as to what is required by the two options for the
895 C<genRand2D> command. The command-line invocation of C<genRand2D> gives you 2000
896 random points that are deposited in a file whose name is printed out in the terminal
897 window in which you execute the command.
898  
899 To become more familiar with all of the different options you can use with this
900 module, you should experiment with the script:
901  
902 generate_random_points.pl
903  
904 You can feed it different 2D histograms --- even made-up 2D histograms --- and look
905 at the histogram of the generated random points to see how well the module is
906 working. Keep in mind, though, if your made-up input histogram has disconnected
907 blobs in it, the random-points that are generated may correspond to just one of the
908 blobs. Since the process of random-point generation involves a random walk, the
909 algorithm may not be able to hop from one blob to another in the input histogram if
910 they are too far apart. As to what exactly you'll get by way of the output histogram
911 would depend on your choice of the width of the proposal density.
912  
913 The C<examples> directory contains the following histogram and bounding-box files
914 for you to get started:
915  
916 hist1.csv bb1.csv
917  
918 hist2.csv bb2.csv
919  
920 If you run the C<generate_random_points.pl> script with the C<hist1.csv> and
921 C<bb1.csv> files, the histogram you get for the 2000 random points generated by the
922 module will look like what you see in the file C<output_histogram_for_hist1.png>. On
923 a Linux machine, you can see this histogram with the usual C<display> command from
924 the ImageMagick library. And if you run C<generate_random_points.pl> script with the
925 C<hist2.csv> and C<bb2.csv> files, you'll see an output histogram that should look
926 like what you see in C<output_histogram_for_hist2.png>.
927  
928 You should also try invoking the command-line calls:
929  
930 genRand2D --histfile hist1.csv --bbfile bb1.csv
931  
932 genRand2D --histfile hist2.csv --bbfile bb2.csv
933  
934  
935 =head1 REQUIRED
936  
937 This module requires the following three modules:
938  
939 List::Util
940 Graphics::GnuplotIF
941 Math::Big
942 Math::Random
943  
944 =head1 EXPORT
945  
946 None by design.
947  
948  
949 =head1 BUGS
950  
951 Please notify the author if you encounter any bugs. When sending email, please place
952 the string 'RandomPointGenerator' in the subject line.
953  
954 =head1 INSTALLATION
955  
956 Download the archive from CPAN in any directory of your choice. Unpack the archive
957 with a command that on a Linux machine would look like:
958  
959 tar zxvf Algorithm-RandomPointGenerator-1.01.tar.gz
960  
961 This will create an installation directory for you whose name will be
962 C<Algorithm-RandomPointGenerator-1.01>. Enter this directory and execute the
963 following commands for a standard install of the module if you have root privileges:
964  
965 perl Makefile.PL
966 make
967 make test
968 sudo make install
969  
970 if you do not have root privileges, you can carry out a non-standard install the
971 module in any directory of your choice by:
972  
973 perl Makefile.PL prefix=/some/other/directory/
974 make
975 make test
976 make install
977  
978 With a non-standard install, you may also have to set your PERL5LIB environment
979 variable so that this module can find the required other modules. How you do that
980 would depend on what platform you are working on. In order to install this module in
981 a Linux machine on which I use tcsh for the shell, I set the PERL5LIB environment
982 variable by
983  
984 setenv PERL5LIB /some/other/directory/lib64/perl5/:/some/other/directory/share/perl5/
985  
986 If I used bash, I'd need to declare:
987  
988 export PERL5LIB=/some/other/directory/lib64/perl5/:/some/other/directory/share/perl5/
989  
990  
991 =head1 THANKS
992  
993 I thank Srezic for pointing out that I needed to downshift the required version of Perl
994 for this module. Fortunately, I had access to an old machine still running Perl
995 5.10.1. The current version is based on my testing the module on that machine.
996  
997 =head1 AUTHOR
998  
999 Avinash Kak, kak@purdue.edu
1000  
1001 If you send email, please place the string "RandomPointGenerator" in your
1002 subject line to get past my spam filter.
1003  
1004 =head1 COPYRIGHT
1005  
1006 This library is free software; you can redistribute it and/or modify it under the
1007 same terms as Perl itself.
1008  
1009 Copyright 2014 Avinash Kak
1010  
1011 =cut
1012  
↑ Summary