示例#1
0
    def __init__(self, records, alphabet=None):
        """Initialize a new MultipleSeqAlignment object.

        Arguments:
        records - A list (or iterator) of SeqRecord objects, whose sequences
                  are all the same length.  This may be an be an empty list.
        alphabet - The alphabet for the whole alignment, typically a gapped
                  alphabet, which should be a super-set of the individual
                  record alphabets.  If omitted, a consensus alphabet is used.

        You would normally load a MSA from a file using Bio.AlignIO, but you
        can do this from a list of SeqRecord objects too:

        >>> from Bio.Alphabet import generic_dna
        >>> from Bio.Seq import Seq
        >>> from Bio.SeqRecord import SeqRecord
        >>> a = SeqRecord(Seq("AAAACGT", generic_dna), id="Alpha")
        >>> b = SeqRecord(Seq("AAA-CGT", generic_dna), id="Beta")
        >>> c = SeqRecord(Seq("AAAAGGT", generic_dna), id="Gamma")
        >>> align = MultipleSeqAlignment([a, b, c])
        >>> print align
        DNAAlphabet() alignment with 3 rows and 7 columns
        AAAACGT Alpha
        AAA-CGT Beta
        AAAAGGT Gamma

        NOTE - The older Bio.Align.Generic.Alignment class only accepted a
        single argument, an alphabet.  This is still supported via a backwards
        compatible "hack" so as not to disrupt existing scripts and users, but
        this will in future be deprecated.
        """
        if isinstance(records, Alphabet.Alphabet) \
        or isinstance(records, Alphabet.AlphabetEncoder):
            if alphabet is None:
                #TODO - Deprecate this backwards compatible mode!                
                alphabet = records
                records = []
            else :
                raise ValueError("Invalid records argument")
        if alphabet is not None :
            if not (isinstance(alphabet, Alphabet.Alphabet) \
            or isinstance(alphabet, Alphabet.AlphabetEncoder)):
                raise ValueError("Invalid alphabet argument")
            self._alphabet = alphabet
        else :
            #Default while we add sequences, will take a consensus later
            self._alphabet = Alphabet.single_letter_alphabet

        self._records = []
        if records:
            self.extend(records)
            if alphabet is None:
                #No alphabet was given, take a consensus alphabet
                self._alphabet = Alphabet._consensus_alphabet(rec.seq.alphabet for \
                                                              rec in self._records \
                                                              if rec.seq is not None)
示例#2
0
    def __add__(self, other):
        """Combines to alignments with the same number of rows by adding them.

        If you have two multiple sequence alignments (MSAs), there are two ways to think
        about adding them - by row or by column. Using the extend method adds by row.
        Using the addition operator adds by column. For example,

        >>> from Bio.Alphabet import generic_dna
        >>> from Bio.Seq import Seq
        >>> from Bio.SeqRecord import SeqRecord
        >>> from Bio.Align import MultipleSeqAlignment
        >>> a1 = SeqRecord(Seq("AAAAC", generic_dna), id="Alpha")
        >>> b1 = SeqRecord(Seq("AAA-C", generic_dna), id="Beta")
        >>> c1 = SeqRecord(Seq("AAAAG", generic_dna), id="Gamma")
        >>> a2 = SeqRecord(Seq("GT", generic_dna), id="Alpha")
        >>> b2 = SeqRecord(Seq("GT", generic_dna), id="Beta")
        >>> c2 = SeqRecord(Seq("GT", generic_dna), id="Gamma")
        >>> left = MultipleSeqAlignment([a1, b1, c1])
        >>> right = MultipleSeqAlignment([a2, b2, c2])

        Now, let's look at these two alignments:

        >>> print left
        DNAAlphabet() alignment with 3 rows and 5 columns
        AAAAC Alpha
        AAA-C Beta
        AAAAG Gamma
        >>> print right
        DNAAlphabet() alignment with 3 rows and 2 columns
        GT Alpha
        GT Beta
        GT Gamma

        And add them:

        >>> print left + right
        DNAAlphabet() alignment with 3 rows and 7 columns
        AAAACGT Alpha
        AAA-CGT Beta
        AAAAGGT Gamma

        For this to work, both alignments must have the same number of records (here
        they both have 3 rows):

        >>> len(left)
        3
        >>> len(right)
        3

        The individual rows are SeqRecord objects, and these can be added together. Refer
        to the SeqRecord documentation for details of how the annotation is handled. This
        example is a special case in that both original alignments shared the same names,
        meaning when the rows are added they also get the same name.
        """
        if not isinstance(other, MultipleSeqAlignment):
            raise NotImplementedError
        if len(self) != len(other):
            raise ValueError(
                "When adding two alignments they must have the same length"
                " (i.e. same number or rows)")
        alpha = Alphabet._consensus_alphabet([self._alphabet, other._alphabet])
        merged = (left + right for left, right in zip(self, other))
        return MultipleSeqAlignment(merged, alpha)
