#!/opt/gensoft/exe/extend_align/1.0/venv/bin/python2.7
# -*- coding: utf-8 -*-

########################################################################################
#                                                                                      #
#    Copyright (C) 2011                                                                #
#    Author: Bertrand Néron                                                            #
#    Organization:'Centre Informatique en Biologie', Institut Pasteur, Paris.          #
#                                                                                      #
#    This program is free software: you can redistribute it and/or modify              #
#    it under the terms of the GNU General Public License version as published by      #
#    the Free Software Foundation, in the version 3 of the License.                    #
#                                                                                      #
#    This program is distributed in the hope that it will be useful,                   #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of                    #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                     #
#    GNU General Public License for more details.                                      #
#                                                                                      #
#    You should have received a copy of the GNU General Public License                 #
#    along with this program (Please refer to the COPYING document).                   #
#    If not, see <http://www.gnu.org/licenses/>.                                       #
########################################################################################

from itertools import izip
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio import AlignIO
from Bio.Align import MultipleSeqAlignment

supported_format = ( 'clustal' , 'fasta' , 'phylip' , 'stockholm' )

def extend_align( alignments , linker = '' , sort_by_id= False ):
    """
    @param alignments: the alignments to link together
    @type alignments: [ MultipleSeqAlignment al1 , ...]
    @param linker: the char which will use to link sequences
    @type linker: string
    @return: the contatenation of input Alignments 
    @rtype: MultipleSeqAlignment instance
    """
    seq_nb = len( alignments[0])
    align_linker = make_linker( linker , seq_nb )
    concat_ali = alignments[0]
    if sort_by_id:
        concat_ali.sort()
    for al in alignments[1:]:
        if len( al ) != seq_nb:
            raise Exception
        if sort_by_id:
            al.sort()
        concat_ali = concat_ali + align_linker + al 
    
    if sort_by_id:
        #the linker records have no ids so the alignment record have no ids too
       ids = [record.id for record in alignments[0] ]
    else:
        ids = concat_id( alignments )
       
    iter =  izip( ids , concat_ali )
    for id, record in iter:
        record.id = id
            
    return concat_ali

def concat_id( alignments ):
    """
    @param alignments: al list of alignment
    @type alignments: [ MultipleSeqAlignment al1 , MultipleSeqAlignment al2 , ...]
    @return: a list 
    @rtype: [string id , ...]
    """
    ids = [ [ record.id for record in al ] for al in  alignments ] 
    ids_iter = izip( *ids )
    concat_id = [ '_'.join( id ) for id in ids_iter ]
    return  concat_id

       
def make_linker( motif , nb ):
    """
    @return: an alignment containing nb seqRecord of motif
    @rtype: string
    @param motif: the motif of the linker
    @type motif: string
    @param nb: the number of sequence in the resulting alignement
    @type nb: integer
    """
    seqs = []
    for i in range( nb ):
        seqs.append( SeqRecord(Seq(motif)))
    align = MultipleSeqAlignment( seqs )
    return align


if __name__ ==  '__main__':

    from optparse import OptionParser
    import sys
    import os.path
    
    usage="""
       %prog [options] extendAlign 
       concatenate several alignments from several files (one per file )
"""
    parser = OptionParser( usage= usage )  
    parser.add_option(  "-i" ,"--input" ,
                       action = "append",
                       type= "string" ,
                       dest = "inputs" ,
                       nargs = 2 ,
                       help = """specify the alignment fileName to concatenate and its format. 
You must specify at least 2 inputs -i file1 fmt1 -i file2 , fmt2.
supported formats are: %s""" %", ".join(supported_format) 
                       )
         
    parser.add_option( "-l" , "--linker" ,
                       action = "store",
                       type= "string" ,
                       dest = "linker" ,
                       help = "specify the linker between sequences",
                       default = "")
    
    parser.add_option( "-o" ,  "--output" ,
                       action = "store",
                       type= "string" ,
                       dest = "output" ,
                       help = "specify the filename of the results (default = standard output)")
    
    parser.add_option(  "--output-format" ,
                       action = "store",
                       type= "string" ,
                       dest = "output_format" ,
                       default = "fasta",
                       help = """specify the alignment format of the resulting alignment
supported formats are: %s
becarefull for phylip format the ids are truncated at 10 characters""" %", ".join(supported_format))
    
    parser.add_option(  "--id" ,
                       action = "store_true",
                       dest = "sort" ,
                       default = False ,
                       help = """sort the alignment in function of there ID before concatenate them.
This option implies that You have the same identifier for the sequences in each alignments.                       
(default use sequences order)""")
    options, args = parser.parse_args()
    
    if  options.inputs is None or len( options.inputs )< 2:
        print "You must specify at least 2 inputs (-i )"
        print parser.print_help()
        sys.exit(1)
        
    output_format = options.output_format.lower()
    if output_format not in supported_format:
        print output_format , " not supported. supported format are : " , supported_format
        print parser.print_help()
        sys.exit(1)
        
    def parse_align( inputs ):
        alignments = []
        for fileName , fmt in inputs:
            if not os.path.exists( fileName ):
                print "cannot access %s: No such file or directory"  %fileName
                sys.exit(1)
            fmt = fmt.lower()
            if fmt not in supported_format:
                print  fmt, " not supported. supported format are : " , supported_format
                print parser.print_help()
                sys.exit(1)
            try:
                align = AlignIO.read( fileName, fmt )
            except Exception , err:
                print "%s is not recognize as %s. supported format are : %s" %(fileName , fmt, ', '.join( supported_format ) )
                print parser.print_help()
                sys.exit(1)
            alignments.append( align )
        return alignments
    
    alignments =  parse_align( options.inputs )   
    
    concat_alignment= extend_align( alignments , linker = options.linker , sort_by_id = options.sort )
    if options.output is None:
        output = sys.stdout
    else:
        try:
            output = open( options.output , 'w')
        except IOError, err:
           pass
    try:
        AlignIO.write(concat_alignment, output , output_format)
    except Exception, err:
        raise err
    finally:
       output.close()
