{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "**Source of the materials**: Biopython cookbook (adapted)\n", "Status: Draft" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Multiple Sequence Alignment objects {#chapter:Bio.AlignIO}\n", "===================================\n", "\n", "This chapter is about Multiple Sequence Alignments, by which we mean a\n", "collection of multiple sequences which have been aligned together –\n", "usually with the insertion of gap characters, and addition of leading or\n", "trailing gaps – such that all the sequence strings are the same length.\n", "Such an alignment can be regarded as a matrix of letters, where each row\n", "is held as a `SeqRecord` object internally.\n", "\n", "We will introduce the `MultipleSeqAlignment` object which holds this\n", "kind of data, and the `Bio.AlignIO` module for reading and writing them\n", "as various file formats (following the design of the `Bio.SeqIO` module\n", "from the previous chapter). Note that both `Bio.SeqIO` and `Bio.AlignIO`\n", "can read and write sequence alignment files. The appropriate choice will\n", "depend largely on what you want to do with the data.\n", "\n", "The final part of this chapter is about our command line wrappers for\n", "common multiple sequence alignment tools like ClustalW and MUSCLE.\n", "\n", "Parsing or Reading Sequence Alignments\n", "--------------------------------------\n", "\n", "We have two functions for reading in sequence alignments,\n", "`Bio.AlignIO.read()` and `Bio.AlignIO.parse()` which following the\n", "convention introduced in `Bio.SeqIO` are for files containing one or\n", "multiple alignments respectively.\n", "\n", "Using `Bio.AlignIO.parse()` will return an *iterator* which\n", "gives `MultipleSeqAlignment` objects. Iterators are typically used in a\n", "for loop. Examples of situations where you will have multiple different\n", "alignments include resampled alignments from the PHYLIP tool `seqboot`,\n", "or multiple pairwise alignments from the EMBOSS tools `water` or\n", "`needle`, or Bill Pearson’s FASTA tools.\n", "\n", "However, in many situations you will be dealing with files which contain\n", "only a single alignment. In this case, you should use the\n", "`Bio.AlignIO.read()` function which returns a single\n", "`MultipleSeqAlignment` object.\n", "\n", "Both functions expect two mandatory arguments:\n", "\n", "1. The first argument is a *handle* to read the data from,\n", " typically an open file (see Section \\[sec:appendix-handles\\]), or\n", " a filename.\n", "\n", "2. The second argument is a lower case string specifying the\n", " alignment format. As in `Bio.SeqIO` we don’t try and guess the file\n", " format for you! See for a full\n", " listing of supported formats.\n", "\n", "There is also an optional `seq_count` argument which is discussed in\n", "Section \\[sec:AlignIO-count-argument\\] below for dealing with ambiguous\n", "file formats which may contain more than one alignment.\n", "\n", "A further optional `alphabet` argument allowing you to specify the\n", "expected alphabet. This can be useful as many alignment file formats do\n", "not explicitly label the sequences as RNA, DNA or protein – which means\n", "`Bio.AlignIO` will default to using a generic alphabet.\n", "\n", "### Single Alignments\n", "\n", "As an example, consider the following annotation rich protein alignment\n", "in the PFAM or Stockholm file format:\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "# STOCKHOLM 1.0\n", "#=GS COATB_BPIKE/30-81 AC P03620.1\n", "#=GS COATB_BPIKE/30-81 DR PDB; 1ifl ; 1-52;\n", "#=GS Q9T0Q8_BPIKE/1-52 AC Q9T0Q8.1\n", "#=GS COATB_BPI22/32-83 AC P15416.1\n", "#=GS COATB_BPM13/24-72 AC P69541.1\n", "#=GS COATB_BPM13/24-72 DR PDB; 2cpb ; 1-49;\n", "#=GS COATB_BPM13/24-72 DR PDB; 2cps ; 1-49;\n", "#=GS COATB_BPZJ2/1-49 AC P03618.1\n", "#=GS Q9T0Q9_BPFD/1-49 AC Q9T0Q9.1\n", "#=GS Q9T0Q9_BPFD/1-49 DR PDB; 1nh4 A; 1-49;\n", "#=GS COATB_BPIF1/22-73 AC P03619.2\n", "#=GS COATB_BPIF1/22-73 DR PDB; 1ifk ; 1-50;\n", "COATB_BPIKE/30-81 AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA\n", "#=GR COATB_BPIKE/30-81 SS -HHHHHHHHHHHHHH--HHHHHHHH--HHHHHHHHHHHHHHHHHHHHH----\n", "Q9T0Q8_BPIKE/1-52 AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA\n", "COATB_BPI22/32-83 DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA\n", "COATB_BPM13/24-72 AEGDDP...AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA\n", "#=GR COATB_BPM13/24-72 SS ---S-T...CHCHHHHCCCCTCCCTTCHHHHHHHHHHHHHHHHHHHHCTT--\n", "COATB_BPZJ2/1-49 AEGDDP...AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA\n", "Q9T0Q9_BPFD/1-49 AEGDDP...AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA\n", "#=GR Q9T0Q9_BPFD/1-49 SS ------...-HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH--\n", "COATB_BPIF1/22-73 FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA\n", "#=GR COATB_BPIF1/22-73 SS XX-HHHH--HHHHHH--HHHHHHH--HHHHHHHHHHHHHHHHHHHHHHH---\n", "#=GC SS_cons XHHHHHHHHHHHHHHHCHHHHHHHHCHHHHHHHHHHHHHHHHHHHHHHHC--\n", "#=GC seq_cons AEssss...AptAhDSLpspAT-hIu.sWshVsslVsAsluIKLFKKFsSKA\n", "//\n", "\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "This is the seed alignment for the Phage\\_Coat\\_Gp8 (PF05371) PFAM\n", "entry, downloaded from a now out of date release of PFAM from\n", ". We can load this file as follows (assuming\n", "it has been saved to disk as “PF05371\\_seed.sth” in the current working\n", "directory):\n", "\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from Bio import AlignIO\n", "alignment = AlignIO.read(\"data/PF05371_seed.sth\", \"stockholm\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "This code will print out a summary of the alignment:\n", "\n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SingleLetterAlphabet() alignment with 7 rows and 52 columns\n", "AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRL...SKA COATB_BPIKE/30-81\n", "AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKL...SRA Q9T0Q8_BPIKE/1-52\n", "DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRL...SKA COATB_BPI22/32-83\n", "AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPM13/24-72\n", "AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPZJ2/1-49\n", "AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA Q9T0Q9_BPFD/1-49\n", "FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKL...SRA COATB_BPIF1/22-73\n" ] } ], "source": [ "print(alignment)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "You’ll notice in the above output the sequences have been truncated. We\n", "could instead write our own code to format this as we please by\n", "iterating over the rows as `SeqRecord` objects:\n", "\n" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Alignment length 52\n" ] } ], "source": [ "from Bio import AlignIO\n", "alignment = AlignIO.read(\"data/PF05371_seed.sth\", \"stockholm\")\n", "print(\"Alignment length %i\" % alignment.get_alignment_length())" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA - COATB_BPIKE/30-81\n", "AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA - Q9T0Q8_BPIKE/1-52\n", "DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA - COATB_BPI22/32-83\n", "AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA - COATB_BPM13/24-72\n", "AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA - COATB_BPZJ2/1-49\n", "AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA - Q9T0Q9_BPFD/1-49\n", "FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA - COATB_BPIF1/22-73\n" ] } ], "source": [ "for record in alignment:\n", " print(\"%s - %s\" % (record.seq, record.id))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "You could also use the alignment object’s `format` method to show it in\n", "a particular file format – see Section \\[sec:alignment-format-method\\]\n", "for details.\n", "\n", "Did you notice in the raw file above that several of the sequences\n", "include database cross-references to the PDB and the associated known\n", "secondary structure? Try this:\n", "\n" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "COATB_BPIKE/30-81 ['PDB; 1ifl ; 1-52;']\n", "COATB_BPM13/24-72 ['PDB; 2cpb ; 1-49;', 'PDB; 2cps ; 1-49;']\n", "Q9T0Q9_BPFD/1-49 ['PDB; 1nh4 A; 1-49;']\n", "COATB_BPIF1/22-73 ['PDB; 1ifk ; 1-50;']\n" ] } ], "source": [ "for record in alignment:\n", " if record.dbxrefs:\n", " print(\"%s %s\" % (record.id, record.dbxrefs))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "To have a look at all the sequence annotation, try this:\n", "\n" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "ID: COATB_BPIKE/30-81\n", "Name: COATB_BPIKE\n", "Description: COATB_BPIKE/30-81\n", "Database cross-references: PDB; 1ifl ; 1-52;\n", "Number of features: 0\n", "/start=30\n", "/accession=P03620.1\n", "/end=81\n", "Per letter annotation for: secondary_structure\n", "Seq('AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA', SingleLetterAlphabet())\n", "ID: Q9T0Q8_BPIKE/1-52\n", "Name: Q9T0Q8_BPIKE\n", "Description: Q9T0Q8_BPIKE/1-52\n", "Number of features: 0\n", "/start=1\n", "/accession=Q9T0Q8.1\n", "/end=52\n", "Seq('AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA', SingleLetterAlphabet())\n", "ID: COATB_BPI22/32-83\n", "Name: COATB_BPI22\n", "Description: COATB_BPI22/32-83\n", "Number of features: 0\n", "/start=32\n", "/accession=P15416.1\n", "/end=83\n", "Seq('DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA', SingleLetterAlphabet())\n", "ID: COATB_BPM13/24-72\n", "Name: COATB_BPM13\n", "Description: COATB_BPM13/24-72\n", "Database cross-references: PDB; 2cpb ; 1-49;, PDB; 2cps ; 1-49;\n", "Number of features: 0\n", "/start=24\n", "/accession=P69541.1\n", "/end=72\n", "Per letter annotation for: secondary_structure\n", "Seq('AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA', SingleLetterAlphabet())\n", "ID: COATB_BPZJ2/1-49\n", "Name: COATB_BPZJ2\n", "Description: COATB_BPZJ2/1-49\n", "Number of features: 0\n", "/start=1\n", "/accession=P03618.1\n", "/end=49\n", "Seq('AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA', SingleLetterAlphabet())\n", "ID: Q9T0Q9_BPFD/1-49\n", "Name: Q9T0Q9_BPFD\n", "Description: Q9T0Q9_BPFD/1-49\n", "Database cross-references: PDB; 1nh4 A; 1-49;\n", "Number of features: 0\n", "/start=1\n", "/accession=Q9T0Q9.1\n", "/end=49\n", "Per letter annotation for: secondary_structure\n", "Seq('AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA', SingleLetterAlphabet())\n", "ID: COATB_BPIF1/22-73\n", "Name: COATB_BPIF1\n", "Description: COATB_BPIF1/22-73\n", "Database cross-references: PDB; 1ifk ; 1-50;\n", "Number of features: 0\n", "/start=22\n", "/accession=P03619.2\n", "/end=73\n", "Per letter annotation for: secondary_structure\n", "Seq('FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA', SingleLetterAlphabet())\n" ] } ], "source": [ "for record in alignment:\n", " print(record)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Sanger provide a nice web interface at\n", " which will actually let\n", "you download this alignment in several other formats. This is what the\n", "file looks like in the FASTA file format:\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", ">COATB_BPIKE/30-81\n", "AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA\n", ">Q9T0Q8_BPIKE/1-52\n", "AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA\n", ">COATB_BPI22/32-83\n", "DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA\n", ">COATB_BPM13/24-72\n", "AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA\n", ">COATB_BPZJ2/1-49\n", "AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA\n", ">Q9T0Q9_BPFD/1-49\n", "AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA\n", ">COATB_BPIF1/22-73\n", "FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA\n", "\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Note the website should have an option about showing gaps as periods\n", "(dots) or dashes, we’ve shown dashes above. Assuming you download and\n", "save this as file “PF05371\\_seed.faa” then you can load it with almost\n", "exactly the same code:\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "from Bio import AlignIO\n", "alignment = AlignIO.read(\"PF05371_seed.faa\", \"fasta\")\n", "print(alignment)\n", "\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "All that has changed in this code is the filename and the format string.\n", "You’ll get the same output as before, the sequences and record\n", "identifiers are the same. However, as you should expect, if you check\n", "each `SeqRecord` there is no annotation nor database cross-references\n", "because these are not included in the FASTA file format.\n", "\n", "Note that rather than using the Sanger website, you could have used\n", "`Bio.AlignIO` to convert the original Stockholm format file into a FASTA\n", "file yourself (see below).\n", "\n", "With any supported file format, you can load an alignment in exactly the\n", "same way just by changing the format string. For example, use “phylip”\n", "for PHYLIP files, “nexus” for NEXUS files or “emboss” for the alignments\n", "output by the EMBOSS tools. There is a full listing on the wiki page\n", "() and in the built in documentation\n", "(also\n", "[online](http://biopython.org/DIST/docs/api/Bio.AlignIO-module.html)):\n", "\n" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on package Bio.AlignIO in Bio:\n", "\n", "NAME\n", " Bio.AlignIO - Multiple sequence alignment input/output as alignment objects.\n", "\n", "DESCRIPTION\n", " The Bio.AlignIO interface is deliberately very similar to Bio.SeqIO, and in\n", " fact the two are connected internally. Both modules use the same set of file\n", " format names (lower case strings). From the user's perspective, you can read\n", " in a PHYLIP file containing one or more alignments using Bio.AlignIO, or you\n", " can read in the sequences within these alignmenta using Bio.SeqIO.\n", " \n", " Bio.AlignIO is also documented at http://biopython.org/wiki/AlignIO and by\n", " a whole chapter in our tutorial:\n", " \n", " * `HTML Tutorial`_\n", " * `PDF Tutorial`_\n", " \n", " .. _`HTML Tutorial`: http://biopython.org/DIST/docs/tutorial/Tutorial.html\n", " .. _`PDF Tutorial`: http://biopython.org/DIST/docs/tutorial/Tutorial.pdf\n", " \n", " Input\n", " -----\n", " For the typical special case when your file or handle contains one and only\n", " one alignment, use the function Bio.AlignIO.read(). This takes an input file\n", " handle (or in recent versions of Biopython a filename as a string), format\n", " string and optional number of sequences per alignment. It will return a single\n", " MultipleSeqAlignment object (or raise an exception if there isn't just one\n", " alignment):\n", " \n", " >>> from Bio import AlignIO\n", " >>> align = AlignIO.read(\"Phylip/interlaced.phy\", \"phylip\")\n", " >>> print(align)\n", " SingleLetterAlphabet() alignment with 3 rows and 384 columns\n", " -----MKVILLFVLAVFTVFVSS---------------RGIPPE...I-- CYS1_DICDI\n", " MAHARVLLLALAVLATAAVAVASSSSFADSNPIRPVTDRAASTL...VAA ALEU_HORVU\n", " ------MWATLPLLCAGAWLLGV--------PVCGAAELSVNSL...PLV CATH_HUMAN\n", " \n", " For the general case, when the handle could contain any number of alignments,\n", " use the function Bio.AlignIO.parse(...) which takes the same arguments, but\n", " returns an iterator giving MultipleSeqAlignment objects (typically used in a\n", " for loop). If you want random access to the alignments by number, turn this\n", " into a list:\n", " \n", " >>> from Bio import AlignIO\n", " >>> alignments = list(AlignIO.parse(\"Emboss/needle.txt\", \"emboss\"))\n", " >>> print(alignments[2])\n", " SingleLetterAlphabet() alignment with 2 rows and 120 columns\n", " -KILIVDDQYGIRILLNEVFNKEGYQTFQAANGLQALDIVTKER...--- ref_rec\n", " LHIVVVDDDPGTCVYIESVFAELGHTCKSFVRPEAAEEYILTHP...HKE gi|94967506|receiver\n", " \n", " Most alignment file formats can be concatenated so as to hold as many\n", " different multiple sequence alignments as possible. One common example\n", " is the output of the tool seqboot in the PHLYIP suite. Sometimes there\n", " can be a file header and footer, as seen in the EMBOSS alignment output.\n", " \n", " Output\n", " ------\n", " Use the function Bio.AlignIO.write(...), which takes a complete set of\n", " Alignment objects (either as a list, or an iterator), an output file handle\n", " (or filename in recent versions of Biopython) and of course the file format::\n", " \n", " from Bio import AlignIO\n", " alignments = ...\n", " count = SeqIO.write(alignments, \"example.faa\", \"fasta\")\n", " \n", " If using a handle make sure to close it to flush the data to the disk::\n", " \n", " from Bio import AlignIO\n", " alignments = ...\n", " with open(\"example.faa\", \"w\") as handle:\n", " count = SeqIO.write(alignments, handle, \"fasta\")\n", " \n", " In general, you are expected to call this function once (with all your\n", " alignments) and then close the file handle. However, for file formats\n", " like PHYLIP where multiple alignments are stored sequentially (with no file\n", " header and footer), then multiple calls to the write function should work as\n", " expected when using handles.\n", " \n", " If you are using a filename, the repeated calls to the write functions will\n", " overwrite the existing file each time.\n", " \n", " Conversion\n", " ----------\n", " The Bio.AlignIO.convert(...) function allows an easy interface for simple\n", " alignnment file format conversions. Additionally, it may use file format\n", " specific optimisations so this should be the fastest way too.\n", " \n", " In general however, you can combine the Bio.AlignIO.parse(...) function with\n", " the Bio.AlignIO.write(...) function for sequence file conversion. Using\n", " generator expressions provides a memory efficient way to perform filtering or\n", " other extra operations as part of the process.\n", " \n", " File Formats\n", " ------------\n", " When specifying the file format, use lowercase strings. The same format\n", " names are also used in Bio.SeqIO and include the following:\n", " \n", " - clustal - Output from Clustal W or X, see also the module Bio.Clustalw\n", " which can be used to run the command line tool from Biopython.\n", " - emboss - EMBOSS tools' \"pairs\" and \"simple\" alignment formats.\n", " - fasta - The generic sequence file format where each record starts with\n", " an identifer line starting with a \">\" character, followed by\n", " lines of sequence.\n", " - fasta-m10 - For the pairswise alignments output by Bill Pearson's FASTA\n", " tools when used with the -m 10 command line option for machine\n", " readable output.\n", " - ig - The IntelliGenetics file format, apparently the same as the\n", " MASE alignment format.\n", " - nexus - Output from NEXUS, see also the module Bio.Nexus which can also\n", " read any phylogenetic trees in these files.\n", " - phylip - Interlaced PHYLIP, as used by the PHLIP tools.\n", " - phylip-sequential - Sequential PHYLIP.\n", " - phylip-relaxed - PHYLIP like format allowing longer names.\n", " - stockholm - A richly annotated alignment file format used by PFAM.\n", " \n", " Note that while Bio.AlignIO can read all the above file formats, it cannot\n", " write to all of them.\n", " \n", " You can also use any file format supported by Bio.SeqIO, such as \"fasta\" or\n", " \"ig\" (which are listed above), PROVIDED the sequences in your file are all the\n", " same length.\n", "\n", "PACKAGE CONTENTS\n", " ClustalIO\n", " EmbossIO\n", " FastaIO\n", " Interfaces\n", " NexusIO\n", " PhylipIO\n", " StockholmIO\n", "\n", "FUNCTIONS\n", " convert(in_file, in_format, out_file, out_format, alphabet=None)\n", " Convert between two alignment files, returns number of alignments.\n", " \n", " - in_file - an input handle or filename\n", " - in_format - input file format, lower case string\n", " - output - an output handle or filename\n", " - out_file - output file format, lower case string\n", " - alphabet - optional alphabet to assume\n", " \n", " **NOTE** - If you provide an output filename, it will be opened which will\n", " overwrite any existing file without warning. This may happen if even the\n", " conversion is aborted (e.g. an invalid out_format name is given).\n", " \n", " parse(handle, format, seq_count=None, alphabet=None)\n", " Iterate over an alignment file as MultipleSeqAlignment objects.\n", " \n", " Arguments:\n", " - handle - handle to the file, or the filename as a string\n", " (note older versions of Biopython only took a handle).\n", " - format - string describing the file format.\n", " - alphabet - optional Alphabet object, useful when the sequence type\n", " cannot be automatically inferred from the file itself\n", " (e.g. fasta, phylip, clustal)\n", " - seq_count - Optional integer, number of sequences expected in each\n", " alignment. Recommended for fasta format files.\n", " \n", " If you have the file name in a string 'filename', use:\n", " \n", " >>> from Bio import AlignIO\n", " >>> filename = \"Emboss/needle.txt\"\n", " >>> format = \"emboss\"\n", " >>> for alignment in AlignIO.parse(filename, format):\n", " ... print(\"Alignment of length %i\" % alignment.get_alignment_length())\n", " Alignment of length 124\n", " Alignment of length 119\n", " Alignment of length 120\n", " Alignment of length 118\n", " Alignment of length 125\n", " \n", " If you have a string 'data' containing the file contents, use::\n", " \n", " from Bio import AlignIO\n", " from StringIO import StringIO\n", " my_iterator = AlignIO.parse(StringIO(data), format)\n", " \n", " Use the Bio.AlignIO.read() function when you expect a single record only.\n", " \n", " read(handle, format, seq_count=None, alphabet=None)\n", " Turns an alignment file into a single MultipleSeqAlignment object.\n", " \n", " Arguments:\n", " - handle - handle to the file, or the filename as a string\n", " (note older versions of Biopython only took a handle).\n", " - format - string describing the file format.\n", " - alphabet - optional Alphabet object, useful when the sequence type\n", " cannot be automatically inferred from the file itself\n", " (e.g. fasta, phylip, clustal)\n", " - seq_count - Optional integer, number of sequences expected in each\n", " alignment. Recommended for fasta format files.\n", " \n", " If the handle contains no alignments, or more than one alignment,\n", " an exception is raised. For example, using a PFAM/Stockholm file\n", " containing one alignment:\n", " \n", " >>> from Bio import AlignIO\n", " >>> filename = \"Clustalw/protein.aln\"\n", " >>> format = \"clustal\"\n", " >>> alignment = AlignIO.read(filename, format)\n", " >>> print(\"Alignment of length %i\" % alignment.get_alignment_length())\n", " Alignment of length 411\n", " \n", " If however you want the first alignment from a file containing\n", " multiple alignments this function would raise an exception.\n", " \n", " >>> from Bio import AlignIO\n", " >>> filename = \"Emboss/needle.txt\"\n", " >>> format = \"emboss\"\n", " >>> alignment = AlignIO.read(filename, format)\n", " Traceback (most recent call last):\n", " ...\n", " ValueError: More than one record found in handle\n", " \n", " Instead use:\n", " \n", " >>> from Bio import AlignIO\n", " >>> filename = \"Emboss/needle.txt\"\n", " >>> format = \"emboss\"\n", " >>> alignment = next(AlignIO.parse(filename, format))\n", " >>> print(\"First alignment has length %i\" % alignment.get_alignment_length())\n", " First alignment has length 124\n", " \n", " You must use the Bio.AlignIO.parse() function if you want to read multiple\n", " records from the handle.\n", " \n", " write(alignments, handle, format)\n", " Write complete set of alignments to a file.\n", " \n", " Arguments:\n", " - alignments - A list (or iterator) of Alignment objects (ideally the\n", " new MultipleSeqAlignment objects), or (if using Biopython\n", " 1.54 or later) a single alignment object.\n", " - handle - File handle object to write to, or filename as string\n", " (note older versions of Biopython only took a handle).\n", " - format - lower case string describing the file format to write.\n", " \n", " You should close the handle after calling this function.\n", " \n", " Returns the number of alignments written (as an integer).\n", "\n", "DATA\n", " __docformat__ = 'restructuredtext en'\n", " print_function = _Feature((2, 6, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0)...\n", "\n", "FILE\n", " /home/tiago_antao/miniconda/lib/python3.5/site-packages/Bio/AlignIO/__init__.py\n", "\n", "\n" ] } ], "source": [ "from Bio import AlignIO\n", "help(AlignIO)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### Multiple Alignments\n", "\n", "The previous section focused on reading files containing a single\n", "alignment. In general however, files can contain more than one\n", "alignment, and to read these files we must use the `Bio.AlignIO.parse()`\n", "function.\n", "\n", "Suppose you have a small alignment in PHYLIP format:\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "5 6\n", "Alpha AACAAC\n", "Beta AACCCC\n", "Gamma ACCAAC\n", "Delta CCACCA\n", "Epsilon CCAAAC\n", "\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "If you wanted to bootstrap a phylogenetic tree using the PHYLIP tools,\n", "one of the steps would be to create a set of many resampled alignments\n", "using the tool `bootseq`. This would give output something like this,\n", "which has been abbreviated for conciseness:\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "5 6\n", "Alpha AAACCA\n", "Beta AAACCC\n", "Gamma ACCCCA\n", "Delta CCCAAC\n", "Epsilon CCCAAA\n", " 5 6\n", "Alpha AAACAA\n", "Beta AAACCC\n", "Gamma ACCCAA\n", "Delta CCCACC\n", "Epsilon CCCAAA\n", " 5 6\n", "Alpha AAAAAC\n", "Beta AAACCC\n", "Gamma AACAAC\n", "Delta CCCCCA\n", "Epsilon CCCAAC\n", "...\n", " 5 6\n", "Alpha AAAACC\n", "Beta ACCCCC\n", "Gamma AAAACC\n", "Delta CCCCAA\n", "Epsilon CAAACC\n", "\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "If you wanted to read this in using `Bio.AlignIO` you could use:\n", "\n" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "ename": "FileNotFoundError", "evalue": "[Errno 2] No such file or directory: 'data/resampled.phy'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mFileNotFoundError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mfrom\u001b[0m \u001b[0mBio\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mAlignIO\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[0malignments\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mAlignIO\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mparse\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"data/resampled.phy\"\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m\"phylip\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[1;32mfor\u001b[0m \u001b[0malignment\u001b[0m \u001b[1;32min\u001b[0m \u001b[0malignments\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 4\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0malignment\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;32m/home/tiago_antao/miniconda/lib/python3.5/site-packages/Bio/AlignIO/__init__.py\u001b[0m in \u001b[0;36mparse\u001b[1;34m(handle, format, seq_count, alphabet)\u001b[0m\n\u001b[0;32m 348\u001b[0m \u001b[1;32mraise\u001b[0m \u001b[0mTypeError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Need integer for seq_count (sequences per alignment)\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 349\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 350\u001b[1;33m \u001b[1;32mwith\u001b[0m \u001b[0mas_handle\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mhandle\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m'rU'\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mfp\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 351\u001b[0m \u001b[1;31m# Map the file format to a sequence iterator:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 352\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mformat\u001b[0m \u001b[1;32min\u001b[0m \u001b[0m_FormatToIterator\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;32m/home/tiago_antao/miniconda/lib/python3.5/contextlib.py\u001b[0m in \u001b[0;36m__enter__\u001b[1;34m(self)\u001b[0m\n\u001b[0;32m 57\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0m__enter__\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 58\u001b[0m \u001b[1;32mtry\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 59\u001b[1;33m \u001b[1;32mreturn\u001b[0m \u001b[0mnext\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mgen\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 60\u001b[0m \u001b[1;32mexcept\u001b[0m \u001b[0mStopIteration\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 61\u001b[0m \u001b[1;32mraise\u001b[0m \u001b[0mRuntimeError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"generator didn't yield\"\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mfrom\u001b[0m \u001b[1;32mNone\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;32m/home/tiago_antao/miniconda/lib/python3.5/site-packages/Bio/File.py\u001b[0m in \u001b[0;36mas_handle\u001b[1;34m(handleish, mode, **kwargs)\u001b[0m\n\u001b[0;32m 88\u001b[0m \u001b[1;32myield\u001b[0m \u001b[0mfp\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 89\u001b[0m \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 90\u001b[1;33m \u001b[1;32mwith\u001b[0m \u001b[0mopen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mhandleish\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mmode\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;33m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mfp\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 91\u001b[0m \u001b[1;32myield\u001b[0m \u001b[0mfp\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 92\u001b[0m \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: 'data/resampled.phy'" ] } ], "source": [ "from Bio import AlignIO\n", "alignments = AlignIO.parse(\"data/resampled.phy\", \"phylip\")\n", "for alignment in alignments:\n", " print(alignment)\n", " print(\"\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "As with the function `Bio.SeqIO.parse()`, using `Bio.AlignIO.parse()`\n", "returns an iterator. If you want to keep all the alignments in memory at\n", "once, which will allow you to access them in any order, then turn the\n", "iterator into a list:\n", "\n" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": false }, "outputs": [ { "ename": "FileNotFoundError", "evalue": "[Errno 2] No such file or directory: 'data/resampled.phy'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mFileNotFoundError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mfrom\u001b[0m \u001b[0mBio\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mAlignIO\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0malignments\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mlist\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mAlignIO\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mparse\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"data/resampled.phy\"\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m\"phylip\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 3\u001b[0m \u001b[0mlast_align\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0malignments\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;33m-\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[0mfirst_align\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0malignments\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;32m/home/tiago_antao/miniconda/lib/python3.5/site-packages/Bio/AlignIO/__init__.py\u001b[0m in \u001b[0;36mparse\u001b[1;34m(handle, format, seq_count, alphabet)\u001b[0m\n\u001b[0;32m 348\u001b[0m \u001b[1;32mraise\u001b[0m \u001b[0mTypeError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Need integer for seq_count (sequences per alignment)\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 349\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 350\u001b[1;33m \u001b[1;32mwith\u001b[0m \u001b[0mas_handle\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mhandle\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m'rU'\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mfp\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 351\u001b[0m \u001b[1;31m# Map the file format to a sequence iterator:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 352\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mformat\u001b[0m \u001b[1;32min\u001b[0m \u001b[0m_FormatToIterator\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;32m/home/tiago_antao/miniconda/lib/python3.5/contextlib.py\u001b[0m in \u001b[0;36m__enter__\u001b[1;34m(self)\u001b[0m\n\u001b[0;32m 57\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0m__enter__\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 58\u001b[0m \u001b[1;32mtry\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 59\u001b[1;33m \u001b[1;32mreturn\u001b[0m \u001b[0mnext\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mgen\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 60\u001b[0m \u001b[1;32mexcept\u001b[0m \u001b[0mStopIteration\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 61\u001b[0m \u001b[1;32mraise\u001b[0m \u001b[0mRuntimeError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"generator didn't yield\"\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mfrom\u001b[0m \u001b[1;32mNone\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;32m/home/tiago_antao/miniconda/lib/python3.5/site-packages/Bio/File.py\u001b[0m in \u001b[0;36mas_handle\u001b[1;34m(handleish, mode, **kwargs)\u001b[0m\n\u001b[0;32m 88\u001b[0m \u001b[1;32myield\u001b[0m \u001b[0mfp\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 89\u001b[0m \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 90\u001b[1;33m \u001b[1;32mwith\u001b[0m \u001b[0mopen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mhandleish\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mmode\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;33m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mfp\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 91\u001b[0m \u001b[1;32myield\u001b[0m \u001b[0mfp\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 92\u001b[0m \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: 'data/resampled.phy'" ] } ], "source": [ "from Bio import AlignIO\n", "alignments = list(AlignIO.parse(\"data/resampled.phy\", \"phylip\"))\n", "last_align = alignments[-1]\n", "first_align = alignments[0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### Ambiguous Alignments {#sec:AlignIO-count-argument}\n", "\n", "Many alignment file formats can explicitly store more than one\n", "alignment, and the division between each alignment is clear. However,\n", "when a general sequence file format has been used there is no such block\n", "structure. The most common such situation is when alignments have been\n", "saved in the FASTA file format. For example consider the following:\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", ">Alpha\n", "ACTACGACTAGCTCAG--G\n", ">Beta\n", "ACTACCGCTAGCTCAGAAG\n", ">Gamma\n", "ACTACGGCTAGCACAGAAG\n", ">Alpha\n", "ACTACGACTAGCTCAGG--\n", ">Beta\n", "ACTACCGCTAGCTCAGAAG\n", ">Gamma\n", "ACTACGGCTAGCACAGAAG\n", "\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "This could be a single alignment containing six sequences (with repeated\n", "identifiers). Or, judging from the identifiers, this is probably two\n", "different alignments each with three sequences, which happen to all have\n", "the same length.\n", "\n", "What about this next example?\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", ">Alpha\n", "ACTACGACTAGCTCAG--G\n", ">Beta\n", "ACTACCGCTAGCTCAGAAG\n", ">Alpha\n", "ACTACGACTAGCTCAGG--\n", ">Gamma\n", "ACTACGGCTAGCACAGAAG\n", ">Alpha\n", "ACTACGACTAGCTCAGG--\n", ">Delta\n", "ACTACGGCTAGCACAGAAG\n", "\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Again, this could be a single alignment with six sequences. However this\n", "time based on the identifiers we might guess this is three pairwise\n", "alignments which by chance have all got the same lengths.\n", "\n", "This final example is similar:\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", ">Alpha\n", "ACTACGACTAGCTCAG--G\n", ">XXX\n", "ACTACCGCTAGCTCAGAAG\n", ">Alpha\n", "ACTACGACTAGCTCAGG\n", ">YYY\n", "ACTACGGCAAGCACAGG\n", ">Alpha\n", "--ACTACGAC--TAGCTCAGG\n", ">ZZZ\n", "GGACTACGACAATAGCTCAGG\n", "\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "In this third example, because of the differing lengths, this cannot be\n", "treated as a single alignment containing all six records. However, it\n", "could be three pairwise alignments.\n", "\n", "Clearly trying to store more than one alignment in a FASTA file is not\n", "ideal. However, if you are forced to deal with these as input files\n", "`Bio.AlignIO` can cope with the most common situation where all the\n", "alignments have the same number of records. One example of this is a\n", "collection of pairwise alignments, which can be produced by the EMBOSS\n", "tools `needle` and `water` – although in this situation, `Bio.AlignIO`\n", "should be able to understand their native output using “emboss” as the\n", "format string.\n", "\n", "To interpret these FASTA examples as several separate alignments, we can\n", "use `Bio.AlignIO.parse()` with the optional `seq_count` argument which\n", "specifies how many sequences are expected in each alignment (in these\n", "examples, 3, 2 and 2 respectively). For example, using the third example\n", "as the input data:\n", "\n" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [ { "ename": "NameError", "evalue": "name 'handle' is not defined", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[1;32mfor\u001b[0m \u001b[0malignment\u001b[0m \u001b[1;32min\u001b[0m \u001b[0mAlignIO\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mparse\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mhandle\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m\"fasta\"\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mseq_count\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;36m2\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 2\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Alignment length %i\"\u001b[0m \u001b[1;33m%\u001b[0m \u001b[0malignment\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mget_alignment_length\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 3\u001b[0m \u001b[1;32mfor\u001b[0m \u001b[0mrecord\u001b[0m \u001b[1;32min\u001b[0m \u001b[0malignment\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"%s - %s\"\u001b[0m \u001b[1;33m%\u001b[0m \u001b[1;33m(\u001b[0m\u001b[0mrecord\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mseq\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mrecord\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mid\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;31mNameError\u001b[0m: name 'handle' is not defined" ] } ], "source": [ "for alignment in AlignIO.parse(handle, \"fasta\", seq_count=2):\n", " print(\"Alignment length %i\" % alignment.get_alignment_length())\n", " for record in alignment:\n", " print(\"%s - %s\" % (record.seq, record.id))\n", " print(\"\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Using `Bio.AlignIO.read()` or `Bio.AlignIO.parse()` without the\n", "`seq_count` argument would give a single alignment containing all six\n", "records for the first two examples. For the third example, an exception\n", "would be raised because the lengths differ preventing them being turned\n", "into a single alignment.\n", "\n", "If the file format itself has a block structure allowing `Bio.AlignIO`\n", "to determine the number of sequences in each alignment directly, then\n", "the `seq_count` argument is not needed. If it is supplied, and doesn’t\n", "agree with the file contents, an error is raised.\n", "\n", "Note that this optional `seq_count` argument assumes each alignment in\n", "the file has the same number of sequences. Hypothetically you may come\n", "across stranger situations, for example a FASTA file containing several\n", "alignments each with a different number of sequences – although I would\n", "love to hear of a real world example of this. Assuming you cannot get\n", "the data in a nicer file format, there is no straight forward way to\n", "deal with this using `Bio.AlignIO`. In this case, you could consider\n", "reading in the sequences themselves using `Bio.SeqIO` and batching them\n", "together to create the alignments as appropriate.\n", "\n", "Writing Alignments\n", "------------------\n", "\n", "We’ve talked about using `Bio.AlignIO.read()` and `Bio.AlignIO.parse()`\n", "for alignment input (reading files), and now we’ll look at\n", "`Bio.AlignIO.write()` which is for alignment output (writing files).\n", "This is a function taking three arguments: some `MultipleSeqAlignment`\n", "objects (or for backwards compatibility the obsolete `Alignment`\n", "objects), a handle or filename to write to, and a sequence format.\n", "\n", "Here is an example, where we start by creating a few\n", "`MultipleSeqAlignment` objects the hard way (by hand, rather than by\n", "loading them from a file). Note we create some `SeqRecord` objects to\n", "construct the alignment from.\n", "\n" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from Bio.Alphabet import generic_dna\n", "from Bio.Seq import Seq\n", "from Bio.SeqRecord import SeqRecord\n", "from Bio.Align import MultipleSeqAlignment\n", "\n", "align1 = MultipleSeqAlignment([\n", " SeqRecord(Seq(\"ACTGCTAGCTAG\", generic_dna), id=\"Alpha\"),\n", " SeqRecord(Seq(\"ACT-CTAGCTAG\", generic_dna), id=\"Beta\"),\n", " SeqRecord(Seq(\"ACTGCTAGDTAG\", generic_dna), id=\"Gamma\"),\n", " ])\n", "\n", "align2 = MultipleSeqAlignment([\n", " SeqRecord(Seq(\"GTCAGC-AG\", generic_dna), id=\"Delta\"),\n", " SeqRecord(Seq(\"GACAGCTAG\", generic_dna), id=\"Epsilon\"),\n", " SeqRecord(Seq(\"GTCAGCTAG\", generic_dna), id=\"Zeta\"),\n", " ])\n", "\n", "align3 = MultipleSeqAlignment([\n", " SeqRecord(Seq(\"ACTAGTACAGCTG\", generic_dna), id=\"Eta\"),\n", " SeqRecord(Seq(\"ACTAGTACAGCT-\", generic_dna), id=\"Theta\"),\n", " SeqRecord(Seq(\"-CTACTACAGGTG\", generic_dna), id=\"Iota\"),\n", " ])\n", "\n", "my_alignments = [align1, align2, align3]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Now we have a list of `Alignment` objects, we’ll write them to a PHYLIP\n", "format file:\n", "\n" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from Bio import AlignIO\n", "AlignIO.write(my_alignments, \"my_example.phy\", \"phylip\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "And if you open this file in your favourite text editor it should look\n", "like this:\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "3 12\n", "Alpha ACTGCTAGCT AG\n", "Beta ACT-CTAGCT AG\n", "Gamma ACTGCTAGDT AG\n", " 3 9\n", "Delta GTCAGC-AG\n", "Epislon GACAGCTAG\n", "Zeta GTCAGCTAG\n", " 3 13\n", "Eta ACTAGTACAG CTG\n", "Theta ACTAGTACAG CT-\n", "Iota -CTACTACAG GTG\n", "\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Its more common to want to load an existing alignment, and save that,\n", "perhaps after some simple manipulation like removing certain rows or\n", "columns.\n", "\n", "Suppose you wanted to know how many alignments the `Bio.AlignIO.write()`\n", "function wrote to the handle? If your alignments were in a list like the\n", "example above, you could just use `len(my_alignments)`, however you\n", "can’t do that when your records come from a generator/iterator.\n", "Therefore the `Bio.AlignIO.write()` function returns the number of\n", "alignments written to the file.\n", "\n", "*Note* - If you tell the `Bio.AlignIO.write()` function to write to a\n", "file that already exists, the old file will be overwritten without any\n", "warning.\n", "\n", "### Converting between sequence alignment file formats {#sec:converting-alignments}\n", "\n", "Converting between sequence alignment file formats with `Bio.AlignIO`\n", "works in the same way as converting between sequence file formats with\n", "`Bio.SeqIO` (Section \\[sec:SeqIO-conversion\\]). We load generally the\n", "alignment(s) using `Bio.AlignIO.parse()` and then save them using the\n", "`Bio.AlignIO.write()` – or just use the `Bio.AlignIO.convert()` helper\n", "function.\n", "\n", "For this example, we’ll load the PFAM/Stockholm format file used earlier\n", "and save it as a Clustal W format file:\n", "\n" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Converted 1 alignments\n" ] } ], "source": [ "from Bio import AlignIO\n", "count = AlignIO.convert(\"data/PF05371_seed.sth\", \"stockholm\", \"PF05371_seed.aln\", \"clustal\")\n", "print(\"Converted %i alignments\" % count)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Or, using `Bio.AlignIO.parse()` and `Bio.AlignIO.write()`:\n", "\n" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Converted 1 alignments\n" ] } ], "source": [ "from Bio import AlignIO\n", "alignments = AlignIO.parse(\"data/PF05371_seed.sth\", \"stockholm\")\n", "count = AlignIO.write(alignments, \"PF05371_seed.aln\", \"clustal\")\n", "print(\"Converted %i alignments\" % count)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "The `Bio.AlignIO.write()` function expects to be given multiple\n", "alignment objects. In the example above we gave it the alignment\n", "iterator returned by `Bio.AlignIO.parse()`.\n", "\n", "In this case, we know there is only one alignment in the file so we\n", "could have used `Bio.AlignIO.read()` instead, but notice we have to pass\n", "this alignment to `Bio.AlignIO.write()` as a single element list:\n", "\n" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from Bio import AlignIO\n", "alignment = AlignIO.read(\"data/PF05371_seed.sth\", \"stockholm\")\n", "AlignIO.write([alignment], \"PF05371_seed.aln\", \"clustal\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Either way, you should end up with the same new Clustal W format file\n", "“PF05371\\_seed.aln” with the following content:\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "CLUSTAL X (1.81) multiple sequence alignment\n", "\n", "\n", "COATB_BPIKE/30-81 AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSS\n", "Q9T0Q8_BPIKE/1-52 AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVS\n", "COATB_BPI22/32-83 DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSS\n", "COATB_BPM13/24-72 AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTS\n", "COATB_BPZJ2/1-49 AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFAS\n", "Q9T0Q9_BPFD/1-49 AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTS\n", "COATB_BPIF1/22-73 FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVS\n", "\n", "COATB_BPIKE/30-81 KA\n", "Q9T0Q8_BPIKE/1-52 RA\n", "COATB_BPI22/32-83 KA\n", "COATB_BPM13/24-72 KA\n", "COATB_BPZJ2/1-49 KA\n", "Q9T0Q9_BPFD/1-49 KA\n", "COATB_BPIF1/22-73 RA\n", "\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Alternatively, you could make a PHYLIP format file which we’ll name\n", "“PF05371\\_seed.phy”:\n", "\n" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from Bio import AlignIO\n", "AlignIO.convert(\"data/PF05371_seed.sth\", \"stockholm\", \"PF05371_seed.phy\", \"phylip\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "This time the output looks like this:\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "7 52\n", "COATB_BPIK AEPNAATNYA TEAMDSLKTQ AIDLISQTWP VVTTVVVAGL VIRLFKKFSS\n", "Q9T0Q8_BPI AEPNAATNYA TEAMDSLKTQ AIDLISQTWP VVTTVVVAGL VIKLFKKFVS\n", "COATB_BPI2 DGTSTATSYA TEAMNSLKTQ ATDLIDQTWP VVTSVAVAGL AIRLFKKFSS\n", "COATB_BPM1 AEGDDP---A KAAFNSLQAS ATEYIGYAWA MVVVIVGATI GIKLFKKFTS\n", "COATB_BPZJ AEGDDP---A KAAFDSLQAS ATEYIGYAWA MVVVIVGATI GIKLFKKFAS\n", "Q9T0Q9_BPF AEGDDP---A KAAFDSLQAS ATEYIGYAWA MVVVIVGATI GIKLFKKFTS\n", "COATB_BPIF FAADDATSQA KAAFDSLTAQ ATEMSGYAWA LVVLVVGATV GIKLFKKFVS\n", "\n", " KA\n", " RA\n", " KA\n", " KA\n", " KA\n", " KA\n", " RA\n", "\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "One of the big handicaps of the original PHYLIP alignment file format is\n", "that the sequence identifiers are strictly truncated at ten characters.\n", "In this example, as you can see the resulting names are still unique -\n", "but they are not very readable. As a result, a more relaxed variant of\n", "the original PHYLIP format is now quite widely used:\n", "\n" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from Bio import AlignIO\n", "AlignIO.convert(\"data/PF05371_seed.sth\", \"stockholm\", \"PF05371_seed.phy\", \"phylip-relaxed\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "This time the output looks like this, using a longer indentation to\n", "allow all the identifers to be given in full::\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "7 52\n", "COATB_BPIKE/30-81 AEPNAATNYA TEAMDSLKTQ AIDLISQTWP VVTTVVVAGL VIRLFKKFSS\n", "Q9T0Q8_BPIKE/1-52 AEPNAATNYA TEAMDSLKTQ AIDLISQTWP VVTTVVVAGL VIKLFKKFVS\n", "COATB_BPI22/32-83 DGTSTATSYA TEAMNSLKTQ ATDLIDQTWP VVTSVAVAGL AIRLFKKFSS\n", "COATB_BPM13/24-72 AEGDDP---A KAAFNSLQAS ATEYIGYAWA MVVVIVGATI GIKLFKKFTS\n", "COATB_BPZJ2/1-49 AEGDDP---A KAAFDSLQAS ATEYIGYAWA MVVVIVGATI GIKLFKKFAS\n", "Q9T0Q9_BPFD/1-49 AEGDDP---A KAAFDSLQAS ATEYIGYAWA MVVVIVGATI GIKLFKKFTS\n", "COATB_BPIF1/22-73 FAADDATSQA KAAFDSLTAQ ATEMSGYAWA LVVLVVGATV GIKLFKKFVS\n", "\n", " KA\n", " RA\n", " KA\n", " KA\n", " KA\n", " KA\n", " RA\n", "\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "If you have to work with the original strict PHYLIP format, then you may\n", "need to compress the identifers somehow – or assign your own names or\n", "numbering system. This following bit of code manipulates the record\n", "identifiers before saving the output:\n", "\n" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{0: 'COATB_BPIKE/30-81', 1: 'Q9T0Q8_BPIKE/1-52', 2: 'COATB_BPI22/32-83', 3: 'COATB_BPM13/24-72', 4: 'COATB_BPZJ2/1-49', 5: 'Q9T0Q9_BPFD/1-49', 6: 'COATB_BPIF1/22-73'}\n" ] }, { "data": { "text/plain": [ "1" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from Bio import AlignIO\n", "alignment = AlignIO.read(\"data/PF05371_seed.sth\", \"stockholm\")\n", "name_mapping = {}\n", "for i, record in enumerate(alignment):\n", " name_mapping[i] = record.id\n", " record.id = \"seq%i\" % i\n", "print(name_mapping)\n", "\n", "AlignIO.write([alignment], \"PF05371_seed.phy\", \"phylip\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Here is the new (strict) PHYLIP format output:\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "7 52\n", "seq0 AEPNAATNYA TEAMDSLKTQ AIDLISQTWP VVTTVVVAGL VIRLFKKFSS\n", "seq1 AEPNAATNYA TEAMDSLKTQ AIDLISQTWP VVTTVVVAGL VIKLFKKFVS\n", "seq2 DGTSTATSYA TEAMNSLKTQ ATDLIDQTWP VVTSVAVAGL AIRLFKKFSS\n", "seq3 AEGDDP---A KAAFNSLQAS ATEYIGYAWA MVVVIVGATI GIKLFKKFTS\n", "seq4 AEGDDP---A KAAFDSLQAS ATEYIGYAWA MVVVIVGATI GIKLFKKFAS\n", "seq5 AEGDDP---A KAAFDSLQAS ATEYIGYAWA MVVVIVGATI GIKLFKKFTS\n", "seq6 FAADDATSQA KAAFDSLTAQ ATEMSGYAWA LVVLVVGATV GIKLFKKFVS\n", "\n", " KA\n", " RA\n", " KA\n", " KA\n", " KA\n", " KA\n", " RA\n", "\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "In general, because of the identifier limitation, working with *strict*\n", "PHYLIP file formats shouldn’t be your first choice. Using the\n", "PFAM/Stockholm format on the other hand allows you to record a lot of\n", "additional annotation too.\n", "\n", "### Getting your alignment objects as formatted strings {#sec:alignment-format-method}\n", "\n", "The `Bio.AlignIO` interface is based on handles, which means if you want\n", "to get your alignment(s) into a string in a particular file format you\n", "need to do a little bit more work (see below). However, you will\n", "probably prefer to take advantage of the alignment object’s `format()`\n", "method. This takes a single mandatory argument, a lower case string\n", "which is supported by `Bio.AlignIO` as an output format. For example:\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "from Bio import AlignIO\n", "alignment = AlignIO.read(\"PF05371_seed.sth\", \"stockholm\")\n", "print(alignment.format(\"clustal\"))\n", "\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "As described in Section \\[sec:SeqRecord-format\\], the `SeqRecord` object\n", "has a similar method using output formats supported by `Bio.SeqIO`.\n", "\n", "Internally the `format()` method is using the `StringIO` string based\n", "handle and calling `Bio.AlignIO.write()`. You can do this in your own\n", "code if for example you are using an older version of Biopython:\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "from Bio import AlignIO\n", "from StringIO import StringIO\n", "\n", "alignments = AlignIO.parse(\"PF05371_seed.sth\", \"stockholm\")\n", "\n", "out_handle = StringIO()\n", "AlignIO.write(alignments, out_handle, \"clustal\")\n", "clustal_data = out_handle.getvalue()\n", "\n", "print(clustal_data)\n", "\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Manipulating Alignments {#sec:manipulating-alignments}\n", "-----------------------\n", "\n", "Now that we’ve covered loading and saving alignments, we’ll look at what\n", "else you can do with them.\n", "\n", "### Slicing alignments\n", "\n", "First of all, in some senses the alignment objects act like a Python\n", "`list` of `SeqRecord` objects (the rows). With this model in mind\n", "hopefully the actions of `len()` (the number of rows) and iteration\n", "(each row as a `SeqRecord`) make sense:\n", "\n" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number of rows: 7\n" ] } ], "source": [ "from Bio import AlignIO\n", "alignment = AlignIO.read(\"data/PF05371_seed.sth\", \"stockholm\")\n", "print(\"Number of rows: %i\" % len(alignment))" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA - COATB_BPIKE/30-81\n", "AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA - Q9T0Q8_BPIKE/1-52\n", "DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA - COATB_BPI22/32-83\n", "AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA - COATB_BPM13/24-72\n", "AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA - COATB_BPZJ2/1-49\n", "AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA - Q9T0Q9_BPFD/1-49\n", "FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA - COATB_BPIF1/22-73\n" ] } ], "source": [ "for record in alignment:\n", " print(\"%s - %s\" % (record.seq, record.id))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "You can also use the list-like `append` and `extend` methods to add more\n", "rows to the alignment (as `SeqRecord` objects). Keeping the list\n", "metaphor in mind, simple slicing of the alignment should also make sense\n", "- it selects some of the rows giving back another alignment object:\n", "\n" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SingleLetterAlphabet() alignment with 7 rows and 52 columns\n", "AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRL...SKA COATB_BPIKE/30-81\n", "AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKL...SRA Q9T0Q8_BPIKE/1-52\n", "DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRL...SKA COATB_BPI22/32-83\n", "AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPM13/24-72\n", "AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPZJ2/1-49\n", "AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA Q9T0Q9_BPFD/1-49\n", "FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKL...SRA COATB_BPIF1/22-73\n" ] } ], "source": [ "print(alignment)" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SingleLetterAlphabet() alignment with 4 rows and 52 columns\n", "AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPM13/24-72\n", "AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPZJ2/1-49\n", "AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA Q9T0Q9_BPFD/1-49\n", "FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKL...SRA COATB_BPIF1/22-73\n" ] } ], "source": [ "print(alignment[3:7])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "What if you wanted to select by column? Those of you who have used the\n", "NumPy matrix or array objects won’t be surprised at this - you use a\n", "double index.\n", "\n" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "T\n" ] } ], "source": [ "print(alignment[2, 6])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Using two integer indices pulls out a single letter, short hand for\n", "this:\n", "\n" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "T\n" ] } ], "source": [ "print(alignment[2].seq[6])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "You can pull out a single column as a string like this:\n", "\n" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "TTT---T\n" ] } ], "source": [ "print(alignment[:, 6])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "You can also select a range of columns. For example, to pick out those\n", "same three rows we extracted earlier, but take just their first six\n", "columns:\n", "\n" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SingleLetterAlphabet() alignment with 3 rows and 6 columns\n", "AEGDDP COATB_BPM13/24-72\n", "AEGDDP COATB_BPZJ2/1-49\n", "AEGDDP Q9T0Q9_BPFD/1-49\n" ] } ], "source": [ "print(alignment[3:6, :6])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Leaving the first index as `:` means take all the rows:\n", "\n" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SingleLetterAlphabet() alignment with 7 rows and 6 columns\n", "AEPNAA COATB_BPIKE/30-81\n", "AEPNAA Q9T0Q8_BPIKE/1-52\n", "DGTSTA COATB_BPI22/32-83\n", "AEGDDP COATB_BPM13/24-72\n", "AEGDDP COATB_BPZJ2/1-49\n", "AEGDDP Q9T0Q9_BPFD/1-49\n", "FAADDA COATB_BPIF1/22-73\n" ] } ], "source": [ "print(alignment[:, :6])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "This brings us to a neat way to remove a section. Notice columns 7, 8\n", "and 9 which are gaps in three of the seven sequences:\n", "\n" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SingleLetterAlphabet() alignment with 7 rows and 3 columns\n", "TNY COATB_BPIKE/30-81\n", "TNY Q9T0Q8_BPIKE/1-52\n", "TSY COATB_BPI22/32-83\n", "--- COATB_BPM13/24-72\n", "--- COATB_BPZJ2/1-49\n", "--- Q9T0Q9_BPFD/1-49\n", "TSQ COATB_BPIF1/22-73\n" ] } ], "source": [ "print(alignment[:, 6:9])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Again, you can slice to get everything after the ninth column:\n", "\n" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SingleLetterAlphabet() alignment with 7 rows and 43 columns\n", "ATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA COATB_BPIKE/30-81\n", "ATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA Q9T0Q8_BPIKE/1-52\n", "ATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA COATB_BPI22/32-83\n", "AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA COATB_BPM13/24-72\n", "AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA COATB_BPZJ2/1-49\n", "AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA Q9T0Q9_BPFD/1-49\n", "AKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA COATB_BPIF1/22-73\n" ] } ], "source": [ "print(alignment[:, 9:])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Now, the interesting thing is that addition of alignment objects works\n", "by column. This lets you do this as a way to remove a block of columns:\n", "\n" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SingleLetterAlphabet() alignment with 7 rows and 49 columns\n", "AEPNAAATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA COATB_BPIKE/30-81\n", "AEPNAAATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA Q9T0Q8_BPIKE/1-52\n", "DGTSTAATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA COATB_BPI22/32-83\n", "AEGDDPAKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA COATB_BPM13/24-72\n", "AEGDDPAKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA COATB_BPZJ2/1-49\n", "AEGDDPAKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA Q9T0Q9_BPFD/1-49\n", "FAADDAAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA COATB_BPIF1/22-73\n" ] } ], "source": [ "edited = alignment[:, :6] + alignment[:, 9:]\n", "print(edited)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Another common use of alignment addition would be to combine alignments\n", "for several different genes into a meta-alignment. Watch out though -\n", "the identifiers need to match up (see Section \\[sec:SeqRecord-addition\\]\n", "for how adding `SeqRecord` objects works). You may find it helpful to\n", "first sort the alignment rows alphabetically by id:\n", "\n" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SingleLetterAlphabet() alignment with 7 rows and 49 columns\n", "DGTSTAATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA COATB_BPI22/32-83\n", "FAADDAAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA COATB_BPIF1/22-73\n", "AEPNAAATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA COATB_BPIKE/30-81\n", "AEGDDPAKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA COATB_BPM13/24-72\n", "AEGDDPAKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA COATB_BPZJ2/1-49\n", "AEPNAAATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA Q9T0Q8_BPIKE/1-52\n", "AEGDDPAKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA Q9T0Q9_BPFD/1-49\n" ] } ], "source": [ "edited.sort()\n", "print(edited)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Note that you can only add two alignments together if they have the same\n", "number of rows.\n", "\n", "### Alignments as arrays\n", "\n", "Depending on what you are doing, it can be more useful to turn the\n", "alignment object into an array of letters – and you can do this with\n", "NumPy:\n", "\n" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Array shape 7 by 52\n" ] } ], "source": [ "import numpy as np\n", "from Bio import AlignIO\n", "alignment = AlignIO.read(\"data/PF05371_seed.sth\", \"stockholm\")\n", "align_array = np.array([list(rec) for rec in alignment], np.character)\n", "print(\"Array shape %i by %i\" % align_array.shape)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "If you will be working heavily with the columns, you can tell NumPy to\n", "store the array by column (as in Fortran) rather then its default of by\n", "row (as in C):\n", "\n" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "collapsed": true }, "outputs": [], "source": [ "align_array = np.array([list(rec) for rec in alignment], np.character, order=\"F\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Note that this leaves the original Biopython alignment object and the\n", "NumPy array in memory as separate objects - editing one will not update\n", "the other!\n", "\n", "Alignment Tools {#sec:alignment-tools}\n", "---------------\n", "\n", "There are *lots* of algorithms out there for aligning sequences, both\n", "pairwise alignments and multiple sequence alignments. These calculations\n", "are relatively slow, and you generally wouldn’t want to write such an\n", "algorithm in Python. Instead, you can use Biopython to invoke a command\n", "line tool on your behalf. Normally you would:\n", "\n", "1. Prepare an input file of your unaligned sequences, typically this\n", " will be a FASTA file which you might create using `Bio.SeqIO`\n", " (see Chapter \\[chapter:Bio.SeqIO\\]).\n", "\n", "2. Call the command line tool to process this input file, typically via\n", " one of Biopython’s command line wrappers (which we’ll discuss here).\n", "\n", "3. Read the output from the tool, i.e. your aligned sequences,\n", " typically using `Bio.AlignIO` (see earlier in this chapter).\n", "\n", "All the command line wrappers we’re going to talk about in this chapter\n", "follow the same style. You create a command line object specifying the\n", "options (e.g. the input filename and the output filename), then invoke\n", "this command line via a Python operating system call (e.g. using the\n", "`subprocess` module).\n", "\n", "Most of these wrappers are defined in the `Bio.Align.Applications`\n", "module:\n", "\n" ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['ClustalOmegaCommandline',\n", " 'ClustalwCommandline',\n", " 'DialignCommandline',\n", " 'MSAProbsCommandline',\n", " 'MafftCommandline',\n", " 'MuscleCommandline',\n", " 'PrankCommandline',\n", " 'ProbconsCommandline',\n", " 'TCoffeeCommandline',\n", " '_ClustalOmega',\n", " '_Clustalw',\n", " '_Dialign',\n", " '_MSAProbs',\n", " '_Mafft',\n", " '_Muscle',\n", " '_Prank',\n", " '_Probcons',\n", " '_TCoffee',\n", " '__all__',\n", " '__builtins__',\n", " '__cached__',\n", " '__doc__',\n", " '__docformat__',\n", " '__file__',\n", " '__loader__',\n", " '__name__',\n", " '__package__',\n", " '__path__',\n", " '__spec__']" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import Bio.Align.Applications\n", "dir(Bio.Align.Applications)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "(Ignore the entries starting with an underscore – these have special\n", "meaning in Python.) The module `Bio.Emboss.Applications` has wrappers\n", "for some of the [EMBOSS suite](http://emboss.sourceforge.net/),\n", "including `needle` and `water`, which are described below in\n", "Section \\[seq:emboss-needle-water\\], and wrappers for the EMBOSS\n", "packaged versions of the PHYLIP tools (which EMBOSS refer to as one of\n", "their EMBASSY packages - third party tools with an EMBOSS style\n", "interface). We won’t explore all these alignment tools here in the\n", "section, just a sample, but the same principles apply.\n", "\n", "### ClustalW {#sec:align_clustal}\n", "\n", "ClustalW is a popular command line tool for multiple sequence alignment\n", "(there is also a graphical interface called ClustalX). Biopython’s\n", "`Bio.Align.Applications` module has a wrapper for this alignment tool\n", "(and several others).\n", "\n", "Before trying to use ClustalW from within Python, you should first try\n", "running the ClustalW tool yourself by hand at the command line, to\n", "familiarise yourself the other options. You’ll find the Biopython\n", "wrapper is very faithful to the actual command line API:\n", "\n" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on class ClustalwCommandline in module Bio.Align.Applications._Clustalw:\n", "\n", "class ClustalwCommandline(Bio.Application.AbstractCommandline)\n", " | Command line wrapper for clustalw (version one or two).\n", " | \n", " | http://www.clustal.org/\n", " | \n", " | Example:\n", " | --------\n", " | \n", " | >>> from Bio.Align.Applications import ClustalwCommandline\n", " | >>> in_file = \"unaligned.fasta\"\n", " | >>> clustalw_cline = ClustalwCommandline(\"clustalw2\", infile=in_file)\n", " | >>> print(clustalw_cline)\n", " | clustalw2 -infile=unaligned.fasta\n", " | \n", " | You would typically run the command line with clustalw_cline() or via\n", " | the Python subprocess module, as described in the Biopython tutorial.\n", " | \n", " | Citation:\n", " | ---------\n", " | \n", " | Larkin MA, Blackshields G, Brown NP, Chenna R, McGettigan PA,\n", " | McWilliam H, Valentin F, Wallace IM, Wilm A, Lopez R, Thompson JD,\n", " | Gibson TJ, Higgins DG. (2007). Clustal W and Clustal X version 2.0.\n", " | Bioinformatics, 23, 2947-2948.\n", " | \n", " | Last checked against versions: 1.83 and 2.1\n", " | \n", " | Method resolution order:\n", " | ClustalwCommandline\n", " | Bio.Application.AbstractCommandline\n", " | builtins.object\n", " | \n", " | Methods defined here:\n", " | \n", " | __init__(self, cmd='clustalw', **kwargs)\n", " | Create a new instance of a command line wrapper object.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Methods inherited from Bio.Application.AbstractCommandline:\n", " | \n", " | __call__(self, stdin=None, stdout=True, stderr=True, cwd=None, env=None)\n", " | Executes the command, waits for it to finish, and returns output.\n", " | \n", " | Runs the command line tool and waits for it to finish. If it returns\n", " | a non-zero error level, an exception is raised. Otherwise two strings\n", " | are returned containing stdout and stderr.\n", " | \n", " | The optional stdin argument should be a string of data which will be\n", " | passed to the tool as standard input.\n", " | \n", " | The optional stdout and stderr argument may be filenames (string),\n", " | but otherwise are treated as a booleans, and control if the output\n", " | should be captured as strings (True, default), or ignored by sending\n", " | it to /dev/null to avoid wasting memory (False). If sent to a file\n", " | or ignored, then empty string(s) are returned.\n", " | \n", " | The optional cwd argument is a string giving the working directory\n", " | to run the command from. See Python's subprocess module documentation\n", " | for more details.\n", " | \n", " | The optional env argument is a dictionary setting the environment\n", " | variables to be used in the new process. By default the current\n", " | process' environment variables are used. See Python's subprocess\n", " | module documentation for more details.\n", " | \n", " | Default example usage::\n", " | \n", " | from Bio.Emboss.Applications import WaterCommandline\n", " | water_cmd = WaterCommandline(gapopen=10, gapextend=0.5,\n", " | stdout=True, auto=True,\n", " | asequence=\"a.fasta\", bsequence=\"b.fasta\")\n", " | print(\"About to run: %s\" % water_cmd)\n", " | std_output, err_output = water_cmd()\n", " | \n", " | This functionality is similar to subprocess.check_output() added in\n", " | Python 2.7. In general if you require more control over running the\n", " | command, use subprocess directly.\n", " | \n", " | As of Biopython 1.56, when the program called returns a non-zero error\n", " | level, a custom ApplicationError exception is raised. This includes\n", " | any stdout and stderr strings captured as attributes of the exception\n", " | object, since they may be useful for diagnosing what went wrong.\n", " | \n", " | __repr__(self)\n", " | Return a representation of the command line object for debugging.\n", " | \n", " | e.g.\n", " | >>> from Bio.Emboss.Applications import WaterCommandline\n", " | >>> cline = WaterCommandline(gapopen=10, gapextend=0.5)\n", " | >>> cline.asequence = \"asis:ACCCGGGCGCGGT\"\n", " | >>> cline.bsequence = \"asis:ACCCGAGCGCGGT\"\n", " | >>> cline.outfile = \"temp_water.txt\"\n", " | >>> print(cline)\n", " | water -outfile=temp_water.txt -asequence=asis:ACCCGGGCGCGGT -bsequence=asis:ACCCGAGCGCGGT -gapopen=10 -gapextend=0.5\n", " | >>> cline\n", " | WaterCommandline(cmd='water', outfile='temp_water.txt', asequence='asis:ACCCGGGCGCGGT', bsequence='asis:ACCCGAGCGCGGT', gapopen=10, gapextend=0.5)\n", " | \n", " | __setattr__(self, name, value)\n", " | Set attribute name to value (PRIVATE).\n", " | \n", " | This code implements a workaround for a user interface issue.\n", " | Without this __setattr__ attribute-based assignment of parameters\n", " | will silently accept invalid parameters, leading to known instances\n", " | of the user assuming that parameters for the application are set,\n", " | when they are not.\n", " | \n", " | >>> from Bio.Emboss.Applications import WaterCommandline\n", " | >>> cline = WaterCommandline(gapopen=10, gapextend=0.5, stdout=True)\n", " | >>> cline.asequence = \"a.fasta\"\n", " | >>> cline.bsequence = \"b.fasta\"\n", " | >>> cline.csequence = \"c.fasta\"\n", " | Traceback (most recent call last):\n", " | ...\n", " | ValueError: Option name csequence was not found.\n", " | >>> print(cline)\n", " | water -stdout -asequence=a.fasta -bsequence=b.fasta -gapopen=10 -gapextend=0.5\n", " | \n", " | This workaround uses a whitelist of object attributes, and sets the\n", " | object attribute list as normal, for these. Other attributes are\n", " | assumed to be parameters, and passed to the self.set_parameter method\n", " | for validation and assignment.\n", " | \n", " | __str__(self)\n", " | Make the commandline string with the currently set options.\n", " | \n", " | e.g.\n", " | >>> from Bio.Emboss.Applications import WaterCommandline\n", " | >>> cline = WaterCommandline(gapopen=10, gapextend=0.5)\n", " | >>> cline.asequence = \"asis:ACCCGGGCGCGGT\"\n", " | >>> cline.bsequence = \"asis:ACCCGAGCGCGGT\"\n", " | >>> cline.outfile = \"temp_water.txt\"\n", " | >>> print(cline)\n", " | water -outfile=temp_water.txt -asequence=asis:ACCCGGGCGCGGT -bsequence=asis:ACCCGAGCGCGGT -gapopen=10 -gapextend=0.5\n", " | >>> str(cline)\n", " | 'water -outfile=temp_water.txt -asequence=asis:ACCCGGGCGCGGT -bsequence=asis:ACCCGAGCGCGGT -gapopen=10 -gapextend=0.5'\n", " | \n", " | set_parameter(self, name, value=None)\n", " | Set a commandline option for a program (OBSOLETE).\n", " | \n", " | Every parameter is available via a property and as a named\n", " | keyword when creating the instance. Using either of these is\n", " | preferred to this legacy set_parameter method which is now\n", " | OBSOLETE, and likely to be DEPRECATED and later REMOVED in\n", " | future releases.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors inherited from Bio.Application.AbstractCommandline:\n", " | \n", " | __dict__\n", " | dictionary for instance variables (if defined)\n", " | \n", " | __weakref__\n", " | list of weak references to the object (if defined)\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data and other attributes inherited from Bio.Application.AbstractCommandline:\n", " | \n", " | parameters = None\n", "\n" ] } ], "source": [ "from Bio.Align.Applications import ClustalwCommandline\n", "help(ClustalwCommandline)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "For the most basic usage, all you need is to have a FASTA input file,\n", "such as\n", "[opuntia.fasta](http://biopython.org/DIST/docs/tutorial/examples/opuntia.fasta)\n", "(available online or in the Doc/examples subdirectory of the Biopython\n", "source code). This is a small FASTA file containing seven prickly-pear\n", "DNA sequences (from the cactus family *Opuntia*).\n", "\n", "By default ClustalW will generate an alignment and guide tree file with\n", "names based on the input FASTA file, in this case `opuntia.aln` and\n", "`opuntia.dnd`, but you can override this or make it explicit:\n", "\n" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "clustalw2 -infile=data/opuntia.fasta\n" ] } ], "source": [ "from Bio.Align.Applications import ClustalwCommandline\n", "cline = ClustalwCommandline(\"clustalw2\", infile=\"data/opuntia.fasta\")\n", "print(cline)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Notice here we have given the executable name as `clustalw2`, indicating\n", "we have version two installed, which has a different filename to version\n", "one (`clustalw`, the default). Fortunately both versions support the\n", "same set of arguments at the command line (and indeed, should be\n", "functionally identical).\n", "\n", "You may find that even though you have ClustalW installed, the above\n", "command doesn’t work – you may get a message about “command not found”\n", "(especially on Windows). This indicated that the ClustalW executable is\n", "not on your PATH (an environment variable, a list of directories to be\n", "searched). You can either update your PATH setting to include the\n", "location of your copy of ClustalW tools (how you do this will depend on\n", "your OS), or simply type in the full path of the tool. For example:\n", "\n" ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import os\n", "from Bio.Align.Applications import ClustalwCommandline\n", "clustalw_exe = r\"C:\\Program Files\\new clustal\\clustalw2.exe\"\n", "clustalw_cline = ClustalwCommandline(clustalw_exe, infile=\"data/opuntia.fasta\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n" ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "collapsed": false }, "outputs": [ { "ename": "AssertionError", "evalue": "Clustal W executable missing", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mAssertionError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[1;32massert\u001b[0m \u001b[0mos\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mpath\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0misfile\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mclustalw_exe\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m\"Clustal W executable missing\"\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 2\u001b[0m \u001b[0mstdout\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mstderr\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mclustalw_cline\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;31mAssertionError\u001b[0m: Clustal W executable missing" ] } ], "source": [ "assert os.path.isfile(clustalw_exe), \"Clustal W executable missing\"\n", "stdout, stderr = clustalw_cline()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Remember, in Python strings `\\n` and `\\t` are by default interpreted as\n", "a new line and a tab – which is why we’re put a letter “r” at the start\n", "for a raw string that isn’t translated in this way. This is generally\n", "good practice when specifying a Windows style file name.\n", "\n", "Internally this uses the `subprocess` module which is now the\n", "recommended way to run another program in Python. This replaces older\n", "options like the `os.system()` and the `os.popen*` functions.\n", "\n", "Now, at this point it helps to know about how command line tools “work”.\n", "When you run a tool at the command line, it will often print text output\n", "directly to screen. This text can be captured or redirected, via two\n", "“pipes”, called standard output (the normal results) and standard error\n", "(for error messages and debug messages). There is also standard input,\n", "which is any text fed into the tool. These names get shortened to stdin,\n", "stdout and stderr. When the tool finishes, it has a return code (an\n", "integer), which by convention is zero for success.\n", "\n", "When you run the command line tool like this via the Biopython wrapper,\n", "it will wait for it to finish, and check the return code. If this is non\n", "zero (indicating an error), an exception is raised. The wrapper then\n", "returns two strings, stdout and stderr.\n", "\n", "In the case of ClustalW, when run at the command line all the important\n", "output is written directly to the output files. Everything normally\n", "printed to screen while you wait (via stdout or stderr) is boring and\n", "can be ignored (assuming it worked).\n", "\n", "What we care about are the two output files, the alignment and the guide\n", "tree. We didn’t tell ClustalW what filenames to use, but it defaults to\n", "picking names based on the input file. In this case the output should be\n", "in the file `opuntia.aln`. You should be able to work out how to read in\n", "the alignment using `Bio.AlignIO` by now:\n", "\n" ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SingleLetterAlphabet() alignment with 7 rows and 906 columns\n", "TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF191\n", "TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF191\n", "TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273287|gb|AF191661.1|AF191\n", "TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273286|gb|AF191660.1|AF191\n", "TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF191\n", "TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF191\n", "TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273291|gb|AF191665.1|AF191\n" ] } ], "source": [ "from Bio import AlignIO\n", "align = AlignIO.read(\"data/opuntia.aln\", \"clustal\")\n", "print(align)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "In case you are interested (and this is an aside from the main thrust of\n", "this chapter), the `opuntia.dnd` file ClustalW creates is just a\n", "standard Newick tree file, and `Bio.Phylo` can parse these:\n", "\n" ] }, { "cell_type": "code", "execution_count": 39, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " _______________ gi|6273291|gb|AF191665.1|AF191665\n", " __________________________|\n", " | | ______ gi|6273290|gb|AF191664.1|AF191664\n", " | |__|\n", " | |_____ gi|6273289|gb|AF191663.1|AF191663\n", " |\n", "_|_________________ gi|6273287|gb|AF191661.1|AF191661\n", " |\n", " |__________ gi|6273286|gb|AF191660.1|AF191660\n", " |\n", " | __ gi|6273285|gb|AF191659.1|AF191659\n", " |___|\n", " | gi|6273284|gb|AF191658.1|AF191658\n", "\n" ] } ], "source": [ "from Bio import Phylo\n", "tree = Phylo.read(\"data/opuntia.dnd\", \"newick\")\n", "Phylo.draw_ascii(tree)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Chapter \\[sec:Phylo\\] covers Biopython’s support for phylogenetic trees\n", "in more depth.\n", "\n", "### MUSCLE\n", "\n", "MUSCLE is a more recent multiple sequence alignment tool than ClustalW,\n", "and Biopython also has a wrapper for it under the\n", "`Bio.Align.Applications` module. As before, we recommend you try using\n", "MUSCLE from the command line before trying it from within Python, as the\n", "Biopython wrapper is very faithful to the actual command line API:\n", "\n" ] }, { "cell_type": "code", "execution_count": 40, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on class MuscleCommandline in module Bio.Align.Applications._Muscle:\n", "\n", "class MuscleCommandline(Bio.Application.AbstractCommandline)\n", " | Command line wrapper for the multiple alignment program MUSCLE.\n", " | \n", " | http://www.drive5.com/muscle/\n", " | \n", " | Example:\n", " | --------\n", " | \n", " | >>> from Bio.Align.Applications import MuscleCommandline\n", " | >>> muscle_exe = r\"C:\\Program Files\\Aligments\\muscle3.8.31_i86win32.exe\"\n", " | >>> in_file = r\"C:\\My Documents\\unaligned.fasta\"\n", " | >>> out_file = r\"C:\\My Documents\\aligned.fasta\"\n", " | >>> muscle_cline = MuscleCommandline(muscle_exe, input=in_file, out=out_file)\n", " | >>> print(muscle_cline)\n", " | \"C:\\Program Files\\Aligments\\muscle3.8.31_i86win32.exe\" -in \"C:\\My Documents\\unaligned.fasta\" -out \"C:\\My Documents\\aligned.fasta\"\n", " | \n", " | You would typically run the command line with muscle_cline() or via\n", " | the Python subprocess module, as described in the Biopython tutorial.\n", " | \n", " | Citations:\n", " | ----------\n", " | \n", " | Edgar, Robert C. (2004), MUSCLE: multiple sequence alignment with high\n", " | accuracy and high throughput, Nucleic Acids Research 32(5), 1792-97.\n", " | \n", " | Edgar, R.C. (2004) MUSCLE: a multiple sequence alignment method with\n", " | reduced time and space complexity. BMC Bioinformatics 5(1): 113.\n", " | \n", " | Last checked against version: 3.7, briefly against 3.8\n", " | \n", " | Method resolution order:\n", " | MuscleCommandline\n", " | Bio.Application.AbstractCommandline\n", " | builtins.object\n", " | \n", " | Methods defined here:\n", " | \n", " | __init__(self, cmd='muscle', **kwargs)\n", " | Create a new instance of a command line wrapper object.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Methods inherited from Bio.Application.AbstractCommandline:\n", " | \n", " | __call__(self, stdin=None, stdout=True, stderr=True, cwd=None, env=None)\n", " | Executes the command, waits for it to finish, and returns output.\n", " | \n", " | Runs the command line tool and waits for it to finish. If it returns\n", " | a non-zero error level, an exception is raised. Otherwise two strings\n", " | are returned containing stdout and stderr.\n", " | \n", " | The optional stdin argument should be a string of data which will be\n", " | passed to the tool as standard input.\n", " | \n", " | The optional stdout and stderr argument may be filenames (string),\n", " | but otherwise are treated as a booleans, and control if the output\n", " | should be captured as strings (True, default), or ignored by sending\n", " | it to /dev/null to avoid wasting memory (False). If sent to a file\n", " | or ignored, then empty string(s) are returned.\n", " | \n", " | The optional cwd argument is a string giving the working directory\n", " | to run the command from. See Python's subprocess module documentation\n", " | for more details.\n", " | \n", " | The optional env argument is a dictionary setting the environment\n", " | variables to be used in the new process. By default the current\n", " | process' environment variables are used. See Python's subprocess\n", " | module documentation for more details.\n", " | \n", " | Default example usage::\n", " | \n", " | from Bio.Emboss.Applications import WaterCommandline\n", " | water_cmd = WaterCommandline(gapopen=10, gapextend=0.5,\n", " | stdout=True, auto=True,\n", " | asequence=\"a.fasta\", bsequence=\"b.fasta\")\n", " | print(\"About to run: %s\" % water_cmd)\n", " | std_output, err_output = water_cmd()\n", " | \n", " | This functionality is similar to subprocess.check_output() added in\n", " | Python 2.7. In general if you require more control over running the\n", " | command, use subprocess directly.\n", " | \n", " | As of Biopython 1.56, when the program called returns a non-zero error\n", " | level, a custom ApplicationError exception is raised. This includes\n", " | any stdout and stderr strings captured as attributes of the exception\n", " | object, since they may be useful for diagnosing what went wrong.\n", " | \n", " | __repr__(self)\n", " | Return a representation of the command line object for debugging.\n", " | \n", " | e.g.\n", " | >>> from Bio.Emboss.Applications import WaterCommandline\n", " | >>> cline = WaterCommandline(gapopen=10, gapextend=0.5)\n", " | >>> cline.asequence = \"asis:ACCCGGGCGCGGT\"\n", " | >>> cline.bsequence = \"asis:ACCCGAGCGCGGT\"\n", " | >>> cline.outfile = \"temp_water.txt\"\n", " | >>> print(cline)\n", " | water -outfile=temp_water.txt -asequence=asis:ACCCGGGCGCGGT -bsequence=asis:ACCCGAGCGCGGT -gapopen=10 -gapextend=0.5\n", " | >>> cline\n", " | WaterCommandline(cmd='water', outfile='temp_water.txt', asequence='asis:ACCCGGGCGCGGT', bsequence='asis:ACCCGAGCGCGGT', gapopen=10, gapextend=0.5)\n", " | \n", " | __setattr__(self, name, value)\n", " | Set attribute name to value (PRIVATE).\n", " | \n", " | This code implements a workaround for a user interface issue.\n", " | Without this __setattr__ attribute-based assignment of parameters\n", " | will silently accept invalid parameters, leading to known instances\n", " | of the user assuming that parameters for the application are set,\n", " | when they are not.\n", " | \n", " | >>> from Bio.Emboss.Applications import WaterCommandline\n", " | >>> cline = WaterCommandline(gapopen=10, gapextend=0.5, stdout=True)\n", " | >>> cline.asequence = \"a.fasta\"\n", " | >>> cline.bsequence = \"b.fasta\"\n", " | >>> cline.csequence = \"c.fasta\"\n", " | Traceback (most recent call last):\n", " | ...\n", " | ValueError: Option name csequence was not found.\n", " | >>> print(cline)\n", " | water -stdout -asequence=a.fasta -bsequence=b.fasta -gapopen=10 -gapextend=0.5\n", " | \n", " | This workaround uses a whitelist of object attributes, and sets the\n", " | object attribute list as normal, for these. Other attributes are\n", " | assumed to be parameters, and passed to the self.set_parameter method\n", " | for validation and assignment.\n", " | \n", " | __str__(self)\n", " | Make the commandline string with the currently set options.\n", " | \n", " | e.g.\n", " | >>> from Bio.Emboss.Applications import WaterCommandline\n", " | >>> cline = WaterCommandline(gapopen=10, gapextend=0.5)\n", " | >>> cline.asequence = \"asis:ACCCGGGCGCGGT\"\n", " | >>> cline.bsequence = \"asis:ACCCGAGCGCGGT\"\n", " | >>> cline.outfile = \"temp_water.txt\"\n", " | >>> print(cline)\n", " | water -outfile=temp_water.txt -asequence=asis:ACCCGGGCGCGGT -bsequence=asis:ACCCGAGCGCGGT -gapopen=10 -gapextend=0.5\n", " | >>> str(cline)\n", " | 'water -outfile=temp_water.txt -asequence=asis:ACCCGGGCGCGGT -bsequence=asis:ACCCGAGCGCGGT -gapopen=10 -gapextend=0.5'\n", " | \n", " | set_parameter(self, name, value=None)\n", " | Set a commandline option for a program (OBSOLETE).\n", " | \n", " | Every parameter is available via a property and as a named\n", " | keyword when creating the instance. Using either of these is\n", " | preferred to this legacy set_parameter method which is now\n", " | OBSOLETE, and likely to be DEPRECATED and later REMOVED in\n", " | future releases.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors inherited from Bio.Application.AbstractCommandline:\n", " | \n", " | __dict__\n", " | dictionary for instance variables (if defined)\n", " | \n", " | __weakref__\n", " | list of weak references to the object (if defined)\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data and other attributes inherited from Bio.Application.AbstractCommandline:\n", " | \n", " | parameters = None\n", "\n" ] } ], "source": [ "from Bio.Align.Applications import MuscleCommandline\n", "help(MuscleCommandline)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "For the most basic usage, all you need is to have a FASTA input file,\n", "such as\n", "[opuntia.fasta](http://biopython.org/DIST/docs/tutorial/examples/opuntia.fasta)\n", "(available online or in the Doc/examples subdirectory of the Biopython\n", "source code). You can then tell MUSCLE to read in this FASTA file, and\n", "write the alignment to an output file:\n", "\n" ] }, { "cell_type": "code", "execution_count": 41, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "muscle -in data/opuntia.fasta -out opuntia.txt\n" ] } ], "source": [ "from Bio.Align.Applications import MuscleCommandline\n", "cline = MuscleCommandline(input=\"data/opuntia.fasta\", out=\"opuntia.txt\")\n", "print(cline)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Note that MUSCLE uses “-in” and “-out” but in Biopython we have to use\n", "“input” and “out” as the keyword arguments or property names. This is\n", "because “in” is a reserved word in Python.\n", "\n", "By default MUSCLE will output the alignment as a FASTA file (using\n", "gapped sequences). The `Bio.AlignIO` module should be able to read this\n", "alignment using `format=fasta`. You can also ask for ClustalW-like\n", "output:\n", "\n" ] }, { "cell_type": "code", "execution_count": 42, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "muscle -in data/opuntia.fasta -out opuntia.aln -clw\n" ] } ], "source": [ "from Bio.Align.Applications import MuscleCommandline\n", "cline = MuscleCommandline(input=\"data/opuntia.fasta\", out=\"opuntia.aln\", clw=True)\n", "print(cline)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Or, strict ClustalW output where the original ClustalW header line is\n", "used for maximum compatibility:\n", "\n" ] }, { "cell_type": "code", "execution_count": 43, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "muscle -in data/opuntia.fasta -out opuntia.aln -clwstrict\n" ] } ], "source": [ "from Bio.Align.Applications import MuscleCommandline\n", "cline = MuscleCommandline(input=\"data/opuntia.fasta\", out=\"opuntia.aln\", clwstrict=True)\n", "print(cline)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "The `Bio.AlignIO` module should be able to read these alignments using\n", "`format=clustal`.\n", "\n", "MUSCLE can also output in GCG MSF format (using the `msf` argument), but\n", "Biopython can’t currently parse that, or using HTML which would give a\n", "human readable web page (not suitable for parsing).\n", "\n", "You can also set the other optional parameters, for example the maximum\n", "number of iterations. See the built in help for details.\n", "\n", "You would then run MUSCLE command line string as described above for\n", "ClustalW, and parse the output using `Bio.AlignIO` to get an alignment\n", "object.\n", "\n", "### MUSCLE using stdout\n", "\n", "Using a MUSCLE command line as in the examples above will write the\n", "alignment to a file. This means there will be no important information\n", "written to the standard out (stdout) or standard error (stderr) handles.\n", "However, by default MUSCLE will write the alignment to standard output\n", "(stdout). We can take advantage of this to avoid having a temporary\n", "output file! For example:\n", "\n" ] }, { "cell_type": "code", "execution_count": 44, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "muscle -in data/opuntia.fasta\n" ] } ], "source": [ "from Bio.Align.Applications import MuscleCommandline\n", "muscle_cline = MuscleCommandline(input=\"data/opuntia.fasta\")\n", "print(muscle_cline)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "If we run this via the wrapper, we get back the output as a string. In\n", "order to parse this we can use `StringIO` to turn it into a handle.\n", "Remember that MUSCLE defaults to using FASTA as the output format:\n", "\n" ] }, { "cell_type": "code", "execution_count": 45, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SingleLetterAlphabet() alignment with 7 rows and 906 columns\n", "TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF191663\n", "TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273291|gb|AF191665.1|AF191665\n", "TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF191664\n", "TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273287|gb|AF191661.1|AF191661\n", "TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273286|gb|AF191660.1|AF191660\n", "TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF191659\n", "TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF191658\n" ] } ], "source": [ "from Bio.Align.Applications import MuscleCommandline\n", "muscle_cline = MuscleCommandline(input=\"data/opuntia.fasta\")\n", "stdout, stderr = muscle_cline()\n", "from io import StringIO\n", "from Bio import AlignIO\n", "align = AlignIO.read(StringIO(stdout), \"fasta\")\n", "print(align)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "The above approach is fairly simple, but if you are dealing with very\n", "large output text the fact that all of stdout and stderr is loaded into\n", "memory as a string can be a potential drawback. Using the `subprocess`\n", "module we can work directly with handles instead:\n", "\n" ] }, { "cell_type": "code", "execution_count": 49, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SingleLetterAlphabet() alignment with 7 rows and 906 columns\n", "TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF191663\n", "TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273291|gb|AF191665.1|AF191665\n", "TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF191664\n", "TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273287|gb|AF191661.1|AF191661\n", "TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273286|gb|AF191660.1|AF191660\n", "TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF191659\n", "TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF191658\n" ] } ], "source": [ "import subprocess\n", "import sys\n", "from Bio.Align.Applications import MuscleCommandline\n", "muscle_cline = MuscleCommandline(input=\"data/opuntia.fasta\")\n", "child = subprocess.Popen(str(muscle_cline),\n", " stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n", " shell=(sys.platform != \"win32\"),\n", " universal_newlines=True)\n", "from Bio import AlignIO\n", "align = AlignIO.read(child.stdout, \"fasta\")\n", "print(align)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### MUSCLE using stdin and stdout\n", "\n", "We don’t actually *need* to have our FASTA input sequences prepared in a\n", "file, because by default MUSCLE will read in the input sequence from\n", "standard input! Note this is a bit more advanced and fiddly, so don’t\n", "bother with this technique unless you need to.\n", "\n", "First, we’ll need some unaligned sequences in memory as `SeqRecord`\n", "objects. For this demonstration I’m going to use a filtered version of\n", "the original FASTA file (using a generator expression), taking just six\n", "of the seven sequences:\n", "\n" ] }, { "cell_type": "code", "execution_count": 73, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from Bio import SeqIO\n", "records = (r for r in SeqIO.parse(\"data/opuntia.fasta\", \"fasta\") if len(r) < 900)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Then we create the MUSCLE command line, leaving the input and output to\n", "their defaults (stdin and stdout). I’m also going to ask for strict\n", "ClustalW format as for the output.\n", "\n" ] }, { "cell_type": "code", "execution_count": 90, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "muscle -clwstrict\n" ] } ], "source": [ "from Bio.Align.Applications import MuscleCommandline\n", "muscle_cline = MuscleCommandline(clwstrict=True)\n", "print(muscle_cline)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Now for the fiddly bits using the `subprocess` module, stdin and stdout:\n", "\n" ] }, { "cell_type": "code", "execution_count": 91, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import subprocess\n", "import sys\n", "child = subprocess.Popen(str(cline),\n", " stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n", " stderr=subprocess.PIPE, universal_newlines=True,\n", " shell=(sys.platform != \"win32\"))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "That should start MUSCLE, but it will be sitting waiting for its FASTA\n", "input sequences, which we must supply via its stdin handle:\n", "\n" ] }, { "cell_type": "code", "execution_count": 92, "metadata": { "collapsed": false }, "outputs": [ { "ename": "BrokenPipeError", "evalue": "[Errno 32] Broken pipe", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mBrokenPipeError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mSeqIO\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mwrite\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mrecords\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mchild\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mstdin\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m\"fasta\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;32m/home/tiago_antao/miniconda/lib/python3.5/site-packages/Bio/SeqIO/__init__.py\u001b[0m in \u001b[0;36mwrite\u001b[1;34m(sequences, handle, format)\u001b[0m\n\u001b[0;32m 481\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mformat\u001b[0m \u001b[1;32min\u001b[0m \u001b[0m_FormatToWriter\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 482\u001b[0m \u001b[0mwriter_class\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0m_FormatToWriter\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mformat\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 483\u001b[1;33m \u001b[0mcount\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mwriter_class\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mfp\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mwrite_file\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0msequences\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 484\u001b[0m \u001b[1;32melif\u001b[0m \u001b[0mformat\u001b[0m \u001b[1;32min\u001b[0m \u001b[0mAlignIO\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_FormatToWriter\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 485\u001b[0m \u001b[1;31m# Try and turn all the records into a single alignment,\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;32m/home/tiago_antao/miniconda/lib/python3.5/site-packages/Bio/SeqIO/Interfaces.py\u001b[0m in \u001b[0;36mwrite_file\u001b[1;34m(self, records)\u001b[0m\n\u001b[0;32m 209\u001b[0m \"\"\"\n\u001b[0;32m 210\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mwrite_header\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 211\u001b[1;33m \u001b[0mcount\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mwrite_records\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mrecords\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 212\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mwrite_footer\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 213\u001b[0m \u001b[1;32mreturn\u001b[0m \u001b[0mcount\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;32m/home/tiago_antao/miniconda/lib/python3.5/site-packages/Bio/SeqIO/Interfaces.py\u001b[0m in \u001b[0;36mwrite_records\u001b[1;34m(self, records)\u001b[0m\n\u001b[0;32m 194\u001b[0m \u001b[0mcount\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m0\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 195\u001b[0m \u001b[1;32mfor\u001b[0m \u001b[0mrecord\u001b[0m \u001b[1;32min\u001b[0m \u001b[0mrecords\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 196\u001b[1;33m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mwrite_record\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mrecord\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 197\u001b[0m \u001b[0mcount\u001b[0m \u001b[1;33m+=\u001b[0m \u001b[1;36m1\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 198\u001b[0m \u001b[1;31m# Mark as true, even if there where no records\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;32m/home/tiago_antao/miniconda/lib/python3.5/site-packages/Bio/SeqIO/FastaIO.py\u001b[0m in \u001b[0;36mwrite_record\u001b[1;34m(self, record)\u001b[0m\n\u001b[0;32m 209\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mwrap\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 210\u001b[0m \u001b[1;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[1;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mlen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mdata\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mwrap\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 211\u001b[1;33m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mhandle\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mwrite\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mdata\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mi\u001b[0m\u001b[1;33m:\u001b[0m\u001b[0mi\u001b[0m \u001b[1;33m+\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mwrap\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m+\u001b[0m \u001b[1;34m\"\\n\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 212\u001b[0m \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 213\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mhandle\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mwrite\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mdata\u001b[0m \u001b[1;33m+\u001b[0m \u001b[1;34m\"\\n\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;31mBrokenPipeError\u001b[0m: [Errno 32] Broken pipe" ] } ], "source": [ "SeqIO.write(records, child.stdin, \"fasta\")" ] }, { "cell_type": "code", "execution_count": 93, "metadata": { "collapsed": false }, "outputs": [ { "ename": "BrokenPipeError", "evalue": "[Errno 32] Broken pipe", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mBrokenPipeError\u001b[0m Traceback (most recent call last)", "\u001b[1;31mBrokenPipeError\u001b[0m: [Errno 32] Broken pipe", "\nDuring handling of the above exception, another exception occurred:\n", "\u001b[1;31mBrokenPipeError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mchild\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mstdin\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mclose\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mBrokenPipeError\u001b[0m: [Errno 32] Broken pipe" ] } ], "source": [ "child.stdin.close()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "After writing the six sequences to the handle, MUSCLE will still be\n", "waiting to see if that is all the FASTA sequences or not – so we must\n", "signal that this is all the input data by closing the handle. At that\n", "point MUSCLE should start to run, and we can ask for the output:\n", "\n" ] }, { "cell_type": "code", "execution_count": 94, "metadata": { "collapsed": false }, "outputs": [ { "ename": "ValueError", "evalue": "No records found in handle", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mfrom\u001b[0m \u001b[0mBio\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mAlignIO\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0malign\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mAlignIO\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mread\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mchild\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mstdout\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m\"clustal\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 3\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0malign\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;32m/home/tiago_antao/miniconda/lib/python3.5/site-packages/Bio/AlignIO/__init__.py\u001b[0m in \u001b[0;36mread\u001b[1;34m(handle, format, seq_count, alphabet)\u001b[0m\n\u001b[0;32m 429\u001b[0m \u001b[0mfirst\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;32mNone\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 430\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mfirst\u001b[0m \u001b[1;32mis\u001b[0m \u001b[1;32mNone\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 431\u001b[1;33m \u001b[1;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"No records found in handle\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 432\u001b[0m \u001b[1;32mtry\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 433\u001b[0m \u001b[0msecond\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mnext\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0miterator\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;31mValueError\u001b[0m: No records found in handle" ] } ], "source": [ "from Bio import AlignIO\n", "align = AlignIO.read(child.stdout, \"clustal\")\n", "print(align)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Wow! There we are with a new alignment of just the six records, without\n", "having created a temporary FASTA input file, or a temporary alignment\n", "output file. However, a word of caution: Dealing with errors with this\n", "style of calling external programs is much more complicated. It also\n", "becomes far harder to diagnose problems, because you can’t try running\n", "MUSCLE manually outside of Biopython (because you don’t have the input\n", "file to supply). There can also be subtle cross platform issues (e.g.\n", "Windows versus Linux, Python 2 versus Python 3), and how you run your\n", "script can have an impact (e.g. at the command line, from IDLE or an\n", "IDE, or as a GUI script). These are all generic Python issues though,\n", "and not specific to Biopython.\n", "\n", "If you find working directly with `subprocess` like this scary, there is\n", "an alternative. If you execute the tool with `muscle_cline()` you can\n", "supply any standard input as a big string, `muscle_cline(stdin=...)`.\n", "So, provided your data isn’t very big, you can prepare the FASTA input\n", "in memory as a string using `StringIO` (see\n", "Section \\[sec:appendix-handles\\]):\n", "\n" ] }, { "cell_type": "code", "execution_count": 95, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "6" ] }, "execution_count": 95, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from Bio import SeqIO\n", "records = (r for r in SeqIO.parse(\"data/opuntia.fasta\", \"fasta\") if len(r) < 900)\n", "handle = StringIO()\n", "SeqIO.write(records, handle, \"fasta\")" ] }, { "cell_type": "code", "execution_count": 96, "metadata": { "collapsed": true }, "outputs": [], "source": [ "data = handle.getvalue()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "You can then run the tool and parse the alignment as follows:\n", "\n" ] }, { "cell_type": "code", "execution_count": 97, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SingleLetterAlphabet() alignment with 6 rows and 900 columns\n", "TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF19166\n", "TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF19166\n", "TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273287|gb|AF191661.1|AF19166\n", "TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273286|gb|AF191660.1|AF19166\n", "TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF19165\n", "TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF19165\n" ] } ], "source": [ "stdout, stderr = muscle_cline(stdin=data)\n", "from Bio import AlignIO\n", "align = AlignIO.read(StringIO(stdout), \"clustal\")\n", "print(align)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "You might find this easier, but it does require more memory (RAM) for\n", "the strings used for the input FASTA and output Clustal formatted data.\n", "\n", "### EMBOSS needle and water {#seq:emboss-needle-water}\n", "\n", "The [EMBOSS](http://emboss.sourceforge.net/) suite includes the `water`\n", "and `needle` tools for Smith-Waterman algorithm local alignment, and\n", "Needleman-Wunsch global alignment. The tools share the same style\n", "interface, so switching between the two is trivial – we’ll just use\n", "`needle` here.\n", "\n", "Suppose you want to do a global pairwise alignment between two\n", "sequences, prepared in FASTA format as follows:\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", ">HBA_HUMAN\n", "MVLSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTYFPHFDLSHGSAQVKGHG\n", "KKVADALTNAVAHVDDMPNALSALSDLHAHKLRVDPVNFKLLSHCLLVTLAAHLPAEFTP\n", "AVHASLDKFLASVSTVLTSKYR\n", "\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "in a file `alpha.fasta`, and secondly in a file `beta.fasta`:\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", ">HBB_HUMAN\n", "MVHLTPEEKSAVTALWGKVNVDEVGGEALGRLLVVYPWTQRFFESFGDLSTPDAVMGNPK\n", "VKAHGKKVLGAFSDGLAHLDNLKGTFATLSELHCDKLHVDPENFRLLGNVLVCVLAHHFG\n", "KEFTPPVQAAYQKVVAGVANALAHKYH\n", "\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Let’s start by creating a complete `needle` command line object in one\n", "go:\n", "\n" ] }, { "cell_type": "code", "execution_count": 98, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "needle -outfile=needle.txt -asequence=data/alpha.faa -bsequence=data/beta.faa -gapopen=10 -gapextend=0.5\n" ] } ], "source": [ "from Bio.Emboss.Applications import NeedleCommandline\n", "needle_cline = NeedleCommandline(asequence=\"data/alpha.faa\", bsequence=\"data/beta.faa\",\n", " gapopen=10, gapextend=0.5, outfile=\"needle.txt\")\n", "print(needle_cline)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Why not try running this by hand at the command prompt? You should see\n", "it does a pairwise comparison and records the output in the file\n", "`needle.txt` (in the default EMBOSS alignment file format).\n", "\n", "Even if you have EMBOSS installed, running this command may not work –\n", "you might get a message about “command not found” (especially on\n", "Windows). This probably means that the EMBOSS tools are not on your PATH\n", "environment variable. You can either update your PATH setting, or simply\n", "tell Biopython the full path to the tool, for example:\n", "\n" ] }, { "cell_type": "code", "execution_count": 99, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from Bio.Emboss.Applications import NeedleCommandline\n", "needle_cline = NeedleCommandline(r\"C:\\EMBOSS\\needle.exe\",\n", " asequence=\"data/alpha.faa\", bsequence=\"data/beta.faa\",\n", " gapopen=10, gapextend=0.5, outfile=\"needle.txt\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Remember in Python that for a default string `\\n` or `\\t` means a new\n", "line or a tab – which is why we’re put a letter “r” at the start for a\n", "raw string.\n", "\n", "At this point it might help to try running the EMBOSS tools yourself by\n", "hand at the command line, to familiarise yourself the other options and\n", "compare them to the Biopython help text:\n", "\n" ] }, { "cell_type": "code", "execution_count": 100, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on class NeedleCommandline in module Bio.Emboss.Applications:\n", "\n", "class NeedleCommandline(_EmbossCommandLine)\n", " | Commandline object for the needle program from EMBOSS.\n", " | \n", " | Method resolution order:\n", " | NeedleCommandline\n", " | _EmbossCommandLine\n", " | _EmbossMinimalCommandLine\n", " | Bio.Application.AbstractCommandline\n", " | builtins.object\n", " | \n", " | Methods defined here:\n", " | \n", " | __init__(self, cmd='needle', **kwargs)\n", " | Create a new instance of a command line wrapper object.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors defined here:\n", " | \n", " | aformat\n", " | Display output in a different specified output format\n", " | \n", " | This controls the addition of the -aformat parameter and its associated value. Set this property to the argument value required.\n", " | \n", " | asequence\n", " | First sequence to align\n", " | \n", " | This controls the addition of the -asequence parameter and its associated value. Set this property to the argument value required.\n", " | \n", " | auto\n", " | Turn off prompts.\n", " | \n", " | Automatic mode disables prompting, so we recommend you set\n", " | this argument all the time when calling an EMBOSS tool from\n", " | Biopython.\n", " | \n", " | \n", " | This property controls the addition of the -auto switch, treat this property as a boolean.\n", " | \n", " | brief\n", " | Display brief identity and similarity\n", " | \n", " | This property controls the addition of the -brief switch, treat this property as a boolean.\n", " | \n", " | bsequence\n", " | Second sequence to align\n", " | \n", " | This controls the addition of the -bsequence parameter and its associated value. Set this property to the argument value required.\n", " | \n", " | datafile\n", " | Matrix file\n", " | \n", " | This controls the addition of the -datafile parameter and its associated value. Set this property to the argument value required.\n", " | \n", " | debug\n", " | Write debug output to program.dbg.\n", " | \n", " | This property controls the addition of the -debug switch, treat this property as a boolean.\n", " | \n", " | die\n", " | Report dying program messages.\n", " | \n", " | This property controls the addition of the -die switch, treat this property as a boolean.\n", " | \n", " | endextend\n", " | The score added to the end gap penality for each base or residue in the end gap.\n", " | \n", " | This controls the addition of the -endextend parameter and its associated value. Set this property to the argument value required.\n", " | \n", " | endopen\n", " | The score taken away when an end gap is created.\n", " | \n", " | This controls the addition of the -endopen parameter and its associated value. Set this property to the argument value required.\n", " | \n", " | endweight\n", " | Apply And gap penalties\n", " | \n", " | This controls the addition of the -endweight parameter and its associated value. Set this property to the argument value required.\n", " | \n", " | error\n", " | Report errors.\n", " | \n", " | This property controls the addition of the -error switch, treat this property as a boolean.\n", " | \n", " | filter\n", " | Read standard input, write standard output.\n", " | \n", " | This property controls the addition of the -filter switch, treat this property as a boolean.\n", " | \n", " | gapextend\n", " | Gap extension penalty\n", " | \n", " | This controls the addition of the -gapextend parameter and its associated value. Set this property to the argument value required.\n", " | \n", " | gapopen\n", " | Gap open penalty\n", " | \n", " | This controls the addition of the -gapopen parameter and its associated value. Set this property to the argument value required.\n", " | \n", " | help\n", " | Report command line options.\n", " | \n", " | More information on associated and general qualifiers can\n", " | be found with -help -verbose\n", " | \n", " | \n", " | This property controls the addition of the -help switch, treat this property as a boolean.\n", " | \n", " | nobrief\n", " | Display extended identity and similarity\n", " | \n", " | This property controls the addition of the -nobrief switch, treat this property as a boolean.\n", " | \n", " | options\n", " | Prompt for standard and additional values.\n", " | \n", " | If you are calling an EMBOSS tool from within Biopython,\n", " | we DO NOT recommend using this option.\n", " | \n", " | \n", " | This property controls the addition of the -options switch, treat this property as a boolean.\n", " | \n", " | outfile\n", " | Output filename\n", " | \n", " | This controls the addition of the -outfile parameter and its associated value. Set this property to the argument value required.\n", " | \n", " | similarity\n", " | Display percent identity and similarity\n", " | \n", " | This controls the addition of the -similarity parameter and its associated value. Set this property to the argument value required.\n", " | \n", " | snucleotide\n", " | Sequences are nucleotide (boolean)\n", " | \n", " | This controls the addition of the -snucleotide parameter and its associated value. Set this property to the argument value required.\n", " | \n", " | sprotein\n", " | Sequences are protein (boolean)\n", " | \n", " | This controls the addition of the -sprotein parameter and its associated value. Set this property to the argument value required.\n", " | \n", " | stdout\n", " | Write standard output.\n", " | \n", " | This property controls the addition of the -stdout switch, treat this property as a boolean.\n", " | \n", " | verbose\n", " | Report some/full command line options\n", " | \n", " | This property controls the addition of the -verbose switch, treat this property as a boolean.\n", " | \n", " | warning\n", " | Report warnings.\n", " | \n", " | This property controls the addition of the -warning switch, treat this property as a boolean.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Methods inherited from Bio.Application.AbstractCommandline:\n", " | \n", " | __call__(self, stdin=None, stdout=True, stderr=True, cwd=None, env=None)\n", " | Executes the command, waits for it to finish, and returns output.\n", " | \n", " | Runs the command line tool and waits for it to finish. If it returns\n", " | a non-zero error level, an exception is raised. Otherwise two strings\n", " | are returned containing stdout and stderr.\n", " | \n", " | The optional stdin argument should be a string of data which will be\n", " | passed to the tool as standard input.\n", " | \n", " | The optional stdout and stderr argument may be filenames (string),\n", " | but otherwise are treated as a booleans, and control if the output\n", " | should be captured as strings (True, default), or ignored by sending\n", " | it to /dev/null to avoid wasting memory (False). If sent to a file\n", " | or ignored, then empty string(s) are returned.\n", " | \n", " | The optional cwd argument is a string giving the working directory\n", " | to run the command from. See Python's subprocess module documentation\n", " | for more details.\n", " | \n", " | The optional env argument is a dictionary setting the environment\n", " | variables to be used in the new process. By default the current\n", " | process' environment variables are used. See Python's subprocess\n", " | module documentation for more details.\n", " | \n", " | Default example usage::\n", " | \n", " | from Bio.Emboss.Applications import WaterCommandline\n", " | water_cmd = WaterCommandline(gapopen=10, gapextend=0.5,\n", " | stdout=True, auto=True,\n", " | asequence=\"a.fasta\", bsequence=\"b.fasta\")\n", " | print(\"About to run: %s\" % water_cmd)\n", " | std_output, err_output = water_cmd()\n", " | \n", " | This functionality is similar to subprocess.check_output() added in\n", " | Python 2.7. In general if you require more control over running the\n", " | command, use subprocess directly.\n", " | \n", " | As of Biopython 1.56, when the program called returns a non-zero error\n", " | level, a custom ApplicationError exception is raised. This includes\n", " | any stdout and stderr strings captured as attributes of the exception\n", " | object, since they may be useful for diagnosing what went wrong.\n", " | \n", " | __repr__(self)\n", " | Return a representation of the command line object for debugging.\n", " | \n", " | e.g.\n", " | >>> from Bio.Emboss.Applications import WaterCommandline\n", " | >>> cline = WaterCommandline(gapopen=10, gapextend=0.5)\n", " | >>> cline.asequence = \"asis:ACCCGGGCGCGGT\"\n", " | >>> cline.bsequence = \"asis:ACCCGAGCGCGGT\"\n", " | >>> cline.outfile = \"temp_water.txt\"\n", " | >>> print(cline)\n", " | water -outfile=temp_water.txt -asequence=asis:ACCCGGGCGCGGT -bsequence=asis:ACCCGAGCGCGGT -gapopen=10 -gapextend=0.5\n", " | >>> cline\n", " | WaterCommandline(cmd='water', outfile='temp_water.txt', asequence='asis:ACCCGGGCGCGGT', bsequence='asis:ACCCGAGCGCGGT', gapopen=10, gapextend=0.5)\n", " | \n", " | __setattr__(self, name, value)\n", " | Set attribute name to value (PRIVATE).\n", " | \n", " | This code implements a workaround for a user interface issue.\n", " | Without this __setattr__ attribute-based assignment of parameters\n", " | will silently accept invalid parameters, leading to known instances\n", " | of the user assuming that parameters for the application are set,\n", " | when they are not.\n", " | \n", " | >>> from Bio.Emboss.Applications import WaterCommandline\n", " | >>> cline = WaterCommandline(gapopen=10, gapextend=0.5, stdout=True)\n", " | >>> cline.asequence = \"a.fasta\"\n", " | >>> cline.bsequence = \"b.fasta\"\n", " | >>> cline.csequence = \"c.fasta\"\n", " | Traceback (most recent call last):\n", " | ...\n", " | ValueError: Option name csequence was not found.\n", " | >>> print(cline)\n", " | water -stdout -asequence=a.fasta -bsequence=b.fasta -gapopen=10 -gapextend=0.5\n", " | \n", " | This workaround uses a whitelist of object attributes, and sets the\n", " | object attribute list as normal, for these. Other attributes are\n", " | assumed to be parameters, and passed to the self.set_parameter method\n", " | for validation and assignment.\n", " | \n", " | __str__(self)\n", " | Make the commandline string with the currently set options.\n", " | \n", " | e.g.\n", " | >>> from Bio.Emboss.Applications import WaterCommandline\n", " | >>> cline = WaterCommandline(gapopen=10, gapextend=0.5)\n", " | >>> cline.asequence = \"asis:ACCCGGGCGCGGT\"\n", " | >>> cline.bsequence = \"asis:ACCCGAGCGCGGT\"\n", " | >>> cline.outfile = \"temp_water.txt\"\n", " | >>> print(cline)\n", " | water -outfile=temp_water.txt -asequence=asis:ACCCGGGCGCGGT -bsequence=asis:ACCCGAGCGCGGT -gapopen=10 -gapextend=0.5\n", " | >>> str(cline)\n", " | 'water -outfile=temp_water.txt -asequence=asis:ACCCGGGCGCGGT -bsequence=asis:ACCCGAGCGCGGT -gapopen=10 -gapextend=0.5'\n", " | \n", " | set_parameter(self, name, value=None)\n", " | Set a commandline option for a program (OBSOLETE).\n", " | \n", " | Every parameter is available via a property and as a named\n", " | keyword when creating the instance. Using either of these is\n", " | preferred to this legacy set_parameter method which is now\n", " | OBSOLETE, and likely to be DEPRECATED and later REMOVED in\n", " | future releases.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors inherited from Bio.Application.AbstractCommandline:\n", " | \n", " | __dict__\n", " | dictionary for instance variables (if defined)\n", " | \n", " | __weakref__\n", " | list of weak references to the object (if defined)\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data and other attributes inherited from Bio.Application.AbstractCommandline:\n", " | \n", " | parameters = None\n", "\n" ] } ], "source": [ "from Bio.Emboss.Applications import NeedleCommandline\n", "help(NeedleCommandline)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Note that you can also specify (or change or look at) the settings like\n", "this:\n", "\n" ] }, { "cell_type": "code", "execution_count": 101, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "needle -outfile=needle.txt -asequence=data/alpha.faa -bsequence=data/beta.faa -gapopen=10 -gapextend=0.5\n" ] } ], "source": [ "from Bio.Emboss.Applications import NeedleCommandline\n", "needle_cline = NeedleCommandline()\n", "needle_cline.asequence=\"data/alpha.faa\"\n", "needle_cline.bsequence=\"data/beta.faa\"\n", "needle_cline.gapopen=10\n", "needle_cline.gapextend=0.5\n", "needle_cline.outfile=\"needle.txt\"\n", "print(needle_cline)\n" ] }, { "cell_type": "code", "execution_count": 102, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "needle.txt\n" ] } ], "source": [ "print(needle_cline.outfile)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Next we want to use Python to run this command for us. As explained\n", "above, for full control, we recommend you use the built in Python\n", "`subprocess` module, but for simple usage the wrapper object usually\n", "suffices:\n", "\n" ] }, { "cell_type": "code", "execution_count": 103, "metadata": { "collapsed": false }, "outputs": [ { "ename": "ApplicationError", "evalue": "Non-zero return code 127 from 'needle -outfile=needle.txt -asequence=data/alpha.faa -bsequence=data/beta.faa -gapopen=10 -gapextend=0.5', message '/bin/sh: 1: needle: not found'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mApplicationError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mstdout\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mstderr\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mneedle_cline\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 2\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mstdout\u001b[0m \u001b[1;33m+\u001b[0m \u001b[0mstderr\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;32m/home/tiago_antao/miniconda/lib/python3.5/site-packages/Bio/Application/__init__.py\u001b[0m in \u001b[0;36m__call__\u001b[1;34m(self, stdin, stdout, stderr, cwd, env)\u001b[0m\n\u001b[0;32m 515\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mreturn_code\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 516\u001b[0m raise ApplicationError(return_code, str(self),\n\u001b[1;32m--> 517\u001b[1;33m stdout_str, stderr_str)\n\u001b[0m\u001b[0;32m 518\u001b[0m \u001b[1;32mreturn\u001b[0m \u001b[0mstdout_str\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mstderr_str\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 519\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;31mApplicationError\u001b[0m: Non-zero return code 127 from 'needle -outfile=needle.txt -asequence=data/alpha.faa -bsequence=data/beta.faa -gapopen=10 -gapextend=0.5', message '/bin/sh: 1: needle: not found'" ] } ], "source": [ "stdout, stderr = needle_cline()\n", "print(stdout + stderr)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Next we can load the output file with `Bio.AlignIO` as discussed earlier\n", "in this chapter, as the `emboss` format:\n", "\n" ] }, { "cell_type": "code", "execution_count": 104, "metadata": { "collapsed": false }, "outputs": [ { "ename": "FileNotFoundError", "evalue": "[Errno 2] No such file or directory: 'needle.txt'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mFileNotFoundError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mfrom\u001b[0m \u001b[0mBio\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mAlignIO\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0malign\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mAlignIO\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mread\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"needle.txt\"\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m\"emboss\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 3\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0malign\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;32m/home/tiago_antao/miniconda/lib/python3.5/site-packages/Bio/AlignIO/__init__.py\u001b[0m in \u001b[0;36mread\u001b[1;34m(handle, format, seq_count, alphabet)\u001b[0m\n\u001b[0;32m 425\u001b[0m \u001b[0miterator\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mparse\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mhandle\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mformat\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mseq_count\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0malphabet\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 426\u001b[0m \u001b[1;32mtry\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 427\u001b[1;33m \u001b[0mfirst\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mnext\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0miterator\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 428\u001b[0m \u001b[1;32mexcept\u001b[0m \u001b[0mStopIteration\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 429\u001b[0m \u001b[0mfirst\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;32mNone\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;32m/home/tiago_antao/miniconda/lib/python3.5/site-packages/Bio/AlignIO/__init__.py\u001b[0m in \u001b[0;36mparse\u001b[1;34m(handle, format, seq_count, alphabet)\u001b[0m\n\u001b[0;32m 348\u001b[0m \u001b[1;32mraise\u001b[0m \u001b[0mTypeError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Need integer for seq_count (sequences per alignment)\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 349\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 350\u001b[1;33m \u001b[1;32mwith\u001b[0m \u001b[0mas_handle\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mhandle\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m'rU'\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mfp\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 351\u001b[0m \u001b[1;31m# Map the file format to a sequence iterator:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 352\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mformat\u001b[0m \u001b[1;32min\u001b[0m \u001b[0m_FormatToIterator\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;32m/home/tiago_antao/miniconda/lib/python3.5/contextlib.py\u001b[0m in \u001b[0;36m__enter__\u001b[1;34m(self)\u001b[0m\n\u001b[0;32m 57\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0m__enter__\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 58\u001b[0m \u001b[1;32mtry\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 59\u001b[1;33m \u001b[1;32mreturn\u001b[0m \u001b[0mnext\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mgen\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 60\u001b[0m \u001b[1;32mexcept\u001b[0m \u001b[0mStopIteration\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 61\u001b[0m \u001b[1;32mraise\u001b[0m \u001b[0mRuntimeError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"generator didn't yield\"\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mfrom\u001b[0m \u001b[1;32mNone\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;32m/home/tiago_antao/miniconda/lib/python3.5/site-packages/Bio/File.py\u001b[0m in \u001b[0;36mas_handle\u001b[1;34m(handleish, mode, **kwargs)\u001b[0m\n\u001b[0;32m 88\u001b[0m \u001b[1;32myield\u001b[0m \u001b[0mfp\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 89\u001b[0m \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 90\u001b[1;33m \u001b[1;32mwith\u001b[0m \u001b[0mopen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mhandleish\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mmode\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;33m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mfp\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 91\u001b[0m \u001b[1;32myield\u001b[0m \u001b[0mfp\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 92\u001b[0m \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: 'needle.txt'" ] } ], "source": [ "from Bio import AlignIO\n", "align = AlignIO.read(\"needle.txt\", \"emboss\")\n", "print(align)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.5.1" } }, "nbformat": 4, "nbformat_minor": 0 }