示例#3
0
    def __init__(self, records, alphabet=None):
        """Initialize a new MultipleSeqAlignment object.

        Arguments:
         - records - A list (or iterator) of SeqRecord objects, whose
                     sequences are all the same length.  This may be an be an
                     empty list.
         - alphabet - The alphabet for the whole alignment, typically a gapped
                      alphabet, which should be a super-set of the individual
                      record alphabets.  If omitted, a consensus alphabet is
                      used.

        You would normally load a MSA from a file using Bio.AlignIO, but you
        can do this from a list of SeqRecord objects too:

        >>> from Bio.Alphabet import generic_dna
        >>> from Bio.Seq import Seq
        >>> from Bio.SeqRecord import SeqRecord
        >>> a = SeqRecord(Seq("AAAACGT", generic_dna), id="Alpha")
        >>> b = SeqRecord(Seq("AAA-CGT", generic_dna), id="Beta")
        >>> c = SeqRecord(Seq("AAAAGGT", generic_dna), id="Gamma")
        >>> align = MultipleSeqAlignment([a, b, c])
        >>> print align
        DNAAlphabet() alignment with 3 rows and 7 columns
        AAAACGT Alpha
        AAA-CGT Beta
        AAAAGGT Gamma

        NOTE - The older Bio.Align.Generic.Alignment class only accepted a
        single argument, an alphabet.  This is still supported via a backwards
        compatible "hack" so as not to disrupt existing scripts and users, but
        is deprecated and will be removed in a future release.
        """
        if isinstance(records, Alphabet.Alphabet) \
        or isinstance(records, Alphabet.AlphabetEncoder):
            if alphabet is None:
                #TODO - Remove this backwards compatible mode!
                alphabet = records
                records = []
                import warnings
                warnings.warn("Invalid records argument: While the old "
                              "Bio.Align.Generic.Alignment class only "
                              "accepted a single argument (the alphabet), the "
                              "newer Bio.Align.MultipleSeqAlignment class "
                              "expects a list/iterator of SeqRecord objects "
                              "(which can be an empty list) and an optional "
                              "alphabet argument")
            else:
                raise ValueError("Invalid records argument")
        if alphabet is not None:
            if not (isinstance(alphabet, Alphabet.Alphabet) \
            or isinstance(alphabet, Alphabet.AlphabetEncoder)):
                raise ValueError("Invalid alphabet argument")
            self._alphabet = alphabet
        else:
            #Default while we add sequences, will take a consensus later
            self._alphabet = Alphabet.single_letter_alphabet

        self._records = []
        if records:
            self.extend(records)
            if alphabet is None:
                #No alphabet was given, take a consensus alphabet
                self._alphabet = Alphabet._consensus_alphabet(rec.seq.alphabet for \
                                                              rec in self._records \
                                                              if rec.seq is not None)
    def __add__(self, other):
        """Combine two alignments with the same number of rows by adding them.

        If you have two multiple sequence alignments (MSAs), there are two ways to think
        about adding them - by row or by column. Using the extend method adds by row.
        Using the addition operator adds by column. For example,

        >>> from Bio.Alphabet import generic_dna
        >>> from Bio.Seq import Seq
        >>> from Bio.SeqRecord import SeqRecord
        >>> from Bio.Align import MultipleSeqAlignment
        >>> a1 = SeqRecord(Seq("AAAAC", generic_dna), id="Alpha")
        >>> b1 = SeqRecord(Seq("AAA-C", generic_dna), id="Beta")
        >>> c1 = SeqRecord(Seq("AAAAG", generic_dna), id="Gamma")
        >>> a2 = SeqRecord(Seq("GT", generic_dna), id="Alpha")
        >>> b2 = SeqRecord(Seq("GT", generic_dna), id="Beta")
        >>> c2 = SeqRecord(Seq("GT", generic_dna), id="Gamma")
        >>> left = MultipleSeqAlignment([a1, b1, c1],
        ...                             annotations={"tool": "demo", "name": "start"})
        >>> right = MultipleSeqAlignment([a2, b2, c2],
        ...                             annotations={"tool": "demo", "name": "end"})

        Now, let's look at these two alignments:

        >>> print(left)
        DNAAlphabet() alignment with 3 rows and 5 columns
        AAAAC Alpha
        AAA-C Beta
        AAAAG Gamma
        >>> print(right)
        DNAAlphabet() alignment with 3 rows and 2 columns
        GT Alpha
        GT Beta
        GT Gamma

        And add them:

        >>> combined = left + right
        >>> print(combined)
        DNAAlphabet() alignment with 3 rows and 7 columns
        AAAACGT Alpha
        AAA-CGT Beta
        AAAAGGT Gamma

        For this to work, both alignments must have the same number of records (here
        they both have 3 rows):

        >>> len(left)
        3
        >>> len(right)
        3
        >>> len(combined)
        3

        The individual rows are SeqRecord objects, and these can be added together. Refer
        to the SeqRecord documentation for details of how the annotation is handled. This
        example is a special case in that both original alignments shared the same names,
        meaning when the rows are added they also get the same name.

        Any common annotations are preserved, but differing annotation is lost. This is
        the same behaviour used in the SeqRecord annotations and is designed to prevent
        accidental propagation of inappropriate values:

        >>> combined.annotations
        {'tool': 'demo'}

        """
        if not isinstance(other, MultipleSeqAlignment):
            raise NotImplementedError
        if len(self) != len(other):
            raise ValueError("When adding two alignments they must have the same length"
                             " (i.e. same number or rows)")
        alpha = Alphabet._consensus_alphabet([self._alphabet, other._alphabet])
        merged = (left + right for left, right in zip(self, other))
        # Take any common annotation:
        annotations = dict()
        for k, v in self.annotations.items():
            if k in other.annotations and other.annotations[k] == v:
                annotations[k] = v
        return MultipleSeqAlignment(merged, alpha, annotations)
