| 1 | #!/usr/bin/env perl | ||
| 2 | |||
| 3 | # Gibbs.pm v1.1 | ||
| 4 | # Author: MH Seabolt | ||
| 5 | # Last updated: 2022-03-22 | ||
| 6 | |||
| 7 | # SYNOPSIS: | ||
| 8 | # A Perl object to instantiate a Gibbs motif sampler tailored for biological sequence data. | ||
| 9 | # Constructs an object (the Gibbs sampler) with some data passed to the constructor, | ||
| 10 | # which can then be randomly sampled in order to identify potentially interesting "most mutually similar" | ||
| 11 | # sequence motifs. | ||
| 12 | |||
| 13 | # Note: some of the methods in this class print output directly to the terminal via STDERR. | ||
| 14 | # This can be redirected or captured as desired. | ||
| 15 | |||
| 16 | ################################################################################## | ||
| 17 | # The MIT License | ||
| 18 | # | ||
| 19 | # Copyright (c) 2022 Matthew H. Seabolt | ||
| 20 | # TO DO: | ||
| 21 | # Include a class method to determine the probability of finding a "significant" | ||
| 22 | # motif of length *k* by random chance, given the length of the sequences that | ||
| 23 | # are given to the Gibbs object. This is different from an e-value (e.g. Blast) | ||
| 24 | # since that probability is based on the database size. | ||
| 25 | # | ||
| 26 | # Permission is hereby granted, free of charge, | ||
| 27 | # to any person obtaining a copy of this software and | ||
| 28 | # associated documentation files (the "Software"), to | ||
| 29 | # deal in the Software without restriction, including | ||
| 30 | # without limitation the rights to use, copy, modify, | ||
| 31 | # merge, publish, distribute, sublicense, and/or sell | ||
| 32 | # copies of the Software, and to permit persons to whom | ||
| 33 | # the Software is furnished to do so, | ||
| 34 | # subject to the following conditions: | ||
| 35 | # | ||
| 36 | # The above copyright notice and this permission notice | ||
| 37 | # shall be included in all copies or substantial portions of the Software. | ||
| 38 | # | ||
| 39 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | ||
| 40 | # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES | ||
| 41 | # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. | ||
| 42 | # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR | ||
| 43 | # ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, | ||
| 44 | # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE | ||
| 45 | # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
| 46 | ################################################################################## | ||
| 47 | |||
| 48 | package Gibbs; | ||
| 49 | |||
| 50 | require Exporter; | ||
| 51 | @ISA = qw(Exporter); | ||
| 52 | @EXPORT = qw(); #Import from other packages | ||
| 53 | |||
| 54 | use strict; | ||
| 55 | use warnings; | ||
| 56 | use List::Util qw(sum min max first); | ||
| 57 | use Scalar::Util; | ||
| 58 | use Storable qw(dclone); | ||
| 59 | use Carp; | ||
| 60 | our $AUTOLOAD; | ||
| 61 | use version; our $VERSION = version->declare("v1.1"); | ||
| 62 | |||
| 63 | |||
| 64 | ################################################################################## | ||
| 65 | |||
| 66 | # Class data and methods | ||
| 67 | # Attributes | ||
| 68 | { | ||
| 69 | # _states and _adj are inherited from Markov parent class | ||
| 70 | my %_attribute_properties = ( | ||
| 71 | _k => 3, # the number of iterations for which nothing changing will be considered convergence, Default 3 | ||
| 72 | _seqs => [ ], # an anon array containing all the DNA sequences we are searching/sampling from | ||
| 73 | _motif_len => 7, # the length of the motif we are searching for, Default 7 | ||
| 74 | _alphabet => '', # the set of possible symbols available | ||
| 75 | _samples => [ ], # a list of the samples we pull, will be updated each iteration | ||
| 76 | _profiles => [ ], # a list of the last k profiles, so that we can tell when we've reached convergence | ||
| 77 | _t => '', # the number of DNA sequences | ||
| 78 | _n => '', # the length of the DNA sequences | ||
| 79 | ); | ||
| 80 | |||
| 81 | # Global variable counter | ||
| 82 | my $_count = 0; | ||
| 83 | |||
| 84 | # Return a list of all attributes | ||
| 85 | sub _all_attributes { | ||
| 86 | keys %_attribute_properties; | ||
| 87 | } | ||
| 88 | |||
| 89 | # Return the default value for a given attribute | ||
| 90 | sub _attribute_default { | ||
| 91 | my( $self, $attribute ) = @_; | ||
| 92 | $_attribute_properties{$attribute}; | ||
| 93 | } | ||
| 94 | |||
| 95 | # Manage the count of existing objects | ||
| 96 | sub get_count { | ||
| 97 | $_count; | ||
| 98 | } | ||
| 99 | sub _incr_count { | ||
| 100 | ++$_count; | ||
| 101 | } | ||
| 102 | sub _decr_count { | ||
| 103 | --$_count; | ||
| 104 | } | ||
| 105 | } | ||
| 106 | |||
| 107 | ############################################################ | ||
| 108 | # CONSTRUCTORS # | ||
| 109 | ############################################################ | ||
| 110 | |||
| 111 | # The contructor method | ||
| 112 | # Construct a new graph (my $node = Markov->new() ); | ||
| 113 | # Returns a scalar reference to a | ||
| 114 | sub new { | ||
| 115 | my ( $class, %arg ) = @_; | ||
| 116 | |||
| 117 | # Create the new object | ||
| 118 | my $self = bless {}, $class; | ||
| 119 | |||
| 120 | foreach my $attribute ( $self->_all_attributes() ) { | ||
| 121 | # E.g. attribute = "_name", argument = "name" | ||
| 122 | my ($argument) = ( $attribute =~ /^_(.*)/ ); | ||
| 123 | # If explicitly given | ||
| 124 | if (exists $arg{$argument}) { | ||
| 125 | $self->{$attribute} = $arg{$argument}; | ||
| 126 | } | ||
| 127 | else { | ||
| 128 | $self->{$attribute} = $self->_attribute_default($attribute); | ||
| 129 | } | ||
| 130 | } | ||
| 131 | |||
| 132 | # Confirm that the DNA attribute exists, then check all sequences are the same length | ||
| 133 | if ( not $self->{_seqs} ) { | ||
| 134 | warn "Gibbs->new() WARNING: DNA attribute does not exist!\n"; | ||
| 135 | return; | ||
| 136 | } | ||
| 137 | |||
| 138 | my $all_same_flag = $self->_all_the_same_length( $self->{_seqs} ); | ||
| 139 | if ( $all_same_flag == 0 ) { | ||
| 140 | warn "Gibbs->new() WARNING: DNA sequences are not all the same length!\n"; | ||
| 141 | return; | ||
| 142 | } | ||
| 143 | |||
| 144 | # Set the alphabet set of characters | ||
| 145 | my %Uniques; | ||
| 146 | foreach my $sequence ( @{ $self->{_seqs} } ) { | ||
| 147 | my @seq = split('', $sequence); | ||
| 148 | $Uniques{$_} = 1 foreach ( @seq ); | ||
| 149 | } | ||
| 150 | my @alphabet = keys %Uniques; | ||
| 151 | $self->{_alphabet} = \@alphabet; | ||
| 152 | |||
| 153 | # Set t and n | ||
| 154 | $self->{_t} = scalar @{$self->{_seqs}}; | ||
| 155 | $self->{_n} = length $self->{_seqs}->[0]; | ||
| 156 | |||
| 157 | # All other attributes should have default values set which will at least allow us to run | ||
| 158 | |||
| 159 | # Return the new object | ||
| 160 | $class->_incr_count(); | ||
| 161 | return $self; | ||
| 162 | } | ||
| 163 | |||
| 164 | # The clone method | ||
| 165 | # All attributes are copied from the calling object, unless specifically overriden | ||
| 166 | # Called from an existing object ( Syntax: $cloned_obj = $obj->clone(); ) | ||
| 167 | sub clone { | ||
| 168 | my ( $caller, %arg ) = @_; | ||
| 169 | # Extract the class name from the calling object | ||
| 170 | my $class =ref($caller); | ||
| 171 | |||
| 172 | # Create a new object | ||
| 173 | my $self = bless {}, $class; | ||
| 174 | |||
| 175 | foreach my $attribute ( $self->_all_attributes() ) { | ||
| 176 | my ($argument) = ( $attribute =~ /^_(.*)/ ); | ||
| 177 | |||
| 178 | # If explicitly given | ||
| 179 | if ( exists $arg{$argument} ) { | ||
| 180 | $self->{$attribute} = $arg{$argument}; | ||
| 181 | } | ||
| 182 | |||
| 183 | # Otherwise, copy attribute of new object from the calling object | ||
| 184 | else { | ||
| 185 | $self->{$attribute} = $caller->{$attribute}; | ||
| 186 | } | ||
| 187 | } | ||
| 188 | $self->_incr_count(); | ||
| 189 | return $self; | ||
| 190 | } | ||
| 191 | |||
| 192 | ####################################### | ||
| 193 | # Autoload getters and setters | ||
| 194 | sub AUTOLOAD { | ||
| 195 | my ( $self, $newvalue ) = @_; | ||
| 196 | my ( $operation, $attribute ) = ( $AUTOLOAD =~ /(get|set)(_\w+)$/ ); | ||
| 197 | |||
| 198 | # Is this a legal method name? | ||
| 199 | unless( $operation && $attribute ) { | ||
| 200 | croak "Method name $AUTOLOAD is not in the recognized form (get|set)_attribute\n"; | ||
| 201 | } | ||
| 202 | unless( exists $self->{$attribute} ) { | ||
| 203 | croak "No such attribute $attribute exists in the class ", ref($self); | ||
| 204 | } | ||
| 205 | |||
| 206 | # Turn off strict references to enable "magic" AUTOLOAD speedup | ||
| 207 | no strict 'refs'; | ||
| 208 | |||
| 209 | # AUTOLOAD accessors | ||
| 210 | if( $operation eq 'get' ) { | ||
| 211 | # Install this accessor definition in the symbol table | ||
| 212 | *{$AUTOLOAD} = sub { | ||
| 213 | my ($self) = @_; | ||
| 214 | $self->{$attribute}; | ||
| 215 | }; | ||
| 216 | } | ||
| 217 | # AUTOLOAD mutators | ||
| 218 | elsif( $operation eq 'set' ) { | ||
| 219 | # Set the attribute value | ||
| 220 | $self->{$attribute} = $newvalue; | ||
| 221 | |||
| 222 | # Install this mutator definition in the symbol table | ||
| 223 | *{$AUTOLOAD} = sub { | ||
| 224 | my ($self, $newvalue) = @_; | ||
| 225 | $self->{$attribute} = $newvalue; | ||
| 226 | }; | ||
| 227 | } | ||
| 228 | |||
| 229 | # Turn strict references back on | ||
| 230 | use strict 'refs'; | ||
| 231 | |||
| 232 | # Return the attribute value | ||
| 233 | return $self->{$attribute}; | ||
| 234 | } | ||
| 235 | |||
| 236 | # When an object is no longer being used, garbage collect it and adjust count of existing objects | ||
| 237 | sub DESTROY { | ||
| 238 | my ( $self ) = @_; | ||
| 239 | $self->_decr_count(); | ||
| 240 | } | ||
| 241 | |||
| 242 | ############################################################ | ||
| 243 | # PUBLIC SUBROUTINES # | ||
| 244 | ############################################################ | ||
| 245 | |||
| 246 | # Start a sample counter -- all print statements within this package automatically go to STDERR | ||
| 247 | my $random_gibbs_sample_count = 0; | ||
| 248 | |||
| 249 | # Samples a random set and prints a score | ||
| 250 | sub sample { | ||
| 251 | my ( $self, $nsamples ) = @_; | ||
| 252 | my @motifs; | ||
| 253 | foreach my $i ( 1 .. $nsamples ) { | ||
| 254 | my $sample = $self->_gibbs_sample(); | ||
| 255 | push @motifs, $sample; | ||
| 256 | } | ||
| 257 | my $best_motif = $self->_max_score( \@motifs ); | ||
| 258 | return $best_motif; | ||
| 259 | } | ||
| 260 | |||
| 261 | # These functions are just aliases of sample() above | ||
| 262 | sub gibbs { my ( $self, $nsamples ) = @_; return $self->sample($nsamples); } | ||
| 263 | sub gibbs_sample { my ( $self, $nsamples ) = @_; return $self->sample($nsamples); } | ||
| 264 | sub search { my ( $self, $nsamples ) = @_; return $self->sample($nsamples); } | ||
| 265 | sub gibbs_search { my ( $self, $nsamples ) = @_; return $self->sample($nsamples); } | ||
| 266 | sub sample_motif { my ( $self, $nsamples ) = @_; return $self->sample($nsamples); } | ||
| 267 | sub find_motif { my ( $self, $nsamples ) = @_; return $self->sample($nsamples); } | ||
| 268 | |||
| 269 | |||
| 270 | # Simply prints an array with each element on a new line | ||
| 271 | sub print_matrix { | ||
| 272 | my ( $self, $list ) = @_; | ||
| 273 | print STDERR join("\n", @{$list}); | ||
| 274 | } | ||
| 275 | |||
| 276 | # Show where the motif is in each sequence, but nicely :) | ||
| 277 | sub show_motif { | ||
| 278 | my ( $self, $starting_positions ) = @_; | ||
| 279 | for ( my $i=0; $i < $self->{_t}; $i++ ) { | ||
| 280 | my $sequence = $self->{_seqs}->[$i]; | ||
| 281 | my $starting_position = $starting_positions->[$i]; | ||
| 282 | my $a = lc ( substr($sequence, 0, $starting_position) ); | ||
| 283 | my $b = uc ( substr($sequence, $starting_position, $self->{_motif_len} ) ); | ||
| 284 | my $c = lc ( substr($sequence, ($starting_position + $self->{_motif_len})) ); | ||
| 285 | print STDERR "$a$b$c\n"; | ||
| 286 | } | ||
| 287 | } | ||
| 288 | |||
| 289 | # Print a given profile to an output file | ||
| 290 | sub print_profile { | ||
| 291 | my ( $self, $filename, $mode ) = @_; | ||
| 292 | my %Profile = %{ $self->{_profiles}->[-1] }; | ||
| 293 | |||
| 294 | # Sanity check | ||
| 295 | $mode = ( $mode && $mode eq ">>" )? ">>" : ">"; | ||
| 296 | $filename = ( $filename )? $filename : "--"; | ||
| 297 | |||
| 298 | # Set the output filehandle | ||
| 299 | my $succout = open( OUT, "$mode", "$filename" ) if ( $filename ne "--" ); | ||
| 300 | my $fhout; | ||
| 301 | if ( $succout ) { $fhout = *OUT; } | ||
| 302 | else { $fhout = *STDOUT; } | ||
| 303 | |||
| 304 | # Print to filehandle | ||
| 305 | print $fhout "$_\t", join("\t", @{$Profile{$_}}, "\n") foreach ( sort keys %Profile ); | ||
| 306 | close $fhout if ( $succout ); | ||
| 307 | } | ||
| 308 | |||
| 309 | ############################################################ | ||
| 310 | # SANITY-CHECKING PROBABILITY SUBROUTINES # | ||
| 311 | ############################################################ | ||
| 312 | |||
| 313 | # Additional public utility functions to determine the probability that a random, unrelated kmer of size k | ||
| 314 | # is present in M of the N sequences of equal length L (and an alphabet of size s), potentially leading us to misleading results. | ||
| 315 | # | ||
| 316 | # Here, we are making the simplifying assumptions that the frequency distribution of kmers is Poisson, | ||
| 317 | # and the distribution of symbols in the alphabet are independent and identical (IID). | ||
| 318 | |||
| 319 | # Returns the minimum (suggested) sequence length such that the probability of a kmer of size k occuring in M sequences is less than or equal to a given probability p. | ||
| 320 | # This is useful to help determine if the sequences being searched for motifs are reasonably likely to contain random, confounding motifs that are likely to just be "noise". | ||
| 321 | sub minimum_suggested_sequence_length { | ||
| 322 | my ( $self, $prob, $m, $k, $s ) = @_; | ||
| 323 | |||
| 324 | # Sanity check incoming parameters | ||
| 325 | $k = ( $k && $k > 0 )? $k : $self->{_motif_len}; # Set $k to the kmer size in the Gibbs object if this parameter is not given | ||
| 326 | $m = ( $m && $m > 0 )? $m : $self->{_t}; # Set $m to the total number of sequences if this parameter is not given | ||
| 327 | $s = ( $s && $s > 0 )? $s : scalar @{$self->{_alphabet}}; | ||
| 328 | $prob = ( $prob && $prob > 0.0 && $prob <= 1.0 )? $prob : 0.01; # Set $prob to a default value of 0.01 | ||
| 329 | my $pK = (1 / $s)**$k; # Probability of any random k-sized kmer using the given alphabet | ||
| 330 | |||
| 331 | # Compute minimum suggested length at the given probability threshold | ||
| 332 | my $length = ($k-1) - $s**$k * log(1 - $prob**(1/$m)); | ||
| 333 | return int $length; | ||
| 334 | } | ||
| 335 | |||
| 336 | # Returns the Poisson probability of identifying a random, non-target kmer of length k from M sequences | ||
| 337 | sub nontarget_motif_probability { | ||
| 338 | my ( $self, $m, $k, $L, $s ) = @_; | ||
| 339 | |||
| 340 | # Sanity check incoming parameters | ||
| 341 | $k = ( $k && $k > 0 && $k <= $self->{_n} )? $k : $self->{_motif_len}; # Set $k to the kmer size in the Gibbs object if this parameter is not given | ||
| 342 | $m = ( $m && $m > 0 && $m <= $self->{_t} )? $m : $self->{_t}; # Set $m to the total number of sequences if this parameter is not given | ||
| 343 | $s = ( $s && $s > 0 )? $s : scalar @{$self->{_alphabet}}; | ||
| 344 | $L = ( $L && $L > 0 )? $L : $self->{_n}; | ||
| 345 | |||
| 346 | # Define some additional parameters for Poisson probability | ||
| 347 | my $pK = (1 / $s)**$k; # Probability of any random k-sized kmer using the given alphabet | ||
| 348 | my $lambda = ($L - ($k-1))*$pK; # Poisson parameter lambda | ||
| 349 | |||
| 350 | # Compute Poisson probability of encountering a random motif under the given parameters | ||
| 351 | my $prob = (1 - exp(-$lambda))**$m; | ||
| 352 | return sprintf("%3.4f", $prob); | ||
| 353 | } | ||
| 354 | |||
| 355 | ############################################################ | ||
| 356 | # PRIVATE SUBROUTINES # | ||
| 357 | ############################################################ | ||
| 358 | |||
| 359 | # Returns TRUE (1) if everything in a list has the same length as everything else | ||
| 360 | sub _all_the_same_length { | ||
| 361 | my ( $self, $list ) = @_; | ||
| 362 | for ( my $i=0; $i < scalar @{$list}; $i++ ) { | ||
| 363 | if ( length $list->[$i] != length $list->[0] ) { | ||
| 364 | return 0; | ||
| 365 | } | ||
| 366 | } | ||
| 367 | # If we make it this far, then everything is the same | ||
| 368 | return 1; | ||
| 369 | } | ||
| 370 | |||
| 371 | # Returns TRUE (1) if everything in a list has the same value as everything else | ||
| 372 | sub _all_the_same_value { | ||
| 373 | my ( $self, $list ) = @_; | ||
| 374 | foreach my $item ( @{$list} ) { | ||
| 375 | if ( $item != $list->[0] || $item ne $list->[0] ) { | ||
| 376 | return 0; | ||
| 377 | } | ||
| 378 | } | ||
| 379 | # If we make it this far, then everything is the same | ||
| 380 | return 1; | ||
| 381 | } | ||
| 382 | |||
| 383 | # Returns TRUE (1) if everything in a list has the same value as everything else | ||
| 384 | # This is more of a quick-and-dirty comparison, but it should get the job done well enough. | ||
| 385 | sub _all_the_same_hashes { | ||
| 386 | my ( $self, $list ) = @_; | ||
| 387 | my @ref_keys = sort keys %{ $list->[0] }; | ||
| 388 | |||
| 389 | # Compare the remaining hashes in the list to the reference hash | ||
| 390 | for ( my $h=0; $h < scalar @{$list}; $h++ ) { | ||
| 391 | my @keys = sort keys %{$list->[$h]}; | ||
| 392 | |||
| 393 | # Check the number of keys and number of values | ||
| 394 | return 0 if ( scalar @ref_keys != scalar @keys ); | ||
| 395 | |||
| 396 | # Compare the values of the hashes | ||
| 397 | foreach my $key ( @ref_keys ) { | ||
| 398 | return 0 if ( not exists $list->[$h]->{$key} ); | ||
| 399 | my @values = @{ $list->[$h]->{$key} }; | ||
| 400 | my @ref_values = @{ $list->[0]->{$key} }; | ||
| 401 | for ( my $v=0; $v < scalar @ref_values; $v++ ) { | ||
| 402 | return 0 if ( $ref_values[$v] != $values[$v] ); | ||
| 403 | } | ||
| 404 | } | ||
| 405 | } | ||
| 406 | # If we make it this far, then everything is the same | ||
| 407 | return 1; | ||
| 408 | } | ||
| 409 | |||
| 410 | # Checks if the most recent *k* profiles have converged | ||
| 411 | sub _check_convergence { | ||
| 412 | my ( $self ) = @_; | ||
| 413 | my $k = $self->get_k; | ||
| 414 | my @last_k_profiles = @{$self->{_profiles}}; | ||
| 415 | if ( scalar @last_k_profiles < $k ) { | ||
| 416 | return 0; | ||
| 417 | } | ||
| 418 | else { | ||
| 419 | return $self->_all_the_same_hashes( \@last_k_profiles ); | ||
| 420 | } | ||
| 421 | } | ||
| 422 | |||
| 423 | # Samples a random set and prints a score | ||
| 424 | sub sample_random_starting_positions { | ||
| 425 | my ( $self, $nsamples ) = @_; | ||
| 426 | my @motifs; | ||
| 427 | foreach my $i ( 1 .. $nsamples ) { | ||
| 428 | my $sample = $self->gibbs_sample(); | ||
| 429 | push @motifs, $sample; | ||
| 430 | } | ||
| 431 | my $best_motif = $self->max_score( \@motifs ); | ||
| 432 | return $best_motif; | ||
| 433 | } | ||
| 434 | |||
| 435 | # Randomly selects starting positions in each string, disallowing any starting positions | ||
| 436 | # that would cause the motif substring to overflow the length of the sequence. | ||
| 437 | sub _get_starting_positions { | ||
| 438 | my ( $self ) = @_; | ||
| 439 | my @start_pos; | ||
| 440 | |||
| 441 | foreach my $i ( 1 .. $self->{_t} ) { | ||
| 442 | push @start_pos, int(rand($self->{_n} - $self->{_motif_len})); | ||
| 443 | } | ||
| 444 | return \@start_pos; | ||
| 445 | } | ||
| 446 | |||
| 447 | # Generates a normalized profile from the sampled motif matrix | ||
| 448 | sub _create_profile { | ||
| 449 | my ( $self, $matrix ) = @_; | ||
| 450 | my %Profile = (); | ||
| 451 | my $alphabet = $self->{_alphabet}; | ||
| 452 | |||
| 453 | # Initialize a hash where keys are each possible symbol in our alphabet, | ||
| 454 | # and values are an anon array, where each index represents a position in the sampled motif | ||
| 455 | foreach my $nucleotide ( @{$alphabet} ) { | ||
| 456 | for ( my $i=0; $i < $self->{_motif_len}; $i++ ) { | ||
| 457 | push @{$Profile{$nucleotide}}, 0; | ||
| 458 | } | ||
| 459 | } | ||
| 460 | |||
| 461 | # Count the occurences of each symbol | ||
| 462 | for ( my $i=0; $i < $self->{_t}; $i++ ) { | ||
| 463 | for ( my $j=0; $j < $self->{_motif_len}; $j++ ) { | ||
| 464 | $Profile{ $matrix->[$i]->[$j] }->[$j] += 1; | ||
| 465 | } | ||
| 466 | } | ||
| 467 | |||
| 468 | # Normalize the counts | ||
| 469 | foreach my $nucleotide ( @{$alphabet} ) { | ||
| 470 | for ( my $j=0; $j < $self->{_motif_len}; $j++ ) { | ||
| 471 | $Profile{$nucleotide}->[$j] /= $self->{_t}; | ||
| 472 | $Profile{$nucleotide}->[$j] = sprintf "%3.3f", $Profile{$nucleotide}->[$j]; | ||
| 473 | } | ||
| 474 | } | ||
| 475 | |||
| 476 | return \%Profile; | ||
| 477 | } | ||
| 478 | |||
| 479 | # Normalizes a list of numerical values | ||
| 480 | sub _normalize { | ||
| 481 | my ( $self, $dist ) = @_; | ||
| 482 | my $probabilities; | ||
| 483 | my $total = sum @{$dist}; | ||
| 484 | foreach my $probability ( @{$dist} ) { | ||
| 485 | push @{$probabilities}, ($probability/$total); | ||
| 486 | } | ||
| 487 | return $probabilities; | ||
| 488 | } | ||
| 489 | |||
| 490 | # Compute the joint probability of sampling a particular profile | ||
| 491 | sub _get_generation_probability { | ||
| 492 | my ( $self, $lmer, $profile ) = @_; | ||
| 493 | my $prob = 1; # Initialize to 1 for easy multiplication | ||
| 494 | |||
| 495 | # The probability of the whole string is the product of the probability of each letter being generated in its position over all letters. | ||
| 496 | my @profile_probs; | ||
| 497 | for ( my $i=0; $i < $self->{_motif_len}; $i++ ) { | ||
| 498 | push @profile_probs, $profile->{ $lmer->[$i] }->[$i]; | ||
| 499 | } | ||
| 500 | |||
| 501 | # It's possible that everything is 0. Return 0 if that's the case | ||
| 502 | return 0 if ( sum @profile_probs == 0 ); | ||
| 503 | |||
| 504 | # Otherwise, find the smallest probability greater than 0 | ||
| 505 | my @filter = grep { $_ != 0 } @profile_probs; | ||
| 506 | my $min_prob = min @filter; | ||
| 507 | |||
| 508 | # Compute the joint probability | ||
| 509 | foreach my $profile_prob ( @profile_probs ) { | ||
| 510 | if ( $profile_prob == 0 ) { | ||
| 511 | $prob *= ( $min_prob * (10**-10) ); # We are using a very tiny number to approximate 0 here, since we may encounter zeros that we dont want to actually multiply by. | ||
| 512 | } | ||
| 513 | else { | ||
| 514 | $prob *= $profile_prob; | ||
| 515 | } | ||
| 516 | } | ||
| 517 | return $prob; | ||
| 518 | } | ||
| 519 | |||
| 520 | # Reads a profile and returns the consensus motif | ||
| 521 | sub _get_motif { | ||
| 522 | my ( $self, $profile ) = @_; | ||
| 523 | my $alphabet = $self->{_alphabet}; | ||
| 524 | my @motif; | ||
| 525 | |||
| 526 | # Get the most probable letter at each position in the profile | ||
| 527 | for ( my $i=0; $i < $self->{_motif_len}; $i++ ) { | ||
| 528 | my @candidates; | ||
| 529 | foreach my $letter ( @{$alphabet} ) { | ||
| 530 | my @tmp = ( $letter, $profile->{$letter}->[$i] ); | ||
| 531 | push @candidates, \@tmp; | ||
| 532 | } | ||
| 533 | push @motif, $self->_max_score( \@candidates )->[0]; | ||
| 534 | } | ||
| 535 | # Join the motif array into a string and return | ||
| 536 | return join("", @motif); | ||
| 537 | } | ||
| 538 | |||
| 539 | # Calculate the score of a given profile | ||
| 540 | sub _get_profile_score { | ||
| 541 | my ( $self, $profile ) = @_; | ||
| 542 | my @list; | ||
| 543 | |||
| 544 | # The score of the profile is the sum of the most frequent letter in every position in the profile's indices | ||
| 545 | # For each position in the motif, get the column from the profile. | ||
| 546 | # Then take the maximum value of the column and sum it with all the other colMaxes. | ||
| 547 | for (my $i=0; $i < $self->{_motif_len}; $i++ ) { | ||
| 548 | my @col; | ||
| 549 | foreach my $freq ( values %{$profile} ) { | ||
| 550 | push @col, $freq->[$i]; | ||
| 551 | } | ||
| 552 | push @list, max @col; | ||
| 553 | } | ||
| 554 | return sum @list; | ||
| 555 | } | ||
| 556 | |||
| 557 | # Returns the maximum valued tuple from a list of tuples, where the value to maximize is the second element in the tuple. | ||
| 558 | sub _max_score { | ||
| 559 | my ( $self, $tuples ) = @_; | ||
| 560 | my $max = -10**10; # Approximate a very low number as the initial max | ||
| 561 | my $tup; | ||
| 562 | |||
| 563 | for ( my $i=0; $i < scalar @{$tuples}; $i++ ) { | ||
| 564 | if ( $tuples->[$i]->[1] >= $max ) { | ||
| 565 | $max = $tuples->[$i]->[1]; | ||
| 566 | $tup = $tuples->[$i]; | ||
| 567 | } | ||
| 568 | else { | ||
| 569 | next; | ||
| 570 | } | ||
| 571 | } | ||
| 572 | return $tup; | ||
| 573 | } | ||
| 574 | |||
| 575 | # This package's way of sampling a normalized distribution | ||
| 576 | sub _choose_from_distribution { | ||
| 577 | my ( $self, $dist ) = @_; | ||
| 578 | my $rand = rand(); # Gets a random value between 0 and 1 | ||
| 579 | |||
| 580 | # Return the index of a randomly sampled element in the distribution | ||
| 581 | for ( my $p=0; $p < scalar @{$dist}; $p++ ) { | ||
| 582 | $rand -= $dist->[$p]; | ||
| 583 | if ( $rand <= 0 ) { | ||
| 584 | return $p; | ||
| 585 | } | ||
| 586 | # Otherwise, keep going | ||
| 587 | } | ||
| 588 | # If we got here, then there are problems :) | ||
| 589 | warn "Gibbs::choose_from_distribution WARNING: Choosing from a distribution is hard. Did you make sure the distribution was normalised?\n"; | ||
| 590 | return; | ||
| 591 | } | ||
| 592 | |||
| 593 | # Randomly select an element from a list and return both the element and the randomly chosen index | ||
| 594 | sub _random_choice { | ||
| 595 | my ( $self, $list ) = @_; | ||
| 596 | my $idx = int(rand(scalar @{$list})); | ||
| 597 | return ( $list->[$idx], $idx ); | ||
| 598 | } | ||
| 599 | |||
| 600 | |||
| 601 | #################################### | ||
| 602 | # The actual Gibbs sampling function | ||
| 603 | sub _gibbs_sample { | ||
| 604 | my ( $self, $motif_k ) = @_; | ||
| 605 | $random_gibbs_sample_count++; | ||
| 606 | |||
| 607 | # Extra quality-of-life addition: | ||
| 608 | # If $motif_k is passed as an argument, update this parameter in the object. | ||
| 609 | if ( $motif_k && int($motif_k) == $motif_k && $motif_k > 0 && $motif_k < $self->{_n} ) { | ||
| 610 | $self->{_motif_len} = $motif_k; | ||
| 611 | } | ||
| 612 | |||
| 613 | |||
| 614 | # Get starting positions and reset our lists of samples and profiles | ||
| 615 | my $starting_positions = $self->_get_starting_positions; | ||
| 616 | $self->{_samples} = [ ]; | ||
| 617 | $self->{_profiles} = [ ]; | ||
| 618 | |||
| 619 | my $c = 0; | ||
| 620 | |||
| 621 | while ( $self->_check_convergence != 1 ) { | ||
| 622 | # Generate new lmers that come from starting positions | ||
| 623 | my $tuples; | ||
| 624 | my $DNA = $self->{_seqs}; | ||
| 625 | for ( my $i=0; $i < $self->{_t}; $i++ ) { | ||
| 626 | my $sub = substr( $self->{_seqs}->[$i], $starting_positions->[$i], $self->{_motif_len} ); | ||
| 627 | my @submotif = split('', $sub); | ||
| 628 | push @{$tuples}, \@submotif; | ||
| 629 | } | ||
| 630 | |||
| 631 | # Choose a sequence from the DNA sequences randomly, | ||
| 632 | # then remove it | ||
| 633 | |||
| 634 | my ( $sequence, $index ) = $self->_random_choice( $self->{_seqs} ); | ||
| 635 | splice( @{$self->{_seqs}}, $index, 1); # Careful here, make sure that we are assigning the spliced list correctly to $self->DNA | ||
| 636 | |||
| 637 | # Make a new profile from the starting positions and save it for convergence checking | ||
| 638 | my %Profile = %{ $self->_create_profile( $tuples ) }; | ||
| 639 | push @{$self->{_profiles}}, \%Profile; | ||
| 640 | |||
| 641 | # If saving this profile overflows the profile buffer, then get rid of the odlest profile in it | ||
| 642 | if ( scalar @{$self->{_profiles}} > $self->{_k} ) { | ||
| 643 | my $trash = shift @{$self->{_profiles}}; | ||
| 644 | } | ||
| 645 | |||
| 646 | # This is just to check how many loops is going and prints the profile itself | ||
| 647 | $c++; | ||
| 648 | print STDERR "\n----------------------------------------- \n"; | ||
| 649 | print STDERR "Sample: $random_gibbs_sample_count Conv.Iter: $c \n"; | ||
| 650 | print STDERR "----------------------------------------- \n"; | ||
| 651 | print STDERR "$_\t", join("\t", @{$Profile{$_}}, "\n") foreach ( sort keys %Profile ); | ||
| 652 | |||
| 653 | |||
| 654 | |||
| 655 | # For each position i in the chosen DNA sequence, find the probability | ||
| 656 | # that the lmer starting in this position is generated by the profile | ||
| 657 | my $probs_ref; | ||
| 658 | for ( my $i=0; $i < ($self->{_n}-$self->{_motif_len}); $i++ ) { | ||
| 659 | my $lmer = substr($sequence, $i, $self->{_motif_len}); | ||
| 660 | my @lmer = split('', $lmer); | ||
| 661 | my $prob = $self->_get_generation_probability( \@lmer, \%Profile ); | ||
| 662 | push @{$probs_ref}, $prob; | ||
| 663 | } | ||
| 664 | my $probs = $self->_normalize( $probs_ref ); | ||
| 665 | |||
| 666 | # Get a new starting index, then put the sequence we spliced out earlier back where it belongs | ||
| 667 | my $new_starting_index = $self->_choose_from_distribution( $probs ); | ||
| 668 | $starting_positions->[$index] = $new_starting_index; | ||
| 669 | splice( @{$self->{_seqs}}, $index, 0, $sequence ); | ||
| 670 | |||
| 671 | # Get the consensus motif and profile score | ||
| 672 | my $motif = $self->_get_motif( \%Profile ); | ||
| 673 | my $score = $self->_get_profile_score( \%Profile ); | ||
| 674 | |||
| 675 | # Add the motif and score to $self->{_samples} | ||
| 676 | my @tmp = ( $motif, $score ); | ||
| 677 | push @{$self->{_samples}}, \@tmp; | ||
| 678 | |||
| 679 | # At this point, the loop will automatically check for convergence before the next iteration. | ||
| 680 | } | ||
| 681 | |||
| 682 | # Of all the samples we took, choose the best one. # Hopefully it's the one we converged to, but may not be... | ||
| 683 | my $best_motif = $self->_max_score( $self->{_samples} ); | ||
| 684 | return $best_motif; # $best_motif is actually a tuple array of ( STR motif and FLOAT score ), we only want to return the STR motif. | ||
| 685 | } | ||
| 686 | |||
| 687 | # Last line in the class must always be 1! | ||
| 688 | # We're done! | ||
| 689 | 1; |