This file is indexed.

/usr/share/perl5/Grinder/KmerCollection.pm is in grinder 0.5.3-3.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
# This file is part of the Grinder package, copyright 2009,2010,2011,2012
# Florent Angly <florent.angly@gmail.com>, under the GPLv3 license


package Grinder::KmerCollection;

=head1 NAME

Grinder::KmerCollection - A collection of kmers from sequences

=head1 SYNOPSIS

  my $col = Grinder::KmerCollection->new( -k    => 10,
                                          -file => 'seqs.fa' );

=head1 DESCRIPTION

Manage a collection of kmers found in various sequences. Store information about
what sequence a kmer was found in and its starting position on the sequence.

=head1 AUTHOR

Florent Angly <florent.angly@gmail.com>

=head1 APPENDIX

The rest of the documentation details each of the object
methods. Internal methods are usually preceded with a _

=cut


use strict;
use warnings;
use Grinder;
use Bio::SeqIO;

use base qw(Bio::Root::Root); # using throw() and _rearrange() methods


=head2 new

 Title   : new
 Usage   : my $col = Grinder::KmerCollection->new( -k => 10, -file => 'seqs.fa', -revcom => 1 );
 Function: Build a new kmer collection
 Args    : -k        set the kmer length (default: 10 bp)
           -revcom   count kmers before and after reverse-complementing sequences
                     (default: 0)
           -seqs     count kmers in the provided arrayref of sequences (Bio::Seq
                     or Bio::SeqFeature objects)
           -ids      if specified, index the sequences provided to -seq using the
                     the IDs in this arrayref instead of using the sequences
                     $seq->id() method
           -file     count kmers in the provided file of sequences
           -weights  if specified, assign the abundance of each sequence from the
                     values in this arrayref

 Returns : Grinder::KmerCollection object

=cut

sub new {
   my ($class, @args) = @_;
   my $self = $class->SUPER::new(@args);
   my($k, $revcom, $seqs, $ids, $file, $weights) =
     $self->_rearrange([qw(K REVCOM SEQS IDS FILE WEIGHTS)], @args);

   $self->k( defined $k ? $k : 10 );

   $self->weights($weights)     if defined $weights;
   $self->add_seqs($seqs, $ids) if defined $seqs;
   $self->add_file($file)       if defined $file;

   return $self;
}


=head2 k

 Usage   : $col->k;
 Function: Get the length of the kmers
 Args    : None
 Returns : Positive integer

=cut

sub k {
   my ($self, $val) = @_;
   if ($val) {
      if ($val < 1) {
         $self->throw("Error: The minimum kmer length is 1 but got $val\n");
      }
      $self->{'k'} = $val;
   }
   return $self->{'k'};
}


=head2 weights

 Usage   : $col->weights({'seq1' => 3, 'seq10' => 0.45});
 Function: Get or set the weight of each sequence. Each sequence is given a
           weight of 1 by default.
 Args    : hashref where the keys are sequence IDs and the values are the weight
           of the corresponding (e.g. their relative abundance)
 Returns : Grinder::KmerCollection object

=cut

sub weights {
   my ($self, $val) = @_;
   if ($val) {
      $self->{'weights'} = $val;
   }
   return $self->{'weights'};
}


=head2 collection_by_kmer

 Usage   : $col->collection_by_kmer;
 Function: Get the collection of kmers, indexed by kmer
 Args    : None
 Returns : A hashref of hashref of arrayref:
              hash->{kmer}->{ID of sequences with this kmer}->[starts of kmer on sequence]

=cut

sub collection_by_kmer {
   my ($self, $val) = @_;
   if ($val) {
      $self->{'collection_by_kmer'} = $val;
   }
   return $self->{'collection_by_kmer'};
}


=head2 collection_by_seq

 Usage   : $col->collection_by_seq;
 Function: Get the collection of kmers, indexed by sequence ID
 Args    : None
 Returns : A hashref of hashref of arrayref:
              hash->{ID of sequences with this kmer}->{kmer}->[starts of kmer on sequence]

=cut

sub collection_by_seq {
   my ($self, $val) = @_;
   if ($val) {
      $self->{'collection_by_seq'} = $val;
   }
   return $self->{'collection_by_seq'};
}


#==============================================================================#


=head2 add_file

 Usage   : $col->add_file('seqs.fa');
 Function: Process the kmers in the given file of sequences.
 Args    : filename
 Returns : Grinder::KmerCollection object

=cut

sub add_file {
   my ($self, $file) = @_;
   my $in = Bio::SeqIO->new( -file => $file );
   while (my $seq = $in->next_seq) {
      $self->add_seqs([ $seq ]);
   }
   $in->close;
   return $self;
}


