#! /usr/bin/env perl

# BioPerl script bc_use_repr_id
#
# Please direct questions and support issues to <bioperl-l@bioperl.org>
#
# Copyright Florent Angly <florent.angly@gmail.com>
#
# You may distribute this module under the same terms as perl itself


use strict;
use warnings;
use Method::Signatures;
use Bio::Community::IO;
use Bio::Community::Meta;
use Bio::Community::Tools::RepresentativeIdConverter;
use Getopt::Euclid qw(:minimal_keys);


=head1 NAME

bc_use_repr_id - Replace member ID by that of their OTU cluster or taxonomic representative

=head1 SYNOPSIS

  bc_use_repr_id -input_files   my_communities.generic   \
                 -output_prefix my_converted_communities \
                 -cluster_file  gg_99_otu_map.txt

or 

  bc_use_repr_id -input_files    my_communities.generic   \
                 -output_prefix  my_converted_communities \
                 -taxassign_file rep_set_tax_assignments.txt

=head1 DESCRIPTION

This script reads a file containing biological communities and a file of OTU
clusters (or taxonomic assignments) and replace the ID of the members in the
communities by the ID of the representative cluster sequence (or by the ID of
the taxonomic representative).

=head1 REQUIRED ARGUMENTS

=over

=item -if <input_files>... | -input_files <input_files>...

Input file containing the communities to process. When providing communities
in a format that supports only one community per file (e.g. gaas), you can
provide multiple input files.

=for Euclid:
   input_files.type: readable

=back

=head1 OPTIONAL ARGUMENTS

=over

=item -cf <cluster_file> | -cluster_file <cluster_file>

The tab-delimited file that defines the OTU clusters. The columns are: OTU ID,
ID of the representative sequence, IDs of the other sequences in the OTU. For
example:

 0	367523
 1	187144
 2	544886	544649
 3	310669
 4	355095	310677	347705	563209 

The OTU files distributed by Greengenes use this format (e.g., 99_otu_map.txt).

=for Euclid:
   cluster_file.type: readable
   cluster_file.excludes: taxassign_file

=item -tf <taxassign_file> | -taxassign_file <taxassign_file>

The tab-delimited file that defines the OTU taxonomic assignemts. The first four
columns (out of 12) should be: OTU ID, taxonomic string, E-value, taxonomic ID.
For example:

345     k__Bacteria; p__Actinobacteria; c__Actinobacteria; o__Actinomycetales; f__Propionibacteriaceae; g__Propionibacterium; s__acnes  5e-138  1042485 95.67   300     13      0       1       300     878     579
346     k__Bacteria; p__Firmicutes; c__Bacilli; o__; f__; g__; s__      8e-134  1064834 99.59   245     1       0       1       245     909     665
347     k__Bacteria; p__Proteobacteria; c__Gammaproteobacteria; o__Pseudomonadales; f__Pseudomonadaceae; g__Pseudomonas; s__    2e-103  959954  98.99   198     2       0       103     300     718     521

The taxonomic assignment files generated by QIIME (rep_set_tax_assignments.txt)
follow this format.

=for Euclid:
   taxassign_file.type: readable
   taxassign_file.excludes: cluster_file

=item -op <output_prefix> | -output_prefix <output_prefix>

Path and prefix for the output files. Default: output_prefix.default

=for Euclid:
   output_prefix.type: string
   output_prefix.default: 'bc_use_repr_id'

=back

=head1 FEEDBACK

=head2 Mailing Lists

User feedback is an integral part of the evolution of this
and other Bioperl modules. Send your comments and suggestions preferably
to one of the Bioperl mailing lists.

Your participation is much appreciated.

  bioperl-l@bioperl.org                  - General discussion
  http://bioperl.org/wiki/Mailing_lists  - About the mailing lists

=head2 Support 

Please direct usage questions or support issues to the mailing list:

I<bioperl-l@bioperl.org>

rather than to the module maintainer directly. Many experienced and 
reponsive experts will be able look at the problem and quickly 
address it. Please include a thorough description of the problem 
with code and data examples if at all possible.

=head2 Reporting Bugs

Report bugs to the Bioperl bug tracking system to help us keep track
the bugs and their resolution.  Bug reports can be submitted via the
web:

  http://bugzilla.open-bio.org/

=head1 AUTHOR - Florent Angly

Email florent.angly@gmail.com

=cut


use_cluster_repr( $ARGV{'input_files'}, $ARGV{'cluster_file'}, $ARGV{'taxassign_file'}, $ARGV{'output_prefix'} );
exit;


func use_cluster_repr ($input_files, $cluster_file, $taxassign_file, $output_prefix) {
   # Read input communities
   my $meta = Bio::Community::Meta->new();
   my $communities = [];
   my $format;
   for my $input_file (@$input_files) {
      my $in = Bio::Community::IO->new( -file => $input_file );
      $format = $in->format;
      if (not $in->explicit_ids) {
         warn("Warning: Input file format, '$format' does not support explicitly ".
            "recording member IDs. Skipping communities in file '$input_file'.\n");
         next;
      }
      while (my $community = $in->next_community) {
         $meta->add_communities([$community]);
      }
      $in->close;
   }

   # Convert IDs
   my $converter = Bio::Community::Tools::RepresentativeIdConverter->new(
      -metacommunity => $meta,
   );
   if (defined $cluster_file) {
      $converter->cluster_file($cluster_file);
   }
   if (defined $taxassign_file) {
      $converter->taxassign_file($taxassign_file);
   }
   my $out_meta = $converter->get_converted_meta;

   # Write metacommunity
   write_communities($out_meta, $output_prefix, $format, '');

   return 1;
}


func write_communities ($meta, $output_prefix, $output_format, $type='') {
   $type ||= '';
   my $multiple_communities = Bio::Community::IO->new(-format=>$output_format)->multiple_communities;
   my $num = 0;
   my $out;
   my $output_file = '';
   while (my $community = $meta->next_community) {
      if (not defined $out) {
         if ($multiple_communities) {
            $output_file = $output_prefix;
         } else {
            $num++;
            $output_file = $output_prefix.'_'.$num;
         }
         if ($type) {
            $output_file .= '_'.$type;
         }
         $output_file .= '.'.$output_format;
         $out = Bio::Community::IO->new(
            -format => $output_format,
            -file   => '>'.$output_file,
         );
      }
      print "Writing community '".$community->name."' to file '$output_file'\n";
      $out->write_community($community);
      if (not $multiple_communities) {
         $out->close;
         $out = undef;
      }
   }
   if (defined $out) {
      $out->close;
   }
   return 1;
}