示例#5
0
    def __init__(self, records, alphabet=None,
                 annotations=None):
        """Initialize a new MultipleSeqAlignment object.

        Arguments:
         - records - A list (or iterator) of SeqRecord objects, whose
                     sequences are all the same length.  This may be an be an
                     empty list.
         - alphabet - The alphabet for the whole alignment, typically a gapped
                      alphabet, which should be a super-set of the individual
                      record alphabets.  If omitted, a consensus alphabet is
                      used.
         - annotations - Information about the whole alignment (dictionary).

        You would normally load a MSA from a file using Bio.AlignIO, but you
        can do this from a list of SeqRecord objects too:

        >>> from Bio.Alphabet import generic_dna
        >>> from Bio.Seq import Seq
        >>> from Bio.SeqRecord import SeqRecord
        >>> from Bio.Align import MultipleSeqAlignment
        >>> a = SeqRecord(Seq("AAAACGT", generic_dna), id="Alpha")
        >>> b = SeqRecord(Seq("AAA-CGT", generic_dna), id="Beta")
        >>> c = SeqRecord(Seq("AAAAGGT", generic_dna), id="Gamma")
        >>> align = MultipleSeqAlignment([a, b, c], annotations={"tool": "demo"})
        >>> print(align)
        DNAAlphabet() alignment with 3 rows and 7 columns
        AAAACGT Alpha
        AAA-CGT Beta
        AAAAGGT Gamma
        >>> align.annotations
        {'tool': 'demo'}

        NOTE - The older Bio.Align.Generic.Alignment class only accepted a
        single argument, an alphabet.  This is still supported via a backwards
        compatible "hack" so as not to disrupt existing scripts and users, but
        is deprecated and will be removed in a future release.
        """
        if isinstance(records, (Alphabet.Alphabet, Alphabet.AlphabetEncoder)):
            if alphabet is None:
                # TODO - Remove this backwards compatible mode!
                alphabet = records
                records = []
                import warnings
                from Bio import BiopythonDeprecationWarning
                warnings.warn("Invalid records argument: While the old "
                              "Bio.Align.Generic.Alignment class only "
                              "accepted a single argument (the alphabet), the "
                              "newer Bio.Align.MultipleSeqAlignment class "
                              "expects a list/iterator of SeqRecord objects "
                              "(which can be an empty list) and an optional "
                              "alphabet argument", BiopythonDeprecationWarning)
            else:
                raise ValueError("Invalid records argument")
        if alphabet is not None:
            if not isinstance(alphabet, (Alphabet.Alphabet, Alphabet.AlphabetEncoder)):
                raise ValueError("Invalid alphabet argument")
            self._alphabet = alphabet
        else:
            # Default while we add sequences, will take a consensus later
            self._alphabet = Alphabet.single_letter_alphabet

        self._records = []
        if records:
            self.extend(records)
            if alphabet is None:
                # No alphabet was given, take a consensus alphabet
                self._alphabet = Alphabet._consensus_alphabet(rec.seq.alphabet for
                                                              rec in self._records
                                                              if rec.seq is not None)

        # Annotations about the whole alignment
        if annotations is None:
            annotations = {}
        elif not isinstance(annotations, dict):
            raise TypeError("annotations argument should be a dict")
        self.annotations = annotations