=head2 add_seqs

 Usage   : $col->add_seqs([$seq1, $seq2]);
 Function: Process the kmers in the given sequences.
 Args    : * arrayref of Bio::Seq or Bio::SeqFeature objects
           * arrayref of IDs to use for the indexing of the sequences
 Returns : Grinder::KmerCollection object

=cut

sub add_seqs {
   my ($self, $seqs, $ids) = @_;
   my $col_by_kmer = $self->collection_by_kmer || {};
   my $col_by_seq  = $self->collection_by_seq  || {};
   my $i = 0;
   for my $seq (@$seqs) {
      my $kmer_counts = $self->_find_kmers($seq);
      while ( my ($kmer, $positions) = each %$kmer_counts ) {
         my $seq_id;
         if (defined $ids) {
           $seq_id = $$ids[$i];
         } else {
           $seq_id = $seq->id;
         }
         $col_by_kmer->{$kmer}->{$seq_id} = $positions;
         $col_by_seq->{$seq_id}->{$kmer}  = $positions;
      }
      $i++;
   }
   $self->collection_by_kmer($col_by_kmer);
   $self->collection_by_seq($col_by_seq);
   return $self;
}


=head2 filter_rare

 Usage   : $col->filter_rare( 2 );
 Function: Remove kmers occurring at less than the (weighted) abundance specified
 Args    : integer
 Returns : Grinder::KmerCollection object

=cut

sub filter_rare {
   my ($self, $min_num) = @_;
   my $changed = 0;
   my $col_by_kmer = $self->collection_by_kmer;
   my $col_by_seq  = $self->collection_by_seq;
   while ( my ($kmer, $sources) = each %$col_by_kmer ) {
      my $count = $self->_sum_from_sources( $sources );
      if ($count < $min_num) {
        # Remove this kmer
        $changed = 1;
        delete $col_by_kmer->{$kmer};
        while ( my ($seq, $seq_kmers) = each %$col_by_seq ) {
          delete $seq_kmers->{$kmer};
          delete $col_by_seq->{$seq} if keys %{$seq_kmers} == 0;
        }
      }
   }
   if ($changed) {
     $self->collection_by_kmer( $col_by_kmer );
     $self->collection_by_seq( $col_by_seq );
   }
   return $self;
}


=head2 filter_shared

 Usage   : $col->filter_shared( 2 );
 Function: Remove kmers occurring in less than the number of sequences specified
 Args    : integer
 Returns : Grinder::KmerCollection object

=cut

sub filter_shared {
   my ($self, $min_shared) = @_;
   my $changed = 0;
   my $col_by_kmer = $self->collection_by_kmer;
   my $col_by_seq  = $self->collection_by_seq;
   while ( my ($kmer, $sources) = each %$col_by_kmer ) {
      my $num_shared = scalar keys %$sources;
      if ($num_shared < $min_shared) {
        $changed = 1;
        delete $col_by_kmer->{$kmer};
        while ( my ($seq, $seq_kmers) = each %$col_by_seq ) {
          delete $seq_kmers->{$kmer};
          delete $col_by_seq->{$seq} if keys %{$seq_kmers} == 0;
        }
      }
   }
   if ($changed) {
     $self->collection_by_kmer( $col_by_kmer );
     $self->collection_by_seq( $col_by_seq );
   }
   return $self;
}


=head2 counts

 Usage   : $col->counts
 Function: Calculate the total count of each kmer. Counts are affected by the
           weights given to the sequences.
 Args    : * restrict sequences to search to specified sequence ID (optional)
           * starting position from which counting should start (optional)
           * 0 to report counts (default), 1 to report frequencies (normalize to 1)
 Returns : * arrayref of the different kmers
           * arrayref of the corresponding total counts

=cut

sub counts {
   my ($self, $id, $start, $freq) = @_;
   my $kmers;
   my $counts;
   my $total = 0;
   my $col_by_kmer = $self->collection_by_kmer;
   while ( my ($kmer, $sources) = each %$col_by_kmer ) {
      my $count = $self->_sum_from_sources( $sources, $id, $start );
      if ($count > 0) {
         push @$kmers, $kmer;
         push @$counts, $count;
         $total += $count;
      }
   }
   if ($freq && $total) {
     $counts = Grinder::normalize($counts, $total);
   }
   return $kmers, $counts;
}