示例#6
0
    def __add__(self, other):
        """Combines to alignments with the same number of rows by adding them.

        If you have two multiple sequence alignments (MSAs), there are two ways to think
        about adding them - by row or by column. Using the extend method adds by row.
        Using the addition operator adds by column. For example,

        >>> from Bio.Alphabet import generic_dna
        >>> from Bio.Seq import Seq
        >>> from Bio.SeqRecord import SeqRecord
        >>> from Bio.Align import MultipleSeqAlignment
        >>> a1 = SeqRecord(Seq("AAAAC", generic_dna), id="Alpha")
        >>> b1 = SeqRecord(Seq("AAA-C", generic_dna), id="Beta")
        >>> c1 = SeqRecord(Seq("AAAAG", generic_dna), id="Gamma")
        >>> a2 = SeqRecord(Seq("GT", generic_dna), id="Alpha")
        >>> b2 = SeqRecord(Seq("GT", generic_dna), id="Beta")
        >>> c2 = SeqRecord(Seq("GT", generic_dna), id="Gamma")
        >>> left = MultipleSeqAlignment([a1, b1, c1])
        >>> right = MultipleSeqAlignment([a2, b2, c2])

        Now, let's look at these two alignments:

        >>> print left
        DNAAlphabet() alignment with 3 rows and 5 columns
        AAAAC Alpha
        AAA-C Beta
        AAAAG Gamma
        >>> print right
        DNAAlphabet() alignment with 3 rows and 2 columns
        GT Alpha
        GT Beta
        GT Gamma

        And add them:

        >>> print left + right
        DNAAlphabet() alignment with 3 rows and 7 columns
        AAAACGT Alpha
        AAA-CGT Beta
        AAAAGGT Gamma

        For this to work, both alignments must have the same number of records (here
        they both have 3 rows):

        >>> len(left)
        3
        >>> len(right)
        3

        The individual rows are SeqRecord objects, and these can be added together. Refer
        to the SeqRecord documentation for details of how the annotation is handled. This
        example is a special case in that both original alignments shared the same names,
        meaning when the rows are added they also get the same name.
        """
        if not isinstance(other, MultipleSeqAlignment):
            raise NotImplementedError
        if len(self) != len(other):
            raise ValueError("When adding two alignments they must have the same length"
                             " (i.e. same number or rows)")
        alpha = Alphabet._consensus_alphabet([self._alphabet, other._alphabet])
        merged = (left+right for left,right in zip(self, other))
        return MultipleSeqAlignment(merged, alpha)
示例#7
0
    def __init__(self,
                 records,
                 alphabet=None,
                 annotations=None,
                 column_annotations=None):
        """Initialize a new MultipleSeqAlignment object.

        Arguments:
         - records - A list (or iterator) of SeqRecord objects, whose
                     sequences are all the same length.  This may be an be an
                     empty list.
         - alphabet - The alphabet for the whole alignment, typically a gapped
                      alphabet, which should be a super-set of the individual
                      record alphabets.  If omitted, a consensus alphabet is
                      used.
         - annotations - Information about the whole alignment (dictionary).
         - column_annotations - Per column annotation (restricted dictionary).
                      This holds Python sequences (lists, strings, tuples)
                      whose length matches the number of columns. A typical
                      use would be a secondary structure consensus string.

        You would normally load a MSA from a file using Bio.AlignIO, but you
        can do this from a list of SeqRecord objects too:

        >>> from Bio.Alphabet import generic_dna
        >>> from Bio.Seq import Seq
        >>> from Bio.SeqRecord import SeqRecord
        >>> from Bio.Align import MultipleSeqAlignment
        >>> a = SeqRecord(Seq("AAAACGT", generic_dna), id="Alpha")
        >>> b = SeqRecord(Seq("AAA-CGT", generic_dna), id="Beta")
        >>> c = SeqRecord(Seq("AAAAGGT", generic_dna), id="Gamma")
        >>> align = MultipleSeqAlignment([a, b, c],
        ...                              annotations={"tool": "demo"},
        ...                              column_annotations={"stats": "CCCXCCC"})
        >>> print(align)
        DNAAlphabet() alignment with 3 rows and 7 columns
        AAAACGT Alpha
        AAA-CGT Beta
        AAAAGGT Gamma
        >>> align.annotations
        {'tool': 'demo'}
        >>> align.column_annotations
        {'stats': 'CCCXCCC'}

        NOTE - The older Bio.Align.Generic.Alignment class only accepted a
        single argument, an alphabet.  This is still supported via a backwards
        compatible "hack" so as not to disrupt existing scripts and users, but
        is deprecated and will be removed in a future release.
        """
        if isinstance(records, (Alphabet.Alphabet, Alphabet.AlphabetEncoder)):
            if alphabet is None:
                # TODO - Remove this backwards compatible mode!
                alphabet = records
                records = []
                import warnings
                from Bio import BiopythonDeprecationWarning
                warnings.warn(
                    "Invalid records argument: While the old "
                    "Bio.Align.Generic.Alignment class only "
                    "accepted a single argument (the alphabet), the "
                    "newer Bio.Align.MultipleSeqAlignment class "
                    "expects a list/iterator of SeqRecord objects "
                    "(which can be an empty list) and an optional "
                    "alphabet argument", BiopythonDeprecationWarning)
            else:
                raise ValueError("Invalid records argument")
        if alphabet is not None:
            if not isinstance(alphabet,
                              (Alphabet.Alphabet, Alphabet.AlphabetEncoder)):
                raise ValueError("Invalid alphabet argument")
            self._alphabet = alphabet
        else:
            # Default while we add sequences, will take a consensus later
            self._alphabet = Alphabet.single_letter_alphabet

        self._records = []
        if records:
            self.extend(records)
            if alphabet is None:
                # No alphabet was given, take a consensus alphabet
                self._alphabet = Alphabet._consensus_alphabet(
                    rec.seq.alphabet for rec in self._records
                    if rec.seq is not None)

        # Annotations about the whole alignment
        if annotations is None:
            annotations = {}
        elif not isinstance(annotations, dict):
            raise TypeError("annotations argument should be a dict")
        self.annotations = annotations

        # Annotations about each colum of the alignment
        if column_annotations is None:
            column_annotations = {}
        # Handle this via the property set function which will validate it
        self.column_annotations = column_annotations