=head2 sources

 Usage   : $col->sources()
 Function: Return the sources of a kmer and their (weighted) abundance.
 Args    : * kmer to get the sources of
           * sources to exclude from the results (optional)
           * 0 to report counts (default), 1 to report frequencies (normalize to 1)
 Returns : * arrayref of the different sources
           * arrayref of the corresponding total counts
           If the kmer requested does not exist, the array will be empty.

=cut

sub sources {
   my ($self, $kmer, $excl, $freq) = @_;

   if (not defined $kmer) {
      die "Error: Need to provide a kmer to sources().\n";
   }

   my $sources = [];
   my $counts = [];
   my $total = 0;
   my $kmer_sources = $self->collection_by_kmer->{$kmer};

   if (defined $kmer_sources) {
      while ( my ($source, $positions) = each %$kmer_sources ) {
         if ( (defined $excl) && ($source eq $excl) ) {
           next;
         }
         push @$sources, $source;
         my $weight = (defined $self->weights) ? ($self->weights->{$source} || 0) : 1;
         my $count  = $weight * scalar @$positions;
         push @$counts, $count;
         $total += $count;
      }
      if ($freq) {
         $counts = Grinder::normalize($counts, $total) if $total > 0;
      }
   }

   return $sources, $counts;
}


=head2 kmers

 Usage   : $col->kmers('seq1');
 Function: This is the inverse of sources(). Return the kmers found in a sequence
           (given its ID) and their (weighted) abundance.
 Args    : * sequence ID to get the kmers of
           * 0 to report counts (default), 1 to report frequencies (normalize to 1)
 Returns : * arrayref of sequence IDs
           * arrayref of the corresponding total counts
           If the sequence ID requested does not exist, the arrays will be empty.
=cut

sub kmers {
   my ($self, $seq_id, $freq) = @_;
   my $kmers = [];
   my $counts = [];
   my $total = 0;
   my $seq_kmers = $self->collection_by_seq->{$seq_id};

   if (defined $seq_kmers) {
      while ( my ($kmer, $positions) = each %$seq_kmers ) {
         push @$kmers, $kmer;
         my $weight = (defined $self->weights) ? ($self->weights->{$seq_id} || 0) : 1;
         my $count  = $weight * scalar @$positions;
         push @$counts, $count;
         $total += $count;
      }
      $counts = Grinder::normalize($counts, $total) if $freq;
   }

   return $kmers, $counts;
}


=head2 positions

 Usage   : $col->positions()
 Function: Return the positions of the given kmer on a given sequence. An error
           is reported if the kmer requested does not exist
 Args    : * desired kmer
           * desired sequence with this kmer
 Returns : Arrayref of the different positions. The arrays will be empty if the
           desired combination of kmer and sequence was not found.

=cut

sub positions {
   my ($self, $kmer, $source) = @_;
   my $kmer_positions = [];
   my $kmer_sources = $self->collection_by_kmer->{$kmer};
   if (defined $kmer_sources) {
      $kmer_positions = $kmer_sources->{$source} || [];
   }
   return $kmer_positions;
}



#======== Internals ===========================================================#


sub _find_kmers {
   # Find all kmers of size k in a sequence (Bio::Seq or Bio::SeqFeature) and
   # return a hashref where the keys are the kmers and the values are the
   # positions of the kmers in the sequences.
   my ($self, $seq) = @_;
   my $k = $self->k;
   my $seq_str;
   if ($seq->isa('Bio::PrimarySeqI')) {
      $seq_str = $seq->seq;
   } elsif ($seq->isa('Bio::SeqFeatureI')) {
      $seq_str = $seq->seq->seq;
   } else {
      $self->throw('Error: Input sequence is not a Bio::SeqI or Bio::SeqFeatureI'.
         ' compliant object');
   }
   $seq_str = uc $seq_str; # case-insensitive
   my $seq_len = length $seq_str;
   my $hash = {};
   for (my $i = 0; $i <= $seq_len - $k ; $i++) {
      my $kmer = substr $seq_str, $i, $k;
      push @{$hash->{$kmer}}, $i + 1;
   }
   return $hash;
}


sub _sum_from_sources {
   # Calculate the number of (weighted) occurences of a kmer. An optional
   # sequence ID and start position to restrict the kmers can be specified.
   my ($self, $sources, $id, $start) = @_;
   $start ||= 1;
   my $count = 0;

   if (defined $id) {
      my $new_sources;
      $new_sources->{$id} = $sources->{$id};
      $sources = $new_sources;
   }

   while ( my ($source, $positions) = each %$sources ) {
      for my $position (@$positions) {
         if ($position >= $start) {
            my $weight = (defined $self->weights) ? ($self->weights->{$source} || 0) : 1;
            $count += $weight;
         }
      }
   }
   return $count;
}


1;