示例#8
0
    def __init__(self, records, alphabet=None,
                 annotations=None, column_annotations=None):
        """Initialize a new MultipleSeqAlignment object.

        Arguments:
         - records - A list (or iterator) of SeqRecord objects, whose
                     sequences are all the same length.  This may be an be an
                     empty list.
         - alphabet - The alphabet for the whole alignment, typically a gapped
                      alphabet, which should be a super-set of the individual
                      record alphabets.  If omitted, a consensus alphabet is
                      used.
         - annotations - Information about the whole alignment (dictionary).
         - column_annotations - Per column annotation (restricted dictionary).
                      This holds Python sequences (lists, strings, tuples)
                      whose length matches the number of columns. A typical
                      use would be a secondary structure consensus string.

        You would normally load a MSA from a file using Bio.AlignIO, but you
        can do this from a list of SeqRecord objects too:

        >>> from Bio.Alphabet import generic_dna
        >>> from Bio.Seq import Seq
        >>> from Bio.SeqRecord import SeqRecord
        >>> from Bio.Align import MultipleSeqAlignment
        >>> a = SeqRecord(Seq("AAAACGT", generic_dna), id="Alpha")
        >>> b = SeqRecord(Seq("AAA-CGT", generic_dna), id="Beta")
        >>> c = SeqRecord(Seq("AAAAGGT", generic_dna), id="Gamma")
        >>> align = MultipleSeqAlignment([a, b, c],
        ...                              annotations={"tool": "demo"},
        ...                              column_annotations={"stats": "CCCXCCC"})
        >>> print(align)
        DNAAlphabet() alignment with 3 rows and 7 columns
        AAAACGT Alpha
        AAA-CGT Beta
        AAAAGGT Gamma
        >>> align.annotations
        {'tool': 'demo'}
        >>> align.column_annotations
        {'stats': 'CCCXCCC'}
        """
        if alphabet is not None:
            if not isinstance(alphabet, (Alphabet.Alphabet, Alphabet.AlphabetEncoder)):
                raise ValueError("Invalid alphabet argument")
            self._alphabet = alphabet
        else:
            # Default while we add sequences, will take a consensus later
            self._alphabet = Alphabet.single_letter_alphabet

        self._records = []
        if records:
            self.extend(records)
            if alphabet is None:
                # No alphabet was given, take a consensus alphabet
                self._alphabet = Alphabet._consensus_alphabet(rec.seq.alphabet for
                                                              rec in self._records
                                                              if rec.seq is not None)

        # Annotations about the whole alignment
        if annotations is None:
            annotations = {}
        elif not isinstance(annotations, dict):
            raise TypeError("annotations argument should be a dict")
        self.annotations = annotations

        # Annotations about each colum of the alignment
        if column_annotations is None:
            column_annotations = {}
        # Handle this via the property set function which will validate it
        self.column_annotations = column_annotations
示例#9
0
def concatenate(alignments, padding_length=0, partitions=None):

    '''
    Concatenate alignments based on the Seq ids; row order does not
    matter. If one alignment contains a Seq id that another one does
    not, gaps will be introduced in place of the missing Seq.

    Args:
        alignments: (tuple, list) Alignments to be concatenated.

        padding_length: Introduce this many gaps between concatenated
            alignments.
    '''

    from Bio import Alphabet
    from Bio.Seq import Seq
    from Bio.SeqRecord import SeqRecord
    from Bio.Align import MultipleSeqAlignment
    if not isinstance(alignments, (list, tuple)):
        raise ValueError('Argument must be a list or a tuple.')
    elif len(alignments) == 1:
        return alignments[0]
    if isinstance(alignments, tuple):
        alignments = list(alignments)
    aln1 = None
    aln2 = None
    if len(alignments) > 2:
        aln2 = alignments.pop()
        result1 = concatenate(alignments=alignments,
                              padding_length=padding_length,
                              partitions=partitions)
        aln1 = result1[0]
        partitions = result1[1]
    elif len(alignments) == 2:
        aln1 = alignments[0]
        aln2 = alignments[1]
    if (not isinstance(aln1, MultipleSeqAlignment) or
            not isinstance(aln2, MultipleSeqAlignment)):
        raise ValueError(
            'Argument must inherit from Bio.Align.MultipleSeqAlignment.')
    alphabet = Alphabet._consensus_alphabet([aln1._alphabet, aln2._alphabet])
    aln1_dict = dict()
    aln2_dict = dict()
    for aln1_s in aln1:
        aln1_dict[aln1_s.id] = aln1_s
    for aln2_s in aln2:
        aln2_dict[aln2_s.id] = aln2_s
    aln1_length = aln1.get_alignment_length()
    aln2_length = aln2.get_alignment_length()
    aln1_gaps = SeqRecord(Seq('-' * aln1_length, alphabet))
    aln2_gaps = SeqRecord(Seq('-' * aln2_length, alphabet))
    padding = SeqRecord(Seq('N' * padding_length, alphabet))

    if not partitions:
        partitions = [(1, aln1_length)]
    partitions.append((1 + aln1_length, padding_length + aln1_length + aln2_length))

    result_seq_list = list()
    for aln1_key in aln1_dict.keys():
        merged_Seq = None
        if aln1_key in aln2_dict:
            merged_Seq = aln1_dict[aln1_key] + padding + aln2_dict[aln1_key]
            merged_Seq.id = aln1_dict[aln1_key].id
            merged_Seq.name = ''
            merged_Seq.description = ''
            aln2_dict.pop(aln1_key)
        else:
            aln1_seq_record = aln1_dict[aln1_key]
            merged_Seq = aln1_seq_record + padding + aln2_gaps
            merged_Seq.id = aln1_seq_record.id
            merged_Seq.name = ''
            merged_Seq.description = ''
        result_seq_list.append(merged_Seq)
    for aln2_seq_record in aln2_dict.values():
        merged_Seq = aln1_gaps + padding + aln2_seq_record
        merged_Seq.id = aln2_seq_record.id
        merged_Seq.name = ''
        merged_Seq.description = ''
        result_seq_list.append(merged_Seq)
    result_alignment = MultipleSeqAlignment(result_seq_list, alphabet)
    result_alignment.sort()
    return((result_alignment, partitions))
示例#10
0
#!/usr/bin/env python3

from Bio import SeqIO
from Bio.Alphabet import IUPAC, HasStopCodon
from Bio import Alphabet
import sys, os
import gzip

binname = sys.argv[1]
item = sys.argv[2]
errorfile = sys.argv[3]

full_prot_ab = Alphabet._consensus_alphabet(
    [IUPAC.extended_protein,
     HasStopCodon(IUPAC.protein)])


def parse_FASTA(inputfasta):
    isdna = True
    isprotein = True

    with open("sanitychecked.fasta", "w") as outfile:
        for read in SeqIO.parse(inputfasta, "fasta", IUPAC.ambiguous_dna):
            if not Alphabet._verify_alphabet(read.seq):
                isdna = False
                break
            SeqIO.write(read, outfile, "fasta")
    if isdna and os.stat("sanitychecked.fasta").st_size != 0:
        print("DNA", end="")
        return
示例#11
0
    def __init__(self,
                 records,
                 alphabet=None,
                 annotations=None,
                 column_annotations=None):
        """Initialize a new MultipleSeqAlignment object.

        Arguments:
         - records - A list (or iterator) of SeqRecord objects, whose
                     sequences are all the same length.  This may be an be an
                     empty list.
         - alphabet - The alphabet for the whole alignment, typically a gapped
                      alphabet, which should be a super-set of the individual
                      record alphabets.  If omitted, a consensus alphabet is
                      used.
         - annotations - Information about the whole alignment (dictionary).
         - column_annotations - Per column annotation (restricted dictionary).
                      This holds Python sequences (lists, strings, tuples)
                      whose length matches the number of columns. A typical
                      use would be a secondary structure consensus string.

        You would normally load a MSA from a file using Bio.AlignIO, but you
        can do this from a list of SeqRecord objects too:

        >>> from Bio.Alphabet import generic_dna
        >>> from Bio.Seq import Seq
        >>> from Bio.SeqRecord import SeqRecord
        >>> from Bio.Align import MultipleSeqAlignment
        >>> a = SeqRecord(Seq("AAAACGT", generic_dna), id="Alpha")
        >>> b = SeqRecord(Seq("AAA-CGT", generic_dna), id="Beta")
        >>> c = SeqRecord(Seq("AAAAGGT", generic_dna), id="Gamma")
        >>> align = MultipleSeqAlignment([a, b, c],
        ...                              annotations={"tool": "demo"},
        ...                              column_annotations={"stats": "CCCXCCC"})
        >>> print(align)
        DNAAlphabet() alignment with 3 rows and 7 columns
        AAAACGT Alpha
        AAA-CGT Beta
        AAAAGGT Gamma
        >>> align.annotations
        {'tool': 'demo'}
        >>> align.column_annotations
        {'stats': 'CCCXCCC'}
        """
        if alphabet is not None:
            if not isinstance(alphabet,
                              (Alphabet.Alphabet, Alphabet.AlphabetEncoder)):
                raise ValueError("Invalid alphabet argument")
            self._alphabet = alphabet
        else:
            # Default while we add sequences, will take a consensus later
            self._alphabet = Alphabet.single_letter_alphabet

        self._records = []
        if records:
            self.extend(records)
            if alphabet is None:
                # No alphabet was given, take a consensus alphabet
                self._alphabet = Alphabet._consensus_alphabet(
                    rec.seq.alphabet for rec in self._records
                    if rec.seq is not None)

        # Annotations about the whole alignment
        if annotations is None:
            annotations = {}
        elif not isinstance(annotations, dict):
            raise TypeError("annotations argument should be a dict")
        self.annotations = annotations

        # Annotations about each colum of the alignment
        if column_annotations is None:
            column_annotations = {}
        # Handle this via the property set function which will validate it
        self.column_annotations = column_annotations