diff -Nru python-biopython-1.62/Bio/Affy/CelFile.py python-biopython-1.63/Bio/Affy/CelFile.py --- python-biopython-1.62/Bio/Affy/CelFile.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Affy/CelFile.py 2013-12-05 14:10:43.000000000 +0000 @@ -58,7 +58,8 @@ if "=" in line: continue words = line.split() - y, x = map(int, words[:2]) + y = int(words[0]) + x = int(words[1]) record.intensities[x, y] = float(words[2]) record.stdevs[x, y] = float(words[3]) record.npix[x, y] = int(words[4]) diff -Nru python-biopython-1.62/Bio/Affy/__init__.py python-biopython-1.63/Bio/Affy/__init__.py --- python-biopython-1.62/Bio/Affy/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Affy/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,2 +1,7 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Deal with Affymetrix related data such as cel files. """ diff -Nru python-biopython-1.62/Bio/Align/AlignInfo.py python-biopython-1.63/Bio/Align/AlignInfo.py --- python-biopython-1.62/Bio/Align/AlignInfo.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Align/AlignInfo.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Extract information from alignment objects. In order to try and avoid huge alignment objects with tons of functions, @@ -9,11 +14,11 @@ o PSSM """ -# standard library +from __future__ import print_function + import math import sys -# biopython modules from Bio import Alphabet from Bio.Alphabet import IUPAC from Bio.Seq import Seq @@ -255,8 +260,8 @@ rep_dict = self._pair_replacement( self.alignment._records[rec_num1].seq, self.alignment._records[rec_num2].seq, - self.alignment._records[rec_num1].annotations.get('weight',1.0), - self.alignment._records[rec_num2].annotations.get('weight',1.0), + self.alignment._records[rec_num1].annotations.get('weight', 1.0), + self.alignment._records[rec_num2].annotations.get('weight', 1.0), rep_dict, skip_items) return rep_dict @@ -316,8 +321,7 @@ #Note the built in set does not have a union_update #which was provided by the sets module's Set set_letters = set_letters.union(record.seq) - list_letters = list(set_letters) - list_letters.sort() + list_letters = sorted(set_letters) all_letters = "".join(list_letters) return all_letters @@ -342,7 +346,7 @@ # and drop it out if isinstance(self.alignment._alphabet, Alphabet.Gapped): skip_items.append(self.alignment._alphabet.gap_char) - all_letters = all_letters.replace(self.alignment._alphabet.gap_char,'') + all_letters = all_letters.replace(self.alignment._alphabet.gap_char, '') # now create the dictionary for first_letter in all_letters: @@ -499,7 +503,7 @@ info_content[residue_num] = column_score # sum up the score - total_info = sum(info_content.itervalues()) + total_info = sum(info_content.values()) # fill in the ic_vector member: holds IC for each column for i in info_content: self.ic_vector[i] = info_content[i] @@ -528,7 +532,7 @@ for record in all_records: try: if record.seq[residue_num] not in to_ignore: - weight = record.annotations.get('weight',1.0) + weight = record.annotations.get('weight', 1.0) freq_info[record.seq[residue_num]] += weight total_count += weight # getting a key error means we've got a problem with the alphabet @@ -575,8 +579,8 @@ if (key != gap_char and key not in e_freq_table): raise ValueError("Expected frequency letters %s " "do not match observed %s" - % (e_freq_table.keys(), - obs_freq.keys() - [gap_char])) + % (list(e_freq_table.keys()), + list(obs_freq.keys()) - [gap_char])) total_info = 0.0 @@ -598,7 +602,7 @@ total_info += letter_info return total_info - def get_column(self,col): + def get_column(self, col): return self.alignment.get_column(col) @@ -647,8 +651,7 @@ def __str__(self): out = " " - all_residues = self.pssm[0][1].keys() - all_residues.sort() + all_residues = sorted(self.pssm[0][1]) # first print out the top header for res in all_residues: @@ -677,14 +680,12 @@ if not summary_info.ic_vector: summary_info.information_content() rep_sequence = summary_info.alignment._records[rep_record].seq - positions = summary_info.ic_vector.keys() - positions.sort() - for pos in positions: + for pos in sorted(summary_info.ic_vector): fout.write("%d %s %.3f\n" % (pos, rep_sequence[pos], summary_info.ic_vector[pos])) if __name__ == "__main__": - print "Quick test" + print("Quick test") from Bio import AlignIO from Bio.Align.Generic import Alignment @@ -696,41 +697,41 @@ alignment = AlignIO.read(open(filename), format) for record in alignment: - print str(record.seq) - print "="*alignment.get_alignment_length() + print(str(record.seq)) + print("="*alignment.get_alignment_length()) summary = SummaryInfo(alignment) consensus = summary.dumb_consensus(ambiguous="N") - print consensus + print(consensus) consensus = summary.gap_consensus(ambiguous="N") - print consensus - print - print summary.pos_specific_score_matrix(chars_to_ignore=['-'], - axis_seq=consensus) - print + print(consensus) + print("") + print(summary.pos_specific_score_matrix(chars_to_ignore=['-'], + axis_seq=consensus)) + print("") #Have a generic alphabet, without a declared gap char, so must tell #provide the frequencies and chars to ignore explicitly. - print summary.information_content(e_freq_table=expected, - chars_to_ignore=['-']) - print - print "Trying a protein sequence with gaps and stops" + print(summary.information_content(e_freq_table=expected, + chars_to_ignore=['-'])) + print("") + print("Trying a protein sequence with gaps and stops") alpha = Alphabet.HasStopCodon(Alphabet.Gapped(Alphabet.generic_protein, "-"), "*") a = Alignment(alpha) a.add_sequence("ID001", "MHQAIFIYQIGYP*LKSGYIQSIRSPEYDNW-") a.add_sequence("ID002", "MH--IFIYQIGYAYLKSGYIQSIRSPEY-NW*") a.add_sequence("ID003", "MHQAIFIYQIGYPYLKSGYIQSIRSPEYDNW*") - print a - print "="*a.get_alignment_length() + print(a) + print("="*a.get_alignment_length()) s = SummaryInfo(a) c = s.dumb_consensus(ambiguous="X") - print c + print(c) c = s.gap_consensus(ambiguous="X") - print c - print - print s.pos_specific_score_matrix(chars_to_ignore=['-', '*'], axis_seq=c) + print(c) + print("") + print(s.pos_specific_score_matrix(chars_to_ignore=['-', '*'], axis_seq=c)) - print s.information_content(chars_to_ignore=['-', '*']) + print(s.information_content(chars_to_ignore=['-', '*'])) - print "Done" + print("Done") diff -Nru python-biopython-1.62/Bio/Align/Applications/_ClustalOmega.py python-biopython-1.63/Bio/Align/Applications/_ClustalOmega.py --- python-biopython-1.62/Bio/Align/Applications/_ClustalOmega.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Align/Applications/_ClustalOmega.py 2013-12-05 14:10:43.000000000 +0000 @@ -11,6 +11,8 @@ """Command line wrapper for the multiple alignment program Clustal Omega. """ +from __future__ import print_function + __docformat__ = "epytext en" # Don't just use plain text in epydoc API pages! from Bio.Application import _Option, _Switch, AbstractCommandline @@ -27,7 +29,7 @@ >>> in_file = "unaligned.fasta" >>> out_file = "aligned.fasta" >>> clustalomega_cline = ClustalOmegaCommandline(infile=in_file, outfile=out_file, verbose=True, auto=True) - >>> print clustalomega_cline + >>> print(clustalomega_cline) clustalo -i unaligned.fasta -o aligned.fasta --auto -v @@ -199,10 +201,10 @@ def _test(): """Run the module's doctests (PRIVATE).""" - print "Running ClustalOmega doctests..." + print("Running ClustalOmega doctests...") import doctest doctest.testmod() - print "Done" + print("Done") if __name__ == "__main__": _test() diff -Nru python-biopython-1.62/Bio/Align/Applications/_Clustalw.py python-biopython-1.63/Bio/Align/Applications/_Clustalw.py --- python-biopython-1.62/Bio/Align/Applications/_Clustalw.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Align/Applications/_Clustalw.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,6 +5,8 @@ """Command line wrapper for the multiple alignment program Clustal W. """ +from __future__ import print_function + __docformat__ = "epytext en" # Don't just use plain text in epydoc API pages! import os @@ -21,7 +23,7 @@ >>> from Bio.Align.Applications import ClustalwCommandline >>> in_file = "unaligned.fasta" >>> clustalw_cline = ClustalwCommandline("clustalw2", infile=in_file) - >>> print clustalw_cline + >>> print(clustalw_cline) clustalw2 -infile=unaligned.fasta You would typically run the command line with clustalw_cline() or via @@ -142,7 +144,7 @@ _Option(["-score", "-SCORE", "SCORE", "score"], "Either: PERCENT or ABSOLUTE", checker_function=lambda x: x in ["percent", "PERCENT", - "absolute","ABSOLUTE"]), + "absolute", "ABSOLUTE"]), # ***Slow Pairwise Alignments:*** _Option(["-pwmatrix", "-PWMATRIX", "PWMATRIX", "pwmatrix"], "Protein weight matrix=BLOSUM, PAM, GONNET, ID or filename", @@ -328,10 +330,10 @@ def _test(): """Run the module's doctests (PRIVATE).""" - print "Running ClustalW doctests..." + print("Running ClustalW doctests...") import doctest doctest.testmod() - print "Done" + print("Done") if __name__ == "__main__": _test() diff -Nru python-biopython-1.62/Bio/Align/Applications/_Dialign.py python-biopython-1.63/Bio/Align/Applications/_Dialign.py --- python-biopython-1.62/Bio/Align/Applications/_Dialign.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Align/Applications/_Dialign.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,6 +5,8 @@ """Command line wrapper for the multiple alignment program DIALIGN2-2. """ +from __future__ import print_function + __docformat__ = "epytext en" # Don't just use plain text in epydoc API pages! from Bio.Application import _Option, _Argument, _Switch, AbstractCommandline @@ -23,7 +25,7 @@ >>> from Bio.Align.Applications import DialignCommandline >>> dialign_cline = DialignCommandline(input="unaligned.fasta", ... fn="aligned", fa=True) - >>> print dialign_cline + >>> print(dialign_cline) dialign2-2 -fa -fn aligned unaligned.fasta You would typically run the command line with dialign_cline() or via @@ -157,7 +159,7 @@ "Maximum number of `*' characters indicating degree " "of local similarity among sequences. By default, no " "stars are used but numbers between 0 and 9, instead.", - checker_function = lambda x: x in range(0,10), + checker_function = lambda x: x in range(0, 10), equate=False), _Switch(["-stdo", "stdo"], "Results written to standard output."), @@ -182,10 +184,10 @@ def _test(): """Run the module's doctests (PRIVATE).""" - print "Running modules doctests..." + print("Running modules doctests...") import doctest doctest.testmod() - print "Done" + print("Done") if __name__ == "__main__": _test() diff -Nru python-biopython-1.62/Bio/Align/Applications/_MSAProbs.py python-biopython-1.63/Bio/Align/Applications/_MSAProbs.py --- python-biopython-1.62/Bio/Align/Applications/_MSAProbs.py 1970-01-01 00:00:00.000000000 +0000 +++ python-biopython-1.63/Bio/Align/Applications/_MSAProbs.py 2013-12-05 14:10:43.000000000 +0000 @@ -0,0 +1,86 @@ +# Copyright 2013 by Christian Brueffer. All rights reserved. +# +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +"""Command line wrapper for the multiple sequence alignment program MSAProbs. +""" + +from __future__ import print_function + +__docformat__ = "epytext en" # Don't just use plain text in epydoc API pages! + +from Bio.Application import _Argument, _Option, _Switch, AbstractCommandline + + +class MSAProbsCommandline(AbstractCommandline): + """Command line wrapper for MSAProbs. + + http://msaprobs.sourceforge.net + + Example: + + >>> from Bio.Align.Applications import MSAProbsCommandline + >>> in_file = "unaligned.fasta" + >>> out_file = "aligned.cla" + >>> cline = MSAProbsCommandline(infile=in_file, outfile=out_file, clustalw=True) + >>> print(cline) + msaprobs -o aligned.cla -clustalw unaligned.fasta + + You would typically run the command line with cline() or via + the Python subprocess module, as described in the Biopython tutorial. + + Citation: + + Yongchao Liu, Bertil Schmidt, Douglas L. Maskell: "MSAProbs: multiple + sequence alignment based on pair hidden Markov models and partition + function posterior probabilities". Bioinformatics, 2010, 26(16): 1958 -1964 + + Last checked against version: 0.9.7 + """ + + def __init__(self, cmd="msaprobs", **kwargs): + # order of parameters is the same as in msaprobs -help + self.parameters = \ + [ + _Option(["-o", "--outfile", "outfile"], + "specify the output file name (STDOUT by default)", + filename=True, + equate=False), + _Option(["-num_threads", "numthreads"], + "specify the number of threads used, and otherwise detect automatically", + checker_function=lambda x: isinstance(x, int)), + _Switch(["-clustalw", "clustalw"], + "use CLUSTALW output format instead of FASTA format"), + _Option(["-c", "consistency"], + "use 0 <= REPS <= 5 (default: 2) passes of consistency transformation", + checker_function=lambda x: isinstance(x, int) and 0 <= x <= 5), + _Option(["-ir", "--iterative-refinement", "iterative_refinement"], + "use 0 <= REPS <= 1000 (default: 10) passes of iterative-refinement", + checker_function=lambda x: isinstance(x, int) and 0 <= x <= 1000), + _Switch(["-v", "verbose"], + "report progress while aligning (default: off)"), + _Option(["-annot", "annot"], + "write annotation for multiple alignment to FILENAME", + filename=True), + _Switch(["-a", "--alignment-order", "alignment_order"], + "print sequences in alignment order rather than input order (default: off)"), + _Option(["-version", "version"], + "print out version of MSAPROBS"), + _Argument(["infile"], + "Multiple sequence input file", + filename=True), + ] + AbstractCommandline.__init__(self, cmd, **kwargs) + + +def _test(): + """Run the module's doctests (PRIVATE).""" + print("Running MSAProbs doctests...") + import doctest + doctest.testmod() + print("Done") + + +if __name__ == "__main__": + _test() diff -Nru python-biopython-1.62/Bio/Align/Applications/_Mafft.py python-biopython-1.63/Bio/Align/Applications/_Mafft.py --- python-biopython-1.62/Bio/Align/Applications/_Mafft.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Align/Applications/_Mafft.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,6 +5,8 @@ """Command line wrapper for the multiple alignment programme MAFFT. """ +from __future__ import print_function + __docformat__ = "epytext en" # Don't just use plain text in epydoc API pages! import os @@ -22,7 +24,7 @@ >>> mafft_exe = "/opt/local/mafft" >>> in_file = "../Doc/examples/opuntia.fasta" >>> mafft_cline = MafftCommandline(mafft_exe, input=in_file) - >>> print mafft_cline + >>> print(mafft_cline) /opt/local/mafft ../Doc/examples/opuntia.fasta If the mafft binary is on the path (typically the case on a Unix style @@ -31,7 +33,7 @@ >>> from Bio.Align.Applications import MafftCommandline >>> in_file = "../Doc/examples/opuntia.fasta" >>> mafft_cline = MafftCommandline(input=in_file) - >>> print mafft_cline + >>> print(mafft_cline) mafft ../Doc/examples/opuntia.fasta You would typically run the command line with mafft_cline() or via @@ -40,9 +42,8 @@ want to save to a file and then parse, e.g.:: stdout, stderr = mafft_cline() - handle = open("aligned.fasta", "w") - handle.write(stdout) - handle.close() + with open("aligned.fasta", "w") as handle: + handle.write(stdout) from Bio import AlignIO align = AlignIO.read("aligned.fasta", "fasta") @@ -78,7 +79,7 @@ Last checked against version: MAFFT v6.717b (2009/12/03) """ def __init__(self, cmd="mafft", **kwargs): - BLOSUM_MATRICES = ["30","45","62","80"] + BLOSUM_MATRICES = ["30", "45", "62", "80"] self.parameters = \ [ #**** Algorithm **** @@ -367,3 +368,4 @@ if __name__ == "__main__": from Bio._utils import run_doctest run_doctest() + diff -Nru python-biopython-1.62/Bio/Align/Applications/_Muscle.py python-biopython-1.63/Bio/Align/Applications/_Muscle.py --- python-biopython-1.62/Bio/Align/Applications/_Muscle.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Align/Applications/_Muscle.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,6 +5,8 @@ """Command line wrapper for the multiple alignment program MUSCLE. """ +from __future__ import print_function + __docformat__ = "epytext en" # Don't just use plain text in epydoc API pages! from Bio.Application import _Option, _Switch, AbstractCommandline @@ -22,7 +24,7 @@ >>> in_file = r"C:\My Documents\unaligned.fasta" >>> out_file = r"C:\My Documents\aligned.fasta" >>> muscle_cline = MuscleCommandline(muscle_exe, input=in_file, out=out_file) - >>> print muscle_cline + >>> print(muscle_cline) "C:\Program Files\Aligments\muscle3.8.31_i86win32.exe" -in "C:\My Documents\unaligned.fasta" -out "C:\My Documents\aligned.fasta" You would typically run the command line with muscle_cline() or via @@ -354,10 +356,10 @@ "Write PHYLIP interleaved output to specified filename", filename=True, equate=False), - _Option(["-physout", "physout"],"Write PHYLIP sequential format to specified filename", + _Option(["-physout", "physout"], "Write PHYLIP sequential format to specified filename", filename=True, equate=False), - _Option(["-htmlout", "htmlout"],"Write HTML output to specified filename", + _Option(["-htmlout", "htmlout"], "Write HTML output to specified filename", filename=True, equate=False), _Option(["-clwout", "clwout"], @@ -467,10 +469,10 @@ def _test(): """Run the module's doctests (PRIVATE).""" - print "Running MUSCLE doctests..." + print("Running MUSCLE doctests...") import doctest doctest.testmod() - print "Done" + print("Done") if __name__ == "__main__": _test() diff -Nru python-biopython-1.62/Bio/Align/Applications/_Prank.py python-biopython-1.63/Bio/Align/Applications/_Prank.py --- python-biopython-1.62/Bio/Align/Applications/_Prank.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Align/Applications/_Prank.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,6 +5,8 @@ """Command line wrapper for the multiple alignment program PRANK. """ +from __future__ import print_function + __docformat__ = "epytext en" # Don't just use plain text in epydoc API pages! from Bio.Application import _Option, _Switch, AbstractCommandline @@ -27,7 +29,7 @@ ... o="aligned", #prefix only! ... f=8, #FASTA output ... notree=True, noxml=True) - >>> print prank_cline + >>> print(prank_cline) prank -d=unaligned.fasta -o=aligned -f=8 -noxml -notree You would typically run the command line with prank_cline() or via @@ -205,10 +207,10 @@ def _test(): """Run the module's doctests (PRIVATE).""" - print "Running modules doctests..." + print("Running modules doctests...") import doctest doctest.testmod() - print "Done" + print("Done") if __name__ == "__main__": _test() diff -Nru python-biopython-1.62/Bio/Align/Applications/_Probcons.py python-biopython-1.63/Bio/Align/Applications/_Probcons.py --- python-biopython-1.62/Bio/Align/Applications/_Probcons.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Align/Applications/_Probcons.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,6 +5,8 @@ """Command line wrapper for the multiple alignment program PROBCONS. """ +from __future__ import print_function + __docformat__ = "epytext en" # Don't just use plain text in epydoc API pages! from Bio.Application import _Option, _Switch, _Argument, AbstractCommandline @@ -23,7 +25,7 @@ >>> from Bio.Align.Applications import ProbconsCommandline >>> probcons_cline = ProbconsCommandline(input="unaligned.fasta", ... clustalw=True) - >>> print probcons_cline + >>> print(probcons_cline) probcons -clustalw unaligned.fasta You would typically run the command line with probcons_cline() or via @@ -32,9 +34,8 @@ want to save to a file and then parse, e.g.:: stdout, stderr = probcons_cline() - handle = open("aligned.aln", "w") - handle.write(stdout) - handle.close() + with open("aligned.aln", "w") as handle: + handle.write(stdout) from Bio import AlignIO align = AlignIO.read("aligned.fasta", "clustalw") @@ -66,16 +67,16 @@ "Use CLUSTALW output format instead of MFA"), _Option(["-c", "c", "--consistency", "consistency" ], "Use 0 <= REPS <= 5 (default: 2) passes of consistency transformation", - checker_function=lambda x: x in range(0,6), + checker_function=lambda x: x in range(0, 6), equate=False), _Option(["-ir", "--iterative-refinement", "iterative-refinement", "ir"], "Use 0 <= REPS <= 1000 (default: 100) passes of " "iterative-refinement", - checker_function=lambda x: x in range(0,1001), + checker_function=lambda x: x in range(0, 1001), equate=False), _Option(["-pre", "--pre-training", "pre-training", "pre"], "Use 0 <= REPS <= 20 (default: 0) rounds of pretraining", - checker_function=lambda x: x in range(0,21), + checker_function=lambda x: x in range(0, 21), equate=False), _Switch(["-pairs", "pairs"], "Generate all-pairs pairwise alignments"), @@ -111,10 +112,10 @@ def _test(): """Run the module's doctests (PRIVATE).""" - print "Running modules doctests..." + print("Running modules doctests...") import doctest doctest.testmod() - print "Done" + print("Done") if __name__ == "__main__": _test() diff -Nru python-biopython-1.62/Bio/Align/Applications/_TCoffee.py python-biopython-1.63/Bio/Align/Applications/_TCoffee.py --- python-biopython-1.62/Bio/Align/Applications/_TCoffee.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Align/Applications/_TCoffee.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,6 +5,8 @@ """Command line wrapper for the multiple alignment program TCOFFEE. """ +from __future__ import print_function + __docformat__ = "epytext en" # Don't just use plain text in epydoc API pages! from Bio.Application import _Option, _Switch, AbstractCommandline @@ -28,7 +30,7 @@ >>> tcoffee_cline = TCoffeeCommandline(infile="unaligned.fasta", ... output="clustalw", ... outfile="aligned.aln") - >>> print tcoffee_cline + >>> print(tcoffee_cline) t_coffee -output clustalw -infile unaligned.fasta -outfile aligned.aln You would typically run the command line with tcoffee_cline() or via @@ -41,7 +43,7 @@ Last checked against: Version_6.92 """ - SEQ_TYPES = ["dna","protein","dna_protein"] + SEQ_TYPES = ["dna", "protein", "dna_protein"] def __init__(self, cmd="t_coffee", **kwargs): self.parameters = [ @@ -102,10 +104,10 @@ def _test(): """Run the module's doctests (PRIVATE).""" - print "Running modules doctests..." + print("Running modules doctests...") import doctest doctest.testmod() - print "Done" + print("Done") if __name__ == "__main__": _test() diff -Nru python-biopython-1.62/Bio/Align/Applications/__init__.py python-biopython-1.63/Bio/Align/Applications/__init__.py --- python-biopython-1.62/Bio/Align/Applications/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Align/Applications/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -6,14 +6,15 @@ __docformat__ = "epytext en" # Don't just use plain text in epydoc API pages! -from _Muscle import MuscleCommandline -from _Clustalw import ClustalwCommandline -from _ClustalOmega import ClustalOmegaCommandline -from _Prank import PrankCommandline -from _Mafft import MafftCommandline -from _Dialign import DialignCommandline -from _Probcons import ProbconsCommandline -from _TCoffee import TCoffeeCommandline +from ._Muscle import MuscleCommandline +from ._Clustalw import ClustalwCommandline +from ._ClustalOmega import ClustalOmegaCommandline +from ._Prank import PrankCommandline +from ._Mafft import MafftCommandline +from ._Dialign import DialignCommandline +from ._Probcons import ProbconsCommandline +from ._TCoffee import TCoffeeCommandline +from ._MSAProbs import MSAProbsCommandline #Make this explicit, then they show up in the API docs __all__ = ["MuscleCommandline", @@ -23,5 +24,6 @@ "MafftCommandline", "DialignCommandline", "ProbconsCommandline", - "TCoffeeCommandline" + "TCoffeeCommandline", + "MSAProbsCommandline", ] diff -Nru python-biopython-1.62/Bio/Align/Generic.py python-biopython-1.63/Bio/Align/Generic.py --- python-biopython-1.62/Bio/Align/Generic.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Align/Generic.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,13 +5,16 @@ # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. -""" +"""Classes for generic sequence alignment. + Contains classes to deal with generic sequence alignment stuff not specific to a particular program or format. Classes: - Alignment """ +from __future__ import print_function + __docformat__ = "epytext en" # Don't just use plain text in epydoc API pages! # biopython @@ -44,7 +47,7 @@ >>> align.add_sequence("Alpha", "ACTGCTAGCTAG") >>> align.add_sequence("Beta", "ACT-CTAGCTAG") >>> align.add_sequence("Gamma", "ACTGCTAGATAG") - >>> print align + >>> print(align) Gapped(IUPACUnambiguousDNA(), '-') alignment with 3 rows and 12 columns ACTGCTAGCTAG Alpha ACT-CTAGCTAG Beta @@ -84,7 +87,7 @@ >>> align.add_sequence("Alpha", "ACTGCTAGCTAG") >>> align.add_sequence("Beta", "ACT-CTAGCTAG") >>> align.add_sequence("Gamma", "ACTGCTAGATAG") - >>> print align + >>> print(align) Gapped(IUPACUnambiguousDNA(), '-') alignment with 3 rows and 12 columns ACTGCTAGCTAG Alpha ACT-CTAGCTAG Beta @@ -96,9 +99,9 @@ lines = ["%s alignment with %i rows and %i columns" % (str(self._alphabet), rows, self.get_alignment_length())] if rows <= 20: - lines.extend([self._str_line(rec) for rec in self._records]) + lines.extend(self._str_line(rec) for rec in self._records) else: - lines.extend([self._str_line(rec) for rec in self._records[:18]]) + lines.extend(self._str_line(rec) for rec in self._records[:18]) lines.append("...") lines.append(self._str_line(self._records[-1])) return "\n".join(lines) @@ -141,7 +144,7 @@ >>> align.add_sequence("Alpha", "ACTGCTAGCTAG") >>> align.add_sequence("Beta", "ACT-CTAGCTAG") >>> align.add_sequence("Gamma", "ACTGCTAGATAG") - >>> print align.format("fasta") + >>> print(align.format("fasta")) >Alpha ACTGCTAGCTAG >Beta @@ -149,7 +152,7 @@ >Gamma ACTGCTAGATAG - >>> print align.format("phylip") + >>> print(align.format("phylip")) 3 12 Alpha ACTGCTAGCT AG Beta ACT-CTAGCT AG @@ -170,7 +173,7 @@ string supported by Bio.AlignIO as an output file format. See also the alignment's format() method.""" if format_spec: - from StringIO import StringIO + from Bio._py3k import StringIO from Bio import AlignIO handle = StringIO() AlignIO.write([self], handle, format_spec) @@ -208,8 +211,8 @@ >>> align.add_sequence("Beta", "ACT-CTAGCTAG") >>> align.add_sequence("Gamma", "ACTGCTAGATAG") >>> for record in align: - ... print record.id - ... print record.seq + ... print(record.id) + ... print(record.seq) Alpha ACTGCTAGCTAG Beta @@ -330,7 +333,7 @@ self._records.append(new_record) - def get_column(self,col): + def get_column(self, col): """Returns a string containing a given column. e.g. @@ -363,23 +366,23 @@ >>> align.add_sequence("Beta", "ACT-CTAGCTAG") >>> align.add_sequence("Gamma", "ACTGCTAGATAG") >>> align.add_sequence("Delta", "ACTGCTTGCTAG") - >>> align.add_sequence("Epsilon","ACTGCTTGATAG") + >>> align.add_sequence("Epsilon", "ACTGCTTGATAG") You can access a row of the alignment as a SeqRecord using an integer index (think of the alignment as a list of SeqRecord objects here): >>> first_record = align[0] - >>> print first_record.id, first_record.seq + >>> print("%s %s" % (first_record.id, first_record.seq)) Alpha ACTGCTAGCTAG >>> last_record = align[-1] - >>> print last_record.id, last_record.seq + >>> print("%s %s" % (last_record.id, last_record.seq)) Epsilon ACTGCTTGATAG You can also access use python's slice notation to create a sub-alignment containing only some of the SeqRecord objects: >>> sub_alignment = align[2:5] - >>> print sub_alignment + >>> print(sub_alignment) Gapped(IUPACUnambiguousDNA(), '-') alignment with 3 rows and 12 columns ACTGCTAGATAG Gamma ACTGCTTGCTAG Delta @@ -389,7 +392,7 @@ can be used to select every second sequence: >>> sub_alignment = align[::2] - >>> print sub_alignment + >>> print(sub_alignment) Gapped(IUPACUnambiguousDNA(), '-') alignment with 3 rows and 12 columns ACTGCTAGCTAG Alpha ACTGCTAGATAG Gamma @@ -398,7 +401,7 @@ Or to get a copy of the alignment with the rows in reverse order: >>> rev_alignment = align[::-1] - >>> print rev_alignment + >>> print(rev_alignment) Gapped(IUPACUnambiguousDNA(), '-') alignment with 5 rows and 12 columns ACTGCTTGATAG Epsilon ACTGCTTGCTAG Delta @@ -430,10 +433,11 @@ def _test(): """Run the Bio.Align.Generic module's doctests.""" - print "Running doctests..." + print("Running doctests...") import doctest doctest.testmod() - print "Done" + print("Done") if __name__ == "__main__": _test() + diff -Nru python-biopython-1.62/Bio/Align/__init__.py python-biopython-1.63/Bio/Align/__init__.py --- python-biopython-1.62/Bio/Align/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Align/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -9,6 +9,8 @@ class, used in the Bio.AlignIO module. """ +from __future__ import print_function + __docformat__ = "epytext en" # Don't just use plain text in epydoc API pages! from Bio.Seq import Seq @@ -32,7 +34,7 @@ >>> from Bio import AlignIO >>> align = AlignIO.read("Clustalw/opuntia.aln", "clustal") - >>> print align + >>> print(align) SingleLetterAlphabet() alignment with 7 rows and 156 columns TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF191 TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF191 @@ -49,7 +51,7 @@ >>> len(align) 7 >>> for record in align: - ... print record.id, len(record) + ... print("%s %i" % (record.id, len(record))) gi|6273285|gb|AF191659.1|AF191 156 gi|6273284|gb|AF191658.1|AF191 156 gi|6273287|gb|AF191661.1|AF191 156 @@ -60,19 +62,19 @@ You can also access individual rows as SeqRecord objects via their index: - >>> print align[0].id + >>> print(align[0].id) gi|6273285|gb|AF191659.1|AF191 - >>> print align[-1].id + >>> print(align[-1].id) gi|6273291|gb|AF191665.1|AF191 And extract columns as strings: - >>> print align[:,1] + >>> print(align[:, 1]) AAAAAAA Or, take just the first ten columns as a sub-alignment: - >>> print align[:,:10] + >>> print(align[:, :10]) SingleLetterAlphabet() alignment with 7 rows and 10 columns TATACATTAA gi|6273285|gb|AF191659.1|AF191 TATACATTAA gi|6273284|gb|AF191658.1|AF191 @@ -86,7 +88,7 @@ remove a section of the alignment. For example, taking just the first and last ten columns: - >>> print align[:,:10] + align[:,-10:] + >>> print(align[:, :10] + align[:, -10:]) SingleLetterAlphabet() alignment with 7 rows and 20 columns TATACATTAAGTGTACCAGA gi|6273285|gb|AF191659.1|AF191 TATACATTAAGTGTACCAGA gi|6273284|gb|AF191658.1|AF191 @@ -130,7 +132,7 @@ >>> b = SeqRecord(Seq("AAA-CGT", generic_dna), id="Beta") >>> c = SeqRecord(Seq("AAAAGGT", generic_dna), id="Gamma") >>> align = MultipleSeqAlignment([a, b, c], annotations={"tool": "demo"}) - >>> print align + >>> print(align) DNAAlphabet() alignment with 3 rows and 7 columns AAAACGT Alpha AAA-CGT Beta @@ -204,7 +206,7 @@ First we create a small alignment (three rows): >>> align = MultipleSeqAlignment([a, b, c]) - >>> print align + >>> print(align) DNAAlphabet() alignment with 3 rows and 7 columns AAAACGT Alpha AAA-CGT Beta @@ -213,7 +215,7 @@ Now we can extend this alignment with another two rows: >>> align.extend([d, e]) - >>> print align + >>> print(align) DNAAlphabet() alignment with 5 rows and 7 columns AAAACGT Alpha AAA-CGT Beta @@ -232,7 +234,7 @@ #Take the first record's length records = iter(records) # records arg could be list or iterator try: - rec = records.next() + rec = next(records) except StopIteration: #Special case, no records return @@ -252,7 +254,7 @@ >>> from Bio import AlignIO >>> align = AlignIO.read("Clustalw/opuntia.aln", "clustal") - >>> print align + >>> print(align) SingleLetterAlphabet() alignment with 7 rows and 156 columns TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF191 TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF191 @@ -273,7 +275,7 @@ Now append this to the alignment, >>> align.append(dummy) - >>> print align + >>> print(align) SingleLetterAlphabet() alignment with 8 rows and 156 columns TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF191 TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF191 @@ -336,12 +338,12 @@ Now, let's look at these two alignments: - >>> print left + >>> print(left) DNAAlphabet() alignment with 3 rows and 5 columns AAAAC Alpha AAA-C Beta AAAAG Gamma - >>> print right + >>> print(right) DNAAlphabet() alignment with 3 rows and 2 columns GT Alpha GT Beta @@ -350,7 +352,7 @@ And add them: >>> combined = left + right - >>> print combined + >>> print(combined) DNAAlphabet() alignment with 3 rows and 7 columns AAAACGT Alpha AAA-CGT Beta @@ -385,10 +387,10 @@ raise ValueError("When adding two alignments they must have the same length" " (i.e. same number or rows)") alpha = Alphabet._consensus_alphabet([self._alphabet, other._alphabet]) - merged = (left+right for left,right in zip(self, other)) + merged = (left+right for left, right in zip(self, other)) # Take any common annotation: annotations = dict() - for k, v in self.annotations.iteritems(): + for k, v in self.annotations.items(): if k in other.annotations and other.annotations[k] == v: annotations[k] = v return MultipleSeqAlignment(merged, alpha, annotations) @@ -430,17 +432,17 @@ index (think of the alignment as a list of SeqRecord objects here): >>> first_record = align[0] - >>> print first_record.id, first_record.seq + >>> print("%s %s" % (first_record.id, first_record.seq)) Alpha AAAACGT >>> last_record = align[-1] - >>> print last_record.id, last_record.seq + >>> print("%s %s" % (last_record.id, last_record.seq)) Epsilon AAA-GGT You can also access use python's slice notation to create a sub-alignment containing only some of the SeqRecord objects: >>> sub_alignment = align[2:5] - >>> print sub_alignment + >>> print(sub_alignment) DNAAlphabet() alignment with 3 rows and 7 columns AAAAGGT Gamma AAAACGT Delta @@ -450,7 +452,7 @@ can be used to select every second sequence: >>> sub_alignment = align[::2] - >>> print sub_alignment + >>> print(sub_alignment) DNAAlphabet() alignment with 3 rows and 7 columns AAAACGT Alpha AAAAGGT Gamma @@ -459,7 +461,7 @@ Or to get a copy of the alignment with the rows in reverse order: >>> rev_alignment = align[::-1] - >>> print rev_alignment + >>> print(rev_alignment) DNAAlphabet() alignment with 5 rows and 7 columns AAA-GGT Epsilon AAAACGT Delta @@ -470,7 +472,7 @@ You can also use two indices to specify both rows and columns. Using simple integers gives you the entry as a single character string. e.g. - >>> align[3,4] + >>> align[3, 4] 'C' This is equivalent to: @@ -485,17 +487,17 @@ To get a single column (as a string) use this syntax: - >>> align[:,4] + >>> align[:, 4] 'CCGCG' Or, to get part of a column, - >>> align[1:3,4] + >>> align[1:3, 4] 'CG' However, in general you get a sub-alignment, - >>> print align[1:5,3:6] + >>> print(align[1:5, 3:6]) DNAAlphabet() alignment with 4 rows and 3 columns -CG Beta AGG Gamma @@ -555,7 +557,7 @@ If you simple try and add these without sorting, you get this: - >>> print align1 + align2 + >>> print(align1 + align2) DNAAlphabet() alignment with 3 rows and 8 columns ACGTCGGT ACGGCGTT @@ -568,7 +570,7 @@ >>> align1.sort() >>> align2.sort() - >>> print align1 + align2 + >>> print(align1 + align2) DNAAlphabet() alignment with 3 rows and 8 columns ACGCCGCT Chicken ACGTCGTT Human @@ -578,13 +580,13 @@ GC content of each sequence. >>> from Bio.SeqUtils import GC - >>> print align1 + >>> print(align1) DNAAlphabet() alignment with 3 rows and 4 columns ACGC Chicken ACGT Human ACGG Mouse >>> align1.sort(key = lambda record: GC(record.seq)) - >>> print align1 + >>> print(align1) DNAAlphabet() alignment with 3 rows and 4 columns ACGT Human ACGC Chicken @@ -594,7 +596,7 @@ but backwards: >>> align1.sort(reverse=True) - >>> print align1 + >>> print(align1) DNAAlphabet() alignment with 3 rows and 4 columns ACGG Mouse ACGT Human @@ -646,3 +648,5 @@ if __name__ == "__main__": from Bio._utils import run_doctest run_doctest() + + diff -Nru python-biopython-1.62/Bio/AlignIO/ClustalIO.py python-biopython-1.63/Bio/AlignIO/ClustalIO.py --- python-biopython-1.62/Bio/AlignIO/ClustalIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/AlignIO/ClustalIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,19 +1,20 @@ -# Copyright 2006-2010 by Peter Cock. All rights reserved. +# Copyright 2006-2013 by Peter Cock. All rights reserved. # # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. -""" -Bio.AlignIO support for the "clustal" output from CLUSTAL W and other tools. +"""Bio.AlignIO support for "clustal" output from CLUSTAL W and other tools. You are expected to use this module via the Bio.AlignIO functions (or the Bio.SeqIO functions if you want to work directly with the gapped sequences). """ +from __future__ import print_function + from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord from Bio.Align import MultipleSeqAlignment -from Interfaces import AlignmentIterator, SequentialAlignmentWriter +from .Interfaces import AlignmentIterator, SequentialAlignmentWriter class ClustalWriter(SequentialAlignmentWriter): @@ -83,7 +84,7 @@ class ClustalIterator(AlignmentIterator): """Clustalw alignment iterator.""" - def next(self): + def __next__(self): handle = self.handle try: #Header we saved from when we were parsing @@ -272,7 +273,7 @@ return alignment if __name__ == "__main__": - print "Running a quick self-test" + print("Running a quick self-test") #This is a truncated version of the example in Tests/cw02.aln #Notice the inclusion of sequence numbers (right hand side) @@ -343,7 +344,7 @@ """ - from StringIO import StringIO + from Bio._py3k import StringIO alignments = list(ClustalIterator(StringIO(aln_example1))) assert 1 == len(alignments) @@ -371,14 +372,14 @@ "LKAKKIDAIMSSLSITEKRQQEIAFTDKLYAADSRLV" for alignment in ClustalIterator(StringIO(aln_example2 + aln_example1)): - print "Alignment with %i records of length %i" \ + print("Alignment with %i records of length %i" \ % (len(alignment), - alignment.get_alignment_length()) + alignment.get_alignment_length())) - print "Checking empty file..." + print("Checking empty file...") assert 0 == len(list(ClustalIterator(StringIO("")))) - print "Checking write/read..." + print("Checking write/read...") alignments = list(ClustalIterator(StringIO(aln_example1))) \ + list(ClustalIterator(StringIO(aln_example2)))*2 handle = StringIO() @@ -388,7 +389,7 @@ assert a.get_alignment_length() == alignments[i].get_alignment_length() handle.seek(0) - print "Testing write/read when there is only one sequence..." + print("Testing write/read when there is only one sequence...") alignment = alignment[0:1] handle = StringIO() ClustalWriter(handle).write_file([alignment]) @@ -465,4 +466,4 @@ assert 1 == len(alignments) assert alignments[0]._version == "2.0.9" - print "The End" + print("The End") diff -Nru python-biopython-1.62/Bio/AlignIO/EmbossIO.py python-biopython-1.63/Bio/AlignIO/EmbossIO.py --- python-biopython-1.62/Bio/AlignIO/EmbossIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/AlignIO/EmbossIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,10 +1,9 @@ -# Copyright 2008-2010 by Peter Cock. All rights reserved. +# Copyright 2008-2013 by Peter Cock. All rights reserved. # # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. -""" -Bio.AlignIO support for the "emboss" alignment output from EMBOSS tools. +"""Bio.AlignIO support for "emboss" alignment output from EMBOSS tools. You are expected to use this module via the Bio.AlignIO functions (or the Bio.SeqIO functions if you want to work directly with the gapped sequences). @@ -13,10 +12,12 @@ example from the alignret, water and needle tools. """ +from __future__ import print_function + from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord from Bio.Align import MultipleSeqAlignment -from Interfaces import AlignmentIterator, SequentialAlignmentWriter +from .Interfaces import AlignmentIterator, SequentialAlignmentWriter class EmbossWriter(SequentialAlignmentWriter): @@ -66,7 +67,7 @@ call the "pairs" and "simple" formats. """ - def next(self): + def __next__(self): handle = self.handle @@ -146,7 +147,7 @@ start = int(start) - 1 end = int(end) else: - assert seq.replace("-", "") != "" + assert seq.replace("-", "") != "", repr(line) start = int(start) - 1 # python counting end = int(end) @@ -164,9 +165,9 @@ if start == end: assert seq.replace("-", "") == "", line else: - assert start - seq_starts[index] == len(seqs[index].replace("-","")), \ + assert start - seq_starts[index] == len(seqs[index].replace("-", "")), \ "Found %i chars so far for sequence %i (%s, %s), line says start %i:\n%s" \ - % (len(seqs[index].replace("-","")), index, id, repr(seqs[index]), + % (len(seqs[index].replace("-", "")), index, id, repr(seqs[index]), start, line) seqs[index] += seq @@ -188,7 +189,7 @@ #Just a spacer? pass else: - print line + print(line) assert False line = handle.readline() @@ -221,7 +222,7 @@ if __name__ == "__main__": - print "Running a quick self-test" + print("Running a quick self-test") #http://emboss.sourceforge.net/docs/themes/alnformats/align.simple simple_example = \ @@ -579,7 +580,7 @@ #--------------------------------------- #---------------------------------------""" - from StringIO import StringIO + from Bio._py3k import StringIO alignments = list(EmbossIterator(StringIO(pair_example))) assert len(alignments) == 1 @@ -616,4 +617,4 @@ assert [r.id for r in alignments[0]] \ == ["asis", "asis"] - print "Done" + print("Done") diff -Nru python-biopython-1.62/Bio/AlignIO/FastaIO.py python-biopython-1.63/Bio/AlignIO/FastaIO.py --- python-biopython-1.62/Bio/AlignIO/FastaIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/AlignIO/FastaIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,8 +3,7 @@ # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. -""" -Bio.AlignIO support for "fasta-m10" output from Bill Pearson's FASTA tools. +"""Bio.AlignIO support for "fasta-m10" output from Bill Pearson's FASTA tools. You are expected to use this module via the Bio.AlignIO functions (or the Bio.SeqIO functions if you want to work directly with the gapped sequences). @@ -20,6 +19,8 @@ which can also be used to store a multiple sequence alignments. """ +from __future__ import print_function + from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord from Bio.Align import MultipleSeqAlignment @@ -77,9 +78,9 @@ handle = ... for a in AlignIO.parse(handle, "fasta-m10"): assert len(a) == 2, "Should be pairwise!" - print "Alignment length %i" % a.get_alignment_length() + print("Alignment length %i" % a.get_alignment_length()) for record in a: - print record.seq, record.name, record.id + print("%s %s %s" % (record.seq, record.name, record.id)) Note that this is not a full blown parser for all the information in the FASTA output - for example, most of the header and all of the @@ -121,16 +122,16 @@ else: m = _extract_alignment_region(match_seq, match_tags) assert len(q) == len(m) - except AssertionError, err: - print "Darn... amino acids vs nucleotide coordinates?" - print tool - print query_seq - print query_tags - print q, len(q) - print match_seq - print match_tags - print m, len(m) - print handle.name + except AssertionError as err: + print("Darn... amino acids vs nucleotide coordinates?") + print(tool) + print(query_seq) + print(query_tags) + print("%s %i" % (q, len(q))) + print(match_seq) + print(match_tags) + print("%s %i" % (m, len(m))) + print(handle.name) raise err assert alphabet is not None @@ -141,9 +142,9 @@ alignment._annotations = {} #Want to record both the query header tags, and the alignment tags. - for key, value in header_tags.iteritems(): + for key, value in header_tags.items(): alignment._annotations[key] = value - for key, value in align_tags.iteritems(): + for key, value in align_tags.items(): alignment._annotations[key] = value #Query @@ -356,7 +357,7 @@ if __name__ == "__main__": - print "Running a quick self-test" + print("Running a quick self-test") #http://emboss.sourceforge.net/docs/themes/alnformats/align.simple simple_example = \ @@ -592,30 +593,29 @@ """ - from StringIO import StringIO + from Bio._py3k import StringIO alignments = list(FastaM10Iterator(StringIO(simple_example))) assert len(alignments) == 4, len(alignments) assert len(alignments[0]) == 2 for a in alignments: - print "Alignment %i sequences of length %i" \ - % (len(a), a.get_alignment_length()) + print("Alignment %i sequences of length %i" \ + % (len(a), a.get_alignment_length())) for r in a: - print "%s %s %i" % (r.seq, r.id, r.annotations["original_length"]) - #print a.annotations - print "Done" + print("%s %s %i" % (r.seq, r.id, r.annotations["original_length"])) + #print(a.annotations) + print("Done") import os path = "../../Tests/Fasta/" - files = [f for f in os.listdir(path) if os.path.splitext(f)[-1] == ".m10"] - files.sort() + files = sorted(f for f in os.listdir(path) if os.path.splitext(f)[-1] == ".m10") for filename in files: if os.path.splitext(filename)[-1] == ".m10": - print - print filename - print "=" * len(filename) + print("") + print(filename) + print("=" * len(filename)) for i, a in enumerate(FastaM10Iterator(open(os.path.join(path, filename)))): - print "#%i, %s" % (i+1, a) + print("#%i, %s" % (i+1, a)) for r in a: if "-" in r.seq: assert r.seq.alphabet.gap_char == "-" diff -Nru python-biopython-1.62/Bio/AlignIO/Interfaces.py python-biopython-1.63/Bio/AlignIO/Interfaces.py --- python-biopython-1.62/Bio/AlignIO/Interfaces.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/AlignIO/Interfaces.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,14 +1,17 @@ -# Copyright 2008-2010 by Peter Cock. All rights reserved. +# Copyright 2008-2013 by Peter Cock. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. -""" -AlignIO support module (not for general use). +"""AlignIO support module (not for general use). Unless you are writing a new parser or writer for Bio.AlignIO, you should not use this module. It provides base classes to try and simplify things. """ +from __future__ import print_function + +import sys # for checking if Python 2 + from Bio.Alphabet import single_letter_alphabet @@ -43,7 +46,7 @@ # or if additional arguments are required. # ##################################################### - def next(self): + def __next__(self): """Return the next alignment in the file. This method should be replaced by any derived class to do something @@ -55,19 +58,29 @@ # into MultipleSeqAlignment objects. # ##################################################### + if sys.version_info[0] < 3: + def next(self): + """Deprecated Python 2 style alias for Python 3 style __next__ method.""" + import warnings + from Bio import BiopythonDeprecationWarning + warnings.warn("Please use next(my_iterator) instead of my_iterator.next(), " + "the .next() method is deprecated and will be removed in a " + "future release of Biopython.", BiopythonDeprecationWarning) + return self.__next__() + def __iter__(self): """Iterate over the entries as MultipleSeqAlignment objects. Example usage for (concatenated) PHYLIP files: - myFile = open("many.phy","r") - for alignment in PhylipIterator(myFile): - print "New alignment:" - for record in alignment: - print record.id - print record.seq - myFile.close()""" - return iter(self.next, None) + with open("many.phy","r") as myFile: + for alignment in PhylipIterator(myFile): + print "New alignment:" + for record in alignment: + print record.id + print record.seq + """ + return iter(self.__next__, None) class AlignmentWriter(object): diff -Nru python-biopython-1.62/Bio/AlignIO/NexusIO.py python-biopython-1.63/Bio/AlignIO/NexusIO.py --- python-biopython-1.62/Bio/AlignIO/NexusIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/AlignIO/NexusIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,8 +3,7 @@ # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. -""" -Bio.AlignIO support for the "nexus" file format. +"""Bio.AlignIO support for the "nexus" file format. You are expected to use this module via the Bio.AlignIO functions (or the Bio.SeqIO functions if you want to work directly with the gapped sequences). @@ -14,10 +13,12 @@ sequences as SeqRecord objects. """ +from __future__ import print_function + from Bio.SeqRecord import SeqRecord from Bio.Nexus import Nexus from Bio.Align import MultipleSeqAlignment -from Interfaces import AlignmentWriter +from .Interfaces import AlignmentWriter from Bio import Alphabet #You can get a couple of example files here: @@ -75,7 +76,7 @@ """ align_iter = iter(alignments) # Could have been a list try: - first_alignment = align_iter.next() + first_alignment = next(align_iter) except StopIteration: first_alignment = None if first_alignment is None: @@ -84,7 +85,7 @@ #Check there is only one alignment... try: - second_alignment = align_iter.next() + second_alignment = next(align_iter) except StopIteration: second_alignment = None if second_alignment is not None: @@ -136,10 +137,10 @@ raise ValueError("Need a DNA, RNA or Protein alphabet") if __name__ == "__main__": - from StringIO import StringIO - print "Quick self test" - print - print "Repeated names without a TAXA block" + from Bio._py3k import StringIO + print("Quick self test") + print("") + print("Repeated names without a TAXA block") handle = StringIO("""#NEXUS [TITLE: NoName] @@ -156,13 +157,13 @@ end; """) for a in NexusIterator(handle): - print a + print(a) for r in a: - print repr(r.seq), r.name, r.id - print "Done" + print("%r %s %s" % (r.seq, r.name, r.id)) + print("Done") - print - print "Repeated names with a TAXA block" + print("") + print("Repeated names with a TAXA block") handle = StringIO("""#NEXUS [TITLE: NoName] @@ -186,21 +187,21 @@ end; """) for a in NexusIterator(handle): - print a + print(a) for r in a: - print repr(r.seq), r.name, r.id - print "Done" - print - print "Reading an empty file" + print("%r %s %s" % (r.seq, r.name, r.id)) + print("Done") + print("") + print("Reading an empty file") assert 0 == len(list(NexusIterator(StringIO()))) - print "Done" - print - print "Writing..." + print("Done") + print("") + print("Writing...") handle = StringIO() NexusWriter(handle).write_file([a]) handle.seek(0) - print handle.read() + print(handle.read()) handle = StringIO() try: diff -Nru python-biopython-1.62/Bio/AlignIO/PhylipIO.py python-biopython-1.63/Bio/AlignIO/PhylipIO.py --- python-biopython-1.62/Bio/AlignIO/PhylipIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/AlignIO/PhylipIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,10 +1,9 @@ -# Copyright 2006-2011 by Peter Cock. All rights reserved. +# Copyright 2006-2013 by Peter Cock. All rights reserved. # Revisions copyright 2011 Brandon Invergo. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. -""" -AlignIO support for the "phylip" format used in Joe Felsenstein's PHYLIP tools. +"""AlignIO support for "phylip" format from Joe Felsenstein's PHYLIP tools. You are expected to use this module via the Bio.AlignIO functions (or the Bio.SeqIO functions if you want to work directly with the gapped sequences). @@ -32,12 +31,16 @@ Biopython 1.58 or later treats dots/periods in the sequence as invalid, both for reading and writing. Older versions did nothing special with a dot/period. """ +from __future__ import print_function + import string +from Bio._py3k import range + from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord from Bio.Align import MultipleSeqAlignment -from Interfaces import AlignmentIterator, SequentialAlignmentWriter +from .Interfaces import AlignmentIterator, SequentialAlignmentWriter _PHYLIP_ID_WIDTH = 10 @@ -161,7 +164,7 @@ def _is_header(self, line): line = line.strip() - parts = filter(None, line.split()) + parts = [x for x in line.split() if x] if len(parts) != 2: return False # First line should have two integers try: @@ -185,7 +188,7 @@ seq = line[self.id_width:].strip().replace(' ', '') return seq_id, seq - def next(self): + def __next__(self): handle = self.handle try: @@ -199,7 +202,7 @@ if not line: raise StopIteration line = line.strip() - parts = filter(None, line.split()) + parts = [x for x in line.split() if x] if len(parts) != 2: raise ValueError("First line should have two integers") try: @@ -220,7 +223,7 @@ # By default, expects STRICT truncation / padding to 10 characters. # Does not require any whitespace between name and seq. - for i in xrange(number_of_seqs): + for i in range(number_of_seqs): line = handle.readline().rstrip() sequence_id, s = self._split_id(line) ids.append(sequence_id) @@ -245,7 +248,7 @@ break #print "New block..." - for i in xrange(number_of_seqs): + for i in range(number_of_seqs): s = line.strip().replace(" ", "") if "." in s: raise ValueError("PHYLIP format no longer allows dots in sequence") @@ -370,7 +373,7 @@ the next. According to the PHYLIP documentation for input file formatting, newlines and spaces may optionally be entered at any point in the sequences. """ - def next(self): + def __next__(self): handle = self.handle try: @@ -384,7 +387,7 @@ if not line: raise StopIteration line = line.strip() - parts = filter(None, line.split()) + parts = [x for x in line.split() if x] if len(parts) != 2: raise ValueError("First line should have two integers") try: @@ -405,7 +408,7 @@ # By default, expects STRICT truncation / padding to 10 characters. # Does not require any whitespace between name and seq. - for i in xrange(number_of_seqs): + for i in range(number_of_seqs): line = handle.readline().rstrip() sequence_id, s = self._split_id(line) ids.append(sequence_id) @@ -439,7 +442,7 @@ if __name__ == "__main__": - print "Running short mini-test" + print("Running short mini-test") phylip_text = """ 8 286 V_Harveyi_ --MKNWIKVA VAAIA--LSA A--------- ---------T VQAATEVKVG @@ -497,13 +500,13 @@ LREALNKAFA EMRADGTYEK LAKKYFDFDV YGG--- """ - from cStringIO import StringIO + from Bio._py3k import StringIO handle = StringIO(phylip_text) count = 0 for alignment in PhylipIterator(handle): for record in alignment: count = count+1 - print record.id + print(record.id) #print str(record.seq) assert count == 8 @@ -600,9 +603,9 @@ list5 = list(PhylipIterator(handle)) assert len(list5) == 1 assert len(list5[0]) == 5 - print "That should have failed..." + print("That should have failed...") except ValueError: - print "Evil multiline non-interlaced example failed as expected" + print("Evil multiline non-interlaced example failed as expected") handle.close() handle = StringIO(phylip_text5a) @@ -611,16 +614,16 @@ assert len(list5) == 1 assert len(list4[0]) == 5 - print "Concatenation" + print("Concatenation") handle = StringIO(phylip_text4 + "\n" + phylip_text4) assert len(list(PhylipIterator(handle))) == 2 handle = StringIO(phylip_text3 + "\n" + phylip_text4 + "\n\n\n" + phylip_text) assert len(list(PhylipIterator(handle))) == 3 - print "OK" + print("OK") - print "Checking write/read" + print("Checking write/read") handle = StringIO() PhylipWriter(handle).write_file(list5) handle.seek(0) @@ -631,4 +634,4 @@ for r1, r2 in zip(a1, a2): assert r1.id == r2.id assert str(r1.seq) == str(r2.seq) - print "Done" + print("Done") diff -Nru python-biopython-1.62/Bio/AlignIO/StockholmIO.py python-biopython-1.63/Bio/AlignIO/StockholmIO.py --- python-biopython-1.62/Bio/AlignIO/StockholmIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/AlignIO/StockholmIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,9 +1,9 @@ -# Copyright 2006-2010 by Peter Cock. All rights reserved. +# Copyright 2006-2013 by Peter Cock. All rights reserved. +# # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. -""" -Bio.AlignIO support for the "stockholm" format (used in the PFAM database). +"""Bio.AlignIO support for "stockholm" format (used in the PFAM database). You are expected to use this module via the Bio.AlignIO functions (or the Bio.SeqIO functions if you want to work directly with the gapped sequences). @@ -29,12 +29,12 @@ >>> from Bio import AlignIO >>> align = AlignIO.read("Stockholm/simple.sth", "stockholm") - >>> print align + >>> print(align) SingleLetterAlphabet() alignment with 2 rows and 104 columns UUAAUCGAGCUCAACACUCUUCGUAUAUCCUC-UCAAUAUGG-G...UGU AP001509.1 AAAAUUGAAUAUCGUUUUACUUGUUUAU-GUCGUGAAU-UGG-C...GAU AE007476.1 >>> for record in align: - ... print record.id, len(record) + ... print("%s %i" % (record.id, len(record))) AP001509.1 104 AE007476.1 104 @@ -47,7 +47,7 @@ >>> from Bio.Alphabet import generic_rna >>> align = AlignIO.read("Stockholm/simple.sth", "stockholm", ... alphabet=generic_rna) - >>> print align + >>> print(align) RNAAlphabet() alignment with 2 rows and 104 columns UUAAUCGAGCUCAACACUCUUCGUAUAUCCUC-UCAAUAUGG-G...UGU AP001509.1 AAAAUUGAAUAUCGUUUUACUUGUUUAU-GUCGUGAAU-UGG-C...GAU AE007476.1 @@ -57,9 +57,9 @@ strings, with one character for each letter in the associated sequence: >>> for record in align: - ... print record.id - ... print record.seq - ... print record.letter_annotations['secondary_structure'] + ... print(record.id) + ... print(record.seq) + ... print(record.letter_annotations['secondary_structure']) AP001509.1 UUAAUCGAGCUCAACACUCUUCGUAUAUCCUC-UCAAUAUGG-GAUGAGGGUCUCUAC-AGGUA-CCGUAAA-UACCUAGCUACGAAAAGAAUGCAGUUAAUGU -----------------<<<<<<<<---..<<-<<-------->>->>..---------<<<<<--------->>>>>--->>>>>>>>--------------- @@ -71,7 +71,7 @@ dictionary. You can output this alignment in many different file formats using Bio.AlignIO.write(), or the MultipleSeqAlignment object's format method: - >>> print align.format("fasta") + >>> print(align.format("fasta")) >AP001509.1 UUAAUCGAGCUCAACACUCUUCGUAUAUCCUC-UCAAUAUGG-GAUGAGGGUCUCUAC-A GGUA-CCGUAAA-UACCUAGCUACGAAAAGAAUGCAGUUAAUGU @@ -83,7 +83,7 @@ Most output formats won't be able to hold the annotation possible in a Stockholm file: - >>> print align.format("stockholm") + >>> print(align.format("stockholm")) # STOCKHOLM 1.0 #=GF SQ 2 AP001509.1 UUAAUCGAGCUCAACACUCUUCGUAUAUCCUC-UCAAUAUGG-GAUGAGGGUCUCUAC-AGGUA-CCGUAAA-UACCUAGCUACGAAAAGAAUGCAGUUAAUGU @@ -110,9 +110,9 @@ >>> from Bio.Alphabet import generic_rna >>> for record in SeqIO.parse("Stockholm/simple.sth", "stockholm", ... alphabet=generic_rna): - ... print record.id - ... print record.seq - ... print record.letter_annotations['secondary_structure'] + ... print(record.id) + ... print(record.seq) + ... print(record.letter_annotations['secondary_structure']) AP001509.1 UUAAUCGAGCUCAACACUCUUCGUAUAUCCUC-UCAAUAUGG-GAUGAGGGUCUCUAC-AGGUA-CCGUAAA-UACCUAGCUACGAAAAGAAUGCAGUUAAUGU -----------------<<<<<<<<---..<<-<<-------->>->>..---------<<<<<--------->>>>>--->>>>>>>>--------------- @@ -124,16 +124,18 @@ secondary structure string here, are also sliced: >>> sub_record = record[10:20] - >>> print sub_record.seq + >>> print(sub_record.seq) AUCGUUUUAC - >>> print sub_record.letter_annotations['secondary_structure'] + >>> print(sub_record.letter_annotations['secondary_structure']) -------<<< """ +from __future__ import print_function + __docformat__ = "epytext en" # not just plaintext from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord from Bio.Align import MultipleSeqAlignment -from Interfaces import AlignmentIterator, SequentialAlignmentWriter +from .Interfaces import AlignmentIterator, SequentialAlignmentWriter class StockholmWriter(SequentialAlignmentWriter): @@ -238,7 +240,7 @@ % (seq_name, self.clean(xref))) #GS = other per sequence annotation - for key, value in record.annotations.iteritems(): + for key, value in record.annotations.items(): if key in self.pfam_gs_mapping: data = self.clean(str(value)) if data: @@ -252,7 +254,7 @@ pass #GR = per row per column sequence annotation - for key, value in record.letter_annotations.iteritems(): + for key, value in record.letter_annotations.items(): if key in self.pfam_gr_mapping and len(str(value)) == len(record.seq): data = self.clean(str(value)) if data: @@ -310,7 +312,7 @@ "OC": "organism_classification", "LO": "look"} - def next(self): + def __next__(self): try: line = self._header del self._header @@ -321,8 +323,6 @@ raise StopIteration if not line.strip() == '# STOCKHOLM 1.0': raise ValueError("Did not find STOCKHOLM header") - #import sys - #print >> sys.stderr, 'Warning file does not start with STOCKHOLM 1.0' # Note: If this file follows the PFAM conventions, there should be # a line containing the number of sequences, e.g. "#=GF SQ 67" @@ -335,7 +335,7 @@ gr = {} gf = {} passed_end_alignment = False - while 1: + while True: line = self.handle.readline() if not line: break # end of file @@ -424,7 +424,7 @@ raise ValueError("Found %i records in this alignment, told to expect %i" % (len(ids), self.records_per_alignment)) - alignment_length = len(seqs.values()[0]) + alignment_length = len(list(seqs.values())[0]) records = [] # Alignment obj will put them all in a list anyway for id in ids: seq = seqs[id] @@ -456,17 +456,17 @@ raise StopIteration def _identifier_split(self, identifier): - """Returns (name,start,end) string tuple from an identier.""" + """Returns (name, start, end) string tuple from an identier.""" if '/' in identifier: name, start_end = identifier.rsplit("/", 1) if start_end.count("-") == 1: try: - start, end = map(int, start_end.split("-")) - return (name, start, end) + start, end = start_end.split("-") + return name, int(start), int(end) except ValueError: # Non-integers after final '/' - fall through pass - return (identifier, None, None) + return identifier, None, None def _get_meta_data(self, identifier, meta_dict): """Takes an itentifier and returns dict of all meta-data matching it. @@ -537,3 +537,4 @@ if __name__ == "__main__": from Bio._utils import run_doctest run_doctest() + diff -Nru python-biopython-1.62/Bio/AlignIO/__init__.py python-biopython-1.63/Bio/AlignIO/__init__.py --- python-biopython-1.62/Bio/AlignIO/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/AlignIO/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -27,7 +27,7 @@ >>> from Bio import AlignIO >>> align = AlignIO.read("Phylip/interlaced.phy", "phylip") - >>> print align + >>> print(align) SingleLetterAlphabet() alignment with 3 rows and 384 columns -----MKVILLFVLAVFTVFVSS---------------RGIPPE...I-- CYS1_DICDI MAHARVLLLALAVLATAAVAVASSSSFADSNPIRPVTDRAASTL...VAA ALEU_HORVU @@ -41,7 +41,7 @@ >>> from Bio import AlignIO >>> alignments = list(AlignIO.parse("Emboss/needle.txt", "emboss")) - >>> print alignments[2] + >>> print(alignments[2]) SingleLetterAlphabet() alignment with 2 rows and 120 columns -KILIVDDQYGIRILLNEVFNKEGYQTFQAANGLQALDIVTKER...--- ref_rec LHIVVVDDDPGTCVYIESVFAELGHTCKSFVRPEAAEEYILTHP...HKE gi|94967506|receiver @@ -65,9 +65,8 @@ from Bio import AlignIO alignments = ... - handle = open("example.faa", "w") - count = SeqIO.write(alignments, handle, "fasta") - handle.close() + with open("example.faa", "w") as handle: + count = SeqIO.write(alignments, handle, "fasta") In general, you are expected to call this function once (with all your alignments) and then close the file handle. However, for file formats @@ -120,8 +119,9 @@ same length. """ -# For using with statement in Python 2.5 or Jython -from __future__ import with_statement + +from __future__ import print_function +from Bio._py3k import basestring __docformat__ = "epytext en" # not just plaintext @@ -144,12 +144,12 @@ from Bio.Alphabet import Alphabet, AlphabetEncoder, _get_base_alphabet from Bio.File import as_handle -import StockholmIO -import ClustalIO -import NexusIO -import PhylipIO -import EmbossIO -import FastaIO +from . import StockholmIO +from . import ClustalIO +from . import NexusIO +from . import PhylipIO +from . import EmbossIO +from . import FastaIO #Convention for format names is "mainname-subtype" in lower case. #Please use the same names as BioPerl and EMBOSS where possible. @@ -313,7 +313,7 @@ >>> filename = "Emboss/needle.txt" >>> format = "emboss" >>> for alignment in AlignIO.parse(filename, format): - ... print "Alignment of length", alignment.get_alignment_length() + ... print("Alignment of length %i" % alignment.get_alignment_length()) Alignment of length 124 Alignment of length 119 Alignment of length 120 @@ -392,7 +392,7 @@ >>> filename = "Clustalw/protein.aln" >>> format = "clustal" >>> alignment = AlignIO.read(filename, format) - >>> print "Alignment of length", alignment.get_alignment_length() + >>> print("Alignment of length %i" % alignment.get_alignment_length()) Alignment of length 411 If however you want the first alignment from a file containing @@ -411,8 +411,8 @@ >>> from Bio import AlignIO >>> filename = "Emboss/needle.txt" >>> format = "emboss" - >>> alignment = AlignIO.parse(filename, format).next() - >>> print "First alignment has length", alignment.get_alignment_length() + >>> alignment = next(AlignIO.parse(filename, format)) + >>> print("First alignment has length %i" % alignment.get_alignment_length()) First alignment has length 124 You must use the Bio.AlignIO.parse() function if you want to read multiple @@ -420,13 +420,13 @@ """ iterator = parse(handle, format, seq_count, alphabet) try: - first = iterator.next() + first = next(iterator) except StopIteration: first = None if first is None: raise ValueError("No records found in handle") try: - second = iterator.next() + second = next(iterator) except StopIteration: second = None if second is not None: @@ -466,3 +466,4 @@ if __name__ == "__main__": from Bio._utils import run_doctest run_doctest() + diff -Nru python-biopython-1.62/Bio/Application/__init__.py python-biopython-1.63/Bio/Application/__init__.py --- python-biopython-1.62/Bio/Application/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Application/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -19,9 +19,12 @@ The finished command line strings are then normally invoked via the built-in Python module subprocess. """ +from __future__ import print_function +from Bio._py3k import basestring + import os +import platform import sys -import StringIO import subprocess import re @@ -31,11 +34,13 @@ #Use this regular expression to test the property names are going to #be valid as Python properties or arguments -_re_prop_name = re.compile(r"[a-zA-Z][a-zA-Z0-9_]*") +_re_prop_name = re.compile(r"^[a-zA-Z][a-zA-Z0-9_]*$") assert _re_prop_name.match("t") assert _re_prop_name.match("test") assert _re_prop_name.match("_test") is None # we don't want private names assert _re_prop_name.match("-test") is None +assert _re_prop_name.match("any-hyphen") is None +assert _re_prop_name.match("underscore_ok") assert _re_prop_name.match("test_name") assert _re_prop_name.match("test2") #These are reserved names in Python itself, @@ -60,7 +65,7 @@ >>> err = ApplicationError(-11, "helloworld", "", "Some error text") >>> err.returncode, err.cmd, err.stdout, err.stderr (-11, 'helloworld', '', 'Some error text') - >>> print err + >>> print(err) Command 'helloworld' returned non-zero exit status -11, 'Some error text' """ @@ -135,7 +140,7 @@ >>> water_cmd.asequence = "asis:ACCCGGGCGCGGT" >>> water_cmd.bsequence = "asis:ACCCGAGCGCGGT" >>> water_cmd.outfile = "temp_water.txt" - >>> print water_cmd + >>> print(water_cmd) water -outfile=temp_water.txt -asequence=asis:ACCCGGGCGCGGT -bsequence=asis:ACCCGAGCGCGGT -gapopen=10 -gapextend=0.5 >>> water_cmd WaterCommandline(cmd='water', outfile='temp_water.txt', asequence='asis:ACCCGGGCGCGGT', bsequence='asis:ACCCGAGCGCGGT', gapopen=10, gapextend=0.5) @@ -157,7 +162,7 @@ ... asequence="asis:ACCCGGGCGCGGT", ... bsequence="asis:ACCCGAGCGCGGT", ... outfile="temp_water.txt") - >>> print water_cmd + >>> print(water_cmd) "C:\Program Files\EMBOSS\water.exe" -outfile=temp_water.txt -asequence=asis:ACCCGGGCGCGGT -bsequence=asis:ACCCGAGCGCGGT -gapopen=10 -gapextend=0.5 Notice that since the path name includes a space it has automatically @@ -238,7 +243,7 @@ "argument value required." % p.names[0] prop = property(getter(name), setter(name), deleter(name), doc) setattr(self.__class__, name, prop) # magic! - for key, value in kwargs.iteritems(): + for key, value in kwargs.items(): self.set_parameter(key, value) def _validate(self): @@ -265,7 +270,7 @@ >>> cline.asequence = "asis:ACCCGGGCGCGGT" >>> cline.bsequence = "asis:ACCCGAGCGCGGT" >>> cline.outfile = "temp_water.txt" - >>> print cline + >>> print(cline) water -outfile=temp_water.txt -asequence=asis:ACCCGGGCGCGGT -bsequence=asis:ACCCGAGCGCGGT -gapopen=10 -gapextend=0.5 >>> str(cline) 'water -outfile=temp_water.txt -asequence=asis:ACCCGGGCGCGGT -bsequence=asis:ACCCGAGCGCGGT -gapopen=10 -gapextend=0.5' @@ -287,7 +292,7 @@ >>> cline.asequence = "asis:ACCCGGGCGCGGT" >>> cline.bsequence = "asis:ACCCGAGCGCGGT" >>> cline.outfile = "temp_water.txt" - >>> print cline + >>> print(cline) water -outfile=temp_water.txt -asequence=asis:ACCCGGGCGCGGT -bsequence=asis:ACCCGAGCGCGGT -gapopen=10 -gapextend=0.5 >>> cline WaterCommandline(cmd='water', outfile='temp_water.txt', asequence='asis:ACCCGGGCGCGGT', bsequence='asis:ACCCGAGCGCGGT', gapopen=10, gapextend=0.5) @@ -387,7 +392,7 @@ Traceback (most recent call last): ... ValueError: Option name csequence was not found. - >>> print cline + >>> print(cline) water -stdout -asequence=a.fasta -bsequence=b.fasta -gapopen=10 -gapextend=0.5 This workaround uses a whitelist of object attributes, and sets the @@ -468,11 +473,23 @@ # #Using universal newlines is important on Python 3, this #gives unicode handles rather than bytes handles. + + #Windows 7 and 8 want shell = True + #platform is easier to understand that sys to determine + #windows version + if sys.platform != "win32": + use_shell = True + else: + win_ver = platform.win32_ver()[0] + if win_ver in ["7", "8"]: + use_shell = True + else: + use_shell = False child_process = subprocess.Popen(str(self), stdin=subprocess.PIPE, stdout=stdout_arg, stderr=stderr_arg, universal_newlines=True, cwd=cwd, env=env, - shell=(sys.platform!="win32")) + shell=use_shell) #Use .communicate as can get deadlocks with .wait(), see Bug 2804 stdout_str, stderr_str = child_process.communicate(stdin) if not stdout: @@ -676,9 +693,9 @@ Note this will not add quotes if they are already included: - >>> print _escape_filename('example with spaces') + >>> print((_escape_filename('example with spaces'))) "example with spaces" - >>> print _escape_filename('"example with spaces"') + >>> print((_escape_filename('"example with spaces"'))) "example with spaces" """ #Is adding the following helpful @@ -712,3 +729,4 @@ if __name__ == "__main__": #Run the doctests _test() + diff -Nru python-biopython-1.62/Bio/Blast/Applications.py python-biopython-1.63/Bio/Blast/Applications.py --- python-biopython-1.62/Bio/Blast/Applications.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Blast/Applications.py 2013-12-05 14:10:43.000000000 +0000 @@ -32,6 +32,8 @@ BMC Bioinformatics 2009, 10:421 doi:10.1186/1471-2105-10-421 """ +from __future__ import print_function + from Bio import BiopythonDeprecationWarning from Bio.Application import _Option, AbstractCommandline, _Switch @@ -206,7 +208,7 @@ ... database="nr", expectation=0.001) >>> cline BlastallCommandline(cmd='blastall', database='nr', infile='m_cold.fasta', expectation=0.001, program='blastx') - >>> print cline + >>> print(cline) blastall -d nr -i m_cold.fasta -e 0.001 -p blastx You would typically run the command line with cline() or via the Python @@ -310,7 +312,7 @@ >>> cline = BlastpgpCommandline(help=True) >>> cline BlastpgpCommandline(cmd='blastpgp', help=True) - >>> print cline + >>> print(cline) blastpgp --help You would typically run the command line with cline() or via the Python @@ -389,7 +391,7 @@ >>> cline = RpsBlastCommandline(help=True) >>> cline RpsBlastCommandline(cmd='rpsblast', help=True) - >>> print cline + >>> print(cline) rpsblast --help You would typically run the command line with cline() or via the Python @@ -455,15 +457,15 @@ "(differs from classic BLAST which used 7 for XML).", equate=False), #TODO - Document and test the column options - _Switch(["-show_gis","show_gis"], + _Switch(["-show_gis", "show_gis"], "Show NCBI GIs in deflines?"), - _Option(["-num_descriptions","num_descriptions"], + _Option(["-num_descriptions", "num_descriptions"], """Number of database sequences to show one-line descriptions for. Integer argument (at least zero). Default is 500. See also num_alignments.""", equate=False), - _Option(["-num_alignments","num_alignments"], + _Option(["-num_alignments", "num_alignments"], """Number of database sequences to show num_alignments for. Integer argument (at least zero). Default is 200. @@ -491,7 +493,7 @@ for b in incompatibles[a]: if self._get_parameter(b): raise ValueError("Options %s and %s are incompatible." - % (a,b)) + % (a, b)) class _NcbiblastCommandline(_NcbibaseblastCommandline): @@ -518,7 +520,7 @@ _Option(["-evalue", "evalue"], "Expectation value cutoff.", equate=False), - _Option(["-word_size","word_size"], + _Option(["-word_size", "word_size"], """Word size for wordfinder algorithm. Integer. Minimum 2.""", @@ -697,7 +699,7 @@ def _validate(self): incompatibles = {"subject_loc":["db", "gilist", "negative_gilist", "seqidlist", "remote"], - "culling_limit":["best_hit_overhang","best_hit_score_edge"], + "culling_limit":["best_hit_overhang", "best_hit_score_edge"], "subject":["db", "gilist", "negative_gilist", "seqidlist"]} self._validate_incompatibilities(incompatibles) _NcbiblastCommandline._validate(self) @@ -757,7 +759,7 @@ ... evalue=0.001, remote=True, ungapped=True) >>> cline NcbiblastpCommandline(cmd='blastp', query='rosemary.pro', db='nr', evalue=0.001, remote=True, ungapped=True) - >>> print cline + >>> print(cline) blastp -query rosemary.pro -db nr -evalue 0.001 -remote -ungapped You would typically run the command line with cline() or via the Python @@ -820,7 +822,7 @@ ... evalue=0.001, out="m_cold.xml", outfmt=5) >>> cline NcbiblastnCommandline(cmd='blastn', out='m_cold.xml', outfmt=5, query='m_cold.fasta', db='nt', evalue=0.001, strand='plus') - >>> print cline + >>> print(cline) blastn -out m_cold.xml -outfmt 5 -query m_cold.fasta -db nt -evalue 0.001 -strand plus You would typically run the command line with cline() or via the Python @@ -889,7 +891,7 @@ Allowed values: 'coding', 'coding_and_optimal' or 'optimal' Requires: template_length.""", - checker_function=lambda value : value in ['coding', 'coding_and_optimal','optimal'], + checker_function=lambda value : value in ['coding', 'coding_and_optimal', 'optimal'], equate=False), _Option(["-template_length", "template_length"], """Discontiguous MegaBLAST template length (integer). @@ -897,7 +899,7 @@ Allowed values: 16, 18, 21 Requires: template_type.""", - checker_function=lambda value : value in [16,18,21,'16','18','21'], + checker_function=lambda value : value in [16, 18, 21, '16', '18', '21'], equate=False), #Extension options: _Switch(["-no_greedy", "no_greedy"], @@ -937,7 +939,7 @@ >>> cline = NcbiblastxCommandline(query="m_cold.fasta", db="nr", evalue=0.001) >>> cline NcbiblastxCommandline(cmd='blastx', query='m_cold.fasta', db='nr', evalue=0.001) - >>> print cline + >>> print(cline) blastx -query m_cold.fasta -db nr -evalue 0.001 You would typically run the command line with cline() or via the Python @@ -1018,7 +1020,7 @@ >>> cline = NcbitblastnCommandline(help=True) >>> cline NcbitblastnCommandline(cmd='tblastn', help=True) - >>> print cline + >>> print(cline) tblastn -help You would typically run the command line with cline() or via the Python @@ -1098,7 +1100,7 @@ >>> cline = NcbitblastxCommandline(help=True) >>> cline NcbitblastxCommandline(cmd='tblastx', help=True) - >>> print cline + >>> print(cline) tblastx -help You would typically run the command line with cline() or via the Python @@ -1161,7 +1163,7 @@ >>> cline = NcbipsiblastCommandline(help=True) >>> cline NcbipsiblastCommandline(cmd='psiblast', help=True) - >>> print cline + >>> print(cline) psiblast -help You would typically run the command line with cline() or via the Python @@ -1266,10 +1268,10 @@ _Ncbiblast2SeqCommandline.__init__(self, cmd, **kwargs) def _validate(self): - incompatibles = {"num_iterations":["remote"], - "in_msa":["in_pssm", "query"], - "in_pssm":["in_msa","query","phi_pattern"], - "ignore_msa_master":["msa_master_idx", "in_pssm", + incompatibles = {"num_iterations": ["remote"], + "in_msa": ["in_pssm", "query"], + "in_pssm": ["in_msa", "query", "phi_pattern"], + "ignore_msa_master": ["msa_master_idx", "in_pssm", "query", "query_loc", "phi_pattern"], } self._validate_incompatibilities(incompatibles) @@ -1287,7 +1289,7 @@ >>> cline = NcbirpsblastCommandline(help=True) >>> cline NcbirpsblastCommandline(cmd='rpsblast', help=True) - >>> print cline + >>> print(cline) rpsblast -help You would typically run the command line with cline() or via the Python @@ -1346,7 +1348,7 @@ _NcbiblastCommandline.__init__(self, cmd, **kwargs) def _validate(self): - incompatibles = {"culling_limit":["best_hit_overhang","best_hit_score_edge"]} + incompatibles = {"culling_limit":["best_hit_overhang", "best_hit_score_edge"]} self._validate_incompatibilities(incompatibles) _NcbiblastCommandline._validate(self) @@ -1362,7 +1364,7 @@ >>> cline = NcbirpstblastnCommandline(help=True) >>> cline NcbirpstblastnCommandline(cmd='rpstblastn', help=True) - >>> print cline + >>> print(cline) rpstblastn -help You would typically run the command line with cline() or via the Python @@ -1413,7 +1415,7 @@ >>> cline = NcbiblastformatterCommandline(archive="example.asn", outfmt=5, out="example.xml") >>> cline NcbiblastformatterCommandline(cmd='blast_formatter', out='example.xml', outfmt=5, archive='example.asn') - >>> print cline + >>> print(cline) blast_formatter -out example.xml -outfmt 5 -archive example.asn You would typically run the command line with cline() or via the Python @@ -1458,3 +1460,4 @@ if __name__ == "__main__": #Run the doctests _test() + diff -Nru python-biopython-1.62/Bio/Blast/NCBIStandalone.py python-biopython-1.63/Bio/Blast/NCBIStandalone.py --- python-biopython-1.62/Bio/Blast/NCBIStandalone.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Blast/NCBIStandalone.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,7 +5,7 @@ # Patches by Mike Poidinger to support multiple databases. # Updated by Peter Cock in 2007 to do a better job on BLAST 2.2.15 -"""Code for calling standalone BLAST and parsing plain text output (OBSOLETE). +"""Code for calling standalone BLAST and parsing plain text output (DEPRECATED). Rather than parsing the human readable plain text BLAST output (which seems to change with every update to BLAST), we and the NBCI recommend you parse the @@ -39,9 +39,9 @@ _ParametersConsumer Consumes parameters information. Functions: -blastall Execute blastall (OBSOLETE). -blastpgp Execute blastpgp (OBSOLETE). -rpsblast Execute rpsblast (OBSOLETE). +blastall Execute blastall. +blastpgp Execute blastpgp. +rpsblast Execute rpsblast. For calling the BLAST command line tools, we encourage you to use the command line wrappers in Bio.Blast.Applications - the three functions @@ -49,14 +49,16 @@ are likely to be deprecated and then removed in future releases. """ -import warnings -warnings.warn("The plain text parser in this module still works at the time of writing, but is considered obsolete and updating it to cope with the latest versions of BLAST is not a priority for us.", PendingDeprecationWarning) +from __future__ import print_function from Bio import BiopythonDeprecationWarning +import warnings +warnings.warn("This module has been deprecated. Consider Bio.SearchIO for " + "parsing BLAST output instead.", BiopythonDeprecationWarning) import os import re -import StringIO +from Bio._py3k import StringIO from Bio import File from Bio.ParserSupport import * @@ -177,7 +179,7 @@ consumer.reference, start='Reference'): # References are normally multiline terminated by a blank line # (or, based on the old code, the RID line) - while 1: + while True: line = uhandle.readline() if is_blank_line(line): consumer.noevent(line) @@ -343,7 +345,7 @@ contains='No hits found') try: read_and_call_while(uhandle, consumer.noevent, blank=1) - except ValueError, err: + except ValueError as err: if str(err) != "Unexpected end of stream.": raise err @@ -435,7 +437,7 @@ self._scan_alignment_header(uhandle, consumer) # Scan a bunch of score/alignment pairs. - while 1: + while True: if self._eof(uhandle): #Shouldn't have issued that _scan_alignment_header event... break @@ -457,7 +459,7 @@ # ... # Length=428 read_and_call(uhandle, consumer.title, start='>') - while 1: + while True: line = safe_readline(uhandle) if line.lstrip().startswith('Length =') \ or line.lstrip().startswith('Length='): @@ -505,7 +507,7 @@ # Sbjct: 70 PNIIQLKD 77 # - while 1: + while True: # Blastn adds an extra line filled with spaces before Query attempt_read_and_call(uhandle, consumer.noevent, start=' ') read_and_call(uhandle, consumer.query, start='Query') @@ -513,7 +515,7 @@ read_and_call(uhandle, consumer.sbjct, start='Sbjct') try: read_and_call_while(uhandle, consumer.noevent, blank=1) - except ValueError, err: + except ValueError as err: if str(err) != "Unexpected end of stream.": raise err # End of File (well, it looks like it with recent versions @@ -527,7 +529,7 @@ def _scan_masterslave_alignment(self, uhandle, consumer): consumer.start_alignment() - while 1: + while True: line = safe_readline(uhandle) # Check to see whether I'm finished reading the alignment. # This is indicated by 1) database section, 2) next psi-blast @@ -551,7 +553,7 @@ def _eof(self, uhandle): try: line = safe_peekline(uhandle) - except ValueError, err: + except ValueError as err: if str(err) != "Unexpected end of stream.": raise err line = "" @@ -644,7 +646,7 @@ # file. try: read_and_call_while(uhandle, consumer.noevent, blank=1) - except ValueError, x: + except ValueError as x: if str(x) != "Unexpected end of stream.": raise consumer.end_database_report() @@ -1003,7 +1005,7 @@ def length(self, line): #e.g. "Length = 81" or more recently, "Length=428" - parts = line.replace(" ","").split("=") + parts = line.replace(" ", "").split("=") assert len(parts)==2, "Unrecognised format length line" self._alignment.length = parts[1] self._alignment.length = _safe_int(self._alignment.length) @@ -1310,15 +1312,13 @@ self._dr.num_sequences_in_database.append(_safe_int(sequences)) def ka_params(self, line): - x = line.split() - self._dr.ka_params = map(_safe_float, x) + self._dr.ka_params = [_safe_float(x) for x in line.split()] def gapped(self, line): self._dr.gapped = 1 def ka_params_gap(self, line): - x = line.split() - self._dr.ka_params_gap = map(_safe_float, x) + self._dr.ka_params_gap = [_safe_float(x) for x in line.split()] def end_database_report(self): pass @@ -1332,9 +1332,8 @@ self._params.matrix = line[8:].rstrip() def gap_penalties(self, line): - x = _get_cols( - line, (3, 5), ncols=6, expected={2:"Existence:", 4:"Extension:"}) - self._params.gap_penalties = map(_safe_float, x) + self._params.gap_penalties = [_safe_float(x) for x in _get_cols( + line, (3, 5), ncols=6, expected={2:"Existence:", 4:"Extension:"})] def num_hits(self, line): if '1st pass' in line: @@ -1637,7 +1636,7 @@ self._parser = parser self._header = [] - def next(self): + def __next__(self): """next(self) -> object Return the next Blast record from the file. If no more records, @@ -1646,7 +1645,7 @@ """ lines = [] query = False - while 1: + while True: line = self._uhandle.readline() if not line: break @@ -1682,11 +1681,21 @@ data = ''.join(lines) if self._parser is not None: - return self._parser.parse(StringIO.StringIO(data)) + return self._parser.parse(StringIO(data)) return data + if sys.version_info[0] < 3: + def next(self): + """Deprecated Python 2 style alias for Python 3 style __next__ method.""" + import warnings + from Bio import BiopythonDeprecationWarning + warnings.warn("Please use next(my_iterator) instead of my_iterator.next(), " + "the .next() method is deprecated and will be removed in a " + "future release of Biopython.", BiopythonDeprecationWarning) + return self.__next__() + def __iter__(self): - return iter(self.next, None) + return iter(self.__next__, None) def blastall(blastcmd, program, database, infile, align_view='7', **keywds): @@ -1753,50 +1762,49 @@ _security_check_parameters(keywds) att2param = { - 'matrix' : '-M', - 'gap_open' : '-G', - 'gap_extend' : '-E', - 'nuc_match' : '-r', - 'nuc_mismatch' : '-q', - 'query_genetic_code' : '-Q', - 'db_genetic_code' : '-D', - - 'gapped' : '-g', - 'expectation' : '-e', - 'wordsize' : '-W', - 'strands' : '-S', - 'keep_hits' : '-K', - 'xdrop' : '-X', - 'hit_extend' : '-f', - 'region_length' : '-L', - 'db_length' : '-z', - 'search_length' : '-Y', - - 'program' : '-p', - 'database' : '-d', - 'infile' : '-i', - 'filter' : '-F', - 'believe_query' : '-J', - 'restrict_gi' : '-l', - 'nprocessors' : '-a', - 'oldengine' : '-V', - - 'html' : '-T', - 'descriptions' : '-v', - 'alignments' : '-b', - 'align_view' : '-m', - 'show_gi' : '-I', - 'seqalign_file' : '-O', - 'outfile' : '-o', + 'matrix': '-M', + 'gap_open': '-G', + 'gap_extend': '-E', + 'nuc_match': '-r', + 'nuc_mismatch': '-q', + 'query_genetic_code': '-Q', + 'db_genetic_code': '-D', + + 'gapped': '-g', + 'expectation': '-e', + 'wordsize': '-W', + 'strands': '-S', + 'keep_hits': '-K', + 'xdrop': '-X', + 'hit_extend': '-f', + 'region_length': '-L', + 'db_length': '-z', + 'search_length': '-Y', + + 'program': '-p', + 'database': '-d', + 'infile': '-i', + 'filter': '-F', + 'believe_query': '-J', + 'restrict_gi': '-l', + 'nprocessors': '-a', + 'oldengine': '-V', + + 'html': '-T', + 'descriptions': '-v', + 'alignments': '-b', + 'align_view': '-m', + 'show_gi': '-I', + 'seqalign_file': '-O', + 'outfile': '-o', } - warnings.warn("This function is deprecated; you are encouraged to the command line wrapper Bio.Blast.Applications.BlastallCommandline instead.", BiopythonDeprecationWarning) - from Applications import BlastallCommandline + from .Applications import BlastallCommandline cline = BlastallCommandline(blastcmd) cline.set_parameter(att2param['program'], program) cline.set_parameter(att2param['database'], database) cline.set_parameter(att2param['infile'], infile) cline.set_parameter(att2param['align_view'], str(align_view)) - for key, value in keywds.iteritems(): + for key, value in keywds.items(): cline.set_parameter(att2param[key], str(value)) return _invoke_blast(cline) @@ -1872,61 +1880,59 @@ align_infile Input alignment file for PSI-BLAST restart. """ - - warnings.warn("This function is deprecated; you are encouraged to the command line wrapper Bio.Blast.Applications.BlastpgpCommandline instead.", BiopythonDeprecationWarning) _security_check_parameters(keywds) att2param = { - 'matrix' : '-M', - 'gap_open' : '-G', - 'gap_extend' : '-E', - 'window_size' : '-A', - 'npasses' : '-j', - 'passes' : '-P', - - 'gapped' : '-g', - 'expectation' : '-e', - 'wordsize' : '-W', - 'keep_hits' : '-K', - 'xdrop' : '-X', - 'hit_extend' : '-f', - 'region_length' : '-L', - 'db_length' : '-Z', - 'search_length' : '-Y', - 'nbits_gapping' : '-N', - 'pseudocounts' : '-c', - 'xdrop_final' : '-Z', - 'xdrop_extension' : '-y', - 'model_threshold' : '-h', - 'required_start' : '-S', - 'required_end' : '-H', - - 'program' : '-p', - 'database' : '-d', - 'infile' : '-i', - 'filter' : '-F', - 'believe_query' : '-J', - 'nprocessors' : '-a', - - 'html' : '-T', - 'descriptions' : '-v', - 'alignments' : '-b', - 'align_view' : '-m', - 'show_gi' : '-I', - 'seqalign_file' : '-O', - 'align_outfile' : '-o', - 'checkpoint_outfile' : '-C', - 'restart_infile' : '-R', - 'hit_infile' : '-k', - 'matrix_outfile' : '-Q', - 'align_infile' : '-B', + 'matrix': '-M', + 'gap_open': '-G', + 'gap_extend': '-E', + 'window_size': '-A', + 'npasses': '-j', + 'passes': '-P', + + 'gapped': '-g', + 'expectation': '-e', + 'wordsize': '-W', + 'keep_hits': '-K', + 'xdrop': '-X', + 'hit_extend': '-f', + 'region_length': '-L', + 'db_length': '-Z', + 'search_length': '-Y', + 'nbits_gapping': '-N', + 'pseudocounts': '-c', + 'xdrop_final': '-Z', + 'xdrop_extension': '-y', + 'model_threshold': '-h', + 'required_start': '-S', + 'required_end': '-H', + + 'program': '-p', + 'database': '-d', + 'infile': '-i', + 'filter': '-F', + 'believe_query': '-J', + 'nprocessors': '-a', + + 'html': '-T', + 'descriptions': '-v', + 'alignments': '-b', + 'align_view': '-m', + 'show_gi': '-I', + 'seqalign_file': '-O', + 'align_outfile': '-o', + 'checkpoint_outfile': '-C', + 'restart_infile': '-R', + 'hit_infile': '-k', + 'matrix_outfile': '-Q', + 'align_infile': '-B', } - from Applications import BlastpgpCommandline + from .Applications import BlastpgpCommandline cline = BlastpgpCommandline(blastcmd) cline.set_parameter(att2param['database'], database) cline.set_parameter(att2param['infile'], infile) cline.set_parameter(att2param['align_view'], str(align_view)) - for key, value in keywds.iteritems(): + for key, value in keywds.items(): cline.set_parameter(att2param[key], str(value)) return _invoke_blast(cline) @@ -1992,46 +1998,44 @@ omitted standard output is used (which you can access from the returned handles). """ - - warnings.warn("This function is deprecated; you are encouraged to the command line wrapper Bio.Blast.Applications.BlastrpsCommandline instead.", BiopythonDeprecationWarning) _security_check_parameters(keywds) att2param = { - 'multihit' : '-P', - 'gapped' : '-g', - 'expectation' : '-e', - 'range_restriction' : '-L', - 'xdrop' : '-X', - 'xdrop_final' : '-Z', - 'xdrop_extension' : '-y', - 'search_length' : '-Y', - 'nbits_gapping' : '-N', - 'protein' : '-p', - 'db_length' : '-z', - - 'database' : '-d', - 'infile' : '-i', - 'filter' : '-F', - 'case_filter' : '-U', - 'believe_query' : '-J', - 'nprocessors' : '-a', - 'logfile' : '-l', - - 'html' : '-T', - 'descriptions' : '-v', - 'alignments' : '-b', - 'align_view' : '-m', - 'show_gi' : '-I', - 'seqalign_file' : '-O', - 'align_outfile' : '-o', + 'multihit': '-P', + 'gapped': '-g', + 'expectation': '-e', + 'range_restriction': '-L', + 'xdrop': '-X', + 'xdrop_final': '-Z', + 'xdrop_extension': '-y', + 'search_length': '-Y', + 'nbits_gapping': '-N', + 'protein': '-p', + 'db_length': '-z', + + 'database': '-d', + 'infile': '-i', + 'filter': '-F', + 'case_filter': '-U', + 'believe_query': '-J', + 'nprocessors': '-a', + 'logfile': '-l', + + 'html': '-T', + 'descriptions': '-v', + 'alignments': '-b', + 'align_view': '-m', + 'show_gi': '-I', + 'seqalign_file': '-O', + 'align_outfile': '-o', } - from Applications import RpsBlastCommandline + from .Applications import RpsBlastCommandline cline = RpsBlastCommandline(blastcmd) cline.set_parameter(att2param['database'], database) cline.set_parameter(att2param['infile'], infile) cline.set_parameter(att2param['align_view'], str(align_view)) - for key, value in keywds.iteritems(): + for key, value in keywds.items(): cline.set_parameter(att2param[key], str(value)) return _invoke_blast(cline) @@ -2135,7 +2139,7 @@ for appending a command line), or ">", "<" or "|" (redirection) and if any are found raises an exception. """ - for key, value in param_dict.iteritems(): + for key, value in param_dict.items(): str_value = str(value) # Could easily be an int or a float for bad_str in [";", "&&", ">", "<", "|"]: if bad_str in str_value: @@ -2192,7 +2196,7 @@ results = handle.read() try: - self._scanner.feed(StringIO.StringIO(results), self._consumer) + self._scanner.feed(StringIO(results), self._consumer) except ValueError: # if we have a bad_report_file, save the info to it first if self._bad_report_handle: @@ -2201,7 +2205,7 @@ # now we want to try and diagnose the error self._diagnose_error( - StringIO.StringIO(results), self._consumer.data) + StringIO(results), self._consumer.data) # if we got here we can't figure out the problem # so we should pass along the syntax error we got diff -Nru python-biopython-1.62/Bio/Blast/NCBIWWW.py python-biopython-1.63/Bio/Blast/NCBIWWW.py --- python-biopython-1.62/Bio/Blast/NCBIWWW.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Blast/NCBIWWW.py 2013-12-05 14:10:43.000000000 +0000 @@ -6,7 +6,8 @@ # Patched by Brad Chapman. # Chris Wroe added modifications for work in myGrid -""" +"""Code to invoke the NCBI BLAST server over the internet. + This module provides code to work with the WWW version of BLAST provided by the NCBI. http://blast.ncbi.nlm.nih.gov/ @@ -15,28 +16,29 @@ qblast Do a BLAST search using the QBLAST API. """ -try: - from cStringIO import StringIO -except ImportError: - from StringIO import StringIO +from __future__ import print_function +from Bio._py3k import StringIO from Bio._py3k import _as_string, _as_bytes +from Bio._py3k import urlopen as _urlopen +from Bio._py3k import urlencode as _urlencode +from Bio._py3k import Request as _Request def qblast(program, database, sequence, - auto_format=None,composition_based_statistics=None, - db_genetic_code=None,endpoints=None,entrez_query='(none)', - expect=10.0,filter=None,gapcosts=None,genetic_code=None, - hitlist_size=50,i_thresh=None,layout=None,lcase_mask=None, - matrix_name=None,nucl_penalty=None,nucl_reward=None, - other_advanced=None,perc_ident=None,phi_pattern=None, - query_file=None,query_believe_defline=None,query_from=None, - query_to=None,searchsp_eff=None,service=None,threshold=None, - ungapped_alignment=None,word_size=None, - alignments=500,alignment_view=None,descriptions=500, - entrez_links_new_window=None,expect_low=None,expect_high=None, - format_entrez_query=None,format_object=None,format_type='XML', - ncbi_gi=None,results_file=None,show_overview=None, megablast=None, + auto_format=None, composition_based_statistics=None, + db_genetic_code=None, endpoints=None, entrez_query='(none)', + expect=10.0, filter=None, gapcosts=None, genetic_code=None, + hitlist_size=50, i_thresh=None, layout=None, lcase_mask=None, + matrix_name=None, nucl_penalty=None, nucl_reward=None, + other_advanced=None, perc_ident=None, phi_pattern=None, + query_file=None, query_believe_defline=None, query_from=None, + query_to=None, searchsp_eff=None, service=None, threshold=None, + ungapped_alignment=None, word_size=None, + alignments=500, alignment_view=None, descriptions=500, + entrez_links_new_window=None, expect_low=None, expect_high=None, + format_entrez_query=None, format_object=None, format_type='XML', + ncbi_gi=None, results_file=None, show_overview=None, megablast=None, ): """Do a BLAST search using the QBLAST server at NCBI. @@ -62,8 +64,6 @@ http://www.ncbi.nlm.nih.gov/BLAST/Doc/urlapi.html """ - import urllib - import urllib2 import time assert program in ['blastn', 'blastp', 'blastx', 'tblastn', 'tblastx'] @@ -74,76 +74,76 @@ # To perform a PSI-BLAST or PHI-BLAST search the service ("Put" and "Get" commands) must be specified # (e.g. psi_blast = NCBIWWW.qblast("blastp", "refseq_protein", input_sequence, service="psi")) parameters = [ - ('AUTO_FORMAT',auto_format), - ('COMPOSITION_BASED_STATISTICS',composition_based_statistics), - ('DATABASE',database), - ('DB_GENETIC_CODE',db_genetic_code), - ('ENDPOINTS',endpoints), - ('ENTREZ_QUERY',entrez_query), - ('EXPECT',expect), - ('FILTER',filter), - ('GAPCOSTS',gapcosts), - ('GENETIC_CODE',genetic_code), - ('HITLIST_SIZE',hitlist_size), - ('I_THRESH',i_thresh), - ('LAYOUT',layout), - ('LCASE_MASK',lcase_mask), - ('MEGABLAST',megablast), - ('MATRIX_NAME',matrix_name), - ('NUCL_PENALTY',nucl_penalty), - ('NUCL_REWARD',nucl_reward), - ('OTHER_ADVANCED',other_advanced), - ('PERC_IDENT',perc_ident), - ('PHI_PATTERN',phi_pattern), - ('PROGRAM',program), + ('AUTO_FORMAT', auto_format), + ('COMPOSITION_BASED_STATISTICS', composition_based_statistics), + ('DATABASE', database), + ('DB_GENETIC_CODE', db_genetic_code), + ('ENDPOINTS', endpoints), + ('ENTREZ_QUERY', entrez_query), + ('EXPECT', expect), + ('FILTER', filter), + ('GAPCOSTS', gapcosts), + ('GENETIC_CODE', genetic_code), + ('HITLIST_SIZE', hitlist_size), + ('I_THRESH', i_thresh), + ('LAYOUT', layout), + ('LCASE_MASK', lcase_mask), + ('MEGABLAST', megablast), + ('MATRIX_NAME', matrix_name), + ('NUCL_PENALTY', nucl_penalty), + ('NUCL_REWARD', nucl_reward), + ('OTHER_ADVANCED', other_advanced), + ('PERC_IDENT', perc_ident), + ('PHI_PATTERN', phi_pattern), + ('PROGRAM', program), #('PSSM',pssm), - It is possible to use PSI-BLAST via this API? - ('QUERY',sequence), - ('QUERY_FILE',query_file), - ('QUERY_BELIEVE_DEFLINE',query_believe_defline), - ('QUERY_FROM',query_from), - ('QUERY_TO',query_to), + ('QUERY', sequence), + ('QUERY_FILE', query_file), + ('QUERY_BELIEVE_DEFLINE', query_believe_defline), + ('QUERY_FROM', query_from), + ('QUERY_TO', query_to), #('RESULTS_FILE',...), - Can we use this parameter? - ('SEARCHSP_EFF',searchsp_eff), - ('SERVICE',service), - ('THRESHOLD',threshold), - ('UNGAPPED_ALIGNMENT',ungapped_alignment), - ('WORD_SIZE',word_size), + ('SEARCHSP_EFF', searchsp_eff), + ('SERVICE', service), + ('THRESHOLD', threshold), + ('UNGAPPED_ALIGNMENT', ungapped_alignment), + ('WORD_SIZE', word_size), ('CMD', 'Put'), ] query = [x for x in parameters if x[1] is not None] - message = _as_bytes(urllib.urlencode(query)) + message = _as_bytes(_urlencode(query)) # Send off the initial query to qblast. # Note the NCBI do not currently impose a rate limit here, other # than the request not to make say 50 queries at once using multiple # threads. - request = urllib2.Request("http://blast.ncbi.nlm.nih.gov/Blast.cgi", - message, - {"User-Agent":"BiopythonClient"}) - handle = urllib2.urlopen(request) + request = _Request("http://blast.ncbi.nlm.nih.gov/Blast.cgi", + message, + {"User-Agent":"BiopythonClient"}) + handle = _urlopen(request) # Format the "Get" command, which gets the formatted results from qblast # Parameters taken from http://www.ncbi.nlm.nih.gov/BLAST/Doc/node6.html on 9 July 2007 rid, rtoe = _parse_qblast_ref_page(handle) parameters = [ - ('ALIGNMENTS',alignments), - ('ALIGNMENT_VIEW',alignment_view), - ('DESCRIPTIONS',descriptions), - ('ENTREZ_LINKS_NEW_WINDOW',entrez_links_new_window), - ('EXPECT_LOW',expect_low), - ('EXPECT_HIGH',expect_high), - ('FORMAT_ENTREZ_QUERY',format_entrez_query), - ('FORMAT_OBJECT',format_object), - ('FORMAT_TYPE',format_type), - ('NCBI_GI',ncbi_gi), - ('RID',rid), - ('RESULTS_FILE',results_file), - ('SERVICE',service), - ('SHOW_OVERVIEW',show_overview), + ('ALIGNMENTS', alignments), + ('ALIGNMENT_VIEW', alignment_view), + ('DESCRIPTIONS', descriptions), + ('ENTREZ_LINKS_NEW_WINDOW', entrez_links_new_window), + ('EXPECT_LOW', expect_low), + ('EXPECT_HIGH', expect_high), + ('FORMAT_ENTREZ_QUERY', format_entrez_query), + ('FORMAT_OBJECT', format_object), + ('FORMAT_TYPE', format_type), + ('NCBI_GI', ncbi_gi), + ('RID', rid), + ('RESULTS_FILE', results_file), + ('SERVICE', service), + ('SHOW_OVERVIEW', show_overview), ('CMD', 'Get'), ] query = [x for x in parameters if x[1] is not None] - message = _as_bytes(urllib.urlencode(query)) + message = _as_bytes(_urlencode(query)) # Poll NCBI until the results are ready. Use a 3 second wait delay = 3.0 @@ -157,10 +157,10 @@ else: previous = current - request = urllib2.Request("http://blast.ncbi.nlm.nih.gov/Blast.cgi", - message, - {"User-Agent":"BiopythonClient"}) - handle = urllib2.urlopen(request) + request = _Request("http://blast.ncbi.nlm.nih.gov/Blast.cgi", + message, + {"User-Agent":"BiopythonClient"}) + handle = _urlopen(request) results = _as_string(handle.read()) # Can see an "\n\n" page while results are in progress, @@ -211,21 +211,21 @@ i = s.find('
') if i != -1: msg = s[i+len('
'):].strip() - msg = msg.split("
",1)[0].split("\n",1)[0].strip() + msg = msg.split("
", 1)[0].split("\n", 1)[0].strip() if msg: raise ValueError("Error message from NCBI: %s" % msg) #In spring 2010 the markup was like this: i = s.find('

') if i != -1: msg = s[i+len('

'):].strip() - msg = msg.split("

",1)[0].split("\n",1)[0].strip() + msg = msg.split("

", 1)[0].split("\n", 1)[0].strip() if msg: raise ValueError("Error message from NCBI: %s" % msg) #Generic search based on the way the error messages start: i = s.find('Message ID#') if i != -1: #Break the message at the first HTML tag - msg = s[i:].split("<",1)[0].split("\n",1)[0].strip() + msg = s[i:].split("<", 1)[0].split("\n", 1)[0].strip() raise ValueError("Error message from NCBI: %s" % msg) #We didn't recognise the error layout :( #print s diff -Nru python-biopython-1.62/Bio/Blast/NCBIXML.py python-biopython-1.63/Bio/Blast/NCBIXML.py --- python-biopython-1.62/Bio/Blast/NCBIXML.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Blast/NCBIXML.py 2013-12-05 14:10:43.000000000 +0000 @@ -21,9 +21,12 @@ Blast records. It uses the BlastParser internally. read Returns a single Blast record. Uses the BlastParser internally. """ +from __future__ import print_function + from Bio.Blast import Record import xml.sax from xml.sax.handler import ContentHandler +from functools import reduce class _XMLparser(ContentHandler): @@ -70,11 +73,11 @@ if hasattr(self, method): eval("self.%s()" % method) if self._debug > 4: - print "NCBIXML: Parsed: " + method + print("NCBIXML: Parsed: " + method) elif self._debug > 3: # Doesn't exist (yet) and may want to warn about it if method not in self._debug_ignore_list: - print "NCBIXML: Ignored: " + method + print("NCBIXML: Ignored: " + method) self._debug_ignore_list.append(method) #We don't care about white space in parent tags like Hsp, @@ -105,11 +108,11 @@ if hasattr(self, method): eval("self.%s()" % method) if self._debug > 2: - print "NCBIXML: Parsed: " + method, self._value + print("NCBIXML: Parsed: %s %s" % (method, self._value)) elif self._debug > 1: # Doesn't exist (yet) and may want to warn about it if method not in self._debug_ignore_list: - print "NCBIXML: Ignored: " + method, self._value + print("NCBIXML: Ignored: %s %s" % (method, self._value)) self._debug_ignore_list.append(method) # Reset character buffer @@ -209,7 +212,7 @@ self._blast = None if self._debug: - print "NCBIXML: Added Blast record to results" + print("NCBIXML: Added Blast record to results") # Header def _end_BlastOutput_program(self): @@ -575,13 +578,13 @@ """ iterator = parse(handle, debug) try: - first = iterator.next() + first = next(iterator) except StopIteration: first = None if first is None: raise ValueError("No records found in handle") try: - second = iterator.next() + second = next(iterator) except StopIteration: second = None if second is not None: @@ -659,7 +662,7 @@ # one XML file for each query! # Finish the old file: - text, pending = (text+pending).split("\n" + XML_START,1) + text, pending = (text+pending).split("\n" + XML_START, 1) pending = XML_START + pending expat_parser.Parse(text, True) # End of XML record @@ -689,28 +692,28 @@ if __name__ == '__main__': import sys - handle = open(sys.argv[1]) - r_list = parse(handle) + with open(sys.argv[1]) as handle: + r_list = parse(handle) for r in r_list: # Small test - print 'Blast of', r.query - print 'Found %s alignments with a total of %s HSPs' % (len(r.alignments), - reduce(lambda a,b: a+b, - [len(a.hsps) for a in r.alignments])) + print('Blast of %s' % r.query) + print('Found %s alignments with a total of %s HSPs' % (len(r.alignments), + reduce(lambda a, b: a+b, + [len(a.hsps) for a in r.alignments]))) for al in r.alignments: - print al.title[:50], al.length, 'bp', len(al.hsps), 'HSPs' + print("%s %i bp %i HSPs" % (al.title[:50], al.length, len(al.hsps))) # Cookbook example E_VALUE_THRESH = 0.04 for alignment in r.alignments: for hsp in alignment.hsps: if hsp.expect < E_VALUE_THRESH: - print '*****' - print 'sequence', alignment.title - print 'length', alignment.length - print 'e value', hsp.expect - print hsp.query[:75] + '...' - print hsp.match[:75] + '...' - print hsp.sbjct[:75] + '...' + print('*****') + print('sequence %s' % alignment.title) + print('length %i' % alignment.length) + print('e value %f' % hsp.expect) + print(hsp.query[:75] + '...') + print(hsp.match[:75] + '...') + print(hsp.sbjct[:75] + '...') diff -Nru python-biopython-1.62/Bio/Blast/ParseBlastTable.py python-biopython-1.63/Bio/Blast/ParseBlastTable.py --- python-biopython-1.62/Bio/Blast/ParseBlastTable.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Blast/ParseBlastTable.py 2013-12-05 14:10:43.000000000 +0000 @@ -8,9 +8,10 @@ Returns a BlastTableRec instance """ +import sys class BlastTableEntry(object): - def __init__(self,in_rec): + def __init__(self, in_rec): bt_fields = in_rec.split() self.qid = bt_fields[0].split('|') self.sid = bt_fields[1].split('|') @@ -55,7 +56,7 @@ self._n = 0 self._in_header = 1 - def next(self): + def __next__(self): self.table_record = BlastTableRec() self._n += 1 inline = self._lookahead @@ -76,6 +77,16 @@ self._in_header = 1 return self.table_record + if sys.version_info[0] < 3: + def next(self): + """Deprecated Python 2 style alias for Python 3 style __next__ method.""" + import warnings + from Bio import BiopythonDeprecationWarning + warnings.warn("Please use next(my_iterator) instead of my_iterator.next(), " + "the .next() method is deprecated and will be removed in a " + "future release of Biopython.", BiopythonDeprecationWarning) + return self.__next__() + def _consume_entry(self, inline): current_entry = BlastTableEntry(inline) self.table_record.add_entry(current_entry) @@ -83,7 +94,7 @@ def _consume_header(self, inline): for keyword in reader_keywords: if keyword in inline: - in_header = self._Parse('_parse_%s' % reader_keywords[keyword],inline) + in_header = self._Parse('_parse_%s' % reader_keywords[keyword], inline) break return in_header @@ -110,4 +121,4 @@ return 0 def _Parse(self, method_name, inline): - return getattr(self,method_name)(inline) + return getattr(self, method_name)(inline) diff -Nru python-biopython-1.62/Bio/Blast/Record.py python-biopython-1.63/Bio/Blast/Record.py --- python-biopython-1.62/Bio/Blast/Record.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Blast/Record.py 2013-12-05 14:10:43.000000000 +0000 @@ -238,7 +238,7 @@ n += 1 generic = Generic.Alignment(alphabet) - for (name,seq) in zip(seq_names,seq_parts): + for (name, seq) in zip(seq_names, seq_parts): generic.add_sequence(name, seq) return generic diff -Nru python-biopython-1.62/Bio/Cluster/__init__.py python-biopython-1.63/Bio/Cluster/__init__.py --- python-biopython-1.62/Bio/Cluster/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Cluster/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + import numpy from Bio.Cluster.cluster import * @@ -66,44 +71,43 @@ extension = ".atr" keyword = "ARRY" nnodes = len(tree) - outputfile = open(jobname+extension, "w") - nodeindex = 0 - nodeID = [''] * nnodes - nodecounts = numpy.zeros(nnodes, int) - nodeorder = numpy.zeros(nnodes) - nodedist = numpy.array([node.distance for node in tree]) - for nodeindex in range(nnodes): - min1 = tree[nodeindex].left - min2 = tree[nodeindex].right - nodeID[nodeindex] = "NODE%dX" % (nodeindex+1) - outputfile.write(nodeID[nodeindex]) - outputfile.write("\t") - if min1 < 0: - index1 = -min1-1 - order1 = nodeorder[index1] - counts1 = nodecounts[index1] - outputfile.write(nodeID[index1]+"\t") - nodedist[nodeindex] = max(nodedist[nodeindex], nodedist[index1]) - else: - order1 = order[min1] - counts1 = 1 - outputfile.write("%s%dX\t" % (keyword, min1)) - if min2 < 0: - index2 = -min2-1 - order2 = nodeorder[index2] - counts2 = nodecounts[index2] - outputfile.write(nodeID[index2]+"\t") - nodedist[nodeindex] = max(nodedist[nodeindex], nodedist[index2]) - else: - order2 = order[min2] - counts2 = 1 - outputfile.write("%s%dX\t" % (keyword, min2)) - outputfile.write(str(1.0-nodedist[nodeindex])) - outputfile.write("\n") - counts = counts1 + counts2 - nodecounts[nodeindex] = counts - nodeorder[nodeindex] = (counts1*order1+counts2*order2) / counts - outputfile.close() + with open(jobname+extension, "w") as outputfile: + nodeindex = 0 + nodeID = [''] * nnodes + nodecounts = numpy.zeros(nnodes, int) + nodeorder = numpy.zeros(nnodes) + nodedist = numpy.array([node.distance for node in tree]) + for nodeindex in range(nnodes): + min1 = tree[nodeindex].left + min2 = tree[nodeindex].right + nodeID[nodeindex] = "NODE%dX" % (nodeindex+1) + outputfile.write(nodeID[nodeindex]) + outputfile.write("\t") + if min1 < 0: + index1 = -min1-1 + order1 = nodeorder[index1] + counts1 = nodecounts[index1] + outputfile.write(nodeID[index1]+"\t") + nodedist[nodeindex] = max(nodedist[nodeindex], nodedist[index1]) + else: + order1 = order[min1] + counts1 = 1 + outputfile.write("%s%dX\t" % (keyword, min1)) + if min2 < 0: + index2 = -min2-1 + order2 = nodeorder[index2] + counts2 = nodecounts[index2] + outputfile.write(nodeID[index2]+"\t") + nodedist[nodeindex] = max(nodedist[nodeindex], nodedist[index2]) + else: + order2 = order[min2] + counts2 = 1 + outputfile.write("%s%dX\t" % (keyword, min2)) + outputfile.write(str(1.0-nodedist[nodeindex])) + outputfile.write("\n") + counts = counts1 + counts2 + nodecounts[nodeindex] = counts + nodeorder[nodeindex] = (counts1*order1+counts2*order2) / counts # Now set up order based on the tree structure index = _treesort(order, nodeorder, nodecounts, tree) return index @@ -511,7 +515,7 @@ aid = 0 filename = jobname postfix = "" - if type(geneclusters) == Tree: + if isinstance(geneclusters, Tree): # This is a hierarchical clustering result. geneindex = _savetree(jobname, geneclusters, gorder, 0) gid = 1 @@ -524,7 +528,7 @@ postfix = "_G%d" % k else: geneindex = numpy.argsort(gorder) - if type(expclusters) == Tree: + if isinstance(expclusters, Tree): # This is a hierarchical clustering result. expindex = _savetree(jobname, expclusters, eorder, 1) aid = 1 @@ -548,24 +552,20 @@ else: label = "ARRAY" names = self.expid - try: - outputfile = open(filename, "w") - except IOError: - raise IOError("Unable to open output file") - outputfile.write(label + "\tGROUP\n") - index = numpy.argsort(order) - n = len(names) - sortedindex = numpy.zeros(n, int) - counter = 0 - cluster = 0 - while counter < n: - for j in index: - if clusterids[j] == cluster: - outputfile.write("%s\t%s\n" % (names[j], cluster)) - sortedindex[counter] = j - counter += 1 - cluster += 1 - outputfile.close() + with open(filename, "w") as outputfile: + outputfile.write(label + "\tGROUP\n") + index = numpy.argsort(order) + n = len(names) + sortedindex = numpy.zeros(n, int) + counter = 0 + cluster = 0 + while counter < n: + for j in index: + if clusterids[j] == cluster: + outputfile.write("%s\t%s\n" % (names[j], cluster)) + sortedindex[counter] = j + counter += 1 + cluster += 1 return sortedindex def _savedata(self, jobname, gid, aid, geneindex, expindex): @@ -575,56 +575,52 @@ else: genename = self.genename (ngenes, nexps) = numpy.shape(self.data) - try: - outputfile = open(jobname+'.cdt', 'w') - except IOError: - raise IOError("Unable to open output file") - if self.mask is not None: - mask = self.mask - else: - mask = numpy.ones((ngenes, nexps), int) - if self.gweight is not None: - gweight = self.gweight - else: - gweight = numpy.ones(ngenes) - if self.eweight is not None: - eweight = self.eweight - else: - eweight = numpy.ones(nexps) - if gid: - outputfile.write('GID\t') - outputfile.write(self.uniqid) - outputfile.write('\tNAME\tGWEIGHT') - # Now add headers for data columns. - for j in expindex: - outputfile.write('\t%s' % self.expid[j]) - outputfile.write('\n') - if aid: - outputfile.write("AID") + with open(jobname+'.cdt', 'w') as outputfile: + if self.mask is not None: + mask = self.mask + else: + mask = numpy.ones((ngenes, nexps), int) + if self.gweight is not None: + gweight = self.gweight + else: + gweight = numpy.ones(ngenes) + if self.eweight is not None: + eweight = self.eweight + else: + eweight = numpy.ones(nexps) if gid: - outputfile.write('\t') - outputfile.write("\t\t") + outputfile.write('GID\t') + outputfile.write(self.uniqid) + outputfile.write('\tNAME\tGWEIGHT') + # Now add headers for data columns. for j in expindex: - outputfile.write('\tARRY%dX' % j) + outputfile.write('\t%s' % self.expid[j]) outputfile.write('\n') - outputfile.write('EWEIGHT') - if gid: - outputfile.write('\t') - outputfile.write('\t\t') - for j in expindex: - outputfile.write('\t%f' % eweight[j]) - outputfile.write('\n') - for i in geneindex: + if aid: + outputfile.write("AID") + if gid: + outputfile.write('\t') + outputfile.write("\t\t") + for j in expindex: + outputfile.write('\tARRY%dX' % j) + outputfile.write('\n') + outputfile.write('EWEIGHT') if gid: - outputfile.write('GENE%dX\t' % i) - outputfile.write("%s\t%s\t%f" % - (self.geneid[i], genename[i], gweight[i])) - for j in expindex: outputfile.write('\t') - if mask[i, j]: - outputfile.write(str(self.data[i, j])) + outputfile.write('\t\t') + for j in expindex: + outputfile.write('\t%f' % eweight[j]) outputfile.write('\n') - outputfile.close() + for i in geneindex: + if gid: + outputfile.write('GENE%dX\t' % i) + outputfile.write("%s\t%s\t%f" % + (self.geneid[i], genename[i], gweight[i])) + for j in expindex: + outputfile.write('\t') + if mask[i, j]: + outputfile.write(str(self.data[i, j])) + outputfile.write('\n') def read(handle): diff -Nru python-biopython-1.62/Bio/Compass/__init__.py python-biopython-1.63/Bio/Compass/__init__.py --- python-biopython-1.62/Bio/Compass/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Compass/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -27,16 +27,16 @@ def read(handle): record = None try: - line = handle.next() + line = next(handle) record = Record() __read_names(record, line) - line = handle.next() + line = next(handle) __read_threshold(record, line) - line = handle.next() + line = next(handle) __read_lengths(record, line) - line = handle.next() + line = next(handle) __read_profilewidth(record, line) - line = handle.next() + line = next(handle) __read_scores(record, line) except StopIteration: if not record: @@ -48,9 +48,9 @@ continue __read_query_alignment(record, line) try: - line = handle.next() + line = next(handle) __read_positive_alignment(record, line) - line = handle.next() + line = next(handle) __read_hit_alignment(record, line) except StopIteration: raise ValueError("Unexpected end of stream.") @@ -60,20 +60,20 @@ def parse(handle): record = None try: - line = handle.next() + line = next(handle) except StopIteration: return while True: try: record = Record() __read_names(record, line) - line = handle.next() + line = next(handle) __read_threshold(record, line) - line = handle.next() + line = next(handle) __read_lengths(record, line) - line = handle.next() + line = next(handle) __read_profilewidth(record, line) - line = handle.next() + line = next(handle) __read_scores(record, line) except StopIteration: raise ValueError("Unexpected end of stream.") @@ -85,9 +85,9 @@ break __read_query_alignment(record, line) try: - line = handle.next() + line = next(handle) __read_positive_alignment(record, line) - line = handle.next() + line = next(handle) __read_hit_alignment(record, line) except StopIteration: raise ValueError("Unexpected end of stream.") diff -Nru python-biopython-1.62/Bio/Crystal/__init__.py python-biopython-1.63/Bio/Crystal/__init__.py --- python-biopython-1.62/Bio/Crystal/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Crystal/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -12,6 +12,10 @@ """ import copy +from functools import reduce + +from Bio._py3k import map +from Bio._py3k import basestring class CrystalError(Exception): @@ -78,7 +82,7 @@ residues = residues.replace('*', ' ') residues = residues.strip() elements = residues.split() - self.data = map(Hetero, elements) + self.data = [Hetero(x) for x in elements] elif isinstance(residues, list): for element in residues: if not isinstance(element, Hetero): @@ -239,18 +243,14 @@ def __repr__(self): output = '' - keys = self.data.keys() - keys.sort() - for key in keys: - output = output + '%s : %s\n' % (key, self.data[ key ]) + for key in sorted(self.data): + output += '%s : %s\n' % (key, self.data[key]) return output def __str__(self): output = '' - keys = self.data.keys() - keys.sort() - for key in keys: - output = output + '%s : %s\n' % (key, self.data[ key ]) + for key in sorted(self.data): + output += '%s : %s\n' % (key, self.data[key]) return output def tostring(self): @@ -266,7 +266,7 @@ if isinstance(item, Chain): self.data[key] = item elif isinstance(item, str): - self.data[ key ] = Chain(item) + self.data[key] = Chain(item) else: raise TypeError diff -Nru python-biopython-1.62/Bio/Data/CodonTable.py python-biopython-1.63/Bio/Data/CodonTable.py --- python-biopython-1.62/Bio/Data/CodonTable.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Data/CodonTable.py 2013-12-05 14:10:43.000000000 +0000 @@ -9,6 +9,8 @@ Last updated for Version 3.9 """ +from __future__ import print_function + from Bio import Alphabet from Bio.Alphabet import IUPAC from Bio.Data import IUPACData @@ -66,8 +68,8 @@ e.g. >>> import Bio.Data.CodonTable - >>> print Bio.Data.CodonTable.standard_dna_table - >>> print Bio.Data.CodonTable.generic_by_id[1] + >>> print(Bio.Data.CodonTable.standard_dna_table) + >>> print(Bio.Data.CodonTable.generic_by_id[1]) """ if self.id: @@ -75,7 +77,7 @@ else: answer = "Table ID unknown" if self.names: - answer += " " + ", ".join(filter(None, self.names)) + answer += " " + ", ".join([x for x in self.names if x]) #Use the main four letters (and the conventional ordering) #even for ambiguous tables @@ -89,19 +91,16 @@ letters = "UCAG" #Build the table... - answer=answer + "\n\n |" + "|".join( - [" %s " % c2 for c2 in letters] - ) + "|" - answer=answer + "\n--+" \ - + "+".join(["---------" for c2 in letters]) + "+--" + answer += "\n\n |" + "|".join(" %s " % c2 for c2 in letters) + "|" + answer += "\n--+" + "+".join("---------" for c2 in letters) + "+--" for c1 in letters: for c3 in letters: line = c1 + " |" for c2 in letters: codon = c1+c2+c3 - line = line + " %s" % codon + line += " %s" % codon if codon in self.stop_codons: - line = line + " Stop|" + line += " Stop|" else: try: amino = self.forward_table[codon] @@ -110,13 +109,12 @@ except TranslationError: amino = "?" if codon in self.start_codons: - line = line + " %s(s)|" % amino + line += " %s(s)|" % amino else: - line = line + " %s |" % amino - line = line + " " + c3 - answer = answer + "\n"+ line - answer=answer + "\n--+" \ - + "+".join(["---------" for c2 in letters]) + "+--" + line += " %s |" % amino + line += " " + c3 + answer += "\n"+ line + answer += "\n--+" + "+".join("---------" for c2 in letters) + "+--" return answer @@ -204,7 +202,7 @@ + "for both proteins and stop codons") # This is a true stop codon - tell the caller about it raise KeyError(codon) - return possible.keys() + return list(possible.keys()) def list_ambiguous_codons(codons, ambiguous_nucleotide_values): @@ -225,14 +223,14 @@ #This will generate things like 'TRR' from ['TAG', 'TGA'], which #we don't want to include: c1_list = sorted(letter for (letter, meanings) - in ambiguous_nucleotide_values.iteritems() - if set([codon[0] for codon in codons]).issuperset(set(meanings))) + in ambiguous_nucleotide_values.items() + if set(codon[0] for codon in codons).issuperset(set(meanings))) c2_list = sorted(letter for (letter, meanings) - in ambiguous_nucleotide_values.iteritems() - if set([codon[1] for codon in codons]).issuperset(set(meanings))) + in ambiguous_nucleotide_values.items() + if set(codon[1] for codon in codons).issuperset(set(meanings))) c3_list = sorted(letter for (letter, meanings) - in ambiguous_nucleotide_values.iteritems() - if set([codon[2] for codon in codons]).issuperset(set(meanings))) + in ambiguous_nucleotide_values.items() + if set(codon[2] for codon in codons).issuperset(set(meanings))) #candidates is a list (not a set) to preserve the iteration order candidates = [] for c1 in c1_list: @@ -290,13 +288,13 @@ self.ambiguous_protein = ambiguous_protein inverted = {} - for name, val in ambiguous_protein.iteritems(): + for name, val in ambiguous_protein.items(): for c in val: x = inverted.get(c, {}) x[name] = 1 inverted[c] = x - for name, val in inverted.iteritems(): - inverted[name] = val.keys() + for name, val in inverted.items(): + inverted[name] = list(val.keys()) self._inverted = inverted self._cache = {} @@ -353,7 +351,7 @@ n = len(possible) possible = [] - for amino, val in ambiguous_possible.iteritems(): + for amino, val in ambiguous_possible.items(): if val == n: possible.append(amino) @@ -384,7 +382,7 @@ """Turns codon table data into objects, and stores them in the dictionaries (PRIVATE).""" #In most cases names are divided by "; ", however there is also #'Bacterial and Plant Plastid' (which used to be just 'Bacterial') - names = [x.strip() for x in name.replace(" and ","; ").split("; ")] + names = [x.strip() for x in name.replace(" and ", "; ").split("; ")] dna = NCBICodonTableDNA(id, names + [alt_name], table, start_codons, stop_codons) @@ -398,7 +396,7 @@ # replace all T's with U's for the RNA tables rna_table = {} generic_table = {} - for codon, val in table.iteritems(): + for codon, val in table.items(): generic_table[codon] = val codon = codon.replace("T", "U") generic_table[codon] = val @@ -422,7 +420,7 @@ generic_start_codons, generic_stop_codons) #The following isn't very elegant, but seems to work nicely. - _merged_values = dict(IUPACData.ambiguous_rna_values.iteritems()) + _merged_values = dict(IUPACData.ambiguous_rna_values.items()) _merged_values["T"] = "U" ambig_generic = AmbiguousCodonTable(generic, Alphabet.NucleotideAlphabet(), @@ -863,9 +861,9 @@ ) #Basic sanity test, -for key, val in generic_by_name.iteritems(): +for key, val in generic_by_name.items(): assert key in ambiguous_generic_by_name[key].names -for key, val in generic_by_id.iteritems(): +for key, val in generic_by_id.items(): assert ambiguous_generic_by_id[key].id == key del key, val @@ -879,7 +877,7 @@ if "UAA" in unambiguous_rna_by_id[n].stop_codons \ and "UGA" in unambiguous_rna_by_id[n].stop_codons: try: - print ambiguous_dna_by_id[n].forward_table["TRA"] + print(ambiguous_dna_by_id[n].forward_table["TRA"]) assert False, "Should be a stop only" except KeyError: pass diff -Nru python-biopython-1.62/Bio/Data/IUPACData.py python-biopython-1.63/Bio/Data/IUPACData.py --- python-biopython-1.62/Bio/Data/IUPACData.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Data/IUPACData.py 2013-12-05 14:10:43.000000000 +0000 @@ -32,15 +32,15 @@ 'S': 'Ser', 'T': 'Thr', 'V': 'Val', 'W': 'Trp', 'Y': 'Tyr', } -protein_letters_1to3_extended = dict(protein_letters_1to3.items() + { +protein_letters_1to3_extended = dict(list(protein_letters_1to3.items()) + list({ 'B': 'Asx', 'X': 'Xaa', 'Z': 'Glx', 'J': 'Xle', 'U': 'Sel', 'O': 'Pyl', -}.items()) +}.items())) -protein_letters_3to1 = dict([(x[1], x[0]) for x in - protein_letters_1to3.items()]) -protein_letters_3to1_extended = dict([(x[1], x[0]) for x in - protein_letters_1to3_extended.items()]) +protein_letters_3to1 = dict((x[1], x[0]) for x in + protein_letters_1to3.items()) +protein_letters_3to1_extended = dict((x[1], x[0]) for x in + protein_letters_1to3_extended.items()) ambiguous_dna_letters = "GATCRYWSMKHBVDN" unambiguous_dna_letters = "GATC" @@ -134,7 +134,7 @@ def _make_ranges(mydict): d = {} - for key, value in mydict.iteritems(): + for key, value in mydict.items(): d[key] = (value, value) return d @@ -159,12 +159,12 @@ def _make_ambiguous_ranges(mydict, weight_table): range_d = {} avg_d = {} - for letter, values in mydict.iteritems(): + for letter, values in mydict.items(): #Following line is a quick hack to skip undefined weights for U and O if len(values) == 1 and values[0] not in weight_table: continue - weights = map(weight_table.get, values) + weights = [weight_table.get(x) for x in values] range_d[letter] = (min(weights), max(weights)) total_w = 0.0 for w in weights: @@ -269,113 +269,113 @@ # For Center of Mass Calculation. # Taken from http://www.chem.qmul.ac.uk/iupac/AtWt/ & PyMol atom_weights = { - 'H' : 1.00794, - 'He' : 4.002602, - 'Li' : 6.941, - 'Be' : 9.012182, - 'B' : 10.811, - 'C' : 12.0107, - 'N' : 14.0067, - 'O' : 15.9994, - 'F' : 18.9984032, - 'Ne' : 20.1797, - 'Na' : 22.989770, - 'Mg' : 24.3050, - 'Al' : 26.981538, - 'Si' : 28.0855, - 'P' : 30.973761, - 'S' : 32.065, - 'Cl' : 35.453, - 'Ar' : 39.948, - 'K' : 39.0983, - 'Ca' : 40.078, - 'Sc' : 44.955910, - 'Ti' : 47.867, - 'V' : 50.9415, - 'Cr' : 51.9961, - 'Mn' : 54.938049, - 'Fe' : 55.845, - 'Co' : 58.933200, - 'Ni' : 58.6934, - 'Cu' : 63.546, - 'Zn' : 65.39, - 'Ga' : 69.723, - 'Ge' : 72.64, - 'As' : 74.92160, - 'Se' : 78.96, - 'Br' : 79.904, - 'Kr' : 83.80, - 'Rb' : 85.4678, - 'Sr' : 87.62, - 'Y' : 88.90585, - 'Zr' : 91.224, - 'Nb' : 92.90638, - 'Mo' : 95.94, - 'Tc' : 98.0, - 'Ru' : 101.07, - 'Rh' : 102.90550, - 'Pd' : 106.42, - 'Ag' : 107.8682, - 'Cd' : 112.411, - 'In' : 114.818, - 'Sn' : 118.710, - 'Sb' : 121.760, - 'Te' : 127.60, - 'I' : 126.90447, - 'Xe' : 131.293, - 'Cs' : 132.90545, - 'Ba' : 137.327, - 'La' : 138.9055, - 'Ce' : 140.116, - 'Pr' : 140.90765, - 'Nd' : 144.24, - 'Pm' : 145.0, - 'Sm' : 150.36, - 'Eu' : 151.964, - 'Gd' : 157.25, - 'Tb' : 158.92534, - 'Dy' : 162.50, - 'Ho' : 164.93032, - 'Er' : 167.259, - 'Tm' : 168.93421, - 'Yb' : 173.04, - 'Lu' : 174.967, - 'Hf' : 178.49, - 'Ta' : 180.9479, - 'W' : 183.84, - 'Re' : 186.207, - 'Os' : 190.23, - 'Ir' : 192.217, - 'Pt' : 195.078, - 'Au' : 196.96655, - 'Hg' : 200.59, - 'Tl' : 204.3833, - 'Pb' : 207.2, - 'Bi' : 208.98038, - 'Po' : 208.98, - 'At' : 209.99, - 'Rn' : 222.02, - 'Fr' : 223.02, - 'Ra' : 226.03, - 'Ac' : 227.03, - 'Th' : 232.0381, - 'Pa' : 231.03588, - 'U' : 238.02891, - 'Np' : 237.05, - 'Pu' : 244.06, - 'Am' : 243.06, - 'Cm' : 247.07, - 'Bk' : 247.07, - 'Cf' : 251.08, - 'Es' : 252.08, - 'Fm' : 257.10, - 'Md' : 258.10, - 'No' : 259.10, - 'Lr' : 262.11, - 'Rf' : 261.11, - 'Db' : 262.11, - 'Sg' : 266.12, - 'Bh' : 264.12, - 'Hs' : 269.13, - 'Mt' : 268.14, + 'H': 1.00794, + 'He': 4.002602, + 'Li': 6.941, + 'Be': 9.012182, + 'B': 10.811, + 'C': 12.0107, + 'N': 14.0067, + 'O': 15.9994, + 'F': 18.9984032, + 'Ne': 20.1797, + 'Na': 22.989770, + 'Mg': 24.3050, + 'Al': 26.981538, + 'Si': 28.0855, + 'P': 30.973761, + 'S': 32.065, + 'Cl': 35.453, + 'Ar': 39.948, + 'K': 39.0983, + 'Ca': 40.078, + 'Sc': 44.955910, + 'Ti': 47.867, + 'V': 50.9415, + 'Cr': 51.9961, + 'Mn': 54.938049, + 'Fe': 55.845, + 'Co': 58.933200, + 'Ni': 58.6934, + 'Cu': 63.546, + 'Zn': 65.39, + 'Ga': 69.723, + 'Ge': 72.64, + 'As': 74.92160, + 'Se': 78.96, + 'Br': 79.904, + 'Kr': 83.80, + 'Rb': 85.4678, + 'Sr': 87.62, + 'Y': 88.90585, + 'Zr': 91.224, + 'Nb': 92.90638, + 'Mo': 95.94, + 'Tc': 98.0, + 'Ru': 101.07, + 'Rh': 102.90550, + 'Pd': 106.42, + 'Ag': 107.8682, + 'Cd': 112.411, + 'In': 114.818, + 'Sn': 118.710, + 'Sb': 121.760, + 'Te': 127.60, + 'I': 126.90447, + 'Xe': 131.293, + 'Cs': 132.90545, + 'Ba': 137.327, + 'La': 138.9055, + 'Ce': 140.116, + 'Pr': 140.90765, + 'Nd': 144.24, + 'Pm': 145.0, + 'Sm': 150.36, + 'Eu': 151.964, + 'Gd': 157.25, + 'Tb': 158.92534, + 'Dy': 162.50, + 'Ho': 164.93032, + 'Er': 167.259, + 'Tm': 168.93421, + 'Yb': 173.04, + 'Lu': 174.967, + 'Hf': 178.49, + 'Ta': 180.9479, + 'W': 183.84, + 'Re': 186.207, + 'Os': 190.23, + 'Ir': 192.217, + 'Pt': 195.078, + 'Au': 196.96655, + 'Hg': 200.59, + 'Tl': 204.3833, + 'Pb': 207.2, + 'Bi': 208.98038, + 'Po': 208.98, + 'At': 209.99, + 'Rn': 222.02, + 'Fr': 223.02, + 'Ra': 226.03, + 'Ac': 227.03, + 'Th': 232.0381, + 'Pa': 231.03588, + 'U': 238.02891, + 'Np': 237.05, + 'Pu': 244.06, + 'Am': 243.06, + 'Cm': 247.07, + 'Bk': 247.07, + 'Cf': 251.08, + 'Es': 252.08, + 'Fm': 257.10, + 'Md': 258.10, + 'No': 259.10, + 'Lr': 262.11, + 'Rf': 261.11, + 'Db': 262.11, + 'Sg': 266.12, + 'Bh': 264.12, + 'Hs': 269.13, + 'Mt': 268.14, } diff -Nru python-biopython-1.62/Bio/DocSQL.py python-biopython-1.63/Bio/DocSQL.py --- python-biopython-1.62/Bio/DocSQL.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/DocSQL.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,8 +5,7 @@ # license. Please see the LICENSE file that should have been included # as part of this package. -""" -Bio.DocSQL: easy access to DB API databases. +"""Bio.DocSQL: easy access to DB API databases. >>> import os >>> import MySQLdb @@ -24,8 +23,7 @@ CreatePeople(message=Success) """ -__version__ = "$Revision: 1.13 $" -# $Source: /home/bartek/cvs2bzr/biopython_fastimport/cvs_repo/biopython/Bio/DocSQL.py,v $ +from __future__ import print_function import sys @@ -121,7 +119,7 @@ def dump(self): for item in self: - print item + print(item) class QueryGeneric(Query): @@ -137,13 +135,23 @@ self.cursor = connection.cursor() self.row_class = query.row_class if query.diagnostics: - print >>sys.stderr, query.statement - print >>sys.stderr, query.params + sys.stderr.write("Query statement: %s\n" % query.statement) + sys.stderr.write("Query params: %s\n" % query.params) self.cursor.execute(query.statement, query.params) - def next(self): + def __next__(self): return self.row_class(self.cursor) + if sys.version_info[0] < 3: + def next(self): + """Deprecated Python 2 style alias for Python 3 style __next__ method.""" + import warnings + from Bio import BiopythonDeprecationWarning + warnings.warn("Please use next(my_iterator) instead of my_iterator.next(), " + "the .next() method is deprecated and will be removed in a " + "future release of Biopython.", BiopythonDeprecationWarning) + return self.__next__() + class QuerySingle(Query, QueryRow): ignore_warnings = 0 @@ -166,7 +174,7 @@ class QueryAll(list, Query): def __init__(self, *args, **keywds): Query.__init__(self, *args, **keywds) - list.__init__(self, map(self.process_row, self.cursor().fetchall())) + list.__init__(self, [self.process_row(r) for r in self.cursor().fetchall()]) def process_row(self, row): return row @@ -195,7 +203,7 @@ def __init__(self, *args, **keywds): try: Create.__init__(self, *args, **keywds) - except MySQLdb.IntegrityError, error_data: + except MySQLdb.IntegrityError as error_data: self.error_message += self.MSG_INTEGRITY_ERROR % error_data[1] try: self.total_count diff -Nru python-biopython-1.62/Bio/Emboss/Applications.py python-biopython-1.63/Bio/Emboss/Applications.py --- python-biopython-1.62/Bio/Emboss/Applications.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Emboss/Applications.py 2013-12-05 14:10:43.000000000 +0000 @@ -12,6 +12,8 @@ programs. """ +from __future__ import print_function + from Bio.Application import _Option, _Switch, AbstractCommandline @@ -38,38 +40,38 @@ def __init__(self, cmd=None, **kwargs): assert cmd is not None extra_parameters = [ - _Switch(["-auto","auto"], + _Switch(["-auto", "auto"], """Turn off prompts. Automatic mode disables prompting, so we recommend you set this argument all the time when calling an EMBOSS tool from Biopython. """), - _Switch(["-stdout","stdout"], + _Switch(["-stdout", "stdout"], "Write standard output."), - _Switch(["-filter","filter"], + _Switch(["-filter", "filter"], "Read standard input, write standard output."), - _Switch(["-options","options"], + _Switch(["-options", "options"], """Prompt for standard and additional values. If you are calling an EMBOSS tool from within Biopython, we DO NOT recommend using this option. """), - _Switch(["-debug","debug"], + _Switch(["-debug", "debug"], "Write debug output to program.dbg."), - _Switch(["-verbose","verbose"], + _Switch(["-verbose", "verbose"], "Report some/full command line options"), - _Switch(["-help","help"], + _Switch(["-help", "help"], """Report command line options. More information on associated and general qualifiers can be found with -help -verbose """), - _Switch(["-warning","warning"], + _Switch(["-warning", "warning"], "Report warnings."), - _Switch(["-error","error"], + _Switch(["-error", "error"], "Report errors."), - _Switch(["-die","die"], + _Switch(["-die", "die"], "Report dying program messages."), ] try: @@ -94,7 +96,7 @@ def __init__(self, cmd=None, **kwargs): assert cmd is not None extra_parameters = [ - _Option(["-outfile","outfile"], + _Option(["-outfile", "outfile"], "Output filename", filename=True), ] @@ -135,7 +137,7 @@ Traceback (most recent call last): ... ValueError: Option name bogusparameter was not found. - >>> print cline + >>> print(cline) eprimer3 -auto -outfile=myresults.out -sequence=mysequence.fas -hybridprobe=True -psizeopt=200 -osizeopt=20 -explainflag=True The equivalent for anyone still using an older version of EMBOSS would be: @@ -145,62 +147,62 @@ >>> cline.oligosize=20 # Old EMBOSS, instead of osizeopt >>> cline.productosize=200 # Old EMBOSS, instead of psizeopt >>> cline.outfile = "myresults.out" - >>> print cline + >>> print(cline) eprimer3 -auto -outfile=myresults.out -sequence=mysequence.fas -hybridprobe=True -productosize=200 -oligosize=20 -explainflag=True """ def __init__(self, cmd="eprimer3", **kwargs): self.parameters = [ - _Option(["-sequence","sequence"], + _Option(["-sequence", "sequence"], "Sequence to choose primers from.", is_required=True), - _Option(["-task","task"], + _Option(["-task", "task"], "Tell eprimer3 what task to perform."), - _Option(["-hybridprobe","hybridprobe"], + _Option(["-hybridprobe", "hybridprobe"], "Find an internal oligo to use as a hyb probe."), - _Option(["-numreturn","numreturn"], + _Option(["-numreturn", "numreturn"], "Maximum number of primer pairs to return."), - _Option(["-includedregion","includedregion"], + _Option(["-includedregion", "includedregion"], "Subregion of the sequence in which to pick primers."), - _Option(["-target","target"], + _Option(["-target", "target"], "Sequence to target for flanking primers."), - _Option(["-excludedregion","excludedregion"], + _Option(["-excludedregion", "excludedregion"], "Regions to exclude from primer picking."), - _Option(["-forwardinput","forwardinput"], + _Option(["-forwardinput", "forwardinput"], "Sequence of a forward primer to check."), - _Option(["-reverseinput","reverseinput"], + _Option(["-reverseinput", "reverseinput"], "Sequence of a reverse primer to check."), - _Option(["-gcclamp","gcclamp"], + _Option(["-gcclamp", "gcclamp"], "The required number of Gs and Cs at the 3' of each primer."), - _Option(["-osize","osize"], + _Option(["-osize", "osize"], "Optimum length of a primer oligo."), - _Option(["-minsize","minsize"], + _Option(["-minsize", "minsize"], "Minimum length of a primer oligo."), - _Option(["-maxsize","maxsize"], + _Option(["-maxsize", "maxsize"], "Maximum length of a primer oligo."), - _Option(["-otm","otm"], + _Option(["-otm", "otm"], "Optimum melting temperature for a primer oligo."), - _Option(["-mintm","mintm"], + _Option(["-mintm", "mintm"], "Minimum melting temperature for a primer oligo."), - _Option(["-maxtm","maxtm"], + _Option(["-maxtm", "maxtm"], "Maximum melting temperature for a primer oligo."), - _Option(["-maxdifftm","maxdifftm"], + _Option(["-maxdifftm", "maxdifftm"], "Maximum difference in melting temperatures between " "forward and reverse primers."), - _Option(["-ogcpercent","ogcpercent"], + _Option(["-ogcpercent", "ogcpercent"], "Optimum GC% for a primer."), - _Option(["-mingc","mingc"], + _Option(["-mingc", "mingc"], "Minimum GC% for a primer."), - _Option(["-maxgc","maxgc"], + _Option(["-maxgc", "maxgc"], "Maximum GC% for a primer."), - _Option(["-saltconc","saltconc"], + _Option(["-saltconc", "saltconc"], "Millimolar salt concentration in the PCR."), - _Option(["-dnaconc","dnaconc"], + _Option(["-dnaconc", "dnaconc"], "Nanomolar concentration of annealing oligos in the PCR."), - _Option(["-maxpolyx","maxpolyx"], + _Option(["-maxpolyx", "maxpolyx"], "Maximum allowable mononucleotide repeat length in a primer."), #Primer length: - _Option(["-productosize","productosize"], + _Option(["-productosize", "productosize"], """Optimum size for the PCR product (OBSOLETE). Option replaced in EMBOSS 6.1.0 by -psizeopt @@ -210,7 +212,7 @@ Option added in EMBOSS 6.1.0, replacing -productosize """), - _Option(["-productsizerange","productsizerange"], + _Option(["-productsizerange", "productsizerange"], """Acceptable range of length for the PCR product (OBSOLETE). Option replaced in EMBOSS 6.1.0 by -prange @@ -221,7 +223,7 @@ Option added in EMBOSS 6.1.0, replacing -productsizerange """), #Primer temperature: - _Option(["-productotm","productotm"], + _Option(["-productotm", "productotm"], """Optimum melting temperature for the PCR product (OBSOLETE). Option replaced in EMBOSS 6.1.0 by -ptmopt @@ -231,7 +233,7 @@ Option added in EMBOSS 6.1.0, replacing -productotm """), - _Option(["-productmintm","productmintm"], + _Option(["-productmintm", "productmintm"], """Minimum allowed melting temperature for the amplicon (OBSOLETE) Option replaced in EMBOSS 6.1.0 by -ptmmin @@ -241,7 +243,7 @@ Option added in EMBOSS 6.1.0, replacing -productmintm """), - _Option(["-productmaxtm","productmaxtm"], + _Option(["-productmaxtm", "productmaxtm"], """Maximum allowed melting temperature for the amplicon (OBSOLETE). Option replaced in EMBOSS 6.1.0 by -ptmmax @@ -262,10 +264,10 @@ Option replaced in EMBOSS 6.1.0 by -oexcluderegion. """), - _Option(["-oligoinput","oligoinput"], + _Option(["-oligoinput", "oligoinput"], "Sequence of the internal oligo."), #Oligo length: - _Option(["-oligosize","oligosize"], + _Option(["-oligosize", "oligosize"], """Optimum length of internal oligo (OBSOLETE). Option replaced in EMBOSS 6.1.0 by -osizeopt. @@ -275,7 +277,7 @@ Option added in EMBOSS 6.1.0, replaces -oligosize """), - _Option(["-oligominsize","oligominsize"], + _Option(["-oligominsize", "oligominsize"], """Minimum length of internal oligo (OBSOLETE)."), Option replaced in EMBOSS 6.1.0 by -ominsize. @@ -285,7 +287,7 @@ Option added in EMBOSS 6.1.0, replaces -oligominsize """), - _Option(["-oligomaxsize","oligomaxsize"], + _Option(["-oligomaxsize", "oligomaxsize"], """Maximum length of internal oligo (OBSOLETE). Option replaced in EMBOSS 6.1.0 by -omaxsize. @@ -296,7 +298,7 @@ Option added in EMBOSS 6.1.0, replaces -oligomaxsize """), #Oligo GC temperature: - _Option(["-oligotm","oligotm"], + _Option(["-oligotm", "oligotm"], """Optimum melting temperature of internal oligo (OBSOLETE). Option replaced in EMBOSS 6.1.0 by -otmopt. @@ -306,7 +308,7 @@ Option added in EMBOSS 6.1.0. """), - _Option(["-oligomintm","oligomintm"], + _Option(["-oligomintm", "oligomintm"], """Minimum melting temperature of internal oligo (OBSOLETE). Option replaced in EMBOSS 6.1.0 by -otmmin. @@ -316,7 +318,7 @@ Option added in EMBOSS 6.1.0, replacing -oligomintm """), - _Option(["-oligomaxtm","oligomaxtm"], + _Option(["-oligomaxtm", "oligomaxtm"], """Maximum melting temperature of internal oligo (OBSOLETE). Option replaced in EMBOSS 6.1.0 by -otmmax. @@ -327,7 +329,7 @@ Option added in EMBOSS 6.1.0, replacing -oligomaxtm """), #Oligo GC percent: - _Option(["-oligoogcpercent","oligoogcpercent"], + _Option(["-oligoogcpercent", "oligoogcpercent"], """Optimum GC% for internal oligo (OBSOLETE). Option replaced in EMBOSS 6.1.0 by -ogcopt. @@ -337,7 +339,7 @@ Option added in EMBOSS 6.1.0, replacing -oligoogcpercent """), - _Option(["-oligomingc","oligomingc"], + _Option(["-oligomingc", "oligomingc"], """Minimum GC% for internal oligo (OBSOLETE). Option replaced in EMBOSS 6.1.0 by -ogcmin. @@ -347,7 +349,7 @@ Option added in EMBOSS 6.1.0, replacing -oligomingc """), - _Option(["-oligomaxgc","oligomaxgc"], + _Option(["-oligomaxgc", "oligomaxgc"], """Maximum GC% for internal oligo. Option replaced in EMBOSS 6.1.0 by -ogcmax @@ -358,7 +360,7 @@ Option added in EMBOSS 6.1.0, replacing -oligomaxgc """), #Oligo salt concentration: - _Option(["-oligosaltconc","oligosaltconc"], + _Option(["-oligosaltconc", "oligosaltconc"], """Millimolar concentration of salt in the hybridisation."), Option replaced in EMBOSS 6.1.0 by -osaltconc @@ -368,7 +370,7 @@ Option added in EMBOSS 6.1.0, replacing -oligosaltconc """), - _Option(["-oligodnaconc","oligodnaconc"], + _Option(["-oligodnaconc", "oligodnaconc"], """Nanomolar concentration of internal oligo in the hybridisation. Option replaced in EMBOSS 6.1.0 by -odnaconc @@ -379,7 +381,7 @@ Option added in EMBOSS 6.1.0, replacing -oligodnaconc """), #Oligo self complementarity - _Option(["-oligoselfany","oligoselfany"], + _Option(["-oligoselfany", "oligoselfany"], """Maximum allowable alignment score for self-complementarity (OBSOLETE). Option replaced in EMBOSS 6.1.0 by -oanyself @@ -389,7 +391,7 @@ Option added in EMBOSS 6.1.0, replacing -oligoselfany """), - _Option(["-oligoselfend","oligoselfend"], + _Option(["-oligoselfend", "oligoselfend"], """Maximum allowable 3`-anchored global alignment score " for self-complementarity (OBSOLETE). @@ -400,7 +402,7 @@ Option added in EMBOSS 6.1.0, replacing -oligoselfend """), - _Option(["-oligomaxpolyx","oligomaxpolyx"], + _Option(["-oligomaxpolyx", "oligomaxpolyx"], """Maximum length of mononucleotide repeat in internal oligo (OBSOLETE). Option replaced in EMBOSS 6.1.0 by -opolyxmax @@ -410,12 +412,12 @@ Option added in EMBOSS 6.1.0, replacing -oligomaxpolyx """), - _Option(["-mispriminglibraryfile","mispriminglibraryfile"], + _Option(["-mispriminglibraryfile", "mispriminglibraryfile"], "File containing library of sequences to avoid amplifying"), - _Option(["-maxmispriming","maxmispriming"], + _Option(["-maxmispriming", "maxmispriming"], "Maximum allowed similarity of primers to sequences in " "library specified by -mispriminglibrary"), - _Option(["-oligomaxmishyb","oligomaxmishyb"], + _Option(["-oligomaxmishyb", "oligomaxmishyb"], """Maximum alignment score for hybridisation of internal oligo to library specified by -oligomishyblibraryfile (OBSOLETE). @@ -438,7 +440,7 @@ Option added in EMBOSS 6.1.0, replacing -oligomishyblibraryfile """), - _Option(["-explainflag","explainflag"], + _Option(["-explainflag", "explainflag"], "Produce output tags with eprimer3 statistics"), ] _EmbossCommandLine.__init__(self, cmd, **kwargs) @@ -449,25 +451,25 @@ """ def __init__(self, cmd="primersearch", **kwargs): self.parameters = [ - _Option(["-seqall","-sequences","sequences","seqall"], + _Option(["-seqall", "-sequences", "sequences", "seqall"], "Sequence to look for the primer pairs in.", is_required=True), #When this wrapper was written primersearch used -sequences #as the argument name. Since at least EMBOSS 5.0 (and #perhaps earlier) this has been -seqall instead. - _Option(["-infile","-primers","primers","infile"], + _Option(["-infile", "-primers", "primers", "infile"], "File containing the primer pairs to search for.", filename=True, is_required=True), #When this wrapper was written primersearch used -primers #as the argument name. Since at least EMBOSS 5.0 (and #perhaps earlier) this has been -infile instead. - _Option(["-mismatchpercent","mismatchpercent"], + _Option(["-mismatchpercent", "mismatchpercent"], "Allowed percentage mismatch (any integer value, default 0).", is_required=True), - _Option(["-snucleotide","snucleotide"], + _Option(["-snucleotide", "snucleotide"], "Sequences are nucleotide (boolean)"), - _Option(["-sprotein","sprotein"], + _Option(["-sprotein", "sprotein"], "Sequences are protein (boolean)"), ] _EmbossCommandLine.__init__(self, cmd, **kwargs) @@ -494,7 +496,7 @@ "number of rate catergories (1-9)"), _Option(["-rate", "rate"], "rate for each category"), - _Option(["-categories","categories"], + _Option(["-categories", "categories"], "File of substitution rate categories"), _Option(["-weights", "weights"], "weights file"), @@ -554,7 +556,7 @@ "is martrix [S]quare pr [u]pper or [l]ower"), _Option(["-treetype", "treetype"], "nj or UPGMA tree (n/u)"), - _Option(["-outgrno","outgrno" ], + _Option(["-outgrno", "outgrno" ], "taxon to use as OG"), _Option(["-jumble", "jumble"], "randommise input order (Y/n)"), @@ -714,7 +716,7 @@ "number of rate catergories (1-9)"), _Option(["-rate", "rate"], "rate for each category"), - _Option(["-catergories","catergories"], + _Option(["-catergories", "catergories"], "file of rates"), _Option(["-weights", "weights"], "weights file"), @@ -771,34 +773,34 @@ """ def __init__(self, cmd="water", **kwargs): self.parameters = [ - _Option(["-asequence","asequence"], + _Option(["-asequence", "asequence"], "First sequence to align", filename=True, is_required=True), - _Option(["-bsequence","bsequence"], + _Option(["-bsequence", "bsequence"], "Second sequence to align", filename=True, is_required=True), - _Option(["-gapopen","gapopen"], + _Option(["-gapopen", "gapopen"], "Gap open penalty", is_required=True), - _Option(["-gapextend","gapextend"], + _Option(["-gapextend", "gapextend"], "Gap extension penalty", is_required=True), - _Option(["-datafile","datafile"], + _Option(["-datafile", "datafile"], "Matrix file", filename=True), _Switch(["-nobrief", "nobrief"], "Display extended identity and similarity"), _Switch(["-brief", "brief"], "Display brief identity and similarity"), - _Option(["-similarity","similarity"], + _Option(["-similarity", "similarity"], "Display percent identity and similarity"), - _Option(["-snucleotide","snucleotide"], + _Option(["-snucleotide", "snucleotide"], "Sequences are nucleotide (boolean)"), - _Option(["-sprotein","sprotein"], + _Option(["-sprotein", "sprotein"], "Sequences are protein (boolean)"), - _Option(["-aformat","aformat"], + _Option(["-aformat", "aformat"], "Display output in a different specified output format")] _EmbossCommandLine.__init__(self, cmd, **kwargs) @@ -808,21 +810,21 @@ """ def __init__(self, cmd="needle", **kwargs): self.parameters = [ - _Option(["-asequence","asequence"], + _Option(["-asequence", "asequence"], "First sequence to align", filename=True, is_required=True), - _Option(["-bsequence","bsequence"], + _Option(["-bsequence", "bsequence"], "Second sequence to align", filename=True, is_required=True), - _Option(["-gapopen","gapopen"], + _Option(["-gapopen", "gapopen"], "Gap open penalty", is_required=True), - _Option(["-gapextend","gapextend"], + _Option(["-gapextend", "gapextend"], "Gap extension penalty", is_required=True), - _Option(["-datafile","datafile"], + _Option(["-datafile", "datafile"], "Matrix file", filename=True), _Option(["-endweight", "endweight"], @@ -836,13 +838,13 @@ "Display extended identity and similarity"), _Switch(["-brief", "brief"], "Display brief identity and similarity"), - _Option(["-similarity","similarity"], + _Option(["-similarity", "similarity"], "Display percent identity and similarity"), - _Option(["-snucleotide","snucleotide"], + _Option(["-snucleotide", "snucleotide"], "Sequences are nucleotide (boolean)"), - _Option(["-sprotein","sprotein"], + _Option(["-sprotein", "sprotein"], "Sequences are protein (boolean)"), - _Option(["-aformat","aformat"], + _Option(["-aformat", "aformat"], "Display output in a different specified output format")] _EmbossCommandLine.__init__(self, cmd, **kwargs) @@ -852,24 +854,24 @@ """ def __init__(self, cmd="needleall", **kwargs): self.parameters = [ - _Option(["-asequence","asequence"], + _Option(["-asequence", "asequence"], "First sequence to align", filename=True, is_required=True), - _Option(["-bsequence","bsequence"], + _Option(["-bsequence", "bsequence"], "Second sequence to align", filename=True, is_required=True), - _Option(["-gapopen","gapopen"], + _Option(["-gapopen", "gapopen"], "Gap open penalty", is_required=True), - _Option(["-gapextend","gapextend"], + _Option(["-gapextend", "gapextend"], "Gap extension penalty", is_required=True), - _Option(["-datafile","datafile"], + _Option(["-datafile", "datafile"], "Matrix file", filename=True), - _Option(["-minscore","minscore"], + _Option(["-minscore", "minscore"], "Exclude alignments with scores below this threshold score."), _Option(["-errorfile", "errorfile"], "Error file to be written to."), @@ -884,13 +886,13 @@ "Display extended identity and similarity"), _Switch(["-brief", "brief"], "Display brief identity and similarity"), - _Option(["-similarity","similarity"], + _Option(["-similarity", "similarity"], "Display percent identity and similarity"), - _Option(["-snucleotide","snucleotide"], + _Option(["-snucleotide", "snucleotide"], "Sequences are nucleotide (boolean)"), - _Option(["-sprotein","sprotein"], + _Option(["-sprotein", "sprotein"], "Sequences are protein (boolean)"), - _Option(["-aformat","aformat"], + _Option(["-aformat", "aformat"], "Display output in a different specified output format")] _EmbossCommandLine.__init__(self, cmd, **kwargs) @@ -900,30 +902,30 @@ """ def __init__(self, cmd="stretcher", **kwargs): self.parameters = [ - _Option(["-asequence","asequence"], + _Option(["-asequence", "asequence"], "First sequence to align", filename=True, is_required=True), - _Option(["-bsequence","bsequence"], + _Option(["-bsequence", "bsequence"], "Second sequence to align", filename=True, is_required=True), - _Option(["-gapopen","gapopen"], + _Option(["-gapopen", "gapopen"], "Gap open penalty", is_required=True, checker_function=lambda value: isinstance(value, int)), - _Option(["-gapextend","gapextend"], + _Option(["-gapextend", "gapextend"], "Gap extension penalty", is_required=True, checker_function=lambda value: isinstance(value, int)), - _Option(["-datafile","datafile"], + _Option(["-datafile", "datafile"], "Matrix file", filename=True), - _Option(["-snucleotide","snucleotide"], + _Option(["-snucleotide", "snucleotide"], "Sequences are nucleotide (boolean)"), - _Option(["-sprotein","sprotein"], + _Option(["-sprotein", "sprotein"], "Sequences are protein (boolean)"), - _Option(["-aformat","aformat"], + _Option(["-aformat", "aformat"], "Display output in a different specified output format")] _EmbossCommandLine.__init__(self, cmd, **kwargs) @@ -933,18 +935,18 @@ """ def __init__(self, cmd="fuzznuc", **kwargs): self.parameters = [ - _Option(["-sequence","sequence"], + _Option(["-sequence", "sequence"], "Sequence database USA", is_required=True), - _Option(["-pattern","pattern"], + _Option(["-pattern", "pattern"], "Search pattern, using standard IUPAC one-letter codes", is_required=True), - _Option(["-mismatch","mismatch"], + _Option(["-mismatch", "mismatch"], "Number of mismatches", is_required=True), - _Option(["-complement","complement"], + _Option(["-complement", "complement"], "Search complementary strand"), - _Option(["-rformat","rformat"], + _Option(["-rformat", "rformat"], "Specify the report format to output in.")] _EmbossCommandLine.__init__(self, cmd, **kwargs) @@ -954,44 +956,44 @@ """ def __init__(self, cmd="est2genome", **kwargs): self.parameters = [ - _Option(["-est","est"], + _Option(["-est", "est"], "EST sequence(s)", is_required=True), - _Option(["-genome","genome"], + _Option(["-genome", "genome"], "Genomic sequence", is_required=True), - _Option(["-match","match"], + _Option(["-match", "match"], "Score for matching two bases"), - _Option(["-mismatch","mismatch"], + _Option(["-mismatch", "mismatch"], "Cost for mismatching two bases"), - _Option(["-gappenalty","gappenalty"], + _Option(["-gappenalty", "gappenalty"], "Cost for deleting a single base in either sequence, " "excluding introns"), - _Option(["-intronpenalty","intronpenalty"], + _Option(["-intronpenalty", "intronpenalty"], "Cost for an intron, independent of length."), - _Option(["-splicepenalty","splicepenalty"], + _Option(["-splicepenalty", "splicepenalty"], "Cost for an intron, independent of length " "and starting/ending on donor-acceptor sites"), - _Option(["-minscore","minscore"], + _Option(["-minscore", "minscore"], "Exclude alignments with scores below this threshold score."), - _Option(["-reverse","reverse"], + _Option(["-reverse", "reverse"], "Reverse the orientation of the EST sequence"), - _Option(["-splice","splice"], + _Option(["-splice", "splice"], "Use donor and acceptor splice sites."), - _Option(["-mode","mode"], + _Option(["-mode", "mode"], "This determines the comparion mode. 'both', 'forward' " "'reverse'"), - _Option(["-best","best"], + _Option(["-best", "best"], "You can print out all comparisons instead of just the best"), - _Option(["-space","space"], + _Option(["-space", "space"], "for linear-space recursion."), - _Option(["-shuffle","shuffle"], + _Option(["-shuffle", "shuffle"], "Shuffle"), - _Option(["-seed","seed"], + _Option(["-seed", "seed"], "Random number seed"), - _Option(["-align","align"], + _Option(["-align", "align"], "Show the alignment."), - _Option(["-width","width"], + _Option(["-width", "width"], "Alignment width") ] _EmbossCommandLine.__init__(self, cmd, **kwargs) @@ -1002,23 +1004,23 @@ """ def __init__(self, cmd="etandem", **kwargs): self.parameters = [ - _Option(["-sequence","sequence"], + _Option(["-sequence", "sequence"], "Sequence", filename=True, is_required=True), - _Option(["-minrepeat","minrepeat"], + _Option(["-minrepeat", "minrepeat"], "Minimum repeat size", is_required=True), - _Option(["-maxrepeat","maxrepeat"], + _Option(["-maxrepeat", "maxrepeat"], "Maximum repeat size", is_required=True), - _Option(["-threshold","threshold"], + _Option(["-threshold", "threshold"], "Threshold score"), - _Option(["-mismatch","mismatch"], + _Option(["-mismatch", "mismatch"], "Allow N as a mismatch"), - _Option(["-uniform","uniform"], + _Option(["-uniform", "uniform"], "Allow uniform consensus"), - _Option(["-rformat","rformat"], + _Option(["-rformat", "rformat"], "Output report format")] _EmbossCommandLine.__init__(self, cmd, **kwargs) @@ -1028,24 +1030,24 @@ """ def __init__(self, cmd="einverted", **kwargs): self.parameters = [ - _Option(["-sequence","sequence"], + _Option(["-sequence", "sequence"], "Sequence", filename=True, is_required=True), - _Option(["-gap","gap"], + _Option(["-gap", "gap"], "Gap penalty", filename=True, is_required=True), - _Option(["-threshold","threshold"], + _Option(["-threshold", "threshold"], "Minimum score threshold", is_required=True), - _Option(["-match","match"], + _Option(["-match", "match"], "Match score", is_required=True), - _Option(["-mismatch","mismatch"], + _Option(["-mismatch", "mismatch"], "Mismatch score", is_required=True), - _Option(["-maxrepeat","maxrepeat"], + _Option(["-maxrepeat", "maxrepeat"], "Maximum separation between the start and end of repeat"), ] _EmbossCommandLine.__init__(self, cmd, **kwargs) @@ -1056,23 +1058,23 @@ """ def __init__(self, cmd="palindrome", **kwargs): self.parameters = [ - _Option(["-sequence","sequence"], + _Option(["-sequence", "sequence"], "Sequence", filename=True, is_required=True), - _Option(["-minpallen","minpallen"], + _Option(["-minpallen", "minpallen"], "Minimum palindrome length", is_required=True), - _Option(["-maxpallen","maxpallen"], + _Option(["-maxpallen", "maxpallen"], "Maximum palindrome length", is_required=True), - _Option(["-gaplimit","gaplimit"], + _Option(["-gaplimit", "gaplimit"], "Maximum gap between repeats", is_required=True), - _Option(["-nummismatches","nummismatches"], + _Option(["-nummismatches", "nummismatches"], "Number of mismatches allowed", is_required=True), - _Option(["-overlap","overlap"], + _Option(["-overlap", "overlap"], "Report overlapping matches", is_required=True), ] @@ -1084,19 +1086,19 @@ """ def __init__(self, cmd="tranalign", **kwargs): self.parameters = [ - _Option(["-asequence","asequence"], + _Option(["-asequence", "asequence"], "Nucleotide sequences to be aligned.", filename=True, is_required=True), - _Option(["-bsequence","bsequence"], + _Option(["-bsequence", "bsequence"], "Protein sequence alignment", filename=True, is_required=True), - _Option(["-outseq","outseq"], + _Option(["-outseq", "outseq"], "Output sequence file.", filename=True, is_required=True), - _Option(["-table","table"], + _Option(["-table", "table"], "Code to use")] _EmbossCommandLine.__init__(self, cmd, **kwargs) @@ -1106,26 +1108,26 @@ """ def __init__(self, cmd="diffseq", **kwargs): self.parameters = [ - _Option(["-asequence","asequence"], + _Option(["-asequence", "asequence"], "First sequence to compare", filename=True, is_required=True), - _Option(["-bsequence","bsequence"], + _Option(["-bsequence", "bsequence"], "Second sequence to compare", filename=True, is_required=True), - _Option(["-wordsize","wordsize"], + _Option(["-wordsize", "wordsize"], "Word size to use for comparisons (10 default)", is_required=True), - _Option(["-aoutfeat","aoutfeat"], + _Option(["-aoutfeat", "aoutfeat"], "File for output of first sequence's features", filename=True, is_required=True), - _Option(["-boutfeat","boutfeat"], + _Option(["-boutfeat", "boutfeat"], "File for output of second sequence's features", filename=True, is_required=True), - _Option(["-rformat","rformat"], + _Option(["-rformat", "rformat"], "Output report file format") ] _EmbossCommandLine.__init__(self, cmd, **kwargs) @@ -1139,7 +1141,7 @@ >>> from Bio.Emboss.Applications import IepCommandline >>> iep_cline = IepCommandline(sequence="proteins.faa", ... outfile="proteins.txt") - >>> print iep_cline + >>> print(iep_cline) iep -outfile=proteins.txt -sequence=proteins.faa You would typically run the command line with iep_cline() or via the @@ -1147,32 +1149,32 @@ """ def __init__(self, cmd="iep", **kwargs): self.parameters = [ - _Option(["-sequence","sequence"], + _Option(["-sequence", "sequence"], "Protein sequence(s) filename", filename=True, is_required=True), - _Option(["-amino","amino"], + _Option(["-amino", "amino"], """Number of N-termini Integer 0 (default) or more. """), - _Option(["-carboxyl","carboxyl"], + _Option(["-carboxyl", "carboxyl"], """Number of C-termini Integer 0 (default) or more. """), - _Option(["-lysinemodified","lysinemodified"], + _Option(["-lysinemodified", "lysinemodified"], """Number of modified lysines Integer 0 (default) or more. """), - _Option(["-disulphides","disulphides"], + _Option(["-disulphides", "disulphides"], """Number of disulphide bridges Integer 0 (default) or more. """), #Should we implement the -termini switch as well? - _Option(["-notermini","notermini"], + _Option(["-notermini", "notermini"], "Exclude (True) or include (False) charge at N and C terminus."), ] _EmbossCommandLine.__init__(self, cmd, **kwargs) @@ -1192,15 +1194,15 @@ """ def __init__(self, cmd="seqret", **kwargs): self.parameters = [ - _Option(["-sequence","sequence"], + _Option(["-sequence", "sequence"], "Input sequence(s) filename", filename=True), - _Option(["-outseq","outseq"], + _Option(["-outseq", "outseq"], "Output sequence file.", filename=True), - _Option(["-sformat","sformat"], + _Option(["-sformat", "sformat"], "Input sequence(s) format (e.g. fasta, genbank)"), - _Option(["-osformat","osformat"], + _Option(["-osformat", "osformat"], "Output sequence(s) format (e.g. fasta, genbank)"), ] _EmbossMinimalCommandLine.__init__(self, cmd, **kwargs) @@ -1226,7 +1228,7 @@ >>> cline.auto = True >>> cline.wordsize = 18 >>> cline.aformat = "pair" - >>> print cline + >>> print(cline) seqmatchall -auto -outfile=opuntia.txt -sequence=opuntia.fasta -wordsize=18 -aformat=pair """ @@ -1238,7 +1240,7 @@ is_required=True), _Option(["-wordsize", "wordsize"], "Word size (Integer 2 or more, default 4)"), - _Option(["-aformat","aformat"], + _Option(["-aformat", "aformat"], "Display output in a different specified output format"), ] _EmbossCommandLine.__init__(self, cmd, **kwargs) @@ -1252,3 +1254,4 @@ if __name__ == "__main__": #Run the doctests _test() + diff -Nru python-biopython-1.62/Bio/Emboss/Primer3.py python-biopython-1.63/Bio/Emboss/Primer3.py --- python-biopython-1.62/Bio/Emboss/Primer3.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Emboss/Primer3.py 2013-12-05 14:10:43.000000000 +0000 @@ -146,7 +146,7 @@ except IndexError: # eprimer3 reports oligo without sequence primer.internal_seq = '' try: - line = handle.next() + line = next(handle) except StopIteration: break if record: @@ -161,11 +161,11 @@ """ iterator = parse(handle) try: - first = iterator.next() + first = next(iterator) except StopIteration: raise ValueError("No records found in handle") try: - second = iterator.next() + second = next(iterator) except StopIteration: second = None if second is not None: diff -Nru python-biopython-1.62/Bio/Emboss/PrimerSearch.py python-biopython-1.63/Bio/Emboss/PrimerSearch.py --- python-biopython-1.62/Bio/Emboss/PrimerSearch.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Emboss/PrimerSearch.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Code to interact with the primersearch program from EMBOSS. """ diff -Nru python-biopython-1.62/Bio/Emboss/__init__.py python-biopython-1.63/Bio/Emboss/__init__.py --- python-biopython-1.62/Bio/Emboss/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Emboss/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,2 +1,7 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Code to interact with the ever-so-useful EMBOSS programs. """ diff -Nru python-biopython-1.62/Bio/Entrez/Parser.py python-biopython-1.63/Bio/Entrez/Parser.py --- python-biopython-1.62/Bio/Entrez/Parser.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Entrez/Parser.py 2013-12-05 14:10:43.000000000 +0000 @@ -36,11 +36,14 @@ import os.path -import urlparse -import urllib import warnings from xml.parsers import expat +#Importing these functions with leading underscore as not intended for reuse +from Bio._py3k import urlopen as _urlopen +from Bio._py3k import urlparse as _urlparse +from Bio._py3k import unicode + # The following four classes are used to add a member .attributes to integers, # strings, lists, and dictionaries, respectively. @@ -182,7 +185,7 @@ raise IOError("Can't parse a closed handle") try: self.parser.ParseFile(handle) - except expat.ExpatError, e: + except expat.ExpatError as e: if self.parser.StartElementHandler: # We saw the initial >> records = Entrez.parse(handle) >>> for record in records: ... # each record is a Python dictionary or list. - ... print record['MedlineCitation']['Article']['ArticleTitle'] + ... print(record['MedlineCitation']['Article']['ArticleTitle']) Biopython: freely available Python tools for computational molecular biology and bioinformatics. PDB file parser and structure class implemented in Python. >>> handle.close() @@ -68,12 +68,17 @@ _open Internally used function. """ -import urllib -import urllib2 +from __future__ import print_function + import time import warnings import os.path +#Importing these functions with leading underscore as not intended for reuse +from Bio._py3k import urlopen as _urlopen +from Bio._py3k import urlencode as _urlencode +from Bio._py3k import HTTPError as _HTTPError + from Bio._py3k import _binary_to_string_handle, _as_bytes email = None @@ -118,7 +123,7 @@ >>> from Bio import Entrez >>> Entrez.email = "Your.Name.Here@example.org" >>> handle = Entrez.efetch(db="nucleotide", id="57240072", rettype="gb", retmode="text") - >>> print handle.readline().strip() + >>> print(handle.readline().strip()) LOCUS AY851612 892 bp DNA linear PLN 10-APR-2007 >>> handle.close() @@ -205,7 +210,7 @@ >>> handle = Entrez.elink(dbfrom="pubmed", id=pmid, linkname="pubmed_pubmed") >>> record = Entrez.read(handle) >>> handle.close() - >>> print record[0]["LinkSetDb"][0]["LinkName"] + >>> print(record[0]["LinkSetDb"][0]["LinkName"]) pubmed_pubmed >>> linked = [link["Id"] for link in record[0]["LinkSetDb"][0]["Link"]] >>> "17121776" in linked @@ -267,9 +272,9 @@ >>> handle = Entrez.esummary(db="journals", id="30367") >>> record = Entrez.read(handle) >>> handle.close() - >>> print record[0]["Id"] + >>> print(record[0]["Id"]) 30367 - >>> print record[0]["Title"] + >>> print(record[0]["Title"]) Computational biology and chemistry """ @@ -303,7 +308,7 @@ >>> handle.close() >>> for row in record["eGQueryResult"]: ... if "pmc" in row["DbName"]: - ... print row["Count"] > 60 + ... print(row["Count"] > 60) True """ @@ -330,9 +335,9 @@ >>> from Bio import Entrez >>> Entrez.email = "Your.Name.Here@example.org" >>> record = Entrez.read(Entrez.espell(term="biopythooon")) - >>> print record["Query"] + >>> print(record["Query"]) biopythooon - >>> print record["CorrectedQuery"] + >>> print(record["CorrectedQuery"]) biopython """ @@ -362,7 +367,7 @@ (if any) of each element in a dictionary my_element.attributes, and the tag name in my_element.tag. """ - from Parser import DataHandler + from .Parser import DataHandler handler = DataHandler(validate) record = handler.read(handle) return record @@ -394,7 +399,7 @@ (if any) of each element in a dictionary my_element.attributes, and the tag name in my_element.tag. """ - from Parser import DataHandler + from .Parser import DataHandler handler = DataHandler(validate) records = handler.parse(handle) return records @@ -446,17 +451,17 @@ a user at the email address provided before blocking access to the E-utilities.""", UserWarning) # Open a handle to Entrez. - options = urllib.urlencode(params, doseq=True) + options = _urlencode(params, doseq=True) #print cgi + "?" + options try: if post: #HTTP POST - handle = urllib2.urlopen(cgi, data=_as_bytes(options)) + handle = _urlopen(cgi, data=_as_bytes(options)) else: #HTTP GET cgi += "?" + options - handle = urllib2.urlopen(cgi) - except urllib2.HTTPError, exception: + handle = _urlopen(cgi) + except _HTTPError as exception: raise exception return _binary_to_string_handle(handle) @@ -466,10 +471,10 @@ def _test(): """Run the module's doctests (PRIVATE).""" - print "Running doctests..." + print("Running doctests...") import doctest doctest.testmod() - print "Done" + print("Done") if __name__ == "__main__": _test() diff -Nru python-biopython-1.62/Bio/ExPASy/ScanProsite.py python-biopython-1.63/Bio/ExPASy/ScanProsite.py --- python-biopython-1.62/Bio/ExPASy/ScanProsite.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/ExPASy/ScanProsite.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,4 +1,12 @@ -import urllib +# Copyright 2009 by Michiel de Hoon. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. + +#Importing these functions with leading underscore as not intended for reuse +from Bio._py3k import urlopen as _urlopen +from Bio._py3k import urlencode as _urlencode + from xml.sax import handler from xml.sax.expatreader import ExpatParser @@ -37,12 +45,12 @@ """ parameters = {'seq': seq, 'output': output} - for key, value in keywords.iteritems(): + for key, value in keywords.items(): if value is not None: parameters[key] = value - command = urllib.urlencode(parameters) + command = _urlencode(parameters) url = "%s/cgi-bin/prosite/PSScan.cgi?%s" % (mirror, command) - handle = urllib.urlopen(url) + handle = _urlopen(url) return handle diff -Nru python-biopython-1.62/Bio/ExPASy/__init__.py python-biopython-1.63/Bio/ExPASy/__init__.py --- python-biopython-1.62/Bio/ExPASy/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/ExPASy/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -17,7 +17,9 @@ sprot_search_de Interface to the sprot-search-de CGI script. """ -import urllib +#Importing these functions with leading underscore as not intended for reuse +from Bio._py3k import urlopen as _urlopen +from Bio._py3k import urlencode as _urlencode def get_prodoc_entry(id, cgi='http://www.expasy.ch/cgi-bin/get-prodoc-entry'): @@ -31,8 +33,7 @@ 'There is no PROSITE documentation entry XXX. Please try again.' """ # Open a handle to ExPASy. - handle = urllib.urlopen("%s?%s" % (cgi, id)) - return handle + return _urlopen("%s?%s" % (cgi, id)) def get_prosite_entry(id, @@ -46,8 +47,7 @@ containing this line: 'There is currently no PROSITE entry for XXX. Please try again.' """ - handle = urllib.urlopen("%s?%s" % (cgi, id)) - return handle + return _urlopen("%s?%s" % (cgi, id)) def get_prosite_raw(id, cgi='http://www.expasy.ch/cgi-bin/get-prosite-raw.pl'): @@ -59,8 +59,7 @@ For a non-existing key, ExPASy returns nothing. """ - handle = urllib.urlopen("%s?%s" % (cgi, id)) - return handle + return _urlopen("%s?%s" % (cgi, id)) def get_sprot_raw(id): @@ -69,7 +68,7 @@ For an ID of XXX, fetches http://www.uniprot.org/uniprot/XXX.txt (as per the http://www.expasy.ch/expasy_urls.html documentation). """ - return urllib.urlopen("http://www.uniprot.org/uniprot/%s.txt" % id) + return _urlopen("http://www.uniprot.org/uniprot/%s.txt" % id) def sprot_search_ful(text, make_wild=None, swissprot=1, trembl=None, @@ -87,9 +86,9 @@ variables['S'] = 'on' if trembl: variables['T'] = 'on' - options = urllib.urlencode(variables) + options = _urlencode(variables) fullcgi = "%s?%s" % (cgi, options) - handle = urllib.urlopen(fullcgi) + handle = _urlopen(fullcgi) return handle @@ -107,7 +106,7 @@ variables['S'] = 'on' if trembl: variables['T'] = 'on' - options = urllib.urlencode(variables) + options = _urlencode(variables) fullcgi = "%s?%s" % (cgi, options) - handle = urllib.urlopen(fullcgi) + handle = _urlopen(fullcgi) return handle diff -Nru python-biopython-1.62/Bio/FSSP/FSSPTools.py python-biopython-1.63/Bio/FSSP/FSSPTools.py --- python-biopython-1.62/Bio/FSSP/FSSPTools.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/FSSP/FSSPTools.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + from Bio import FSSP import copy from Bio.Align import Generic @@ -28,11 +33,9 @@ for j in align_dict.abs(i).pos_align_dict: # loop within a position mult_align_dict[j] += align_dict.abs(i).pos_align_dict[j].aa - seq_order = mult_align_dict.keys() - seq_order.sort() fssp_align = Generic.Alignment(Alphabet.Gapped( Alphabet.IUPAC.extended_protein)) - for i in seq_order: + for i in sorted(mult_align_dict): fssp_align.add_sequence(sum_dict[i].pdb2+sum_dict[i].chain2, mult_align_dict[i]) # fssp_align._add_numbering_table() @@ -65,8 +68,7 @@ attr_value = getattr(sum_dict[prot_num], filter_attribute) if attr_value >= low_bound and attr_value <= high_bound: new_sum_dict[prot_num] = sum_dict[prot_num] - prot_numbers = new_sum_dict.keys() - prot_numbers.sort() + prot_numbers = sorted(new_sum_dict) for pos_num in new_align_dict.abs_res_dict: new_align_dict.abs(pos_num).pos_align_dict = {} for prot_num in prot_numbers: @@ -84,8 +86,7 @@ for prot_num in sum_dict: if sum_dict[prot_num].pdb2+sum_dict[prot_num].chain2 == cur_pdb_name: new_sum_dict[prot_num] = sum_dict[prot_num] - prot_numbers = new_sum_dict.keys() - prot_numbers.sort() + prot_numbers = sorted(new_sum_dict) for pos_num in new_align_dict.abs_res_dict: new_align_dict.abs(pos_num).pos_align_dict = {} for prot_num in prot_numbers: diff -Nru python-biopython-1.62/Bio/FSSP/__init__.py python-biopython-1.63/Bio/FSSP/__init__.py --- python-biopython-1.62/Bio/FSSP/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/FSSP/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Parser for FSSP files, used in a database of protein fold classifications. This is a module to handle FSSP files. For now it parses only the header, @@ -10,8 +15,10 @@ tuple of two instances. mult_align: returns a Biopython alignment object """ +from __future__ import print_function + import re -import fssp_rec +from . import fssp_rec from Bio.Align import Generic from Bio import Alphabet fff_rec = fssp_rec.fff_rec @@ -91,7 +98,7 @@ def __init__(self, in_str): self.raw = in_str in_rec = in_str.strip().split() - # print in_rec + # print(in_rec) self.nr = int(in_rec[0][:-1]) self.pdb1 = in_rec[1][:4] if len(in_rec[1]) == 4: @@ -128,7 +135,7 @@ class FSSPAlignRec(object): def __init__(self, in_fff_rec): - # print in_fff_rec + # print(in_fff_rec) self.abs_res_num = int(in_fff_rec[fssp_rec.align.abs_res_num]) self.pdb_res_num = in_fff_rec[fssp_rec.align.pdb_res_num].strip() self.chain_id = in_fff_rec[fssp_rec.align.chain_id] @@ -182,9 +189,7 @@ # Returns a sequence string def sequence(self, num): s = '' - sorted_pos_nums = self.abs_res_dict.keys() - sorted_pos_nums.sort() - for i in sorted_pos_nums: + for i in sorted(self.abs_res_dict): s += self.abs(i).pos_align_dict[num].aa return s @@ -192,13 +197,11 @@ mult_align_dict = {} for j in self.abs(1).pos_align_dict: mult_align_dict[j] = '' - for fssp_rec in self.itervalues(): + for fssp_rec in self.values(): for j in fssp_rec.pos_align_dict: mult_align_dict[j] += fssp_rec.pos_align_dict[j].aa - seq_order = mult_align_dict.keys() - seq_order.sort() out_str = '' - for i in seq_order: + for i in sorted(mult_align_dict): out_str += '> %d\n' % i k = 0 for j in mult_align_dict[i]: @@ -222,7 +225,6 @@ header = FSSPHeader() sum_dict = FSSPSumDict() align_dict = FSSPAlignDict() - # fssp_handle=open(fssp_handlename) curline = fssp_handle.readline() while not summary_title.match(curline): # Still in title @@ -246,7 +248,7 @@ curline = fssp_handle.readline() if not alignments_title.match(curline): if equiv_title.match(curline): - # print "Reached equiv_title" + # print("Reached equiv_title") break else: raise ValueError('Bad FSSP file: no alignments title record found') @@ -266,9 +268,9 @@ align_dict[key].add_align_list(align_list) curline = fssp_handle.readline() if not curline: - print 'EOFEOFEOF' + print('EOFEOFEOF') raise EOFError - for i in align_dict.itervalues(): + for i in align_dict.values(): i.pos_align_list2dict() del i.PosAlignList align_dict.build_resnum_list() diff -Nru python-biopython-1.62/Bio/File.py python-biopython-1.63/Bio/File.py --- python-biopython-1.62/Bio/File.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/File.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,5 +1,6 @@ # Copyright 1999 by Jeffrey Chang. All rights reserved. -# Copyright 2009-2012 by Peter Cock. All rights reserved. +# Copyright 2009-2013 by Peter Cock. All rights reserved. +# # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. @@ -15,14 +16,16 @@ files are also defined under Bio.File but these are not intended for direct use. """ -# For with statement in Python 2.5 -from __future__ import with_statement +from __future__ import print_function + import codecs import os +import sys import contextlib -import StringIO import itertools +from Bio._py3k import basestring + try: from collections import UserDict as _dict_base except ImportError: @@ -86,10 +89,10 @@ and index_db functions. """ handle = open(filename, "rb") - import bgzf + from . import bgzf try: return bgzf.BgzfReader(mode="rb", fileobj=handle) - except ValueError, e: + except ValueError as e: assert "BGZF" in str(e) #Not a BGZF file after all, rewind to start: handle.seek(0) @@ -113,12 +116,17 @@ def __iter__(self): return self - def next(self): + def __next__(self): next = self.readline() if not next: raise StopIteration return next + if sys.version_info[0] < 3: + def next(self): + """Python 2 style alias for Python 3 style __next__ method.""" + return self.__next__() + def readlines(self, *args, **keywds): lines = self._saved + self._handle.readlines(*args, **keywds) self._saved = [] @@ -160,9 +168,7 @@ return line def tell(self): - lengths = map(len, self._saved) - sum = reduce(lambda x, y: x+y, lengths, 0) - return self._handle.tell() - sum + return self._handle.tell() - sum(len(line) for line in self._saved) def seek(self, *args): self._saved = [] @@ -271,7 +277,7 @@ def __str__(self): #TODO - How best to handle the __str__ for SeqIO and SearchIO? if self: - return "{%r : %s(...), ...}" % (self.keys()[0], self._obj_repr) + return "{%r : %s(...), ...}" % (list(self.keys())[0], self._obj_repr) else: return "{}" @@ -282,37 +288,34 @@ """How many records are there?""" return len(self._offsets) - if hasattr(dict, "iteritems"): - #Python 2, use iteritems but not items etc - def values(self): - """Would be a list of the SeqRecord objects, but not implemented. + def items(self): + """Iterate over the (key, SeqRecord) items. - In general you can be indexing very very large files, with millions - of sequences. Loading all these into memory at once as SeqRecord - objects would (probably) use up all the RAM. Therefore we simply - don't support this dictionary method. - """ - raise NotImplementedError("Due to memory concerns, when indexing a " - "sequence file you cannot access all the " - "records at once.") - - def items(self): - """Would be a list of the (key, SeqRecord) tuples, but not implemented. - - In general you can be indexing very very large files, with millions - of sequences. Loading all these into memory at once as SeqRecord - objects would (probably) use up all the RAM. Therefore we simply - don't support this dictionary method. - """ - raise NotImplementedError("Due to memory concerns, when indexing a " - "sequence file you cannot access all the " - "records at once.") + This tries to act like a Python 3 dictionary, and does not return + a list of (key, value) pairs due to memory concerns. + """ + for key in self.__iter__(): + yield key, self.__getitem__(key) - def keys(self): - """Return a list of all the keys (SeqRecord identifiers).""" - #TODO - Stick a warning in here for large lists? Or just refuse? - return self._offsets.keys() + def values(self): + """Iterate over the SeqRecord items. + + This tries to act like a Python 3 dictionary, and does not return + a list of value due to memory concerns. + """ + for key in self.__iter__(): + yield self.__getitem__(key) + + def keys(self): + """Iterate over the keys. + + This tries to act like a Python 3 dictionary, and does not return + a list of keys due to memory concerns. + """ + return self.__iter__() + if hasattr(dict, "iteritems"): + #Python 2, also define iteritems etc def itervalues(self): """Iterate over the SeqRecord) items.""" for key in self.__iter__(): @@ -327,22 +330,6 @@ """Iterate over the keys.""" return self.__iter__() - else: - #Python 3 - define items and values as iterators - def items(self): - """Iterate over the (key, SeqRecord) items.""" - for key in self.__iter__(): - yield key, self.__getitem__(key) - - def values(self): - """Iterate over the SeqRecord items.""" - for key in self.__iter__(): - yield self.__getitem__(key) - - def keys(self): - """Iterate over the keys.""" - return self.__iter__() - def __iter__(self): """Iterate over the keys.""" return iter(self._offsets) @@ -487,7 +474,7 @@ if filenames and filenames != self._filenames: con.close() raise ValueError("Index file has different filenames") - except _OperationalError, err: + except _OperationalError as err: con.close() raise ValueError("Not a Biopython index database? %s" % err) #Now we have the format (from the DB if not given to us), @@ -504,7 +491,7 @@ #Create the index con = _sqlite.connect(index_filename) self._con = con - #print "Creating index" + #print("Creating index") # Sqlite PRAGMA settings for speed con.execute("PRAGMA synchronous=OFF") con.execute("PRAGMA locking_mode=EXCLUSIVE") @@ -537,8 +524,8 @@ batch = list(itertools.islice(offset_iter, 100)) if not batch: break - #print "Inserting batch of %i offsets, %s ... %s" \ - # % (len(batch), batch[0][0], batch[-1][0]) + #print("Inserting batch of %i offsets, %s ... %s" \ + # % (len(batch), batch[0][0], batch[-1][0])) con.executemany( "INSERT INTO offset_data (key,file_number,offset,length) VALUES (?,?,?,?);", batch) @@ -549,11 +536,11 @@ else: random_access_proxy._handle.close() self._length = count - #print "About to index %i entries" % count + #print("About to index %i entries" % count) try: con.execute("CREATE UNIQUE INDEX IF NOT EXISTS " "key_index ON offset_data(key);") - except _IntegrityError, err: + except _IntegrityError as err: self._proxies = random_access_proxies self.close() con.close() @@ -562,7 +549,7 @@ con.execute("UPDATE meta_data SET value = ? WHERE key = ?;", (count, "count")) con.commit() - #print "Index created" + #print("Index created") self._proxies = random_access_proxies self._max_open = max_open self._index_filename = index_filename diff -Nru python-biopython-1.62/Bio/GA/Crossover/General.py python-biopython-1.63/Bio/GA/Crossover/General.py --- python-biopython-1.62/Bio/GA/Crossover/General.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/GA/Crossover/General.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """General functionality for crossover that doesn't apply. This collects Crossover stuff that doesn't deal with any specific diff -Nru python-biopython-1.62/Bio/GA/Crossover/GeneralPoint.py python-biopython-1.63/Bio/GA/Crossover/GeneralPoint.py --- python-biopython-1.62/Bio/GA/Crossover/GeneralPoint.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/GA/Crossover/GeneralPoint.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """ Generalized N-Point Crossover. @@ -31,6 +36,8 @@ # standard modules import random +from Bio._py3k import range + class GeneralPointCrossover(object): """Perform n-point crossover between genomes at some defined rates. @@ -85,8 +92,8 @@ xlocs = self._generate_locs( bound[0] ) # copy new genome strings over - tmp = self._crossover(0, new_org, (x_locs,y_locs)) - new_org[1].genome = self._crossover(1, new_org, (x_locs,y_locs)) + tmp = self._crossover(0, new_org, (x_locs, y_locs)) + new_org[1].genome = self._crossover(1, new_org, (x_locs, y_locs)) new_org[0].genome = tmp return new_org @@ -103,9 +110,9 @@ """ results = [] for increment in range(self._npoints): - x = random.randint(1,bound-1) + x = random.randint(1, bound-1) while (x in results): # uniqueness - x = random.randint(1,bound-1) + x = random.randint(1, bound-1) results.append( x ) results.sort() # sorted return [0]+results+[bound] # [0, +n points+, bound] @@ -125,7 +132,7 @@ return type: sequence (to replace no[x]) """ s = no[ x ].genome[ :locs[ x ][1] ] - for n in range(1,self._npoints): + for n in range(1, self._npoints): # flipflop between genome_0 and genome_1 mode = (x+n)%2 # _generate_locs gives us [0, +n points+, bound] @@ -149,7 +156,7 @@ See GeneralPoint._generate_locs documentation for details """ - return [0, random.randint(1,bound-1), bound] + return [0, random.randint(1, bound-1), bound] def _crossover( self, x, no, locs ): """Replacement crossover @@ -166,14 +173,14 @@ Interleaving: AbCdEfG, aBcDeFg """ def __init__(self,crossover_prob=0.1): - GeneralPointCrossover.__init__(self,0,crossover_prob) + GeneralPointCrossover.__init__(self, 0, crossover_prob) - def _generate_locs(self,bound): - return range(-1,bound+1) + def _generate_locs(self, bound): + return list(range(-1, bound+1)) def _crossover( self, x, no, locs ): s = no[ x ].genome[ 0:1 ] - for n in range(1,self._npoints+2): + for n in range(1, self._npoints+2): mode = ( x+n )%2 s += no[ mode ].genome[ n:n+1 ] return s+no[mode].genome[self._npoints+3:] diff -Nru python-biopython-1.62/Bio/GA/Crossover/Point.py python-biopython-1.63/Bio/GA/Crossover/Point.py --- python-biopython-1.62/Bio/GA/Crossover/Point.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/GA/Crossover/Point.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Perform two-point crossovers between the genomes of two organisms. This module performs single-point crossover between two genomes. @@ -11,7 +16,7 @@ """ # standard modules -from GeneralPoint import TwoCrossover +from .GeneralPoint import TwoCrossover class SinglePointCrossover(TwoCrossover): diff -Nru python-biopython-1.62/Bio/GA/Crossover/TwoPoint.py python-biopython-1.63/Bio/GA/Crossover/TwoPoint.py --- python-biopython-1.62/Bio/GA/Crossover/TwoPoint.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/GA/Crossover/TwoPoint.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Perform two-point crossovers between the genomes of two organisms. This module performs two-point crossover between two genomes. @@ -16,7 +21,7 @@ """ # standard modules -from GeneralPoint import TwoCrossover +from .GeneralPoint import TwoCrossover class TwoPointCrossover(TwoCrossover): diff -Nru python-biopython-1.62/Bio/GA/Crossover/Uniform.py python-biopython-1.63/Bio/GA/Crossover/Uniform.py --- python-biopython-1.62/Bio/GA/Crossover/Uniform.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/GA/Crossover/Uniform.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Perform uniform crossovers between the genomes of two organisms. @@ -40,7 +45,7 @@ # determine if we have a crossover crossover_chance = random.random() if crossover_chance <= self._crossover_prob: - minlen = min(len(new_org_1.genome),len(new_org_2.genome)) + minlen = min(len(new_org_1.genome), len(new_org_2.genome)) for i in range( minlen ): uniform_chance = random.random() if uniform_chance <= self._uniform_prob: diff -Nru python-biopython-1.62/Bio/GA/Evolver.py python-biopython-1.63/Bio/GA/Evolver.py --- python-biopython-1.62/Bio/GA/Evolver.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/GA/Evolver.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,9 +1,16 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Evolution Strategies for a Population. Evolver classes manage a population of individuals, and are responsible for taking care of the transition from one generation to the next. """ # standard modules +from __future__ import print_function + import sys @@ -67,7 +74,7 @@ # sort the population so we can look at duplicates self._population.sort() for org in self._population: - print org + print(org) sys.exit() return self._population diff -Nru python-biopython-1.62/Bio/GA/Mutation/General.py python-biopython-1.63/Bio/GA/Mutation/General.py --- python-biopython-1.62/Bio/GA/Mutation/General.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/GA/Mutation/General.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """General functionality for mutations. """ # standard library diff -Nru python-biopython-1.62/Bio/GA/Mutation/Simple.py python-biopython-1.63/Bio/GA/Mutation/Simple.py --- python-biopython-1.62/Bio/GA/Mutation/Simple.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/GA/Mutation/Simple.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,8 +1,15 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Perform Simple mutations on an organism's genome. """ # standard modules import random +from Bio._py3k import range + class SinglePositionMutation(object): """Perform a conversion mutation, but only at a single point in the genome. @@ -36,7 +43,7 @@ if mutation_chance <= self._mutation_rate: # pick a gene position to mutate at mutation_pos = \ - self._pos_rand.choice(range(len(mutated_org.genome))) + self._pos_rand.choice(list(range(len(mutated_org.genome)))) # get a new letter to replace the position at new_letter = self._switch_rand.choice(gene_choices) diff -Nru python-biopython-1.62/Bio/GA/Organism.py python-biopython-1.63/Bio/GA/Organism.py --- python-biopython-1.62/Bio/GA/Organism.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/GA/Organism.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Deal with an Organism in a Genetic Algorithm population. """ # standard modules diff -Nru python-biopython-1.62/Bio/GA/Repair/Stabilizing.py python-biopython-1.63/Bio/GA/Repair/Stabilizing.py --- python-biopython-1.62/Bio/GA/Repair/Stabilizing.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/GA/Repair/Stabilizing.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Methods for performing repairs that will Stabilize genomes. These methods perform repair to keep chromosomes from drifting too far in @@ -42,7 +47,7 @@ new_org = organism.copy() # start getting rid of ambiguous items - while 1: + while True: # first find all of the ambigous items seq_genome = new_org.genome.toseq() all_ambiguous = self._ambig_finder.find_ambiguous(str(seq_genome)) diff -Nru python-biopython-1.62/Bio/GA/Selection/Abstract.py python-biopython-1.63/Bio/GA/Selection/Abstract.py --- python-biopython-1.62/Bio/GA/Selection/Abstract.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/GA/Selection/Abstract.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Base selection class from which all Selectors should derive. """ diff -Nru python-biopython-1.62/Bio/GA/Selection/Diversity.py python-biopython-1.63/Bio/GA/Selection/Diversity.py --- python-biopython-1.62/Bio/GA/Selection/Diversity.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/GA/Selection/Diversity.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Select individuals into a new population trying to maintain diversity. This selection mechanism seeks to try and get both high fitness levels @@ -11,8 +16,8 @@ from Bio.Seq import MutableSeq # local modules -from Abstract import AbstractSelection -from Tournament import TournamentSelection +from .Abstract import AbstractSelection +from .Tournament import TournamentSelection class DiversitySelection(AbstractSelection): diff -Nru python-biopython-1.62/Bio/GA/Selection/RouletteWheel.py python-biopython-1.63/Bio/GA/Selection/RouletteWheel.py --- python-biopython-1.62/Bio/GA/Selection/RouletteWheel.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/GA/Selection/RouletteWheel.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Implement Roulette Wheel selection on a population. This implements Roulette Wheel selection in which individuals are @@ -9,7 +14,7 @@ import copy # local modules -from Abstract import AbstractSelection +from .Abstract import AbstractSelection class RouletteWheelSelection(AbstractSelection): @@ -49,8 +54,7 @@ # set up the current probabilities for selecting organisms # from the population prob_wheel = self._set_up_wheel(population) - probs = prob_wheel.keys() - probs.sort() + probs = sorted(prob_wheel) # now create the new population with the same size as the original new_population = [] diff -Nru python-biopython-1.62/Bio/GA/Selection/Tournament.py python-biopython-1.63/Bio/GA/Selection/Tournament.py --- python-biopython-1.62/Bio/GA/Selection/Tournament.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/GA/Selection/Tournament.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Provide Tournament style selection. This implements selection based on a tournament style. In this model of @@ -9,7 +14,7 @@ import random # local modules -from Abstract import AbstractSelection +from .Abstract import AbstractSelection class TournamentSelection(AbstractSelection): diff -Nru python-biopython-1.62/Bio/GenBank/Record.py python-biopython-1.63/Bio/GenBank/Record.py --- python-biopython-1.62/Bio/GenBank/Record.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/GenBank/Record.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Hold GenBank data in a straightforward format. classes: diff -Nru python-biopython-1.62/Bio/GenBank/Scanner.py python-biopython-1.63/Bio/GenBank/Scanner.py --- python-biopython-1.62/Bio/GenBank/Scanner.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/GenBank/Scanner.py 2013-12-05 14:10:43.000000000 +0000 @@ -26,6 +26,8 @@ # for more details of this format, and an example. # Added by Ying Huang & Iddo Friedberg +from __future__ import print_function + import warnings import re from Bio.Seq import Seq @@ -78,23 +80,23 @@ line = self.handle.readline() if not line: if self.debug: - print "End of file" + print("End of file") return None if line[:self.HEADER_WIDTH] == self.RECORD_START: if self.debug > 1: - print "Found the start of a record:\n" + line + print("Found the start of a record:\n" + line) break line = line.rstrip() if line == "//": if self.debug > 1: - print "Skipping // marking end of last record" + print("Skipping // marking end of last record") elif line == "": if self.debug > 1: - print "Skipping blank line before record" + print("Skipping blank line before record") else: #Ignore any header before the first ID/LOCUS line. if self.debug > 1: - print "Skipping header line before record:\n" + line + print("Skipping header line before record:\n" + line) self.line = line return line @@ -116,14 +118,14 @@ line = line.rstrip() if line in self.FEATURE_START_MARKERS: if self.debug: - print "Found header table" + print("Found header table") break #if line[:self.HEADER_WIDTH]==self.FEATURE_START_MARKER[:self.HEADER_WIDTH]: - # if self.debug : print "Found header table (?)" + # if self.debug : print("Found header table (?)") # break if line[:self.HEADER_WIDTH].rstrip() in self.SEQUENCE_HEADERS: if self.debug: - print "Found start of sequence" + print("Found start of sequence") break if line == "//": raise ValueError("Premature end of sequence data marker '//' found") @@ -143,7 +145,7 @@ """ if self.line.rstrip() not in self.FEATURE_START_MARKERS: if self.debug: - print "Didn't find any feature table" + print("Didn't find any feature table") return [] while self.line.rstrip() in self.FEATURE_START_MARKERS: @@ -156,14 +158,14 @@ raise ValueError("Premature end of line during features table") if line[:self.HEADER_WIDTH].rstrip() in self.SEQUENCE_HEADERS: if self.debug: - print "Found start of sequence" + print("Found start of sequence") break line = line.rstrip() if line == "//": raise ValueError("Premature end of features table, marker '//' found") if line in self.FEATURE_END_MARKERS: if self.debug: - print "Found end of features" + print("Found end of features") line = self.handle.readline() break if line[2:self.FEATURE_QUALIFIER_INDENT].strip() == "": @@ -260,14 +262,14 @@ Note that no whitespace is removed. """ #Skip any blank lines - iterator = iter(filter(None, lines)) + iterator = (x for x in lines if x) try: - line = iterator.next() + line = next(iterator) feature_location = line.strip() while feature_location[-1:] == ",": #Multiline location, still more to come! - line = iterator.next() + line = next(iterator) feature_location += line.strip() qualifiers = [] @@ -291,26 +293,26 @@ elif value == '"': #One single quote if self.debug: - print "Single quote %s:%s" % (key, value) + print("Single quote %s:%s" % (key, value)) #DO NOT remove the quote... qualifiers.append((key, value)) elif value[0] == '"': #Quoted... value_list = [value] while value_list[-1][-1] != '"': - value_list.append(iterator.next()) + value_list.append(next(iterator)) value = '\n'.join(value_list) #DO NOT remove the quotes... qualifiers.append((key, value)) else: #Unquoted - #if debug : print "Unquoted line %s:%s" % (key,value) + #if debug : print("Unquoted line %s:%s" % (key,value)) qualifiers.append((key, value)) else: #Unquoted continuation assert len(qualifiers) > 0 assert key == qualifiers[-1][0] - #if debug : print "Unquoted Cont %s:%s" % (key, line) + #if debug : print("Unquoted Cont %s:%s" % (key, line)) if qualifiers[-1][1] is None: raise StopIteration qualifiers[-1] = (key, qualifiers[-1][1] + "\n" + line) @@ -607,11 +609,30 @@ #Looks like the semi colon separated style introduced in 2006 self._feed_first_line_new(consumer, line) elif line[self.HEADER_WIDTH:].count(";") == 3: - #Looks like the pre 2006 style - self._feed_first_line_old(consumer, line) + if line.rstrip().endswith(" SQ"): + #EMBL-bank patent data + self._feed_first_line_patents(consumer,line) + else: + #Looks like the pre 2006 style + self._feed_first_line_old(consumer, line) else: raise ValueError('Did not recognise the ID line layout:\n' + line) + def _feed_first_line_patents(self, consumer, line): + #Either Non-Redundant Level 1 database records, + #ID ; ; ; + #e.g. ID NRP_AX000635; PRT; NR1; 15 SQ + # + #Or, Non-Redundant Level 2 database records: + #ID ; ; ; + #e.g. ID NRP0000016E; PRT; NR2; 5 SQ + fields = line[self.HEADER_WIDTH:].rstrip()[:-3].split(";") + assert len(fields) == 4 + consumer.locus(fields[0]) + consumer.residue_type(fields[1]) + consumer.data_file_division(fields[2]) + #TODO - Record cluster size? + def _feed_first_line_old(self, consumer, line): #Expects an ID line in the style before 2006, e.g. #ID SC10H5 standard; DNA; PRO; 4870 BP. @@ -679,7 +700,7 @@ def _feed_seq_length(self, consumer, text): length_parts = text.split() assert len(length_parts) == 2, "Invalid sequence length string %r" % text - assert length_parts[1].upper() in ["BP", "BP.", "AA."] + assert length_parts[1].upper() in ["BP", "BP.", "AA", "AA."] consumer.size(length_parts[0]) def _feed_header_lines(self, consumer, lines): @@ -785,7 +806,7 @@ getattr(consumer, consumer_dict[line_type])(data) else: if self.debug: - print "Ignoring EMBL header line:\n%s" % line + print("Ignoring EMBL header line:\n%s" % line) def _feed_misc_lines(self, consumer, lines): #TODO - Should we do something with the information on the SQ line(s)? @@ -797,7 +818,7 @@ line = line[5:].strip() contig_location = line while True: - line = line_iter.next() + line = next(line_iter) if not line: break elif line.startswith("CO "): @@ -806,6 +827,14 @@ else: raise ValueError('Expected CO (contig) continuation line, got:\n' + line) consumer.contig_location(contig_location) + if line.startswith("SQ Sequence "): + #e.g. + #SQ Sequence 219 BP; 82 A; 48 C; 33 G; 45 T; 11 other; + # + #Or, EMBL-bank patent, e.g. + #SQ Sequence 465 AA; 3963407aa91d3a0d622fec679a4524e0; MD5; + self._feed_seq_length(consumer, line[14:].rstrip().rstrip(";").split(";", 1)[0]) + #TODO - Record the checksum etc? return except StopIteration: raise ValueError("Problem in misc lines before sequence") @@ -839,7 +868,7 @@ """ if self.line.rstrip() not in self.FEATURE_START_MARKERS: if self.debug: - print "Didn't find any feature table" + print("Didn't find any feature table") return [] while self.line.rstrip() in self.FEATURE_START_MARKERS: @@ -854,14 +883,14 @@ raise ValueError("Premature end of line during features table") if line[:self.HEADER_WIDTH].rstrip() in self.SEQUENCE_HEADERS: if self.debug: - print "Found start of sequence" + print("Found start of sequence") break line = line.rstrip() if line == "//": raise ValueError("Premature end of features table, marker '//' found") if line in self.FEATURE_END_MARKERS: if self.debug: - print "Found end of features" + print("Found end of features") line = self.handle.readline() break if line[2:self.FEATURE_QUALIFIER_INDENT].strip() == "": @@ -1227,11 +1256,11 @@ #VERSION (version and gi) #REFERENCE (eference_num and reference_bases) #ORGANISM (organism and taxonomy) - lines = filter(None, lines) + lines = [_f for _f in lines if _f] lines.append("") # helps avoid getting StopIteration all the time line_iter = iter(lines) try: - line = line_iter.next() + line = next(line_iter) while True: if not line: break @@ -1248,14 +1277,14 @@ consumer.version(data) else: if self.debug: - print "Version [" + data.split(' GI:')[0] + "], gi [" + data.split(' GI:')[1] + "]" + print("Version [" + data.split(' GI:')[0] + "], gi [" + data.split(' GI:')[1] + "]") consumer.version(data.split(' GI:')[0]) consumer.gi(data.split(' GI:')[1]) #Read in the next line! - line = line_iter.next() + line = next(line_iter) elif line_type == 'REFERENCE': if self.debug > 1: - print "Found reference [" + data + "]" + print("Found reference [" + data + "]") #Need to call consumer.reference_num() and consumer.reference_bases() #e.g. # REFERENCE 1 (bases 1 to 86436) @@ -1270,12 +1299,12 @@ #Read in the next line, and see if its more of the reference: while True: - line = line_iter.next() + line = next(line_iter) if line[:GENBANK_INDENT] == GENBANK_SPACER: #Add this continuation to the data string data += " " + line[GENBANK_INDENT:] if self.debug > 1: - print "Extended reference text [" + data + "]" + print("Extended reference text [" + data + "]") else: #End of the reference, leave this text in the variable "line" break @@ -1286,11 +1315,11 @@ data = data.replace(' ', ' ') if ' ' not in data: if self.debug > 2: - print 'Reference number \"' + data + '\"' + print('Reference number \"' + data + '\"') consumer.reference_num(data) else: if self.debug > 2: - print 'Reference number \"' + data[:data.find(' ')] + '\", \"' + data[data.find(' ') + 1:] + '\"' + print('Reference number \"' + data[:data.find(' ')] + '\", \"' + data[data.find(' ') + 1:] + '\"') consumer.reference_num(data[:data.find(' ')]) consumer.reference_bases(data[data.find(' ') + 1:]) elif line_type == 'ORGANISM': @@ -1305,7 +1334,7 @@ organism_data = data lineage_data = "" while True: - line = line_iter.next() + line = next(line_iter) if line[0:GENBANK_INDENT] == GENBANK_SPACER: if lineage_data or ";" in line: lineage_data += " " + line[GENBANK_INDENT:] @@ -1316,23 +1345,23 @@ break consumer.organism(organism_data) if lineage_data.strip() == "" and self.debug > 1: - print "Taxonomy line(s) missing or blank" + print("Taxonomy line(s) missing or blank") consumer.taxonomy(lineage_data.strip()) del organism_data, lineage_data elif line_type == 'COMMENT': if self.debug > 1: - print "Found comment" + print("Found comment") #This can be multiline, and should call consumer.comment() once #with a list where each entry is a line. comment_list = [] comment_list.append(data) while True: - line = line_iter.next() + line = next(line_iter) if line[0:GENBANK_INDENT] == GENBANK_SPACER: data = line[GENBANK_INDENT:] comment_list.append(data) if self.debug > 2: - print "Comment continuation [" + data + "]" + print("Comment continuation [" + data + "]") else: #End of the comment break @@ -1342,7 +1371,7 @@ #Its a semi-automatic entry! #Now, this may be a multi line entry... while True: - line = line_iter.next() + line = next(line_iter) if line[0:GENBANK_INDENT] == GENBANK_SPACER: data += ' ' + line[GENBANK_INDENT:] else: @@ -1352,9 +1381,9 @@ break else: if self.debug: - print "Ignoring GenBank header line:\n" % line + print("Ignoring GenBank header line:\n" % line) #Read in next line - line = line_iter.next() + line = next(line_iter) except StopIteration: raise ValueError("Problem in header") @@ -1370,13 +1399,13 @@ line = line[10:].strip() if line: if self.debug: - print "base_count = " + line + print("base_count = " + line) consumer.base_count(line) if line.startswith('ORIGIN'): line = line[6:].strip() if line: if self.debug: - print "origin_name = " + line + print("origin_name = " + line) consumer.origin_name(line) if line.startswith('WGS '): line = line[3:].strip() @@ -1388,7 +1417,7 @@ line = line[6:].strip() contig_location = line while True: - line = line_iter.next() + line = next(line_iter) if not line: break elif line[:GENBANK_INDENT] == GENBANK_SPACER: @@ -1408,7 +1437,7 @@ raise ValueError("Problem in misc lines before sequence") if __name__ == "__main__": - from StringIO import StringIO + from Bio._py3k import StringIO gbk_example = \ """LOCUS SCU49845 5028 bp DNA PLN 21-JUN-1999 @@ -1724,58 +1753,58 @@ // """ - print "GenBank CDS Iteration" - print "=====================" + print("GenBank CDS Iteration") + print("=====================") g = GenBankScanner() for record in g.parse_cds_features(StringIO(gbk_example)): - print record + print(record) g = GenBankScanner() for record in g.parse_cds_features(StringIO(gbk_example2), tags2id=('gene', 'locus_tag', 'product')): - print record + print(record) g = GenBankScanner() for record in g.parse_cds_features(StringIO(gbk_example + "\n" + gbk_example2), tags2id=('gene', 'locus_tag', 'product')): - print record + print(record) - print - print "GenBank Iteration" - print "=================" + print("") + print("GenBank Iteration") + print("=================") g = GenBankScanner() for record in g.parse_records(StringIO(gbk_example), do_features=False): - print record.id, record.name, record.description - print record.seq + print("%s %s %s" % (record.id, record.name, record.description)) + print(record.seq) g = GenBankScanner() for record in g.parse_records(StringIO(gbk_example), do_features=True): - print record.id, record.name, record.description - print record.seq + print("%s %s %s" % (record.id, record.name, record.description)) + print(record.seq) g = GenBankScanner() for record in g.parse_records(StringIO(gbk_example2), do_features=False): - print record.id, record.name, record.description - print record.seq + print("%s %s %s" % (record.id, record.name, record.description)) + print(record.seq) g = GenBankScanner() for record in g.parse_records(StringIO(gbk_example2), do_features=True): - print record.id, record.name, record.description - print record.seq + print("%s %s %s" % (record.id, record.name, record.description)) + print(record.seq) - print - print "EMBL CDS Iteration" - print "==================" + print("") + print("EMBL CDS Iteration") + print("==================") e = EmblScanner() for record in e.parse_cds_features(StringIO(embl_example)): - print record + print(record) - print - print "EMBL Iteration" - print "==============" + print("") + print("EMBL Iteration") + print("==============") e = EmblScanner() for record in e.parse_records(StringIO(embl_example), do_features=True): - print record.id, record.name, record.description - print record.seq + print("%s %s %s" % (record.id, record.name, record.description)) + print(record.seq) diff -Nru python-biopython-1.62/Bio/GenBank/__init__.py python-biopython-1.63/Bio/GenBank/__init__.py --- python-biopython-1.62/Bio/GenBank/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/GenBank/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,5 +1,6 @@ # Copyright 2000 by Jeffrey Chang, Brad Chapman. All rights reserved. -# Copyright 2006-2011 by Peter Cock. All rights reserved. +# Copyright 2006-2013 by Peter Cock. All rights reserved. +# # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. @@ -38,14 +39,17 @@ location parser. """ +from __future__ import print_function + import re +import sys # for checking if Python 2 # other Biopython stuff from Bio import SeqFeature # other Bio.GenBank stuff -from utils import FeatureValueCleaner -from Scanner import GenBankScanner +from .utils import FeatureValueCleaner +from .Scanner import GenBankScanner #Constants used to parse GenBank header lines GENBANK_INDENT = 12 @@ -65,7 +69,7 @@ _within_position = r"\(\d+\.\d+\)" _re_within_position = re.compile(_within_position) _within_location = r"([<>]?\d+|%s)\.\.([<>]?\d+|%s)" \ - % (_within_position,_within_position) + % (_within_position, _within_position) assert _re_within_position.match("(3.9)") assert re.compile(_within_location).match("(3.9)..10") assert re.compile(_within_location).match("26..(30.33)") @@ -74,7 +78,7 @@ _oneof_position = r"one\-of\(\d+(,\d+)+\)" _re_oneof_position = re.compile(_oneof_position) _oneof_location = r"([<>]?\d+|%s)\.\.([<>]?\d+|%s)" \ - % (_oneof_position,_oneof_position) + % (_oneof_position, _oneof_position) assert _re_oneof_position.match("one-of(6,9)") assert re.compile(_oneof_location).match("one-of(6,9)..101") assert re.compile(_oneof_location).match("one-of(6,9)..one-of(101,104)") @@ -156,7 +160,7 @@ >>> p = _pos("<5") >>> p BeforePosition(5) - >>> print p + >>> print(p) <5 >>> int(p) 5 @@ -169,7 +173,7 @@ >>> p = _pos("one-of(5,8,11)") >>> p OneOfPosition(11, choices=[ExactPosition(5), ExactPosition(8), ExactPosition(11)]) - >>> print p + >>> print(p) one-of(5,8,11) >>> int(p) 11 @@ -182,7 +186,7 @@ >>> p = _pos("<5", -1) >>> p BeforePosition(4) - >>> print p + >>> print(p) <4 >>> int(p) 4 @@ -203,7 +207,7 @@ elif pos_str.startswith(">"): return SeqFeature.AfterPosition(int(pos_str[1:])+offset) elif _re_within_position.match(pos_str): - s,e = pos_str[1:-1].split(".") + s, e = pos_str[1:-1].split(".") s = int(s) + offset e = int(e) + offset if offset == -1: @@ -284,7 +288,7 @@ #e.g. "123" s = loc_str e = loc_str - return SeqFeature.FeatureLocation(_pos(s,-1), _pos(e), strand) + return SeqFeature.FeatureLocation(_pos(s, -1), _pos(e), strand) def _split_compound_loc(compound_loc): @@ -367,7 +371,7 @@ self.handle = handle self._parser = parser - def next(self): + def __next__(self): """Return the next GenBank record from the handle. Will return None if we ran out of records. @@ -387,8 +391,18 @@ except StopIteration: return None + if sys.version_info[0] < 3: + def next(self): + """Deprecated Python 2 style alias for Python 3 style __next__ method.""" + import warnings + from Bio import BiopythonDeprecationWarning + warnings.warn("Please use next(my_iterator) instead of my_iterator.next(), " + "the .next() method is deprecated and will be removed in a " + "future release of Biopython.", BiopythonDeprecationWarning) + return self.__next__() + def __iter__(self): - return iter(self.next, None) + return iter(self.__next__, None) class ParserFailureError(Exception): @@ -509,7 +523,7 @@ """ # first replace all line feeds with spaces # Also, EMBL style accessions are split with ';' - accession = accession_string.replace("\n", " ").replace(";"," ") + accession = accession_string.replace("\n", " ").replace(";", " ") return [x.strip() for x in accession.split() if x.strip()] @@ -560,9 +574,7 @@ """Replace multiple spaces in the passed text with single spaces. """ # get rid of excessive spaces - text_parts = text.split(" ") - text_parts = filter(None, text_parts) - return ' '.join(text_parts) + return ' '.join(x for x in text.split(" ") if x) def _remove_spaces(self, text): """Remove all spaces from the passed text. @@ -672,7 +684,7 @@ self.data.annotations['wgs'] = content.split('-') def add_wgs_scafld(self, content): - self.data.annotations.setdefault('wgs_scafld',[]).append(content.split('-')) + self.data.annotations.setdefault('wgs_scafld', []).append(content.split('-')) def nid(self, content): self.data.annotations['nid'] = content @@ -708,7 +720,7 @@ "Project:28471" as part of this transition. """ content = content.replace("GenomeProject:", "Project:") - self.data.dbxrefs.extend([p for p in content.split() if p]) + self.data.dbxrefs.extend(p for p in content.split() if p) def dblink(self, content): """Store DBLINK cross references as dbxrefs in our record object. @@ -1041,9 +1053,9 @@ ref = None try: loc = _loc(part, self._expected_size, part_strand) - except ValueError, err: - print location_line - print part + except ValueError as err: + print(location_line) + print(part) raise err f = SeqFeature.SeqFeature(location=loc, ref=ref, location_operator=cur_feature.location_operator, @@ -1202,7 +1214,8 @@ seq_alphabet = IUPAC.ambiguous_dna else: seq_alphabet = IUPAC.ambiguous_rna - elif 'PROTEIN' in self._seq_type.upper(): + elif 'PROTEIN' in self._seq_type.upper() \ + or self._seq_type == "PRT": # PRT is used in EMBL-bank for patents seq_alphabet = IUPAC.protein # or extended protein? # work around ugly GenBank records which have circular or # linear but no indication of sequence type @@ -1224,7 +1237,7 @@ """ def __init__(self): _BaseGenBankConsumer.__init__(self) - import Record + from . import Record self.data = Record.Record() self._seq_data = [] @@ -1286,7 +1299,7 @@ self.data.keywords = self._split_keywords(content) def project(self, content): - self.data.projects.extend([p for p in content.split() if p]) + self.data.projects.extend(p for p in content.split() if p) def dblink(self, content): self.data.dblinks.append(content) @@ -1310,7 +1323,7 @@ if self._cur_reference is not None: self.data.references.append(self._cur_reference) - import Record + from . import Record self._cur_reference = Record.Reference() self._cur_reference.number = content @@ -1347,11 +1360,11 @@ def comment(self, content): self.data.comment += "\n".join(content) - def primary_ref_line(self,content): + def primary_ref_line(self, content): """Data for the PRIMARY line""" self.data.primary.append(content) - def primary(self,content): + def primary(self, content): pass def features_line(self, content): @@ -1372,7 +1385,7 @@ # first add on feature information if we've got any self._add_feature() - import Record + from . import Record self._cur_feature = Record.Feature() self._cur_feature.key = content @@ -1407,7 +1420,7 @@ /pseudo which would be passed in with the next key (since no other tags separate them in the file) """ - import Record + from . import Record for content in content_list: # the record parser keeps the /s -- add them if we don't have 'em if not content.startswith("/"): @@ -1467,11 +1480,10 @@ """Iterate over GenBank formatted entries as Record objects. >>> from Bio import GenBank - >>> handle = open("GenBank/NC_000932.gb") - >>> for record in GenBank.parse(handle): - ... print record.accession + >>> with open("GenBank/NC_000932.gb") as handle: + ... for record in GenBank.parse(handle): + ... print(record.accession) ['NC_000932'] - >>> handle.close() To get SeqRecord objects use Bio.SeqIO.parse(..., format="gb") instead. @@ -1483,24 +1495,23 @@ """Read a handle containing a single GenBank entry as a Record object. >>> from Bio import GenBank - >>> handle = open("GenBank/NC_000932.gb") - >>> record = GenBank.read(handle) - >>> print record.accession + >>> with open("GenBank/NC_000932.gb") as handle: + ... record = GenBank.read(handle) + ... print(record.accession) ['NC_000932'] - >>> handle.close() To get a SeqRecord object use Bio.SeqIO.read(..., format="gb") instead. """ iterator = parse(handle) try: - first = iterator.next() + first = next(iterator) except StopIteration: first = None if first is None: raise ValueError("No records found in handle") try: - second = iterator.next() + second = next(iterator) except StopIteration: second = None if second is not None: @@ -1512,22 +1523,22 @@ """Run the Bio.GenBank module's doctests.""" import doctest import os - if os.path.isdir(os.path.join("..","..","Tests")): - print "Running doctests..." + if os.path.isdir(os.path.join("..", "..", "Tests")): + print("Running doctests...") cur_dir = os.path.abspath(os.curdir) - os.chdir(os.path.join("..","..","Tests")) + os.chdir(os.path.join("..", "..", "Tests")) doctest.testmod() os.chdir(cur_dir) del cur_dir - print "Done" + print("Done") elif os.path.isdir(os.path.join("Tests")): - print "Running doctests..." + print("Running doctests...") cur_dir = os.path.abspath(os.curdir) os.chdir(os.path.join("Tests")) doctest.testmod() os.chdir(cur_dir) del cur_dir - print "Done" + print("Done") if __name__ == "__main__": _test() diff -Nru python-biopython-1.62/Bio/GenBank/utils.py python-biopython-1.63/Bio/GenBank/utils.py --- python-biopython-1.62/Bio/GenBank/utils.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/GenBank/utils.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Useful utilities for helping in parsing GenBank files. """ diff -Nru python-biopython-1.62/Bio/Geo/Record.py python-biopython-1.63/Bio/Geo/Record.py --- python-biopython-1.62/Bio/Geo/Record.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Geo/Record.py 2013-12-05 14:10:43.000000000 +0000 @@ -4,8 +4,7 @@ # license. Please see the LICENSE file that should have been included # as part of this package. -""" -Hold GEO data in a straightforward format. +"""Hold GEO data in a straightforward format. classes: o Record - All of the information in an GEO record. @@ -14,6 +13,8 @@ """ +from __future__ import print_function + class Record(object): """Hold GEO information in a format similar to the original record. @@ -37,55 +38,53 @@ def __str__( self ): output = '' - output = output + 'GEO Type: %s\n' % self.entity_type - output = output + 'GEO Id: %s\n' % self.entity_id - att_keys = self.entity_attributes.keys() - att_keys.sort() + output += 'GEO Type: %s\n' % self.entity_type + output += 'GEO Id: %s\n' % self.entity_id + att_keys = sorted(self.entity_attributes) for key in att_keys: - contents = self.entity_attributes[ key ] + contents = self.entity_attributes[key] if isinstance(contents, list): for item in contents: try: - output = output + '%s: %s\n' % ( key, item[ :40 ] ) - output = output + out_block( item[ 40: ] ) + output += '%s: %s\n' % ( key, item[:40]) + output += out_block(item[40:]) except: pass elif isinstance(contents, str): - output = output + '%s: %s\n' % ( key, contents[ :40 ] ) - output = output + out_block( contents[ 40: ] ) + output += '%s: %s\n' % (key, contents[:40]) + output += out_block(contents[40:]) else: - print contents - output = output + '%s: %s\n' % ( key, val[ :40 ] ) - output = output + out_block( val[ 40: ] ) - col_keys = self.col_defs.keys() - col_keys.sort() - output = output + 'Column Header Definitions\n' + print(contents) + output += '%s: %s\n' % (key, val[:40]) + output += out_block(val[40:]) + col_keys = sorted(self.col_defs.keys()) + output += 'Column Header Definitions\n' for key in col_keys: - val = self.col_defs[ key ] - output = output + ' %s: %s\n' % ( key, val[ :40 ] ) - output = output + out_block( val[ 40: ], ' ' ) + val = self.col_defs[key] + output += ' %s: %s\n' % (key, val[:40]) + output += out_block(val[40:], ' ') #May have to display VERY large tables, #so only show the first 20 lines of data - MAX_ROWS = 20+1 # include header in count + MAX_ROWS = 20 + 1 # include header in count for row in self.table_rows[0:MAX_ROWS]: - output = output + '%s: ' % self.table_rows.index( row ) + output += '%s: ' % self.table_rows.index(row) for col in row: - output = output + '%s\t' % col - output = output + '\n' + output += '%s\t' % col + output += '\n' if len(self.table_rows) > MAX_ROWS: - output = output + '...\n' + output += '...\n' row = self.table_rows[-1] - output = output + '%s: ' % self.table_rows.index( row ) + output += '%s: ' % self.table_rows.index(row) for col in row: - output = output + '%s\t' % col - output = output + '\n' + output += '%s\t' % col + output += '\n' return output def out_block( text, prefix = '' ): output = '' - for j in range( 0, len( text ), 80 ): - output = output + '%s%s\n' % ( prefix, text[ j: j + 80 ] ) - output = output + '\n' + for j in range(0, len(text), 80): + output += '%s%s\n' % (prefix, text[j:j+80]) + output += '\n' return output diff -Nru python-biopython-1.62/Bio/Geo/__init__.py python-biopython-1.63/Bio/Geo/__init__.py --- python-biopython-1.62/Bio/Geo/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Geo/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -9,7 +9,7 @@ http://www.ncbi.nlm.nih.gov/geo/ """ -import Record +from . import Record def _read_key_value(line): @@ -44,7 +44,7 @@ continue key, value = _read_key_value(line) if key in record.entity_attributes: - if type(record.entity_attributes[key])==list: + if isinstance(record.entity_attributes[key], list): record.entity_attributes[key].append(value) else: existing = record.entity_attributes[key] diff -Nru python-biopython-1.62/Bio/Graphics/BasicChromosome.py python-biopython-1.63/Bio/Graphics/BasicChromosome.py --- python-biopython-1.62/Bio/Graphics/BasicChromosome.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Graphics/BasicChromosome.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Draw representations of organism chromosomes with added information. These classes are meant to model the drawing of pictures of chromosomes. diff -Nru python-biopython-1.62/Bio/Graphics/ColorSpiral.py python-biopython-1.63/Bio/Graphics/ColorSpiral.py --- python-biopython-1.62/Bio/Graphics/ColorSpiral.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Graphics/ColorSpiral.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Generate RGB colours suitable for distinguishing categorical data. This module provides a class that implements a spiral 'path' through HSV @@ -189,5 +194,5 @@ colors = cs.get_colors(len(l)) dict = {} for item in l: - dict[item] = colors.next() + dict[item] = next(colors) return dict diff -Nru python-biopython-1.62/Bio/Graphics/Comparative.py python-biopython-1.63/Bio/Graphics/Comparative.py --- python-biopython-1.62/Bio/Graphics/Comparative.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Graphics/Comparative.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Plots to compare information between different sources. This file contains high level plots which are designed to be used to diff -Nru python-biopython-1.62/Bio/Graphics/DisplayRepresentation.py python-biopython-1.63/Bio/Graphics/DisplayRepresentation.py --- python-biopython-1.62/Bio/Graphics/DisplayRepresentation.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Graphics/DisplayRepresentation.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Represent information for graphical display. Classes in this module are designed to hold information in a way that diff -Nru python-biopython-1.62/Bio/Graphics/Distribution.py python-biopython-1.63/Bio/Graphics/Distribution.py --- python-biopython-1.62/Bio/Graphics/Distribution.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Graphics/Distribution.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Display information distributed across a Chromosome-like object. These classes are meant to show the distribution of some kind of information diff -Nru python-biopython-1.62/Bio/Graphics/GenomeDiagram/_AbstractDrawer.py python-biopython-1.63/Bio/Graphics/GenomeDiagram/_AbstractDrawer.py --- python-biopython-1.62/Bio/Graphics/GenomeDiagram/_AbstractDrawer.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Graphics/GenomeDiagram/_AbstractDrawer.py 2013-12-05 14:10:43.000000000 +0000 @@ -40,6 +40,10 @@ """ # ReportLab imports +from __future__ import print_function + +from Bio._py3k import range + from reportlab.lib import pagesizes from reportlab.lib import colors from reportlab.graphics.shapes import * @@ -190,7 +194,7 @@ strokecolor, color = _stroke_and_fill_colors(color, border) xy_list = [] - for (x,y) in list_of_points: + for (x, y) in list_of_points: xy_list.append(x) xy_list.append(y) @@ -300,7 +304,7 @@ newdata.append((start, graph_data[0][0]+(graph_data[1][0]-graph_data[0][0])/2., graph_data[0][1])) # add middle set - for index in xrange(1, len(graph_data)-1): + for index in range(1, len(graph_data)-1): lastxval, lastyval = graph_data[index-1] xval, yval = graph_data[index] nextxval, nextyval = graph_data[index+1] diff -Nru python-biopython-1.62/Bio/Graphics/GenomeDiagram/_CircularDrawer.py python-biopython-1.63/Bio/Graphics/GenomeDiagram/_CircularDrawer.py --- python-biopython-1.62/Bio/Graphics/GenomeDiagram/_CircularDrawer.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Graphics/GenomeDiagram/_CircularDrawer.py 2013-12-05 14:10:43.000000000 +0000 @@ -12,16 +12,20 @@ """CircularDrawer module for GenomeDiagram.""" # ReportLab imports +from __future__ import print_function + from reportlab.graphics.shapes import * from reportlab.lib import colors from reportlab.pdfbase import _fontdata from reportlab.graphics.shapes import ArcPath +from Bio._py3k import range + # GenomeDiagram imports -from _AbstractDrawer import AbstractDrawer, draw_polygon, intermediate_points -from _AbstractDrawer import _stroke_and_fill_colors -from _FeatureSet import FeatureSet -from _GraphSet import GraphSet +from ._AbstractDrawer import AbstractDrawer, draw_polygon, intermediate_points +from ._AbstractDrawer import _stroke_and_fill_colors +from ._FeatureSet import FeatureSet +from ._GraphSet import GraphSet from math import ceil, pi, cos, sin, asin @@ -437,7 +441,7 @@ # Default to placing the label the bottom of the feature # as drawn on the page, meaning feature end on left half label_angle = endangle + 0.5 * pi # Make text radial - sinval, cosval = endsin,endcos + sinval, cosval = endsin, endcos else: # Default to placing the label on the bottom of the feature, # which means the feature end when on right hand half @@ -492,8 +496,8 @@ if self.end < endB: endB = self.end - trackobjA = cross_link._trackA(self._parent.tracks.values()) - trackobjB = cross_link._trackB(self._parent.tracks.values()) + trackobjA = cross_link._trackA(list(self._parent.tracks.values())) + trackobjB = cross_link._trackB(list(self._parent.tracks.values())) assert trackobjA is not None assert trackobjB is not None if trackobjA == trackobjB: @@ -572,7 +576,7 @@ # Get graph data data_quartiles = graph.quartiles() - minval, maxval = data_quartiles[0],data_quartiles[4] + minval, maxval = data_quartiles[0], data_quartiles[4] btm, ctr, top = self.track_radii[self.current_track_level] trackheight = 0.5*(top-btm) datarange = maxval - minval @@ -627,7 +631,7 @@ # Set the number of pixels per unit for the data data_quartiles = graph.quartiles() - minval, maxval = data_quartiles[0],data_quartiles[4] + minval, maxval = data_quartiles[0], data_quartiles[4] btm, ctr, top = self.track_radii[self.current_track_level] trackheight = 0.5*(top-btm) datarange = maxval - minval @@ -686,7 +690,7 @@ # Get graph data data_quartiles = graph.quartiles() - minval, maxval = data_quartiles[0],data_quartiles[4] + minval, maxval = data_quartiles[0], data_quartiles[4] midval = (maxval + minval)/2. # mid is the value at the X-axis btm, ctr, top = self.track_radii[self.current_track_level] trackheight = (top-btm) @@ -820,7 +824,7 @@ for set in track.get_sets(): if set.__class__ is GraphSet: # Y-axis - for n in xrange(7): + for n in range(7): angle = n * 1.0471975511965976 if angle < startangle or endangle < angle: continue @@ -912,7 +916,7 @@ #if 0.5*pi < tickangle < 1.5*pi: # y1 -= label_offset labelgroup = Group(label) - labelgroup.transform = (1,0,0,1, x1, y1) + labelgroup.transform = (1, 0, 0, 1, x1, y1) else: labelgroup = None return tick, labelgroup @@ -978,7 +982,7 @@ theta, costheta, sintheta = self.canvas_angle(pos) if theta < startangle or endangle < theta: continue - x,y = self.xcenter+btm*sintheta, self.ycenter+btm*costheta # start text halfway up marker + x, y = self.xcenter+btm*sintheta, self.ycenter+btm*costheta # start text halfway up marker labelgroup = Group(label) labelangle = self.sweep*2*pi*(pos-self.start)/self.length - pi/2 if theta > pi: @@ -1061,12 +1065,12 @@ # Calculate trig values for angle and coordinates startcos, startsin = cos(startangle), sin(startangle) endcos, endsin = cos(endangle), sin(endangle) - x0,y0 = self.xcenter, self.ycenter # origin of the circle - x1,y1 = (x0+inner_radius*startsin, y0+inner_radius*startcos) - x2,y2 = (x0+inner_radius*endsin, y0+inner_radius*endcos) - x3,y3 = (x0+outer_radius*endsin, y0+outer_radius*endcos) - x4,y4 = (x0+outer_radius*startsin, y0+outer_radius*startcos) - return draw_polygon([(x1,y1),(x2,y2),(x3,y3),(x4,y4)], color, border) + x0, y0 = self.xcenter, self.ycenter # origin of the circle + x1, y1 = (x0+inner_radius*startsin, y0+inner_radius*startcos) + x2, y2 = (x0+inner_radius*endsin, y0+inner_radius*endcos) + x3, y3 = (x0+outer_radius*endsin, y0+outer_radius*endcos) + x4, y4 = (x0+outer_radius*startsin, y0+outer_radius*startcos) + return draw_polygon([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], color, border) def _draw_arc_line(self, path, start_radius, end_radius, start_angle, end_angle, move=False): @@ -1145,11 +1149,11 @@ inner_endcos, inner_endsin = cos(inner_endangle), sin(inner_endangle) outer_startcos, outer_startsin = cos(outer_startangle), sin(outer_startangle) outer_endcos, outer_endsin = cos(outer_endangle), sin(outer_endangle) - x1,y1 = (x0+inner_radius*inner_startsin, y0+inner_radius*inner_startcos) - x2,y2 = (x0+inner_radius*inner_endsin, y0+inner_radius*inner_endcos) - x3,y3 = (x0+outer_radius*outer_endsin, y0+outer_radius*outer_endcos) - x4,y4 = (x0+outer_radius*outer_startsin, y0+outer_radius*outer_startcos) - return draw_polygon([(x1,y1),(x2,y2),(x3,y3),(x4,y4)], color, border, + x1, y1 = (x0+inner_radius*inner_startsin, y0+inner_radius*inner_startcos) + x2, y2 = (x0+inner_radius*inner_endsin, y0+inner_radius*inner_endcos) + x3, y3 = (x0+outer_radius*outer_endsin, y0+outer_radius*outer_endcos) + x4, y4 = (x0+outer_radius*outer_startsin, y0+outer_radius*outer_startcos) + return draw_polygon([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], color, border, #default is mitre/miter which can stick out too much: strokeLineJoin=1, # 1=round ) @@ -1181,7 +1185,7 @@ shaft_inner_radius = inner_radius + corner_len shaft_outer_radius = outer_radius - corner_len - cornerangle_delta = max(0.0,min(abs(boxheight)*0.5*corner/middle_radius, abs(angle*0.5))) + cornerangle_delta = max(0.0, min(abs(boxheight)*0.5*corner/middle_radius, abs(angle*0.5))) if angle < 0: cornerangle_delta *= -1 # reverse it @@ -1271,7 +1275,7 @@ shaft_height = boxheight*shaft_height_ratio shaft_inner_radius = middle_radius - 0.5*shaft_height shaft_outer_radius = middle_radius + 0.5*shaft_height - headangle_delta = max(0.0,min(abs(boxheight)*head_length_ratio/middle_radius, abs(angle))) + headangle_delta = max(0.0, min(abs(boxheight)*head_length_ratio/middle_radius, abs(angle))) if angle < 0: headangle_delta *= -1 # reverse it if orientation=="right": @@ -1290,21 +1294,21 @@ startcos, startsin = cos(startangle), sin(startangle) headcos, headsin = cos(headangle), sin(headangle) endcos, endsin = cos(endangle), sin(endangle) - x0,y0 = self.xcenter, self.ycenter # origin of the circle + x0, y0 = self.xcenter, self.ycenter # origin of the circle if 0.5 >= abs(angle) and abs(headangle_delta) >= abs(angle): #If the angle is small, and the arrow is all head, #cheat and just use a triangle. if orientation=="right": - x1,y1 = (x0+inner_radius*startsin, y0+inner_radius*startcos) - x2,y2 = (x0+outer_radius*startsin, y0+outer_radius*startcos) - x3,y3 = (x0+middle_radius*endsin, y0+middle_radius*endcos) + x1, y1 = (x0+inner_radius*startsin, y0+inner_radius*startcos) + x2, y2 = (x0+outer_radius*startsin, y0+outer_radius*startcos) + x3, y3 = (x0+middle_radius*endsin, y0+middle_radius*endcos) else: - x1,y1 = (x0+inner_radius*endsin, y0+inner_radius*endcos) - x2,y2 = (x0+outer_radius*endsin, y0+outer_radius*endcos) - x3,y3 = (x0+middle_radius*startsin, y0+middle_radius*startcos) + x1, y1 = (x0+inner_radius*endsin, y0+inner_radius*endcos) + x2, y2 = (x0+outer_radius*endsin, y0+outer_radius*endcos) + x3, y3 = (x0+middle_radius*startsin, y0+middle_radius*startcos) #return draw_polygon([(x1,y1),(x2,y2),(x3,y3)], color, border, # stroke_line_join=1) - return Polygon([x1,y1,x2,y2,x3,y3], + return Polygon([x1, y1, x2, y2, x3, y3], strokeColor=border or color, fillColor=color, strokeLineJoin=1, # 1=round, not mitre! @@ -1425,7 +1429,7 @@ startcos, startsin = cos(startangle), sin(startangle) headcos, headsin = cos(headangle), sin(headangle) endcos, endsin = cos(endangle), sin(endangle) - x0,y0 = self.xcenter, self.ycenter # origin of the circle + x0, y0 = self.xcenter, self.ycenter # origin of the circle p = ArcPath(strokeColor=strokecolor, fillColor=color, diff -Nru python-biopython-1.62/Bio/Graphics/GenomeDiagram/_Colors.py python-biopython-1.63/Bio/Graphics/GenomeDiagram/_Colors.py --- python-biopython-1.62/Bio/Graphics/GenomeDiagram/_Colors.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Graphics/GenomeDiagram/_Colors.py 2013-12-05 14:10:43.000000000 +0000 @@ -21,6 +21,9 @@ """ # ReportLab imports +from __future__ import print_function +from Bio._py3k import basestring + from reportlab.lib import colors @@ -107,20 +110,20 @@ Reads information from a file containing color information and stores it internally """ - lines = open(filename, 'r').readlines() - for line in lines: - data = line.strip().split('\t') - try: - label = int(data[0]) - red, green, blue = int(data[1]), int(data[2]), int(data[3]) - if len(data) > 4: - comment = data[4] - else: - comment = "" - self._colorscheme[label] = (self.int255_color((red, green, blue)), - comment) - except: - raise ValueError("Expected INT \t INT \t INT \t INT \t string input") + with open(filename, 'r').readlines() as lines: + for line in lines: + data = line.strip().split('\t') + try: + label = int(data[0]) + red, green, blue = int(data[1]), int(data[2]), int(data[3]) + if len(data) > 4: + comment = data[4] + else: + comment = "" + self._colorscheme[label] = (self.int255_color((red, green, blue)), + comment) + except: + raise ValueError("Expected INT \t INT \t INT \t INT \t string input") def get_artemis_colorscheme(self): """ get_artemis_colorscheme(self) @@ -145,7 +148,7 @@ value = int(value) except ValueError: if value.count('.'): # dot-delimited - value = int(artemis_color.split('.',1)[0]) # Use only first integer + value = int(artemis_color.split('.', 1)[0]) # Use only first integer else: raise if value in self._artemis_colorscheme: @@ -209,12 +212,12 @@ # Test code gdct = ColorTranslator() - print gdct.float1_color((0.5, 0.5, 0.5)) - print gdct.int255_color((1, 75, 240)) - print gdct.artemis_color(7) - print gdct.scheme_color(2) - - print gdct.translate((0.5, 0.5, 0.5)) - print gdct.translate((1, 75, 240)) - print gdct.translate(7) - print gdct.translate(2) + print(gdct.float1_color((0.5, 0.5, 0.5))) + print(gdct.int255_color((1, 75, 240))) + print(gdct.artemis_color(7)) + print(gdct.scheme_color(2)) + + print(gdct.translate((0.5, 0.5, 0.5))) + print(gdct.translate((1, 75, 240))) + print(gdct.translate(7)) + print(gdct.translate(2)) diff -Nru python-biopython-1.62/Bio/Graphics/GenomeDiagram/_Diagram.py python-biopython-1.63/Bio/Graphics/GenomeDiagram/_Diagram.py --- python-biopython-1.62/Bio/Graphics/GenomeDiagram/_Diagram.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Graphics/GenomeDiagram/_Diagram.py 2013-12-05 14:10:43.000000000 +0000 @@ -36,9 +36,9 @@ renderPM=None # GenomeDiagram -from _LinearDrawer import LinearDrawer -from _CircularDrawer import CircularDrawer -from _Track import Track +from ._LinearDrawer import LinearDrawer +from ._CircularDrawer import CircularDrawer +from ._Track import Track from Bio.Graphics import _write @@ -315,7 +315,7 @@ #just uses a cStringIO or StringIO handle with the drawToFile method. #In order to put all our complicated file format specific code in one #place we'll just use a StringIO handle here: - from StringIO import StringIO + from Bio._py3k import StringIO handle = StringIO() self.write(handle, output, dpi) return handle.getvalue() @@ -335,8 +335,7 @@ if track_level not in self.tracks: # No track at that level self.tracks[track_level] = track # so just add it else: # Already a track there, so shunt all higher tracks up one - occupied_levels = self.get_levels() # Get list of occupied levels... - occupied_levels.sort() # ...sort it... + occupied_levels = sorted(self.get_levels()) # Get list of occupied levels... occupied_levels.reverse() # ...reverse it (highest first) for val in occupied_levels: # If track value >= that to be added @@ -360,8 +359,7 @@ if track_level not in self.tracks: # No track at that level self.tracks[track_level] = newtrack # so just add it else: # Already a track there, so shunt all higher tracks up one - occupied_levels = self.get_levels() # Get list of occupied levels... - occupied_levels.sort() # ...sort it... + occupied_levels = sorted(self.get_levels()) # Get list of occupied levels... occupied_levels.reverse() # ...reverse (highest first)... for val in occupied_levels: if val >= track_level: # Track value >= that to be added @@ -384,7 +382,7 @@ Returns a list of the tracks contained in the diagram """ - return self.tracks.values() + return list(self.tracks.values()) def move_track(self, from_level, to_level): """ move_track(self, from_level, to_level) @@ -425,9 +423,7 @@ Return a sorted list of levels occupied by tracks in the diagram """ - levels = self.tracks.keys() - levels.sort() - return levels + return sorted(self.tracks) def get_drawn_levels(self): """ get_drawn_levels(self) -> [int, int, ...] @@ -435,10 +431,7 @@ Return a sorted list of levels occupied by tracks that are not explicitly hidden """ - drawn_levels = [key for key in self.tracks.keys() if - not self.tracks[key].hide] # get list of shown levels - drawn_levels.sort() - return drawn_levels + return sorted(key for key in self.tracks if not self.tracks[key].hide) def range(self): """ range(self) -> (int, int) diff -Nru python-biopython-1.62/Bio/Graphics/GenomeDiagram/_Feature.py python-biopython-1.63/Bio/Graphics/GenomeDiagram/_Feature.py --- python-biopython-1.62/Bio/Graphics/GenomeDiagram/_Feature.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Graphics/GenomeDiagram/_Feature.py 2013-12-05 14:10:43.000000000 +0000 @@ -27,7 +27,7 @@ from reportlab.lib import colors # GenomeDiagram imports -from _Colors import ColorTranslator +from ._Colors import ColorTranslator class Feature(object): diff -Nru python-biopython-1.62/Bio/Graphics/GenomeDiagram/_FeatureSet.py python-biopython-1.63/Bio/Graphics/GenomeDiagram/_FeatureSet.py --- python-biopython-1.62/Bio/Graphics/GenomeDiagram/_FeatureSet.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Graphics/GenomeDiagram/_FeatureSet.py 2013-12-05 14:10:43.000000000 +0000 @@ -34,11 +34,13 @@ # IMPORTS # ReportLab +from __future__ import print_function + from reportlab.pdfbase import _fontdata from reportlab.lib import colors # GenomeDiagram -from _Feature import Feature +from ._Feature import Feature # Builtins import re @@ -181,7 +183,7 @@ """ # If no attribute or value specified, return all features if attribute is None or value is None: - return self.features.values() + return list(self.features.values()) # If no comparator is specified, return all features where the attribute # value matches that passed if comparator is None: @@ -210,7 +212,7 @@ Return a list of all ids for the feature set """ - return self.features.keys() + return list(self.features.keys()) def range(self): """ range(self) diff -Nru python-biopython-1.62/Bio/Graphics/GenomeDiagram/_Graph.py python-biopython-1.63/Bio/Graphics/GenomeDiagram/_Graph.py --- python-biopython-1.62/Bio/Graphics/GenomeDiagram/_Graph.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Graphics/GenomeDiagram/_Graph.py 2013-12-05 14:10:43.000000000 +0000 @@ -28,6 +28,8 @@ """ # ReportLab imports +from __future__ import print_function + from reportlab.lib import colors from math import sqrt @@ -146,7 +148,7 @@ Return data as a list of sorted (position, value) tuples """ data = [] - for xval in self.data.keys(): + for xval in self.data: yval = self.data[xval] data.append((xval, yval)) data.sort() @@ -168,8 +170,7 @@ Returns the (minimum, lowerQ, medianQ, upperQ, maximum) values as a tuple """ - data = self.data.values() - data.sort() + data = sorted(self.data.values()) datalen = len(data) return(data[0], data[datalen//4], data[datalen//2], data[3*datalen//4], data[-1]) @@ -180,8 +181,7 @@ Returns the range of the data, i.e. its start and end points on the genome as a (start, end) tuple """ - positions = self.data.keys() - positions.sort() + positions = sorted(self.data) # i.e. dict keys # Return first and last positions in graph #print len(self.data) return (positions[0], positions[-1]) @@ -191,7 +191,7 @@ Returns the mean value for the data points """ - data = self.data.values() + data = list(self.data.values()) sum = 0. for item in data: sum += float(item) @@ -202,7 +202,7 @@ Returns the sample standard deviation for the data """ - data = self.data.values() + data = list(self.data.values()) m = self.mean() runtotal = 0. for entry in data: @@ -238,10 +238,8 @@ high = index.stop if index.step is not None and index.step != 1: raise ValueError - positions = self.data.keys() - positions.sort() outlist = [] - for pos in positions: + for pos in sorted(self.data): if pos >= low and pos <=high: outlist.append((pos, self.data[pos])) return outlist diff -Nru python-biopython-1.62/Bio/Graphics/GenomeDiagram/_GraphSet.py python-biopython-1.63/Bio/Graphics/GenomeDiagram/_GraphSet.py --- python-biopython-1.62/Bio/Graphics/GenomeDiagram/_GraphSet.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Graphics/GenomeDiagram/_GraphSet.py 2013-12-05 14:10:43.000000000 +0000 @@ -30,9 +30,11 @@ """ # ReportLab imports +from __future__ import print_function + from reportlab.lib import colors -from _Graph import GraphData +from ._Graph import GraphData class GraphSet(object): @@ -141,16 +143,14 @@ Return a list of all graphs in the graph set, sorted by id (for reliable stacking...) """ - ids = self._graphs.keys() - ids.sort() - return [self._graphs[id] for id in ids] + return [self._graphs[id] for id in sorted(self._graphs)] def get_ids(self): """ get_ids(self) -> [int, int, ...] Return a list of all ids for the graph set """ - return self._graphs.keys() + return list(self._graphs.keys()) def range(self): """ range(self) -> (int, int) @@ -172,7 +172,7 @@ """ data = [] for graph in self._graphs.values(): - data += graph.data.values() + data += list(graph.data.values()) data.sort() datalen = len(data) return(data[0], data[datalen/4], data[datalen/2], @@ -235,4 +235,4 @@ gdgs.add_graph(testdata1, 'TestData 1') gdgs.add_graph(testdata2, 'TestData 2') - print gdgs + print(gdgs) diff -Nru python-biopython-1.62/Bio/Graphics/GenomeDiagram/_LinearDrawer.py python-biopython-1.63/Bio/Graphics/GenomeDiagram/_LinearDrawer.py --- python-biopython-1.62/Bio/Graphics/GenomeDiagram/_LinearDrawer.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Graphics/GenomeDiagram/_LinearDrawer.py 2013-12-05 14:10:43.000000000 +0000 @@ -27,15 +27,17 @@ """ # ReportLab imports +from __future__ import print_function + from reportlab.graphics.shapes import * from reportlab.lib import colors # GenomeDiagram imports -from _AbstractDrawer import AbstractDrawer, draw_box, draw_arrow -from _AbstractDrawer import draw_cut_corner_box, _stroke_and_fill_colors -from _AbstractDrawer import intermediate_points, angle2trig -from _FeatureSet import FeatureSet -from _GraphSet import GraphSet +from ._AbstractDrawer import AbstractDrawer, draw_box, draw_arrow +from ._AbstractDrawer import draw_cut_corner_box, _stroke_and_fill_colors +from ._AbstractDrawer import intermediate_points, angle2trig +from ._FeatureSet import FeatureSet +from ._GraphSet import GraphSet from math import ceil @@ -635,7 +637,7 @@ else: x2 = self.xlim box = draw_box((x1, tbtm), (x2, ttop), # Grey track bg - colors.Color(0.96,0.96, 0.96)) # is just a box + colors.Color(0.96, 0.96, 0.96)) # is just a box greytrack_bgs.append(box) if track.greytrack_labels: # If labels are required @@ -724,7 +726,7 @@ # several parts, and one or more of those parts may end up being # drawn on a non-existent fragment. So we check that the start and # end fragments do actually exist in terms of the drawing - allowed_fragments = self.fragment_limits.keys() + allowed_fragments = list(self.fragment_limits.keys()) if start_fragment in allowed_fragments and end_fragment in allowed_fragments: #print feature.name, feature.start, feature.end, start_offset, end_offset if start_fragment == end_fragment: # Feature is found on one fragment @@ -783,8 +785,8 @@ if self.end < endB: endB = self.end - trackobjA = cross_link._trackA(self._parent.tracks.values()) - trackobjB = cross_link._trackB(self._parent.tracks.values()) + trackobjA = cross_link._trackA(list(self._parent.tracks.values())) + trackobjB = cross_link._trackB(list(self._parent.tracks.values())) assert trackobjA is not None assert trackobjB is not None if trackobjA == trackobjB: @@ -818,7 +820,7 @@ strokecolor, fillcolor = _stroke_and_fill_colors(cross_link.color, cross_link.border) - allowed_fragments = self.fragment_limits.keys() + allowed_fragments = list(self.fragment_limits.keys()) start_fragmentA, start_offsetA = self.canvas_location(startA) end_fragmentA, end_offsetA = self.canvas_location(endA) @@ -895,14 +897,14 @@ if fragment < start_fragmentB: extra = [self.x0 + self.pagewidth, 0.5 * (yA + yB)] else: - extra = [self.x0 , 0.5 * (yA + yB)] + extra = [self.x0, 0.5 * (yA + yB)] else: if fragment < start_fragmentB: extra = [self.x0 + self.pagewidth, 0.7*yA + 0.3*yB, self.x0 + self.pagewidth, 0.3*yA + 0.7*yB] else: - extra = [self.x0 , 0.3*yA + 0.7*yB, - self.x0 , 0.7*yA + 0.3*yB] + extra = [self.x0, 0.3*yA + 0.7*yB, + self.x0, 0.7*yA + 0.3*yB] answer.append(Polygon([xAs, yA, xAe, yA] + extra, strokeColor=strokecolor, fillColor=fillcolor, @@ -915,14 +917,14 @@ if fragment < start_fragmentA: extra = [self.x0 + self.pagewidth, 0.5 * (yA + yB)] else: - extra = [self.x0 , 0.5 * (yA + yB)] + extra = [self.x0, 0.5 * (yA + yB)] else: if fragment < start_fragmentA: extra = [self.x0 + self.pagewidth, 0.3*yA + 0.7*yB, self.x0 + self.pagewidth, 0.7*yA + 0.3*yB] else: - extra = [self.x0 , 0.7*yA + 0.3*yB, - self.x0 , 0.3*yA + 0.7*yB] + extra = [self.x0, 0.7*yA + 0.3*yB, + self.x0, 0.3*yA + 0.7*yB] answer.append(Polygon([xBs, yB, xBe, yB] + extra, strokeColor=strokecolor, fillColor=fillcolor, @@ -989,15 +991,15 @@ ctr += self.fragment_lines[fragment][0] top += self.fragment_lines[fragment][0] except: # Only called if the method screws up big time - print "We've got a screw-up" - print self.start, self.end - print self.fragment_bases - print x0, x1 + print("We've got a screw-up") + print("%s %s" % (self.start, self.end)) + print(self.fragment_bases) + print("%r %r" % (x0, x1)) for locstart, locend in feature.locations: - print self.canvas_location(locstart) - print self.canvas_location(locend) - print 'FEATURE\n', feature - 1/0 + print(self.canvas_location(locstart)) + print(self.canvas_location(locend)) + print('FEATURE\n%s' % feature) + raise # Distribution dictionary for various ways of drawing the feature draw_methods = {'BOX': self._draw_sigil_box, @@ -1094,7 +1096,7 @@ # Get graph data data_quartiles = graph.quartiles() - minval, maxval = data_quartiles[0],data_quartiles[4] + minval, maxval = data_quartiles[0], data_quartiles[4] btm, ctr, top = self.track_offsets[self.current_track_level] trackheight = 0.5*(top-btm) datarange = maxval - minval @@ -1164,7 +1166,7 @@ # Get graph data and information data_quartiles = graph.quartiles() - minval, maxval = data_quartiles[0],data_quartiles[4] + minval, maxval = data_quartiles[0], data_quartiles[4] midval = (maxval + minval)/2. # mid is the value at the X-axis btm, ctr, top = self.track_offsets[self.current_track_level] trackheight = (top-btm) @@ -1242,7 +1244,7 @@ # Set the number of pixels per unit for the data data_quartiles = graph.quartiles() - minval, maxval = data_quartiles[0],data_quartiles[4] + minval, maxval = data_quartiles[0], data_quartiles[4] btm, ctr, top = self.track_offsets[self.current_track_level] trackheight = 0.5*(top-btm) datarange = maxval - minval @@ -1346,7 +1348,7 @@ else: y1 = bottom y2 = top - return draw_box((x1,y1), (x2,y2), **kwargs) + return draw_box((x1, y1), (x2, y2), **kwargs) def _draw_sigil_octo(self, bottom, center, top, x1, x2, strand, **kwargs): """Draw OCTO sigil, a box with the corners cut off.""" @@ -1359,7 +1361,7 @@ else: y1 = bottom y2 = top - return draw_cut_corner_box((x1,y1), (x2,y2), **kwargs) + return draw_cut_corner_box((x1, y1), (x2, y2), **kwargs) def _draw_sigil_jaggy(self, bottom, center, top, x1, x2, strand, color, border=None, **kwargs): @@ -1421,7 +1423,7 @@ y1 = bottom y2 = top orientation = "right" # backward compatibility - return draw_arrow((x1,y1), (x2,y2), orientation=orientation, **kwargs) + return draw_arrow((x1, y1), (x2, y2), orientation=orientation, **kwargs) def _draw_sigil_big_arrow(self, bottom, center, top, x1, x2, strand, **kwargs): """Draw BIGARROW sigil, like ARROW but straddles the axis.""" @@ -1429,4 +1431,4 @@ orientation = "left" else: orientation = "right" - return draw_arrow((x1,bottom), (x2,top), orientation=orientation, **kwargs) + return draw_arrow((x1, bottom), (x2, top), orientation=orientation, **kwargs) diff -Nru python-biopython-1.62/Bio/Graphics/GenomeDiagram/_Track.py python-biopython-1.63/Bio/Graphics/GenomeDiagram/_Track.py --- python-biopython-1.62/Bio/Graphics/GenomeDiagram/_Track.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Graphics/GenomeDiagram/_Track.py 2013-12-05 14:10:43.000000000 +0000 @@ -27,12 +27,15 @@ """ -# ReportLab imports +from __future__ import print_function + from reportlab.lib import colors +from Bio._py3k import range + # GenomeDiagram imports -from _FeatureSet import FeatureSet -from _GraphSet import GraphSet +from ._FeatureSet import FeatureSet +from ._GraphSet import GraphSet class Track(object): @@ -88,7 +91,7 @@ labels on the grey track o greytrack_font_rotation Int describing the angle through which to - rotate the grey track labels + rotate the grey track labels (Linear only) o greytrack_font_color colors.Color describing the color to draw the grey track labels @@ -166,7 +169,7 @@ labels on the grey track o greytrack_font_rotation Int describing the angle through which to - rotate the grey track labels + rotate the grey track labels (Linear only) o greytrack_font_color colors.Color describing the color to draw the grey track labels (overridden by @@ -301,14 +304,14 @@ Return the sets contained in this track """ - return self._sets.values() + return list(self._sets.values()) def get_ids(self): """ get_ids(self) -> [int, int, ...] Return the ids of all sets contained in this track """ - return self._sets.keys() + return list(self._sets.keys()) def range(self): """ range(self) -> (int, int) @@ -378,8 +381,8 @@ # test code from Bio import SeqIO - from _FeatureSet import FeatureSet - from _GraphSet import GraphSet + from ._FeatureSet import FeatureSet + from ._GraphSet import GraphSet from random import normalvariate genbank_entry = SeqIO.read('/data/genomes/Bacteria/Nanoarchaeum_equitans/NC_005213.gbk', 'gb') @@ -397,15 +400,15 @@ gdt.add_set(gdfs2) graphdata = [] - for pos in xrange(1, len(genbank_entry.seq), 1000): + for pos in range(1, len(genbank_entry.seq), 1000): graphdata.append((pos, normalvariate(0.5, 0.1))) gdgs = GraphSet(2, 'test data') gdgs.add_graph(graphdata, 'Test Data') gdt.add_set(gdgs) - print gdt.get_ids() + print(gdt.get_ids()) sets = gdt.get_sets() for set in sets: - print set + print(set) - print gdt.get_element_limits() + print(gdt.get_element_limits()) diff -Nru python-biopython-1.62/Bio/Graphics/GenomeDiagram/__init__.py python-biopython-1.63/Bio/Graphics/GenomeDiagram/__init__.py --- python-biopython-1.62/Bio/Graphics/GenomeDiagram/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Graphics/GenomeDiagram/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -12,11 +12,11 @@ #Local imports, to make these classes available directly under the #Bio.Graphics.GenomeDiagram namespace: -from _Diagram import Diagram -from _Track import Track -from _FeatureSet import FeatureSet -from _GraphSet import GraphSet -from _CrossLink import CrossLink +from ._Diagram import Diagram +from ._Track import Track +from ._FeatureSet import FeatureSet +from ._GraphSet import GraphSet +from ._CrossLink import CrossLink #Not (currently) made public, #from _Colors import ColorTranslator diff -Nru python-biopython-1.62/Bio/Graphics/__init__.py python-biopython-1.63/Bio/Graphics/__init__.py --- python-biopython-1.62/Bio/Graphics/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Graphics/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -61,7 +61,7 @@ #If output is not a string, then .upper() will trigger #an attribute error... drawmethod = formatdict[format.upper()] # select drawing method - except (KeyError,AttributeError): + except (KeyError, AttributeError): raise ValueError("Output format should be one of %s" % ", ".join(formatdict)) diff -Nru python-biopython-1.62/Bio/HMM/DynamicProgramming.py python-biopython-1.63/Bio/HMM/DynamicProgramming.py --- python-biopython-1.62/Bio/HMM/DynamicProgramming.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/HMM/DynamicProgramming.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,9 +1,16 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Dynamic Programming algorithms for general usage. This module contains classes which implement Dynamic Programming algorithms that can be used generally. """ +from Bio._py3k import range + class AbstractDPAlgorithms(object): """An abstract class to calculate forward and backward probabilities. @@ -137,7 +144,7 @@ # -- recursion # first loop over the training sequence backwards # Recursion step: (i = L - 1 ... 1) - all_indexes = range(len(self._seq.emissions) - 1) + all_indexes = list(range(len(self._seq.emissions) - 1)) all_indexes.reverse() for i in all_indexes: # now loop over the letters in the state path diff -Nru python-biopython-1.62/Bio/HMM/MarkovModel.py python-biopython-1.63/Bio/HMM/MarkovModel.py --- python-biopython-1.62/Bio/HMM/MarkovModel.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/HMM/MarkovModel.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Deal with representations of Markov Models. """ # standard modules @@ -8,7 +13,8 @@ #TODO - Take advantage of defaultdict once Python 2.4 is dead? #from collections import defaultdict -# biopython +from Bio._py3k import range + from Bio.Seq import MutableSeq @@ -191,7 +197,7 @@ self.initial_prob = copy.copy(initial_prob) # ensure that all referenced states are valid - for state in initial_prob.iterkeys(): + for state in initial_prob: assert state in self._state_alphabet.letters, \ "State %s was not found in the sequence alphabet" % state @@ -264,7 +270,7 @@ "allow_transition or allow_all_transitions first.") transitions_from = _calculate_from_transitions(self.transition_prob) - for from_state in transitions_from.keys(): + for from_state in transitions_from: freqs = _gen_random_array(len(transitions_from[from_state])) for to_state in transitions_from[from_state]: self.transition_prob[(from_state, to_state)] = freqs.pop() @@ -282,7 +288,7 @@ "Allow some or all emissions.") emissions = _calculate_emissions(self.emission_prob) - for state in emissions.iterkeys(): + for state in emissions: freqs = _gen_random_array(len(emissions[state])) for symbol in emissions[state]: self.emission_prob[(state, symbol)] = freqs.pop() @@ -617,7 +623,7 @@ # --- traceback traceback_seq = MutableSeq('', state_alphabet) - loop_seq = range(1, len(sequence)) + loop_seq = list(range(1, len(sequence))) loop_seq.reverse() # last_state is the last state in the most probable state sequence. diff -Nru python-biopython-1.62/Bio/HMM/Trainer.py python-biopython-1.63/Bio/HMM/Trainer.py --- python-biopython-1.62/Bio/HMM/Trainer.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/HMM/Trainer.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Provide trainers which estimate parameters based on training sequences. These should be used to 'train' a Markov Model prior to actually using @@ -16,7 +21,7 @@ import math # local stuff -from DynamicProgramming import ScaledDPAlgorithms +from .DynamicProgramming import ScaledDPAlgorithms class TrainingSequence(object): @@ -104,8 +109,7 @@ calculation. """ # get an ordered list of all items - all_ordered = counts.keys() - all_ordered.sort() + all_ordered = sorted(counts) ml_estimation = {} @@ -191,7 +195,7 @@ prev_log_likelihood = None num_iterations = 1 - while 1: + while True: transition_count = self._markov_model.get_blank_transitions() emission_count = self._markov_model.get_blank_emissions() diff -Nru python-biopython-1.62/Bio/HMM/Utilities.py python-biopython-1.63/Bio/HMM/Utilities.py --- python-biopython-1.62/Bio/HMM/Utilities.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/HMM/Utilities.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Generic functions which are useful for working with HMMs. This just collects general functions which you might like to use in @@ -5,6 +10,8 @@ """ +from __future__ import print_function + def pretty_print_prediction(emissions, real_state, predicted_state, emission_title = "Emissions", real_title = "Real State", @@ -33,19 +40,19 @@ cur_position = 0 # while we still have more than seq_length characters to print - while 1: + while True: if (cur_position + seq_length) < len(emissions): extension = seq_length else: extension = len(emissions) - cur_position - print "%s%s" % (emission_title, - emissions[cur_position:cur_position + seq_length]) - print "%s%s" % (real_title, - real_state[cur_position:cur_position + seq_length]) - print "%s%s\n" % (predicted_title, + print("%s%s" % (emission_title, + emissions[cur_position:cur_position + seq_length])) + print("%s%s" % (real_title, + real_state[cur_position:cur_position + seq_length])) + print("%s%s\n" % (predicted_title, predicted_state[cur_position: - cur_position + seq_length]) + cur_position + seq_length])) if (len(emissions) < (cur_position + seq_length)): break diff -Nru python-biopython-1.62/Bio/HotRand.py python-biopython-1.63/Bio/HotRand.py --- python-biopython-1.62/Bio/HotRand.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/HotRand.py 2013-12-05 14:10:43.000000000 +0000 @@ -8,19 +8,24 @@ support biosimulations that rely on random numbers. """ -import urllib +from __future__ import print_function + +#Importing these functions with leading underscore as not intended for reuse +from Bio._py3k import urlopen as _urlopen +from Bio._py3k import urlencode as _urlencode + from Bio import BiopythonDeprecationWarning import warnings warnings.warn("The HotRand module is deprecated and likely to be removed in a future release of Biopython. Please use an alternative RNG.", BiopythonDeprecationWarning) -def byte_concat( text ): +def byte_concat(text): val = 0 - numbytes = len( text ) - for i in range( 0, numbytes ): + numbytes = len(text) + for i in range(0, numbytes): val = val * 256 - val = val + ord( text[ i ] ) - + # Slice trick for Python 2 and 3 to get single char (byte) string: + val += ord(text[i:i+1]) return val @@ -29,46 +34,47 @@ def __init__( self ): # self.url = 'http://www.fourmilab.ch/cgi-bin/uncgi/Hotbits?num=5000&min=1&max=6&col=1' self.url = 'http://www.random.org/cgi-bin/randbyte?' - self.query = { 'nbytes': 128, 'fmt': 'h' } + self.query = {'nbytes': 128, 'fmt': 'h'} self.fill_hot_cache() - def fill_hot_cache( self ): - url = self.url + urllib.urlencode( self.query ) - fh = urllib.urlopen( url ) + def fill_hot_cache(self): + url = self.url + _urlencode(self.query) + fh = _urlopen(url) self.hot_cache = fh.read() fh.close() - def next_num( self, num_digits = 4 ): + def next_num(self, num_digits=4): cache = self.hot_cache - numbytes = num_digits / 2 - if( len( cache ) % numbytes != 0 ): - print 'len_cache is %d' % len( cache ) + # Must explicitly use integer division on python 3 + numbytes = num_digits // 2 + if len(cache) % numbytes != 0: + print('len_cache is %d' % len(cache)) raise ValueError - if( cache == '' ): + if cache == '': self.fill_hot_cache() cache = self.hot_cache - hexdigits = cache[ :numbytes ] - self.hot_cache = cache[ numbytes: ] - return byte_concat( hexdigits ) + hexdigits = cache[:numbytes] + self.hot_cache = cache[numbytes:] + return byte_concat(hexdigits) class HotRandom(object): - def __init__( self ): + def __init__(self): self.hot_cache = HotCache( ) - def hot_rand( self, high, low = 0 ): + def hot_rand(self, high, low=0): span = high - low val = self.hot_cache.next_num() - val = ( span * val ) >> 16 - val = val + low + val = (span * val) >> 16 + val += low return val -if( __name__ == '__main__' ): +if __name__ == '__main__': hot_random = HotRandom() - for j in range( 0, 130 ): - print hot_random.hot_rand( 25 ) - nums = [ '0000', 'abcd', '1234', '5555', '4321', 'aaaa', 'ffff' ] + for j in range(0, 130): + print(hot_random.hot_rand(25)) + nums = ['0000', 'abcd', '1234', '5555', '4321', 'aaaa', 'ffff'] for num in nums: - print hex_convert( num ) + print(int(num, 16)) diff -Nru python-biopython-1.62/Bio/Index.py python-biopython-1.63/Bio/Index.py --- python-biopython-1.62/Bio/Index.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Index.py 2013-12-05 14:10:43.000000000 +0000 @@ -16,9 +16,12 @@ """ import os import array -import cPickle import shelve +try: + import cPickle as pickle # Only available under Python 2 +except ImportError: + import pickle # Python 3 class _ShelveIndex(dict): """An index file wrapped around shelve. @@ -89,16 +92,16 @@ # Load the database if it exists if os.path.exists(indexname): - handle = open(indexname) - version = self._toobj(handle.readline().rstrip()) - if version != self.__version: - raise IOError("Version %s doesn't match my version %s" - % (version, self.__version)) - for line in handle: - key, value = line.split() - key, value = self._toobj(key), self._toobj(value) - self[key] = value - self.__changed = 0 + with open(indexname) as handle: + version = self._toobj(handle.readline().rstrip()) + if version != self.__version: + raise IOError("Version %s doesn't match my version %s" + % (version, self.__version)) + for line in handle: + key, value = line.split() + key, value = self._toobj(key), self._toobj(value) + self[key] = value + self.__changed = 0 def update(self, dict): self.__changed = 1 @@ -118,12 +121,11 @@ def __del__(self): if self.__changed: - handle = open(self._indexname, 'w') - handle.write("%s\n" % self._tostr(self.__version)) - for key, value in self.items(): - handle.write("%s %s\n" % - (self._tostr(key), self._tostr(value))) - handle.close() + with open(self._indexname, 'w') as handle: + handle.write("%s\n" % self._tostr(self.__version)) + for key, value in self.items(): + handle.write("%s %s\n" % + (self._tostr(key), self._tostr(value))) def _tostr(self, obj): # I need a representation of the object that's saveable to @@ -133,15 +135,13 @@ # the integers into strings and join them together with commas. # It's not the most efficient way of storing things, but it's # relatively fast. - s = cPickle.dumps(obj) + s = pickle.dumps(obj) intlist = array.array('b', s) - strlist = map(str, intlist) - return ','.join(strlist) + return ','.join(str(i) for i in intlist) def _toobj(self, str): - intlist = map(int, str.split(',')) + intlist = [int(i) for i in str.split(',')] intlist = array.array('b', intlist) - strlist = map(chr, intlist) - return cPickle.loads(''.join(strlist)) + return pickle.loads(''.join(chr(i) for i in intlist)) Index = _InMemoryIndex diff -Nru python-biopython-1.62/Bio/KDTree/KDTree.py python-biopython-1.63/Bio/KDTree/KDTree.py --- python-biopython-1.62/Bio/KDTree/KDTree.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/KDTree/KDTree.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,8 +3,7 @@ # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. -""" -KD tree data structure for searching N-dimensional vectors. +"""KD tree data structure for searching N-dimensional vectors. The KD tree data structure can be used for all kinds of searches that involve N-dimensional vectors, e.g. neighbor searches (find all points @@ -14,6 +13,8 @@ Otfried Schwarzkopf). Author: Thomas Hamelryck. """ +from __future__ import print_function + from numpy import sum, sqrt, array from numpy.random import random @@ -54,9 +55,9 @@ else: l2 = len(r) if l1 == l2: - print "Passed." + print("Passed.") else: - print "Not passed: %i != %i." % (l1, l2) + print("Not passed: %i != %i." % (l1, l2)) def _test(nr_points, dim, bucket_size, radius): @@ -87,9 +88,9 @@ if _dist(p, center) <= radius: l2 = l2 + 1 if l1 == l2: - print "Passed." + print("Passed.") else: - print "Not passed: %i != %i." % (l1, l2) + print("Not passed: %i != %i." % (l1, l2)) class KDTree(object): @@ -245,7 +246,7 @@ indices = kdtree.all_get_indices() radii = kdtree.all_get_radii() - print "Found %i point pairs within radius %f." % (len(indices), query_radius) + print("Found %i point pairs within radius %f." % (len(indices), query_radius)) # Do 10 individual queries @@ -261,4 +262,4 @@ radii = kdtree.get_radii() x, y, z = center - print "Found %i points in radius %f around center (%.2f, %.2f, %.2f)." % (len(indices), query_radius, x, y, z) + print("Found %i points in radius %f around center (%.2f, %.2f, %.2f)." % (len(indices), query_radius, x, y, z)) diff -Nru python-biopython-1.62/Bio/KDTree/__init__.py python-biopython-1.63/Bio/KDTree/__init__.py --- python-biopython-1.62/Bio/KDTree/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/KDTree/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """ The KD tree data structure can be used for all kinds of searches that involve N-dimensional vectors. For example, neighbor searches (find all points @@ -7,4 +12,4 @@ Otfried Schwarzkopf). """ -from KDTree import KDTree +from .KDTree import KDTree diff -Nru python-biopython-1.62/Bio/KEGG/Compound/__init__.py python-biopython-1.63/Bio/KEGG/Compound/__init__.py --- python-biopython-1.62/Bio/KEGG/Compound/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/KEGG/Compound/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -4,8 +4,7 @@ # license. Please see the LICENSE file that should have been included # as part of this package. -""" -This module provides code to work with the KEGG Ligand/Compound database. +"""Code to work with the KEGG Ligand/Compound database. Functions: parse - Returns an iterator giving Record objects. @@ -15,18 +14,20 @@ """ # other Biopython stuff +from __future__ import print_function + from Bio.KEGG import _write_kegg from Bio.KEGG import _wrap_kegg # Set up line wrapping rules (see Bio.KEGG._wrap_kegg) name_wrap = [0, "", - (" ","$",1,1), - ("-","$",1,1)] + (" ", "$", 1, 1), + ("-", "$", 1, 1)] id_wrap = lambda indent : [indent, "", - (" ","",1,0)] + (" ", "", 1, 0)] struct_wrap = lambda indent : [indent, "", - (" ","",1,1)] + (" ", "", 1, 1)] class Record(object): @@ -132,10 +133,10 @@ example, using one of the example KEGG files in the Biopython test suite, - >>> handle = open("KEGG/compound.sample") - >>> for record in parse(handle): - ... print record.entry, record.name[0] - ... + >>> with open("KEGG/compound.sample") as handle: + ... for record in parse(handle): + ... print("%s %s" % (record.entry, record.name[0])) + ... C00023 Iron C00017 Protein C00099 beta-Alanine @@ -144,7 +145,6 @@ C00348 Undecaprenyl phosphate C00349 2-Methyl-3-oxopropanoate C01386 NH2Mec - >>> handle.close() """ record = Record() @@ -174,7 +174,7 @@ record.enzyme.append(enzyme) elif keyword=="PATHWAY ": if data[:5]=='PATH:': - path, map, name = data.split(None,2) + path, map, name = data.split(None, 2) pathway = (path[:-1], map, name) record.pathway.append(pathway) else: @@ -204,3 +204,4 @@ if __name__ == "__main__": from Bio._utils import run_doctest run_doctest() + diff -Nru python-biopython-1.62/Bio/KEGG/Enzyme/__init__.py python-biopython-1.63/Bio/KEGG/Enzyme/__init__.py --- python-biopython-1.62/Bio/KEGG/Enzyme/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/KEGG/Enzyme/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -4,8 +4,7 @@ # license. Please see the LICENSE file that should have been included # as part of this package. -""" -This module provides code to work with the KEGG Enzyme database. +"""Code to work with the KEGG Enzyme database. Functions: parse - Returns an iterator giving Record objects. @@ -14,23 +13,25 @@ Record -- Holds the information from a KEGG Enzyme record. """ +from __future__ import print_function + from Bio.KEGG import _write_kegg from Bio.KEGG import _wrap_kegg # Set up line wrapping rules (see Bio.KEGG._wrap_kegg) rxn_wrap = [0, "", - (" + ","",1,1), - (" = ","",1,1), - (" ","$",1,1), - ("-","$",1,1)] + (" + ", "", 1, 1), + (" = ", "", 1, 1), + (" ", "$", 1, 1), + ("-", "$", 1, 1)] name_wrap = [0, "", - (" ","$",1,1), - ("-","$",1,1)] + (" ", "$", 1, 1), + ("-", "$", 1, 1)] id_wrap = lambda indent : [indent, "", - (" ","",1,0)] + (" ", "", 1, 0)] struct_wrap = lambda indent : [indent, "", - (" ","",1,1)] + (" ", "", 1, 1)] class Record(object): @@ -202,10 +203,10 @@ example, using one of the example KEGG files in the Biopython test suite, - >>> handle = open("KEGG/enzyme.sample") - >>> for record in parse(handle): - ... print record.entry, record.name[0] - ... + >>> with open("KEGG/enzyme.sample") as handle: + ... for record in parse(handle): + ... print("%s %s" % (record.entry, record.name[0])) + ... 1.1.1.1 Alcohol dehydrogenase 1.1.1.62 Estradiol 17beta-dehydrogenase 1.1.1.68 Transferred to EC 1.7.99.5 @@ -214,7 +215,6 @@ 2.4.1.68 Glycoprotein 6-alpha-L-fucosyltransferase 3.1.1.6 Acetylesterase 2.7.2.1 Acetate kinase - >>> handle.close() """ record = Record() @@ -263,7 +263,7 @@ record.effector.append(data.strip(";")) elif keyword=="GENES ": if data[3:5]==': ': - key, values = data.split(":",1) + key, values = data.split(":", 1) values = [value.split("(")[0] for value in values.split()] row = (key, values) record.genes.append(row) @@ -281,11 +281,11 @@ record.name.append(data.strip(";")) elif keyword=="PATHWAY ": if data[:5]=='PATH:': - _, map_num, name = data.split(None,2) + _, map_num, name = data.split(None, 2) pathway = ('PATH', map_num, name) record.pathway.append(pathway) else: - ec_num, name = data.split(None,1) + ec_num, name = data.split(None, 1) pathway = 'PATH', ec_num, name record.pathway.append(pathway) elif keyword=="PRODUCT ": @@ -313,3 +313,4 @@ if __name__ == "__main__": from Bio._utils import run_doctest run_doctest() + diff -Nru python-biopython-1.62/Bio/KEGG/__init__.py python-biopython-1.63/Bio/KEGG/__init__.py --- python-biopython-1.62/Bio/KEGG/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/KEGG/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -37,7 +37,7 @@ indent = " " * wrap_rule[0] connect = wrap_rule[1] rules = wrap_rule[2:] - while 1: + while True: if len(line) <= max_width: wrapped_line = wrapped_line + line s = s + wrapped_line diff -Nru python-biopython-1.62/Bio/LogisticRegression.py python-biopython-1.63/Bio/LogisticRegression.py --- python-biopython-1.62/Bio/LogisticRegression.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/LogisticRegression.py 2013-12-05 14:10:43.000000000 +0000 @@ -2,8 +2,7 @@ # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. -""" -This module provides code for doing logistic regressions. +"""Code for doing logistic regressions. Classes: @@ -16,6 +15,8 @@ classify Classify an observation into a class. """ +from __future__ import print_function + import numpy import numpy.linalg @@ -99,8 +100,8 @@ Xtyp = numpy.dot(Xt, y-p) # Calculate the first derivative. XtWX = numpy.dot(numpy.dot(Xt, W), X) # Calculate the second derivative. #u, s, vt = singular_value_decomposition(XtWX) - #print "U", u - #print "S", s + #print("U %s" % u) + #print("S %s" % s) delta = numpy.linalg.solve(XtWX, Xtyp) if numpy.fabs(stepsize-1.0) > 0.001: delta = delta * stepsize @@ -109,7 +110,7 @@ raise RuntimeError("Didn't converge.") lr = LogisticRegression() - lr.beta = map(float, beta) # Convert back to regular array. + lr.beta = [float(x) for x in beta] # Convert back to regular array. return lr diff -Nru python-biopython-1.62/Bio/MarkovModel.py python-biopython-1.63/Bio/MarkovModel.py --- python-biopython-1.62/Bio/MarkovModel.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/MarkovModel.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """ This is an implementation of a state-emitting MarkovModel. I am using terminology similar to Manning and Schutze. @@ -61,8 +66,8 @@ self.p_emission = p_emission def __str__(self): - import StringIO - handle = StringIO.StringIO() + from Bio._py3k import StringIO + handle = StringIO() save(self, handle) handle.seek(0) return handle.read() @@ -100,14 +105,14 @@ line = _readline_and_check_start(handle, "TRANSITION:") for i in range(len(states)): line = _readline_and_check_start(handle, " %s:" % states[i]) - mm.p_transition[i,:] = map(float, line.split()[1:]) + mm.p_transition[i,:] = [float(v) for v in line.split()[1:]] # Load the emission. mm.p_emission = numpy.zeros((N, M)) line = _readline_and_check_start(handle, "EMISSION:") for i in range(len(states)): line = _readline_and_check_start(handle, " %s:" % states[i]) - mm.p_emission[i,:] = map(float, line.split()[1:]) + mm.p_emission[i,:] = [float(v) for v in line.split()[1:]] return mm @@ -123,12 +128,10 @@ w(" %s: %g\n" % (mm.states[i], mm.p_initial[i])) w("TRANSITION:\n") for i in range(len(mm.p_transition)): - x = map(str, mm.p_transition[i]) - w(" %s: %s\n" % (mm.states[i], ' '.join(x))) + w(" %s: %s\n" % (mm.states[i], ' '.join(str(x) for x in mm.p_transition[i]))) w("EMISSION:\n") for i in range(len(mm.p_emission)): - x = map(str, mm.p_emission[i]) - w(" %s: %s\n" % (mm.states[i], ' '.join(x))) + w(" %s: %s\n" % (mm.states[i], ' '.join(str(x) for x in mm.p_emission[i]))) # XXX allow them to specify starting points @@ -164,12 +167,12 @@ raise ValueError("pseudo_initial not shape len(states)") if pseudo_transition is not None: pseudo_transition = numpy.asarray(pseudo_transition) - if pseudo_transition.shape != (N,N): + if pseudo_transition.shape != (N, N): raise ValueError("pseudo_transition not shape " + "len(states) X len(states)") if pseudo_emission is not None: pseudo_emission = numpy.asarray(pseudo_emission) - if pseudo_emission.shape != (N,M): + if pseudo_emission.shape != (N, M): raise ValueError("pseudo_emission not shape " + "len(states) X len(alphabet)") @@ -182,7 +185,7 @@ training_outputs.append([indexes[x] for x in outputs]) # Do some sanity checking on the outputs. - lengths = map(len, training_outputs) + lengths = [len(x) for x in training_outputs] if min(lengths) == 0: raise ValueError("I got training data with outputs of length 0") @@ -209,17 +212,18 @@ p_initial = _copy_and_check(p_initial, (N,)) if p_transition is None: - p_transition = _random_norm((N,N)) + p_transition = _random_norm((N, N)) else: - p_transition = _copy_and_check(p_transition, (N,N)) + p_transition = _copy_and_check(p_transition, (N, N)) if p_emission is None: - p_emission = _random_norm((N,M)) + p_emission = _random_norm((N, M)) else: - p_emission = _copy_and_check(p_emission, (N,M)) + p_emission = _copy_and_check(p_emission, (N, M)) # Do all the calculations in log space to avoid underflows. - lp_initial, lp_transition, lp_emission = map( - numpy.log, (p_initial, p_transition, p_emission)) + lp_initial = numpy.log(p_initial) + lp_transition = numpy.log(p_transition) + lp_emission = numpy.log(p_emission) if pseudo_initial is not None: lpseudo_initial = numpy.log(pseudo_initial) else: @@ -255,7 +259,7 @@ % MAX_ITERATIONS) # Return everything back in normal space. - return map(numpy.exp, (lp_initial, lp_transition, lp_emission)) + return [numpy.exp(x) for x in (lp_initial, lp_transition, lp_emission)] def _baum_welch_one(N, M, outputs, @@ -286,13 +290,13 @@ bmat[j][t+1] lp_traverse[i][j] = lp # Normalize the probability for this time step. - lp_arc[:,:,t] = lp_traverse - _logsum(lp_traverse) + lp_arc[:,:, t] = lp_traverse - _logsum(lp_traverse) # Sum of all the transitions out of state i at time t. lp_arcout_t = numpy.zeros((N, T)) for t in range(T): for i in range(N): - lp_arcout_t[i][t] = _logsum(lp_arc[i,:,t]) + lp_arcout_t[i][t] = _logsum(lp_arc[i,:, t]) # Sum of all the transitions out of state i. lp_arcout = numpy.zeros(N) @@ -300,7 +304,7 @@ lp_arcout[i] = _logsum(lp_arcout_t[i,:]) # UPDATE P_INITIAL. - lp_initial = lp_arcout_t[:,0] + lp_initial = lp_arcout_t[:, 0] if lpseudo_initial is not None: lp_initial = _logvecadd(lp_initial, lpseudo_initial) lp_initial = lp_initial - _logsum(lp_initial) @@ -310,7 +314,7 @@ # transitions out of i. for i in range(N): for j in range(N): - lp_transition[i][j] = _logsum(lp_arc[i,j,:]) - lp_arcout[i] + lp_transition[i][j] = _logsum(lp_arc[i, j,:]) - lp_arcout[i] if lpseudo_transition is not None: lp_transition[i] = _logvecadd(lp_transition[i], lpseudo_transition) lp_transition[i] = lp_transition[i] - _logsum(lp_transition[i]) @@ -323,7 +327,7 @@ for t in range(T): k = outputs[t] for j in range(N): - ksum[k] = logaddexp(ksum[k], lp_arc[i,j,t]) + ksum[k] = logaddexp(ksum[k], lp_arc[i, j, t]) ksum = ksum - _logsum(ksum) # Normalize if lpseudo_emission is not None: ksum = _logvecadd(ksum, lpseudo_emission[i]) @@ -337,7 +341,7 @@ # the _forward algorithm and calculate from the clean one, but # that may be more expensive than overshooting the training by one # step. - return _logsum(fmat[:,T]) + return _logsum(fmat[:, T]) def _forward(N, T, lp_initial, lp_transition, lp_emission, outputs): @@ -348,7 +352,7 @@ matrix = numpy.zeros((N, T+1)) # Initialize the first column to be the initial values. - matrix[:,0] = lp_initial + matrix[:, 0] = lp_initial for t in range(1, T+1): k = outputs[t-1] for j in range(N): @@ -408,12 +412,12 @@ raise ValueError("pseudo_initial not shape len(states)") if pseudo_transition is not None: pseudo_transition = numpy.asarray(pseudo_transition) - if pseudo_transition.shape != (N,N): + if pseudo_transition.shape != (N, N): raise ValueError("pseudo_transition not shape " + "len(states) X len(states)") if pseudo_emission is not None: pseudo_emission = numpy.asarray(pseudo_emission) - if pseudo_emission.shape != (N,M): + if pseudo_emission.shape != (N, M): raise ValueError("pseudo_emission not shape " + "len(states) X len(alphabet)") @@ -449,7 +453,7 @@ # p_transition is the probability that a state leads to the next # one. C(i,j)/C(i) where i and j are states. - p_transition = numpy.zeros((N,N)) + p_transition = numpy.zeros((N, N)) if pseudo_transition: p_transition = p_transition + pseudo_transition for states in training_states: @@ -461,10 +465,10 @@ # p_emission is the probability of an output given a state. # C(s,o)|C(s) where o is an output and s is a state. - p_emission = numpy.zeros((N,M)) + p_emission = numpy.zeros((N, M)) if pseudo_emission: p_emission = p_emission + pseudo_emission - p_emission = numpy.ones((N,M)) + p_emission = numpy.ones((N, M)) for outputs, states in zip(training_outputs, training_states): for o, s in zip(outputs, states): p_emission[s, o] += 1 @@ -485,10 +489,9 @@ # _viterbi does calculations in log space. Add a tiny bit to the # matrices so that the logs will not break. - x = mm.p_initial + VERY_SMALL_NUMBER - y = mm.p_transition + VERY_SMALL_NUMBER - z = mm.p_emission + VERY_SMALL_NUMBER - lp_initial, lp_transition, lp_emission = map(numpy.log, (x, y, z)) + lp_initial = numpy.log(mm.p_initial + VERY_SMALL_NUMBER) + lp_transition = numpy.log(mm.p_transition + VERY_SMALL_NUMBER) + lp_emission = numpy.log(mm.p_emission + VERY_SMALL_NUMBER) # Change output into a list of indexes into the alphabet. indexes = itemindex(mm.alphabet) output = [indexes[x] for x in output] @@ -514,16 +517,16 @@ # Store the best scores. scores = numpy.zeros((N, T)) - scores[:,0] = lp_initial + lp_emission[:,output[0]] + scores[:, 0] = lp_initial + lp_emission[:, output[0]] for t in range(1, T): k = output[t] for j in range(N): # Find the most likely place it came from. - i_scores = scores[:,t-1] + \ - lp_transition[:,j] + \ - lp_emission[j,k] + i_scores = scores[:, t-1] + \ + lp_transition[:, j] + \ + lp_emission[j, k] indexes = _argmaxes(i_scores) - scores[j,t] = i_scores[indexes[0]] + scores[j, t] = i_scores[indexes[0]] backtrace[j][t] = indexes # Do the backtrace. First, find a good place to start. Then, @@ -533,7 +536,7 @@ # it by keeping our own stack. in_process = [] # list of (t, states, score) results = [] # return values. list of (states, score) - indexes = _argmaxes(scores[:,T-1]) # pick the first place + indexes = _argmaxes(scores[:, T-1]) # pick the first place for i in indexes: in_process.append((T-1, [i], scores[i][T-1])) while in_process: diff -Nru python-biopython-1.62/Bio/MaxEntropy.py python-biopython-1.63/Bio/MaxEntropy.py --- python-biopython-1.62/Bio/MaxEntropy.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/MaxEntropy.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,15 +3,16 @@ # license. Please see the LICENSE file that should have been included # as part of this package. -""" -Maximum Entropy code. +"""Maximum Entropy code. -Uses Improved Iterative Scaling: -XXX ref +Uses Improved Iterative Scaling. +""" +#TODO Define terminology -# XXX need to define terminology +from __future__ import print_function +from functools import reduce -""" +from Bio._py3k import map import numpy @@ -123,7 +124,7 @@ expects = [] for feature in features: sum = 0.0 - for (i, j), f in feature.iteritems(): + for (i, j), f in feature.items(): sum += p_yx[i][j] * f expects.append(sum/len(xs)) return expects @@ -141,7 +142,7 @@ # Calculate log P(y, x). assert len(features) == len(alphas) for feature, alpha in zip(features, alphas): - for (x, y), f in feature.iteritems(): + for (x, y), f in feature.items(): prob_yx[x][y] += alpha * f # Take an exponent to get P(y, x) prob_yx = numpy.exp(prob_yx) @@ -171,7 +172,7 @@ # f#(x, y) = SUM_i feature(x, y) f_sharp = numpy.zeros((N, nclasses)) for feature in features: - for (i, j), f in feature.iteritems(): + for (i, j), f in feature.items(): f_sharp[i][j] += f return f_sharp @@ -184,7 +185,7 @@ iters = 0 while iters < max_newton_iterations: # iterate for Newton's method f_newton = df_newton = 0.0 # evaluate the function and derivative - for (i, j), f in feature.iteritems(): + for (i, j), f in feature.items(): prod = prob_yx[i][j] * f * numpy.exp(delta * f_sharp[i][j]) f_newton += prod df_newton += prod * f_sharp[i][j] @@ -334,4 +335,4 @@ xe=train(xcar, ycar, user_functions) for xv, yv in zip(xcar, ycar): xc=classify(xe, xv) - print 'Pred:', xv, 'gives', xc, 'y is', yv + print('Pred: %s gives %s y is %s' % (xv, xc, yv)) diff -Nru python-biopython-1.62/Bio/Medline/__init__.py python-biopython-1.63/Bio/Medline/__init__.py --- python-biopython-1.62/Bio/Medline/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Medline/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,8 +3,7 @@ # license. Please see the LICENSE file that should have been included # as part of this package. -""" -This module provides code to work with Medline. +"""Code to work with Medline from the NCBI. Classes: Record A dictionary holding Medline data. @@ -15,6 +14,8 @@ """ +from __future__ import print_function + class Record(dict): """A dictionary holding information from a Medline record. All data are stored under the mnemonic appearing in the Medline @@ -105,12 +106,13 @@ Typical usage: from Bio import Medline - handle = open("mymedlinefile") - records = Medline.parse(handle) - for record in record: - print record['TI'] + with open("mymedlinefile") as handle: + records = Medline.parse(handle) + for record in record: + print(record['TI']) """ + #TODO - Turn that into a working doctest # These keys point to string values textkeys = ("ID", "PMID", "SO", "RF", "NI", "JC", "TA", "IS", "CY", "TT", "CA", "IP", "VI", "DP", "YR", "PG", "LID", "DA", "LR", "OWN", @@ -135,7 +137,7 @@ record[key] = [] record[key].append(line[6:]) try: - line = handle.next() + line = next(handle) except StopIteration: finished = True else: @@ -160,10 +162,11 @@ Typical usage: from Bio import Medline - handle = open("mymedlinefile") - record = Medline.read(handle) - print record['TI'] + with open("mymedlinefile") as handle: + record = Medline.read(handle) + print(record['TI']) """ + #TODO - Turn that into a working doctest records = parse(handle) - return records.next() + return next(records) diff -Nru python-biopython-1.62/Bio/Motif/Applications/_AlignAce.py python-biopython-1.63/Bio/Motif/Applications/_AlignAce.py --- python-biopython-1.62/Bio/Motif/Applications/_AlignAce.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Motif/Applications/_AlignAce.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,144 +0,0 @@ -# Copyright 2003-2009 by Bartek Wilczynski. All rights reserved. -# Revisions copyright 2009 by Peter Cock. -# This code is part of the Biopython distribution and governed by its -# license. Please see the LICENSE file that should have been included -# as part of this package. -"""This module provides code to work with the standalone version of AlignACE, -for motif search in DNA sequences. - -AlignACE homepage: - -http://arep.med.harvard.edu/mrnadata/mrnasoft.html - -AlignACE Citations: - -Computational identification of cis-regulatory elements associated with -groups of functionally related genes in Saccharomyces cerevisiae, -Hughes, JD, Estep, PW, Tavazoie S, & GM Church, Journal of Molecular -Biology 2000 Mar 10;296(5):1205-14. - -Finding DNA Regulatory Motifs within Unaligned Non-Coding Sequences -Clustered by Whole-Genome mRNA Quantitation, -Roth, FR, Hughes, JD, Estep, PE & GM Church, Nature Biotechnology -1998 Oct;16(10):939-45. - -""" -from Bio.Application import AbstractCommandline, _Option, _Argument - -import warnings -from Bio import BiopythonDeprecationWarning - - -class AlignAceCommandline(AbstractCommandline): - """Create a commandline for the AlignAce program (DEPRECATED). - - Example: - - >>> from Bio.Motif.Applications import AlignAceCommandline - >>> in_file = "sequences.fasta" - >>> alignace_cline = AlignAceCommandline(infile=in_file, gcback=0.55) - >>> print alignace_cline - AlignACE -i sequences.fasta -gcback 0.55 - - You would typically run the command line with alignace_cline() or via - the Python subprocess module, as described in the Biopython tutorial. - """ - def __init__(self, cmd="AlignACE", **kwargs): - warnings.warn("""The AlignACE application wrapper is deprecated and - is likely to be removed in a future release of Biopython, - since an up to date version of the AlignACE software - cannot be obtained anymore. If you have a copy of - AlignACE 4, please consider contacting the Biopython - developers.""", BiopythonDeprecationWarning) - self.parameters = \ - [ - _Option(["-i", "infile"], - "Input Sequence file in FASTA format.", - checker_function=lambda x: isinstance(x, str), - equate=False, - filename=True), - - _Option(["-numcols", "numcols"], - "Number of columns to align", - equate=False, - checker_function=lambda x: isinstance(x, int)), - - _Option(["-expect", "expect"], - "number of sites expected in model", - equate=False, - checker_function=lambda x: isinstance(x, int)), - - _Option(["-gcback", "gcback"], - "background fractional GC content of input sequence", - equate=False, - checker_function=lambda x: isinstance(x, float)), - - _Option(["-minpass", "minpass"], - "minimum number of non-improved passes in phase 1", - equate=False, - checker_function=lambda x: isinstance(x, int)), - - _Option(["-seed", "seed"], - "set seed for random number generator (time)", - equate=False, - checker_function=lambda x: isinstance(x, int)), - - _Option(["-undersample", "undersample"], - "possible sites / (expect * numcols * seedings)", - equate=False, - checker_function=lambda x: isinstance(x, int)), - - _Option(["-oversample", "oversample"], - "1/undersample", - equate=False, - checker_function=lambda x: isinstance(x, int)), - ] - AbstractCommandline.__init__(self, cmd, **kwargs) - - -class CompareAceCommandline(AbstractCommandline): - """Create a commandline for the CompareAce program (DEPRECATED). - - Example: - - >>> from Bio.Motif.Applications import CompareAceCommandline - >>> m1_file = "sequences1.fasta" - >>> m2_file = "sequences2.fasta" - >>> compareace_cline = CompareAceCommandline(motif1=m1_file, motif2=m2_file) - >>> print compareace_cline - CompareACE sequences1.fasta sequences2.fasta - - You would typically run the command line with compareace_cline() or via - the Python subprocess module, as described in the Biopython tutorial. - """ - def __init__(self, cmd="CompareACE", **kwargs): - warnings.warn("""The CompareACE application wrapper is deprecated and - is likely to be removed in a future release of Biopython, - since an up to date version of the AlignACE software - cannot be obtained anymore. If you have a copy of - AlignACE 4, please consider contacting the Biopython - developers.""", BiopythonDeprecationWarning) - self.parameters = \ - [ - _Argument(["motif1"], - "name of file containing motif 1", - checker_function=lambda x: isinstance(x, str), - filename=True), - _Argument(["motif2"], - "name of file containing motif 2", - checker_function=lambda x: isinstance(x, str), - filename=True), - ] - AbstractCommandline.__init__(self, cmd, **kwargs) - - -def _test(): - """Run the module's doctests (PRIVATE).""" - print "Running AlignAce doctests..." - import doctest - doctest.testmod() - print "Done" - - -if __name__ == "__main__": - _test() diff -Nru python-biopython-1.62/Bio/Motif/Applications/_XXmotif.py python-biopython-1.63/Bio/Motif/Applications/_XXmotif.py --- python-biopython-1.62/Bio/Motif/Applications/_XXmotif.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Motif/Applications/_XXmotif.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,182 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2012 by Christian Brueffer. All rights reserved. -# -# This code is part of the Biopython distribution and governed by its -# license. Please see the LICENSE file that should have been included -# as part of this package. -"""Command line wrapper for the motif finding program XXmotif.""" - -import os -from Bio.Application import AbstractCommandline, _Option, _Switch, _Argument - - -class XXmotifCommandline(AbstractCommandline): - """Command line wrapper for XXmotif. - - http://xxmotif.genzentrum.lmu.de/ - - Example: - - >>> from Bio.Motif.Applications import XXmotifCommandline - >>> out_dir = "results" - >>> in_file = "sequences.fasta" - >>> xxmotif_cline = XXmotifCommandline(outdir=out_dir, seqfile=in_file, revcomp=True) - >>> print xxmotif_cline - XXmotif results sequences.fasta --revcomp - - You would typically run the command line with xxmotif_cline() or via - the Python subprocess module, as described in the Biopython tutorial. - - Citations: - - Luehr S, Hartmann H, and Söding J. The XXmotif web server for eXhaustive, - weight matriX-based motif discovery in nucleotide sequences, - Nucleic Acids Res. 40: W104-W109 (2012). - - Hartmann H, Guthoehrlein EW, Siebert M., Luehr S, and Söding J. P-value - based regulatory motif discovery using positional weight matrices - (to be published) - - Last checked against version: 1.3 - """ - - def __init__(self, cmd="XXmotif", **kwargs): - # order of parameters is the same as in XXmotif --help - _valid_alphabet = set("ACGTNX") - - self.parameters = \ - [ - _Argument(["outdir", "OUTDIR"], - "output directory for all results", - filename = True, - is_required = True, - # XXmotif currently does not accept spaces in the outdir name - checker_function = lambda x: " " not in x), - _Argument(["seqfile", "SEQFILE"], - "file name with sequences from positive set in FASTA format", - filename = True, - is_required = True, - # XXmotif currently only accepts a pure filename - checker_function = lambda x: os.path.split(x)[0] == ""), - - # Options - _Option(["--negSet", "negSet", "negset", "NEGSET"], - "sequence set which has to be used as a reference set", - filename = True, - equate = False), - _Switch(["--zoops", "zoops", "ZOOPS"], - "use zero-or-one occurrence per sequence model (DEFAULT)"), - _Switch(["--mops", "mops", "MOPS"], - "use multiple occurrence per sequence model"), - _Switch(["--oops", "oops", "OOPS"], - "use one occurrence per sequence model"), - _Switch(["--revcomp", "revcomp", "REVCOMP"], - "search in reverse complement of sequences as well (DEFAULT: NO)"), - _Option(["--background-model-order", "background-model-order", "BACKGROUND-MODEL-ORDER"], - "order of background distribution (DEFAULT: 2, 8(--negset) )", - checker_function = lambda x: isinstance(x, int), - equate = False), - _Option(["--pseudo", "pseudo", "PSEUDO"], - "percentage of pseudocounts used (DEFAULT: 10)", - checker_function = lambda x: isinstance(x, int), - equate = False), - _Option(["-g", "--gaps", "gaps", "GAPS"], - "maximum number of gaps used for start seeds [0-3] (DEFAULT: 0)", - checker_function = lambda x: x in [0-3], - equate = False), - _Option(["--type", "type", "TYPE"], - "defines what kind of start seeds are used (DEFAULT: ALL)" - "possible types: ALL, FIVEMERS, PALINDROME, TANDEM, NOPALINDROME, NOTANDEM", - checker_function = lambda x: x in ["ALL", "all", - "FIVEMERS", "fivemers", - "PALINDROME", "palindrome", - "TANDEM", "tandem", - "NOPALINDROME", "nopalindrome", - "NOTANDEM", "notandem"], - equate = False), - _Option(["--merge-motif-threshold", "merge-motif-threshold", "MERGE-MOTIF-THRESHOLD"], - "defines the similarity threshold for merging motifs (DEFAULT: HIGH)" - "possible modes: LOW, MEDIUM, HIGH", - checker_function = lambda x: x in ["LOW", "low", - "MEDIUM", "medium", - "HIGH", "high"], - equate = False), - _Switch(["--no-pwm-length-optimization", "no-pwm-length-optimization", "NO-PWM-LENGTH-OPTIMIZATION"], - "do not optimize length during iterations (runtime advantages)"), - _Option(["--max-match-positions", "max-match-positions", "MAX-MATCH-POSITIONS"], - "max number of positions per motif (DEFAULT: 17, higher values will lead to very long runtimes)", - checker_function = lambda x: isinstance(x, int), - equate = False), - _Switch(["--batch", "batch", "BATCH"], - "suppress progress bars (reduce output size for batch jobs)"), - _Option(["--maxPosSetSize", "maxPosSetSize", "maxpossetsize", "MAXPOSSETSIZE"], - "maximum number of sequences from the positive set used [DEFAULT: all]", - checker_function = lambda x: isinstance(x, int), - equate = False), - # does not make sense in biopython - #_Switch(["--help", "help", "HELP"], - # "print this help page"), - _Option(["--trackedMotif", "trackedMotif", "trackedmotif", "TRACKEDMOTIF"], - "inspect extensions and refinement of a given seed (DEFAULT: not used)", - checker_function = lambda x: any((c in _valid_alphabet) for c in x), - equate = False), - - # Using conservation information - _Option(["--format", "format", "FORMAT"], - "defines what kind of format the input sequences have (DEFAULT: FASTA)", - checker_function = lambda x: x in ["FASTA", "fasta", - "MFASTA", "mfasta"], - equate = False), - _Option(["--maxMultipleSequences", "maxMultipleSequences", "maxmultiplesequences", "MAXMULTIPLESEQUENCES"], - "maximum number of sequences used in an alignment [DEFAULT: all]", - checker_function = lambda x: isinstance(x, int), - equate = False), - - # Using localization information - _Switch(["--localization", "localization", "LOCALIZATION"], - "use localization information to calculate combined P-values" - "(sequences should have all the same length)"), - _Option(["--downstream", "downstream", "DOWNSTREAM"], - "number of residues in positive set downstream of anchor point (DEFAULT: 0)", - checker_function = lambda x: isinstance(x, int), - equate = False), - - # Start with self defined motif - _Option(["-m", "--startMotif", "startMotif", "startmotif", "STARTMOTIF"], - "Start motif (IUPAC characters)", - checker_function = lambda x: any((c in _valid_alphabet) for c in x), - equate = False), - _Option(["-p", "--profileFile", "profileFile", "profilefile", "PROFILEFILE"], - "profile file", - filename = True, - equate = False), - _Option(["--startRegion", "startRegion", "startregion", "STARTREGION"], - "expected start position for motif occurrences relative to anchor point (--localization)", - checker_function = lambda x: isinstance(x, int), - equate = False), - _Option(["--endRegion", "endRegion", "endregion", "ENDREGION"], - "expected end position for motif occurrences relative to anchor point (--localization)", - checker_function = lambda x: isinstance(x, int), - equate = False), - - # XXmotif wrapper options - _Switch(["--XXmasker", "masker"], - "mask the input sequences for homology, repeats and low complexity regions"), - _Switch(["--XXmasker-pos", "maskerpos"], - "mask only the positive set for homology, repeats and low complexity regions"), - _Switch(["--no-graphics", "nographics"], - "run XXmotif without graphical output"), - ] - AbstractCommandline.__init__(self, cmd, **kwargs) - - -def _test(): - """Run the module's doctests (PRIVATE).""" - print "Running XXmotif doctests..." - import doctest - doctest.testmod() - print "Done" - - -if __name__ == "__main__": - _test() diff -Nru python-biopython-1.62/Bio/Motif/Applications/__init__.py python-biopython-1.63/Bio/Motif/Applications/__init__.py --- python-biopython-1.62/Bio/Motif/Applications/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Motif/Applications/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,9 +1,9 @@ # Copyright 2009 by Bartek Wilczynski. All rights reserved. -# Revisions copyright 2009 by Peter Cock. +# Revisions copyright 2009-2013 by Peter Cock. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. -"""Motif command line tool wrappers.""" -from _AlignAce import AlignAceCommandline -from _AlignAce import CompareAceCommandline -from _XXmotif import XXmotifCommandline +"""Motif command line tool wrappers (DEPRECATED, see Bio.motifs instead).""" +from Bio.motifs.applications import AlignAceCommandline +from Bio.motifs.applications import CompareAceCommandline +from Bio.motifs.applications import XXmotifCommandline diff -Nru python-biopython-1.62/Bio/Motif/Parsers/AlignAce.py python-biopython-1.63/Bio/Motif/Parsers/AlignAce.py --- python-biopython-1.62/Bio/Motif/Parsers/AlignAce.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Motif/Parsers/AlignAce.py 2013-12-05 14:10:43.000000000 +0000 @@ -21,8 +21,8 @@ def read(handle): """read(handle)""" record = Record() - record.ver = handle.next() - record.cmd_line = handle.next() + record.ver = next(handle) + record.cmd_line = next(handle) for line in handle: if line.strip() == "": pass @@ -44,7 +44,7 @@ elif line[:3]=="MAP": record.current_motif.score = float(line.split()[-1]) elif len(line.split("\t"))==4: - seq = Seq(line.split("\t")[0],IUPAC.unambiguous_dna) + seq = Seq(line.split("\t")[0], IUPAC.unambiguous_dna) record.current_motif.add_instance(seq) elif "*" in line: record.current_motif.set_mask(line.strip("\n\c")) diff -Nru python-biopython-1.62/Bio/Motif/Parsers/MAST.py python-biopython-1.63/Bio/Motif/Parsers/MAST.py --- python-biopython-1.62/Bio/Motif/Parsers/MAST.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Motif/Parsers/MAST.py 2013-12-05 14:10:43.000000000 +0000 @@ -59,10 +59,10 @@ for line in handle: if line.startswith('DATABASE AND MOTIFS'): break - line = handle.next() + line = next(handle) if not line.startswith('****'): raise ValueError("Line does not start with '****':\n%s" % line) - line = handle.next() + line = next(handle) if not 'DATABASE' in line: raise ValueError("Line does not contain 'DATABASE':\n%s" % line) words = line.strip().split() @@ -74,7 +74,7 @@ for line in handle: if 'MOTIF WIDTH' in line: break - line = handle.next() + line = next(handle) if not '----' in line: raise ValueError("Line does not contain '----':\n%s" % line) for line in handle: @@ -96,7 +96,7 @@ for line in handle: if line.startswith('SEQUENCE NAME'): break - line = handle.next() + line = next(handle) if not line.startswith('---'): raise ValueError("Line does not start with '---':\n%s" % line) for line in handle: @@ -105,7 +105,7 @@ else: sequence, description_evalue_length = line.split(None, 1) record.sequences.append(sequence) - line = handle.next() + line = next(handle) if not line.startswith('****'): raise ValueError("Line does not start with '****':\n%s" % line) @@ -117,7 +117,7 @@ for line in handle: if line.startswith('SEQUENCE NAME'): break - line = handle.next() + line = next(handle) if not line.startswith('---'): raise ValueError("Line does not start with '---':\n%s" % line) for line in handle: @@ -129,7 +129,7 @@ else: sequence, pvalue, diagram = line.split() record.diagrams[sequence] = diagram - line = handle.next() + line = next(handle) if not line.startswith('****'): raise ValueError("Line does not start with '****':\n%s" % line) diff -Nru python-biopython-1.62/Bio/Motif/Parsers/MEME.py python-biopython-1.63/Bio/Motif/Parsers/MEME.py --- python-biopython-1.62/Bio/Motif/Parsers/MEME.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Motif/Parsers/MEME.py 2013-12-05 14:10:43.000000000 +0000 @@ -4,6 +4,8 @@ # license. Please see the LICENSE file that should have been included # as part of this package. +from __future__ import print_function + from Bio.Alphabet import IUPAC from Bio import Seq import re @@ -18,12 +20,12 @@ Example: - >>> f = open("meme.output.txt") >>> from Bio.Motif.Parsers import MEME - >>> record = MEME.read(f) + >>> with open("meme.output.txt") as f: + ... record = MEME.read(f) >>> for motif in record.motifs: ... for instance in motif.instances: - ... print instance.motif_name, instance.sequence_name, instance.strand, instance.pvalue + ... print(instance.motif_name, instance.sequence_name, instance.strand, instance.pvalue) """ record = MEMERecord() @@ -45,7 +47,7 @@ __read_motif_sequences(motif, handle, 'revcomp' in record.command) __skip_unused_lines(handle) try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError('Unexpected end of stream: Expected to find new motif, or the summary of motifs') if line.startswith("SUMMARY OF MOTIFS"): @@ -72,20 +74,20 @@ self.evalue = 0.0 def _numoccurrences (self, number): - if type(number) == int: + if isinstance(number, int): self.num_occurrences = number else: number = int(number) self.num_occurrences = number - def get_instance_by_name (self,name): + def get_instance_by_name (self, name): for i in self.instances: if i.sequence_name == name: return i return None def add_instance_from_values (self, name = 'default', pvalue = 1, sequence = 'ATA', start = 0, strand = '+'): - inst = MEMEInstance(sequence,self.alphabet) + inst = MEMEInstance(sequence, self.alphabet) inst._pvalue(pvalue) inst._seqname(name) inst._start(start) @@ -99,7 +101,7 @@ self.add_instance(inst) def _evalue (self, evalue): - if type(evalue) == float: + if isinstance(evalue, float): self.evalue = evalue else: evalue = float(evalue) @@ -125,11 +127,11 @@ def _motifname (self, name): self.motif_name = name - def _start (self,start): + def _start (self, start): start = int(start) self.start = start - def _pvalue (self,pval): + def _pvalue (self, pval): pval = float(pval) self.pvalue = pval @@ -187,31 +189,31 @@ else: raise ValueError("Unexpected end of stream: 'TRAINING SET' not found.") try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError("Unexpected end of stream: Expected to find line starting with '****'") if not line.startswith('****'): raise ValueError("Line does not start with '****':\n%s" % line) try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError("Unexpected end of stream: Expected to find line starting with 'DATAFILE'") if not line.startswith('DATAFILE'): raise ValueError("Line does not start with 'DATAFILE':\n%s" % line) line = line.strip() - line = line.replace('DATAFILE= ','') + line = line.replace('DATAFILE= ', '') record.datafile = line def __read_alphabet(record, handle): try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError("Unexpected end of stream: Expected to find line starting with 'ALPHABET'") if not line.startswith('ALPHABET'): raise ValueError("Line does not start with 'ALPHABET':\n%s" % line) line = line.strip() - line = line.replace('ALPHABET= ','') + line = line.replace('ALPHABET= ', '') if line == 'ACGT': al = IUPAC.unambiguous_dna else: @@ -221,13 +223,13 @@ def __read_sequence_names(record, handle): try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError("Unexpected end of stream: Expected to find line starting with 'Sequence name'") if not line.startswith('Sequence name'): raise ValueError("Line does not start with 'Sequence name':\n%s" % line) try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError("Unexpected end of stream: Expected to find line starting with '----'") if not line.startswith('----'): @@ -251,7 +253,7 @@ else: raise ValueError("Unexpected end of stream: Expected to find line starting with 'command'") line = line.strip() - line = line.replace('command: ','') + line = line.replace('command: ', '') record.command = line @@ -279,19 +281,19 @@ def __read_motif_sequences(motif, handle, rv): try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError('Unexpected end of stream: Failed to find motif sequences') if not line.startswith('---'): raise ValueError("Line does not start with '---':\n%s" % line) try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError("Unexpected end of stream: Expected to find line starting with 'Sequence name'") if not line.startswith('Sequence name'): raise ValueError("Line does not start with 'Sequence name':\n%s" % line) try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError('Unexpected end of stream: Failed to find motif sequences') if not line.startswith('---'): @@ -338,13 +340,13 @@ else: raise ValueError("Unexpected end of stream: Expected to find line starting with 'Time'") try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError('Unexpected end of stream: Expected to find blank line') if line.strip(): raise ValueError("Expected blank line, but got:\n%s" % line) try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError("Unexpected end of stream: Expected to find line starting with '***'") if not line.startswith('***'): @@ -356,3 +358,4 @@ raise ValueError("Unexpected end of stream: Expected to find line starting with '***'") if not line.startswith('***'): raise ValueError("Line does not start with '***':\n%s" % line) + diff -Nru python-biopython-1.62/Bio/Motif/Thresholds.py python-biopython-1.63/Bio/Motif/Thresholds.py --- python-biopython-1.62/Bio/Motif/Thresholds.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Motif/Thresholds.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,7 +5,7 @@ # as part of this package. """Approximate calculation of appropriate thresholds for motif finding """ -import math,random +import math, random class ScoreDistribution(object): """ Class representing approximate score distribution for a given motif. @@ -15,8 +15,8 @@ thresholds for motif occurences. """ def __init__(self,motif,precision=10**3): - self.min_score=min(0.0,motif.min_score()) - self.interval=max(0.0,motif.max_score())-self.min_score + self.min_score=min(0.0, motif.min_score()) + self.interval=max(0.0, motif.max_score())-self.min_score self.n_points=precision*motif.length self.step=self.interval/(self.n_points-1) self.mo_density=[0.0]*self.n_points @@ -24,27 +24,27 @@ self.bg_density=[0.0]*self.n_points self.bg_density[-self._index_diff(self.min_score)]=1.0 self.ic=motif.ic() - for lo,mo in zip(motif.log_odds(),motif.pwm()): - self.modify(lo,mo,motif.background) + for lo, mo in zip(motif.log_odds(), motif.pwm()): + self.modify(lo, mo, motif.background) def _index_diff(self,x,y=0.0): return int((x-y+0.5*self.step)//self.step) - def _add(self,i,j): - return max(0,min(self.n_points-1,i+j)) + def _add(self, i, j): + return max(0, min(self.n_points-1, i+j)) - def modify(self,scores,mo_probs,bg_probs): + def modify(self, scores, mo_probs, bg_probs): mo_new=[0.0]*self.n_points bg_new=[0.0]*self.n_points - for k, v in scores.iteritems(): + for k, v in scores.items(): d=self._index_diff(v) for i in range(self.n_points): - mo_new[self._add(i,d)]+=self.mo_density[i]*mo_probs[k] - bg_new[self._add(i,d)]+=self.bg_density[i]*bg_probs[k] + mo_new[self._add(i, d)]+=self.mo_density[i]*mo_probs[k] + bg_new[self._add(i, d)]+=self.bg_density[i]*bg_probs[k] self.mo_density=mo_new self.bg_density=bg_new - def threshold_fpr(self,fpr): + def threshold_fpr(self, fpr): """ Approximate the log-odds threshold which makes the type I error (false positive rate). """ @@ -55,7 +55,7 @@ prob+=self.bg_density[i] return self.min_score+i*self.step - def threshold_fnr(self,fnr): + def threshold_fnr(self, fnr): """ Approximate the log-odds threshold which makes the type II error (false negative rate). """ @@ -78,7 +78,7 @@ fpr+=self.bg_density[i] fnr-=self.mo_density[i] if return_rate: - return self.min_score+i*self.step,fpr + return self.min_score+i*self.step, fpr else: return self.min_score+i*self.step diff -Nru python-biopython-1.62/Bio/Motif/_Motif.py python-biopython-1.63/Bio/Motif/_Motif.py --- python-biopython-1.62/Bio/Motif/_Motif.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Motif/_Motif.py 2013-12-05 14:10:43.000000000 +0000 @@ -4,10 +4,15 @@ # as part of this package. """Implementation of sequence motifs (PRIVATE). """ + +from __future__ import print_function + +from Bio._py3k import range + from Bio.Seq import Seq from Bio.SubsMat import FreqTable from Bio.Alphabet import IUPAC -import math,random +import math, random class Motif(object): """ @@ -32,19 +37,20 @@ self.name="" def _check_length(self, len): + # TODO - Change parameter name (len clashes with built in function)? if self.length is None: self.length = len elif self.length != len: - print "len",self.length,self.instances, len - raise ValueError("You can't change the length of the motif") + raise ValueError("You can't change the length of the motif " + "%r %r %r" % (self.length, self.instances, len)) - def _check_alphabet(self,alphabet): + def _check_alphabet(self, alphabet): if self.alphabet is None: self.alphabet=alphabet elif self.alphabet != alphabet: raise ValueError("Wrong Alphabet") - def add_instance(self,instance): + def add_instance(self, instance): """ adds new instance to the motif """ @@ -63,7 +69,7 @@ self._log_odds_is_current = False - def set_mask(self,mask): + def set_mask(self, mask): """ sets the mask for the motif @@ -90,7 +96,7 @@ return self._pwm #we need to compute new pwm self._pwm = [] - for i in xrange(self.length): + for i in range(self.length): dict = {} #filling the dict with 0's for letter in self.alphabet.letters: @@ -110,7 +116,7 @@ dict[seq[i]]+=1 except KeyError: #we need to ignore non-alphabet letters pass - self._pwm.append(FreqTable.FreqTable(dict,FreqTable.COUNT,self.alphabet)) + self._pwm.append(FreqTable.FreqTable(dict, FreqTable.COUNT, self.alphabet)) self._pwm_is_current=1 return self._pwm @@ -124,10 +130,10 @@ #we need to compute new pwm self._log_odds = [] pwm=self.pwm(laplace) - for i in xrange(self.length): + for i in range(self.length): d = {} for a in self.alphabet.letters: - d[a]=math.log(pwm[i][a]/self.background[a],2) + d[a]=math.log(pwm[i][a]/self.background[a], 2) self._log_odds.append(d) self._log_odds_is_current=1 return self._log_odds @@ -141,7 +147,7 @@ res+=2 for a in self.alphabet.letters: if pwm[i][a]!=0: - res+=pwm[i][a]*math.log(pwm[i][a],2) + res+=pwm[i][a]*math.log(pwm[i][a], 2) return res def exp_score(self,st_dev=False): @@ -156,25 +162,25 @@ ex2=0.0 for a in self.alphabet.letters: if pwm[i][a]!=0: - ex1+=pwm[i][a]*(math.log(pwm[i][a],2)-math.log(self.background[a],2)) - ex2+=pwm[i][a]*(math.log(pwm[i][a],2)-math.log(self.background[a],2))**2 + ex1+=pwm[i][a]*(math.log(pwm[i][a], 2)-math.log(self.background[a], 2)) + ex2+=pwm[i][a]*(math.log(pwm[i][a], 2)-math.log(self.background[a], 2))**2 exs+=ex1 var+=ex2-ex1**2 if st_dev: - return exs,math.sqrt(var) + return exs, math.sqrt(var) else: return exs - def search_instances(self,sequence): + def search_instances(self, sequence): """ a generator function, returning found positions of instances of the motif in a given sequence """ if not self.has_instances: raise ValueError ("This motif has no instances") - for pos in xrange(0,len(sequence)-self.length+1): + for pos in range(0, len(sequence)-self.length+1): for instance in self.instances: if instance.tostring()==sequence[pos:pos+self.length].tostring(): - yield(pos,instance) + yield(pos, instance) break # no other instance will fit (we don't want to return multiple hits) def score_hit(self,sequence,position,normalized=0,masked=0): @@ -183,7 +189,7 @@ """ lo=self.log_odds() score = 0.0 - for pos in xrange(self.length): + for pos in range(self.length): a = sequence[position+pos] if not masked or self.mask[pos]: try: @@ -205,14 +211,14 @@ rc = self.reverse_complement() sequence=sequence.tostring().upper() - for pos in xrange(0,len(sequence)-self.length+1): - score = self.score_hit(sequence,pos,normalized,masked) + for pos in range(0, len(sequence)-self.length+1): + score = self.score_hit(sequence, pos, normalized, masked) if score > threshold: - yield (pos,score) + yield (pos, score) if both: - rev_score = rc.score_hit(sequence,pos,normalized,masked) + rev_score = rc.score_hit(sequence, pos, normalized, masked) if rev_score > threshold: - yield (-pos,rev_score) + yield (-pos, rev_score) def dist_pearson(self, motif, masked = 0): """ @@ -225,26 +231,26 @@ raise ValueError("Cannot compare motifs with different alphabets") max_p=-2 - for offset in range(-self.length+1,motif.length): + for offset in range(-self.length+1, motif.length): if offset<0: - p = self.dist_pearson_at(motif,-offset) + p = self.dist_pearson_at(motif, -offset) else: #offset>=0 - p = motif.dist_pearson_at(self,offset) + p = motif.dist_pearson_at(self, offset) if max_p=0 - p = other.dist_product_at(self,offset) + p = other.dist_product_at(self, offset) if max_p=0 - d = other.dist_dpq_at(self,offset) + d = other.dist_dpq_at(self, offset) overlap = other.length-offset - overlap = min(self.length,other.length,overlap) - out = self.length+other.length-2*overlap - #print d,1.0*(overlap+out)/overlap,d*(overlap+out)/overlap + overlap = min(self.length, other.length, overlap) + out = self.length+other.length - 2*overlap + #print("%f %f %f" % (d,1.0*(overlap+out)/overlap,d*(overlap+out)/overlap)) #d = d/(2*overlap) d = (d/(out+overlap))*(2*overlap+out)/(2*overlap) - #print d - d_s.append((offset,d)) - if min_d> d: - min_d=d - min_o=-offset - return min_d,min_o#,d_s + #print(d) + d_s.append((offset, d)) + if min_d > d: + min_d = d + min_o = -offset + return min_d, min_o #,d_s - def dist_dpq_at(self,other,offset): + def dist_dpq_at(self, other, offset): """ calculates the dist_dpq measure with a given offset. offset should satisfy 0<=offset<=len(self) """ - def dpq (f1,f2,alpha): + def dpq (f1, f2, alpha): s=0 for n in alpha.letters: avg=(f1[n]+f2[n])/2 - s+=f1[n]*math.log(f1[n]/avg,2)+f2[n]*math.log(f2[n]/avg,2) + s+=f1[n]*math.log(f1[n]/avg, 2)+f2[n]*math.log(f2[n]/avg, 2) return math.sqrt(s) s=0 - for i in range(max(self.length,offset+other.length)): + for i in range(max(self.length, offset+other.length)): f1=self[i] f2=other[i-offset] - s+=dpq(f1,f2,self.alphabet) + s+=dpq(f1, f2, self.alphabet) return s - def _read(self,stream): + def _read(self, stream): """Reads the motif from the stream (in AlignAce format). the self.alphabet variable must be set beforehand. If the last line contains asterisks it is used for setting mask """ - while 1: + while True: ln = stream.readline() if "*" in ln: self.set_mask(ln.strip("\n\c")) break - self.add_instance(Seq(ln.strip(),self.alphabet)) + self.add_instance(Seq(ln.strip(), self.alphabet)) def __str__(self,masked=False): """ string representation of a motif. @@ -366,7 +372,7 @@ str = str + inst.tostring() + "\n" if masked: - for i in xrange(self.length): + for i in range(self.length): if self.mask[i]: str = str + "*" else: @@ -384,7 +390,7 @@ else: return self.length - def _write(self,stream): + def _write(self, stream): """ writes the motif to the stream """ @@ -400,7 +406,7 @@ if not self.has_instances: self.make_instances_from_counts() str = "" - for i,inst in enumerate(self.instances): + for i, inst in enumerate(self.instances): str = str + ">instance%d\n"%i + inst.tostring() + "\n" return str @@ -434,24 +440,24 @@ The instances are fake, but the pwm is accurate. """ - return self._from_horiz_matrix(stream,letters="ACGT",make_instances=make_instances) + return self._from_horiz_matrix(stream, letters="ACGT", make_instances=make_instances) def _from_vert_matrix(self,stream,letters=None,make_instances=False): """reads a vertical count matrix from stream and fill in the counts. """ self.counts = {} - self.has_counts=True + self.has_counts = True if letters is None: - letters=self.alphabet.letters - self.length=0 + letters = self.alphabet.letters + self.length = 0 for i in letters: - self.counts[i]=[] + self.counts[i] = [] for ln in stream.readlines(): - rec=map(float,ln.strip().split()) - for k,v in zip(letters,rec): + rec = [float(x) for x in ln.strip().split()] + for k, v in zip(letters, rec): self.counts[k].append(v) - self.length+=1 + self.length += 1 self.set_mask("*"*self.length) if make_instances is True: self.make_instances_from_counts() @@ -468,14 +474,14 @@ for i in letters: ln = stream.readline().strip().split() #if there is a letter in the beginning, ignore it - if ln[0]==i: - ln=ln[1:] - #print ln + if ln[0] == i: + ln = ln[1:] + #print(ln) try: - self.counts[i]=map(int,ln) + self.counts[i] = [int(x) for x in ln] except ValueError: #not integers - self.counts[i]=map(float,ln) #map(lambda s: int(100*float(s)),ln) - #print counts[i] + self.counts[i] = [float(x) for x in ln] + #print(counts[i]) s = sum(self.counts[nuc][0] for nuc in letters) l = len(self.counts[letters[0]]) @@ -492,27 +498,27 @@ In case the sums of counts are different for different columnes, the shorter columns are padded with background. """ - alpha="".join(self.alphabet.letters) + alpha = "".join(self.alphabet.letters) #col[i] is a column taken from aligned motif instances - col=[] - self.has_instances=True - self.instances=[] - s = sum(map(lambda nuc: self.counts[nuc][0],self.alphabet.letters)) + col = [] + self.has_instances = True + self.instances = [] + s = sum(self.counts[nuc][0] for nuc in self.alphabet.letters) for i in range(self.length): col.append("") for n in self.alphabet.letters: - col[i] = col[i]+ (n*(self.counts[n][i])) - if len(col[i])>> from Bio import Motif - >>> for motif in Motif.parse(open("Motif/alignace.out"),"AlignAce"): - ... print motif.consensus() + >>> for motif in Motif.parse(open("Motif/alignace.out"), "AlignAce"): + ... print(motif.consensus()) TCTACGATTGAG CTGCACCTAGCTACGAGTGAG GTGCCCTAAGCATACTAGGCG @@ -93,7 +95,7 @@ for m in parser(handle).motifs: yield m -def read(handle,format): +def read(handle, format): """Reads a motif from a handle using a specified file-format. This supports the same formats as Bio.Motif.parse(), but @@ -101,14 +103,14 @@ reading a pfm file: >>> from Bio import Motif - >>> motif = Motif.read(open("Motif/SRF.pfm"),"jaspar-pfm") + >>> motif = Motif.read(open("Motif/SRF.pfm"), "jaspar-pfm") >>> motif.consensus() Seq('GCCCATATATGG', IUPACUnambiguousDNA()) Or a single-motif MEME file, >>> from Bio import Motif - >>> motif = Motif.read(open("Motif/meme.out"),"MEME") + >>> motif = Motif.read(open("Motif/meme.out"), "MEME") >>> motif.consensus() Seq('CTCAATCGTA', IUPACUnambiguousDNA()) @@ -116,7 +118,7 @@ an exception is raised: >>> from Bio import Motif - >>> motif = Motif.read(open("Motif/alignace.out"),"AlignAce") + >>> motif = Motif.read(open("Motif/alignace.out"), "AlignAce") Traceback (most recent call last): ... ValueError: More than one motif found in handle @@ -126,7 +128,7 @@ shown in the example above). Instead use: >>> from Bio import Motif - >>> motif = Motif.parse(open("Motif/alignace.out"),"AlignAce").next() + >>> motif = next(Motif.parse(open("Motif/alignace.out"), "AlignAce")) >>> motif.consensus() Seq('TCTACGATTGAG', IUPACUnambiguousDNA()) @@ -135,13 +137,13 @@ """ iterator = parse(handle, format) try: - first = iterator.next() + first = next(iterator) except StopIteration: first = None if first is None: raise ValueError("No motifs found in handle") try: - second = iterator.next() + second = next(iterator) except StopIteration: second = None if second is not None: @@ -157,14 +159,14 @@ """ import doctest import os - if os.path.isdir(os.path.join("..","..","Tests")): - print "Runing doctests..." + if os.path.isdir(os.path.join("..", "..", "Tests")): + print("Runing doctests...") cur_dir = os.path.abspath(os.curdir) - os.chdir(os.path.join("..","..","Tests")) + os.chdir(os.path.join("..", "..", "Tests")) doctest.testmod() os.chdir(cur_dir) del cur_dir - print "Done" + print("Done") if __name__ == "__main__": #Run the doctests diff -Nru python-biopython-1.62/Bio/NMR/NOEtools.py python-biopython-1.63/Bio/NMR/NOEtools.py --- python-biopython-1.62/Bio/NMR/NOEtools.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/NMR/NOEtools.py 2013-12-05 14:10:43.000000000 +0000 @@ -6,7 +6,7 @@ # peaklist with predicted crosspeaks directly from the # input assignment peaklist. -import xpktools +from . import xpktools def predictNOE(peaklist, originNuc, detectedNuc, originResNum, toResNum): diff -Nru python-biopython-1.62/Bio/NMR/__init__.py python-biopython-1.63/Bio/NMR/__init__.py --- python-biopython-1.62/Bio/NMR/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/NMR/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Code for working with NMR data This directory currently contains contributions from diff -Nru python-biopython-1.62/Bio/NMR/xpktools.py python-biopython-1.63/Bio/NMR/xpktools.py --- python-biopython-1.62/Bio/NMR/xpktools.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/NMR/xpktools.py 2013-12-05 14:10:43.000000000 +0000 @@ -8,6 +8,8 @@ # provides methods for extracting data by the field name # which is listed in the last line of the peaklist header. +from __future__ import print_function + import sys # * * * * * INITIALIZATIONS * * * * * @@ -37,7 +39,7 @@ try: self.fields["entrynum"] = datlist[0] - except IndexError, e: + except IndexError as e: pass @@ -47,23 +49,18 @@ # The data lines are available as a list def __init__(self, infn): - self.data = [] # init the data line list + with open(infn, 'r') as infile: - infile = open(infn, 'r') + # Read in the header lines + self.firstline = infile.readline().split("\012")[0] + self.axislabels = infile.readline().split("\012")[0] + self.dataset = infile.readline().split("\012")[0] + self.sw = infile.readline().split("\012")[0] + self.sf = infile.readline().split("\012")[0] + self.datalabels = infile.readline().split("\012")[0] - # Read in the header lines - self.firstline = infile.readline().split("\012")[0] - self.axislabels = infile.readline().split("\012")[0] - self.dataset = infile.readline().split("\012")[0] - self.sw = infile.readline().split("\012")[0] - self.sf = infile.readline().split("\012")[0] - self.datalabels = infile.readline().split("\012")[0] - - # Read in the data lines to a list - line = infile.readline() - while line: - self.data.append(line.split("\012")[0]) - line = infile.readline() + # Read in the data lines to a list + self.data = [line.split("\012")[0] for line in infile] def residue_dict(self, index): # Generate a dictionary idexed by residue number or a nucleus @@ -106,40 +103,19 @@ return self.dict def write_header(self, outfn): - outfile = _try_open_write(outfn) - outfile.write(self.firstline) - outfile.write("\012") - outfile.write(self.axislabels) - outfile.write("\012") - outfile.write(self.dataset) - outfile.write("\012") - outfile.write(self.sw) - outfile.write("\012") - outfile.write(self.sf) - outfile.write("\012") - outfile.write(self.datalabels) - outfile.write("\012") - outfile.close() - - -def _try_open_read(fn): - # Try to open a file for reading. Exit on IOError - try: - infile = open(fn, 'r') - except IOError, e: - print "file", fn, "could not be opened for reading - quitting." - sys.exit(0) - return infile - - -def _try_open_write(fn): - # Try to open a file for writing. Exit on IOError - try: - infile = open(fn, 'w') - except IOError, e: - print "file", fn, "could not be opened for writing - quitting." - sys.exit(0) - return infile + with open(outfn, 'wb') as outfile: + outfile.write(self.firstline) + outfile.write("\012") + outfile.write(self.axislabels) + outfile.write("\012") + outfile.write(self.dataset) + outfile.write("\012") + outfile.write(self.sw) + outfile.write("\012") + outfile.write(self.sf) + outfile.write("\012") + outfile.write(self.datalabels) + outfile.write("\012") def replace_entry(line, fieldn, newentry): @@ -231,12 +207,6 @@ return outlist -def _sort_keys(dictionary): - keys = dictionary.keys() - sorted_keys = keys.sort() - return sorted_keys - - def _read_dicts(fn_list, keyatom): # Read multiple files into a list of residue dictionaries dict_list = [] diff -Nru python-biopython-1.62/Bio/NaiveBayes.py python-biopython-1.63/Bio/NaiveBayes.py --- python-biopython-1.62/Bio/NaiveBayes.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/NaiveBayes.py 2013-12-05 14:10:43.000000000 +0000 @@ -26,6 +26,8 @@ """ +from __future__ import print_function + import numpy @@ -156,7 +158,7 @@ nb.classes = list(set(results)) else: class_freq = _contents(results) - nb.classes = class_freq.keys() + nb.classes = list(class_freq.keys()) percs = class_freq nb.classes.sort() # keep it tidy @@ -230,6 +232,6 @@ carmodel = train(xcar, ycar) carresult = classify(carmodel, ['Red', 'Sports', 'Domestic']) - print 'Is Yes?', carresult + print('Is Yes? %s' % carresult) carresult = classify(carmodel, ['Red', 'SUV', 'Domestic']) - print 'Is No?', carresult + print('Is No? %s' % carresult) diff -Nru python-biopython-1.62/Bio/NeuralNetwork/BackPropagation/Layer.py python-biopython-1.63/Bio/NeuralNetwork/BackPropagation/Layer.py --- python-biopython-1.62/Bio/NeuralNetwork/BackPropagation/Layer.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/NeuralNetwork/BackPropagation/Layer.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Model a single layer in a nueral network. These classes deal with a layers in the neural network (ie. the input layer, @@ -7,6 +12,8 @@ import math import random +from Bio._py3k import range + def logistic_function(value): """Transform the value with the logistic function. @@ -37,7 +44,7 @@ else: lower_range = 1 - self.nodes = range(lower_range, num_nodes + 1) + self.nodes = list(range(lower_range, num_nodes + 1)) self.weights = {} @@ -104,7 +111,7 @@ o inputs -- A list of inputs into the network -- this must be equal to the number of nodes in the layer. """ - if len(inputs) != len(self.values.keys()) - 1: + if len(inputs) != len(self.values) - 1: raise ValueError("Inputs do not match input layer nodes.") # set the node values from the inputs diff -Nru python-biopython-1.62/Bio/NeuralNetwork/BackPropagation/Network.py python-biopython-1.63/Bio/NeuralNetwork/BackPropagation/Network.py --- python-biopython-1.62/Bio/NeuralNetwork/BackPropagation/Network.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/NeuralNetwork/BackPropagation/Network.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Represent Neural Networks. This module contains classes to represent Generic Neural Networks that @@ -59,7 +64,7 @@ of the prevoious weight change to use. """ num_iterations = 0 - while 1: + while True: num_iterations += 1 training_error = 0.0 for example in training_examples: @@ -103,10 +108,7 @@ # update the predicted values for these inputs self._input.update(inputs) - output_keys = self._output.values.keys() - output_keys.sort() - outputs = [] - for output_key in output_keys: + for output_key in sorted(self._output.values): outputs.append(self._output.values[output_key]) return outputs diff -Nru python-biopython-1.62/Bio/NeuralNetwork/Gene/Motif.py python-biopython-1.63/Bio/NeuralNetwork/Gene/Motif.py --- python-biopython-1.62/Bio/NeuralNetwork/Gene/Motif.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/NeuralNetwork/Gene/Motif.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Find and deal with motifs in biological sequence data. Representing DNA (or RNA or proteins) in a neural network can be difficult @@ -12,7 +17,7 @@ from Bio.Seq import Seq # local modules -from Pattern import PatternRepository +from .Pattern import PatternRepository class MotifFinder(object): @@ -201,7 +206,7 @@ # as long as we have some motifs present, normalize them # otherwise we'll just return 0 for everything if max_count > 0: - for motif in seq_motifs.keys(): + for motif in seq_motifs: seq_motifs[motif] = (float(seq_motifs[motif] - min_count) / float(max_count)) diff -Nru python-biopython-1.62/Bio/NeuralNetwork/Gene/Pattern.py python-biopython-1.63/Bio/NeuralNetwork/Gene/Pattern.py --- python-biopython-1.62/Bio/NeuralNetwork/Gene/Pattern.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/NeuralNetwork/Gene/Pattern.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Generic functionality useful for all gene representations. This module contains classes which can be used for all the different @@ -76,7 +81,7 @@ """ all_patterns = [] - while 1: + while True: cur_line = input_handle.readline() if not(cur_line): @@ -90,7 +95,7 @@ if self._alphabet is not None: # make single patterns (not signatures) into lists, so we # can check signatures and single patterns the same - if type(cur_pattern) != type(tuple([])): + if not isinstance(cur_pattern, tuple): test_pattern = [cur_pattern] else: test_pattern = cur_pattern diff -Nru python-biopython-1.62/Bio/NeuralNetwork/Gene/Schema.py python-biopython-1.63/Bio/NeuralNetwork/Gene/Schema.py --- python-biopython-1.62/Bio/NeuralNetwork/Gene/Schema.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/NeuralNetwork/Gene/Schema.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Deal with Motifs or Signatures allowing ambiguity in the sequences. This class contains Schema which deal with Motifs and Signatures at @@ -11,15 +16,18 @@ motifs or signatures. """ # standard modules +from __future__ import print_function + import random import re -# biopython +from Bio._py3k import range + from Bio import Alphabet from Bio.Seq import MutableSeq # neural network libraries -from Pattern import PatternRepository +from .Pattern import PatternRepository # genetic algorithm libraries from Bio.GA import Organism @@ -605,7 +613,7 @@ assert total_count > 0, "Expected to have motifs to match" while (float(matched_count) / float(total_count)) < motif_percent: new_schema, matching_motifs = \ - self._get_unique_schema(schema_info.keys(), + self._get_unique_schema(list(schema_info.keys()), all_motifs, num_ambiguous) # get the number of counts for the new schema and clean up @@ -650,7 +658,7 @@ # doesn't match any old schema num_tries = 0 - while 1: + while True: # pick a motif to work from and make a schema from it cur_motif = random.choice(motif_list) @@ -704,8 +712,8 @@ new_schema_list = list(motif) for add_ambiguous in range(num_ambiguous): # add an ambiguous position in a new place in the motif - while 1: - ambig_pos = random.choice(range(len(new_schema_list))) + while True: + ambig_pos = random.choice(list(range(len(new_schema_list)))) # only add a position if it isn't already ambiguous # otherwise, we'll try again diff -Nru python-biopython-1.62/Bio/NeuralNetwork/Gene/Signature.py python-biopython-1.63/Bio/NeuralNetwork/Gene/Signature.py --- python-biopython-1.62/Bio/NeuralNetwork/Gene/Signature.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/NeuralNetwork/Gene/Signature.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Find and deal with signatures in biological sequence data. In addition to representing sequences according to motifs (see Motif.py @@ -11,7 +16,7 @@ from Bio.Seq import Seq # local stuff -from Pattern import PatternRepository +from .Pattern import PatternRepository class SignatureFinder(object): diff -Nru python-biopython-1.62/Bio/NeuralNetwork/StopTraining.py python-biopython-1.63/Bio/NeuralNetwork/StopTraining.py --- python-biopython-1.62/Bio/NeuralNetwork/StopTraining.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/NeuralNetwork/StopTraining.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Classes to help deal with stopping training a neural network. One of the key issues with training a neural network is knowning when to @@ -13,6 +18,8 @@ """ +from __future__ import print_function + class ValidationIncreaseStop(object): """Class to stop training on a network when the validation error increases. @@ -51,20 +58,20 @@ """ if num_iterations % 10 == 0: if self.verbose: - print "%s; Training Error:%s; Validation Error:%s"\ - % (num_iterations, training_error, validation_error) + print("%s; Training Error:%s; Validation Error:%s"\ + % (num_iterations, training_error, validation_error)) if num_iterations > self.min_iterations: if self.last_error is not None: if validation_error > self.last_error: if self.verbose: - print "Validation Error increasing -- Stop" + print("Validation Error increasing -- Stop") return 1 if self.max_iterations is not None: if num_iterations > self.max_iterations: if self.verbose: - print "Reached maximum number of iterations -- Stop" + print("Reached maximum number of iterations -- Stop") return 1 self.last_error = validation_error diff -Nru python-biopython-1.62/Bio/NeuralNetwork/Training.py python-biopython-1.63/Bio/NeuralNetwork/Training.py --- python-biopython-1.62/Bio/NeuralNetwork/Training.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/NeuralNetwork/Training.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Provide classes for dealing with Training Neural Networks. """ # standard modules diff -Nru python-biopython-1.62/Bio/Nexus/Nexus.py python-biopython-1.63/Bio/Nexus/Nexus.py --- python-biopython-1.62/Bio/Nexus/Nexus.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Nexus/Nexus.py 2013-12-05 14:10:43.000000000 +0000 @@ -9,9 +9,13 @@ Based upon 'NEXUS: An extensible file format for systematic information' Maddison, Swofford, Maddison. 1997. Syst. Biol. 46(4):590-621 """ -# For with in Python/Jython 2.5 -from __future__ import with_statement +from __future__ import print_function +from Bio._py3k import zip +from Bio._py3k import range +from Bio._py3k import basestring + +from functools import reduce import copy import math import random @@ -22,21 +26,22 @@ from Bio.Data import IUPACData from Bio.Seq import Seq -from Trees import Tree +from .Trees import Tree -INTERLEAVE=70 -SPECIAL_COMMANDS=['charstatelabels','charlabels','taxlabels', 'taxset', 'charset','charpartition','taxpartition', - 'matrix','tree', 'utree','translate','codonposset','title'] -KNOWN_NEXUS_BLOCKS = ['trees','data', 'characters', 'taxa', 'sets','codons'] -PUNCTUATION='()[]{}/\,;:=*\'"`+-<>' -MRBAYESSAFE='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_' -WHITESPACE=' \t\n' -#SPECIALCOMMENTS=['!','&','%','/','\\','@'] #original list of special comments -SPECIALCOMMENTS=['&'] # supported special comment ('tree' command), all others are ignored -CHARSET='chars' -TAXSET='taxa' -CODONPOSITIONS='codonpositions' -DEFAULTNEXUS='#NEXUS\nbegin data; dimensions ntax=0 nchar=0; format datatype=dna; end; ' +INTERLEAVE = 70 +SPECIAL_COMMANDS = ['charstatelabels', 'charlabels', 'taxlabels', 'taxset', + 'charset', 'charpartition', 'taxpartition', 'matrix', + 'tree', 'utree', 'translate', 'codonposset', 'title'] +KNOWN_NEXUS_BLOCKS = ['trees', 'data', 'characters', 'taxa', 'sets', 'codons'] +PUNCTUATION = '()[]{}/\,;:=*\'"`+-<>' +MRBAYESSAFE = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_' +WHITESPACE = ' \t\n' +#SPECIALCOMMENTS = ['!','&','%','/','\\','@'] #original list of special comments +SPECIALCOMMENTS = ['&'] # supported special comment ('tree' command), all others are ignored +CHARSET = 'chars' +TAXSET = 'taxa' +CODONPOSITIONS = 'codonpositions' +DEFAULTNEXUS = '#NEXUS\nbegin data; dimensions ntax=0 nchar=0; format datatype=dna; end; ' class NexusError(Exception): @@ -44,12 +49,15 @@ class CharBuffer(object): - """Helps reading NEXUS-words and characters from a buffer.""" - def __init__(self,string): + """Helps reading NEXUS-words and characters from a buffer (semi-PRIVATE). + + This class is not intended for public use (any more). + """ + def __init__(self, string): if string: - self.buffer=list(string) + self.buffer = list(string) else: - self.buffer=[] + self.buffer = [] def peek(self): if self.buffer: @@ -58,21 +66,26 @@ return None def peek_nonwhitespace(self): - b=''.join(self.buffer).strip() + b = ''.join(self.buffer).strip() if b: return b[0] else: return None - def next(self): + def __next__(self): if self.buffer: return self.buffer.pop(0) else: return None + if sys.version_info[0] < 3: + def next(self): + """Deprecated Python 2 style alias for Python 3 style __next__ method.""" + return self.__next__() + def next_nonwhitespace(self): while True: - p=self.next() + p = next(self) if p is None: break if p not in WHITESPACE: @@ -81,23 +94,23 @@ def skip_whitespace(self): while self.buffer[0] in WHITESPACE: - self.buffer=self.buffer[1:] + self.buffer = self.buffer[1:] - def next_until(self,target): + def next_until(self, target): for t in target: try: - pos=self.buffer.index(t) + pos = self.buffer.index(t) except ValueError: pass else: - found=''.join(self.buffer[:pos]) - self.buffer=self.buffer[pos:] + found = ''.join(self.buffer[:pos]) + self.buffer = self.buffer[pos:] return found else: return None - def peek_word(self,word): - return ''.join(self.buffer[:len(word)])==word + def peek_word(self, word): + return ''.join(self.buffer[:len(word)]) == word def next_word(self): """Return the next NEXUS word from a string. @@ -105,32 +118,33 @@ This deals with single and double quotes, whitespace and punctuation. """ - word=[] - quoted=False - first=self.next_nonwhitespace() # get first character + word = [] + quoted = False + first = self.next_nonwhitespace() # get first character if not first: # return empty if only whitespace left return None word.append(first) - if first=="'": # word starts with a quote - quoted="'" - elif first=='"': - quoted='"' + if first == "'": # word starts with a quote + quoted = "'" + elif first == '"': + quoted = '"' elif first in PUNCTUATION: # if it's punctuation, return immediately return first while True: - c=self.peek() - if c==quoted: # a quote? - word.append(self.next()) # store quote - if self.peek()==quoted: # double quote - skip=self.next() # skip second quote + c = self.peek() + if c == quoted: # a quote? + word.append(next(self)) # store quote + if self.peek() == quoted: # double quote + skip = next(self) # skip second quote elif quoted: # second single quote ends word break elif quoted: - word.append(self.next()) # if quoted, then add anything - elif not c or c in PUNCTUATION or c in WHITESPACE: # if not quoted and special character, stop + word.append(next(self)) # if quoted, then add anything + elif not c or c in PUNCTUATION or c in WHITESPACE: + # if not quoted and special character, stop break else: - word.append(self.next()) # standard character + word.append(next(self)) # standard character return ''.join(word) def rest(self): @@ -144,65 +158,64 @@ See Wheeler (1990), Cladistics 6:269-275. """ - def __init__(self,symbols,gap): - self.data={} - self.symbols=[s for s in symbols] - self.symbols.sort() + def __init__(self, symbols, gap): + self.data = {} + self.symbols = sorted(symbols) if gap: self.symbols.append(gap) for x in self.symbols: - for y in [s for s in self.symbols if s!=x]: - self.set(x,y,0) + for y in [s for s in self.symbols if s != x]: + self.set(x, y, 0) - def set(self,x,y,value): - if x>y: - x,y=y,x - self.data[x+y]=value - - def add(self,x,y,value): - if x>y: - x,y=y,x - self.data[x+y]+=value + def set(self, x, y, value): + if x > y: + x, y = y, x + self.data[x + y] = value + + def add(self, x, y, value): + if x > y: + x, y = y, x + self.data[x + y] += value def sum(self): - return reduce(lambda x,y:x+y,self.data.values()) + return reduce(lambda x, y:x+y, self.data.values()) def transformation(self): - total=self.sum() - if total!=0: + total = self.sum() + if total != 0: for k in self.data: - self.data[k]=self.data[k]/float(total) + self.data[k] = self.data[k] / float(total) return self def weighting(self): for k in self.data: - if self.data[k]!=0: - self.data[k]=-math.log(self.data[k]) + if self.data[k] != 0: + self.data[k] = -math.log(self.data[k]) return self - def smprint(self,name='your_name_here'): - matrix='usertype %s stepmatrix=%d\n' % (name,len(self.symbols)) - matrix+=' %s\n' % ' '.join(self.symbols) + def smprint(self, name='your_name_here'): + matrix = 'usertype %s stepmatrix=%d\n' % (name, len(self.symbols)) + matrix += ' %s\n' % ' '.join(self.symbols) for x in self.symbols: - matrix+='[%s]'.ljust(8) % x + matrix += '[%s]'.ljust(8) % x for y in self.symbols: - if x==y: - matrix+=' . ' + if x == y: + matrix += ' . ' else: - if x>y: - x1,y1=y,x + if x > y: + x1, y1 = y, x else: - x1,y1=x,y - if self.data[x1+y1]==0: - matrix+='inf. ' + x1, y1 = x, y + if self.data[x1 + y1] == 0: + matrix += 'inf. ' else: - matrix+='%2.2f'.ljust(10) % (self.data[x1+y1]) - matrix+='\n' - matrix+=';\n' + matrix += '%2.2f'.ljust(10) % (self.data[x1 + y1]) + matrix += '\n' + matrix += ';\n' return matrix -def safename(name,mrbayes=False): +def safename(name, mrbayes=False): """Return a taxon identifier according to NEXUS standard. Wrap quotes around names with punctuation or whitespace, and double @@ -212,12 +225,12 @@ for the mrbayes software package. """ if mrbayes: - safe=name.replace(' ','_') - safe=''.join([c for c in safe if c in MRBAYESSAFE]) + safe = name.replace(' ', '_') + safe = ''.join(c for c in safe if c in MRBAYESSAFE) else: - safe=name.replace("'","''") + safe = name.replace("'", "''") if set(safe).intersection(set(WHITESPACE+PUNCTUATION)): - safe="'"+safe+"'" + safe = "'" + safe + "'" return safe @@ -226,58 +239,54 @@ if not word: return None while (word.startswith("'") and word.endswith("'")) or (word.startswith('"') and word.endswith('"')): - word=word[1:-1] + word = word[1:-1] return word -def get_start_end(sequence, skiplist=['-','?']): +def get_start_end(sequence, skiplist=['-', '?']): """Return position of first and last character which is not in skiplist. Skiplist defaults to ['-','?']).""" - length=len(sequence) - if length==0: - return None,None - end=length-1 - while end>=0 and (sequence[end] in skiplist): - end-=1 - start=0 - while start= 0 and (sequence[end] in skiplist): + end -= 1 + start = 0 + while start < length and (sequence[start] in skiplist): + start += 1 + if start == length and end == -1: # empty sequence + return -1, -1 else: - return start,end + return start, end def _sort_keys_by_values(p): """Returns a sorted list of keys of p sorted by values of p.""" - startpos=[(p[pn],pn) for pn in p if p[pn]] - startpos.sort() - # parenthisis added because of py3k - return (zip(*startpos))[1] + return sorted((pn for pn in p if p[pn]), key = lambda pn: p[pn]) def _make_unique(l): """Check that all values in list are unique and return a pruned and sorted list.""" - l=list(set(l)) - l.sort() - return l + return sorted(set(l)) -def _unique_label(previous_labels,label): +def _unique_label(previous_labels, label): """Returns a unique name if label is already in previous_labels.""" while label in previous_labels: if label.split('.')[-1].startswith('copy'): - label='.'.join(label.split('.')[:-1])+'.copy'+str(eval('0'+label.split('.')[-1][4:])+1) + label = '.'.join(label.split('.')[:-1]) \ + + '.copy' + str(eval('0'+label.split('.')[-1][4:])+1) else: - label+='.copy' + label += '.copy' return label def _seqmatrix2strmatrix(matrix): """Converts a Seq-object matrix to a plain sequence-string matrix.""" - return dict([(t, str(matrix[t])) for t in matrix]) + return dict((t, str(matrix[t])) for t in matrix) def _compact4nexus(orig_list): @@ -287,30 +296,29 @@ if not orig_list: return '' - orig_list=list(set(orig_list)) - orig_list.sort() - shortlist=[] - clist=orig_list[:] - clist.append(clist[-1]+.5) # dummy value makes it easier - while len(clist)>1: - step=1 - for i,x in enumerate(clist): - if x==clist[0]+i*step: # are we still in the right step? + orig_list = sorted(set(orig_list)) + shortlist = [] + clist = orig_list[:] + clist.append(clist[-1] + .5) # dummy value makes it easier + while len(clist) > 1: + step = 1 + for i, x in enumerate(clist): + if x == clist[0] + i*step: # are we still in the right step? continue - elif i==1 and len(clist)>3 and clist[i+1]-x==x-clist[0]: + elif i == 1 and len(clist) > 3 and clist[i+1] - x == x - clist[0]: # second element, and possibly at least 3 elements to link, # and the next one is in the right step - step=x-clist[0] + step = x - clist[0] else: # pattern broke, add all values before current position to new list - sub=clist[:i] - if len(sub)==1: + sub = clist[:i] + if len(sub) == 1: shortlist.append(str(sub[0]+1)) else: - if step==1: - shortlist.append('%d-%d' % (sub[0]+1,sub[-1]+1)) + if step == 1: + shortlist.append('%d-%d' % (sub[0]+1, sub[-1]+1)) else: - shortlist.append('%d-%d\\%d' % (sub[0]+1,sub[-1]+1,step)) - clist=clist[i:] + shortlist.append('%d-%d\\%d' % (sub[0]+1, sub[-1]+1, step)) + clist = clist[i:] break return ' '.join(shortlist) @@ -325,64 +333,66 @@ if not matrices: return None - name=matrices[0][0] - combined=copy.deepcopy(matrices[0][1]) # initiate with copy of first matrix - mixed_datatypes=(len(set([n[1].datatype for n in matrices]))>1) + name = matrices[0][0] + combined = copy.deepcopy(matrices[0][1]) # initiate with copy of first matrix + mixed_datatypes = (len(set(n[1].datatype for n in matrices)) > 1) if mixed_datatypes: - combined.datatype='None' # dealing with mixed matrices is application specific. You take care of that yourself! + # dealing with mixed matrices is application specific. + # You take care of that yourself! + combined.datatype = 'None' # raise NexusError('Matrices must be of same datatype') - combined.charlabels=None - combined.statelabels=None - combined.interleave=False - combined.translate=None + combined.charlabels = None + combined.statelabels = None + combined.interleave = False + combined.translate = None # rename taxon sets and character sets and name them with prefix - for cn,cs in combined.charsets.iteritems(): - combined.charsets['%s.%s' % (name,cn)]=cs + for cn, cs in combined.charsets.items(): + combined.charsets['%s.%s' % (name, cn)]=cs del combined.charsets[cn] - for tn,ts in combined.taxsets.iteritems(): - combined.taxsets['%s.%s' % (name,tn)]=ts + for tn, ts in combined.taxsets.items(): + combined.taxsets['%s.%s' % (name, tn)]=ts del combined.taxsets[tn] # previous partitions usually don't make much sense in combined matrix # just initiate one new partition parted by single matrices - combined.charpartitions={'combined':{name:range(combined.nchar)}} - for n,m in matrices[1:]: # add all other matrices - both=[t for t in combined.taxlabels if t in m.taxlabels] - combined_only=[t for t in combined.taxlabels if t not in both] - m_only=[t for t in m.taxlabels if t not in both] + combined.charpartitions = {'combined':{name:list(range(combined.nchar))}} + for n, m in matrices[1:]: # add all other matrices + both = [t for t in combined.taxlabels if t in m.taxlabels] + combined_only = [t for t in combined.taxlabels if t not in both] + m_only = [t for t in m.taxlabels if t not in both] for t in both: # concatenate sequences and unify gap and missing character symbols - combined.matrix[t]+=Seq(str(m.matrix[t]).replace(m.gap,combined.gap).replace(m.missing,combined.missing),combined.alphabet) + combined.matrix[t] += Seq(str(m.matrix[t]).replace(m.gap, combined.gap).replace(m.missing, combined.missing), combined.alphabet) # replace date of missing taxa with symbol for missing data for t in combined_only: - combined.matrix[t]+=Seq(combined.missing*m.nchar,combined.alphabet) + combined.matrix[t] += Seq(combined.missing*m.nchar, combined.alphabet) for t in m_only: - combined.matrix[t]=Seq(combined.missing*combined.nchar,combined.alphabet)+\ - Seq(str(m.matrix[t]).replace(m.gap,combined.gap).replace(m.missing,combined.missing),combined.alphabet) + combined.matrix[t] = Seq(combined.missing*combined.nchar, combined.alphabet) + \ + Seq(str(m.matrix[t]).replace(m.gap, combined.gap).replace(m.missing, combined.missing), combined.alphabet) combined.taxlabels.extend(m_only) # new taxon list - for cn,cs in m.charsets.iteritems(): # adjust character sets for new matrix - combined.charsets['%s.%s' % (n,cn)]=[x+combined.nchar for x in cs] + for cn, cs in m.charsets.items(): # adjust character sets for new matrix + combined.charsets['%s.%s' % (n, cn)] = [x+combined.nchar for x in cs] if m.taxsets: if not combined.taxsets: - combined.taxsets={} + combined.taxsets = {} # update taxon sets - combined.taxsets.update(dict(('%s.%s' % (n,tn),ts) - for tn,ts in m.taxsets.iteritems())) + combined.taxsets.update(dict(('%s.%s' % (n, tn), ts) + for tn, ts in m.taxsets.items())) # update new charpartition - combined.charpartitions['combined'][n]=range(combined.nchar,combined.nchar+m.nchar) + combined.charpartitions['combined'][n] = list(range(combined.nchar, combined.nchar+m.nchar)) # update charlabels if m.charlabels: if not combined.charlabels: - combined.charlabels={} - combined.charlabels.update(dict((combined.nchar+i,label) - for (i,label) in m.charlabels.iteritems())) - combined.nchar+=m.nchar # update nchar and ntax - combined.ntax+=len(m_only) + combined.charlabels = {} + combined.charlabels.update(dict((combined.nchar + i, label) + for (i, label) in m.charlabels.items())) + combined.nchar += m.nchar # update nchar and ntax + combined.ntax += len(m_only) # some prefer partitions, some charsets: # make separate charset for ecah initial dataset for c in combined.charpartitions['combined']: - combined.charsets[c]=combined.charpartitions['combined'][c] + combined.charsets[c] = combined.charpartitions['combined'][c] return combined @@ -401,41 +411,46 @@ NOTE: this function is very slow for large files, and obsolete when using C extension cnexus """ - contents=iter(text) - newtext=[] - newline=[] - quotelevel='' - speciallevel=False - commlevel=0 + contents = iter(text) + newtext = [] + newline = [] + quotelevel = '' + speciallevel = False + commlevel = 0 #Parse with one character look ahead (for special comments) - t2 = contents.next() + t2 = next(contents) while True: t = t2 try: - t2 = contents.next() + t2 = next(contents) except StopIteration: t2 = None if t is None: break - if t==quotelevel and not (commlevel or speciallevel): # matching quote ends quotation - quotelevel='' - elif not quotelevel and not (commlevel or speciallevel) and (t=='"' or t=="'"): # single or double quote starts quotation + if t == quotelevel and not (commlevel or speciallevel): + # matching quote ends quotation + quotelevel = '' + elif not quotelevel and not (commlevel or speciallevel) and (t == '"' or t == "'"): + # single or double quote starts quotation quotelevel=t - elif not quotelevel and t=='[': # opening bracket outside a quote - if t2 in SPECIALCOMMENTS and commlevel==0 and not speciallevel: - speciallevel=True - else: - commlevel+=1 - elif not quotelevel and t==']': # closing bracket ioutside a quote + elif not quotelevel and t == '[': + # opening bracket outside a quote + if t2 in SPECIALCOMMENTS and commlevel == 0 and not speciallevel: + speciallevel = True + else: + commlevel += 1 + elif not quotelevel and t == ']': + # closing bracket ioutside a quote if speciallevel: - speciallevel=False + speciallevel = False else: - commlevel-=1 - if commlevel<0: + commlevel -= 1 + if commlevel < 0: raise NexusError('Nexus formatting error: unmatched ]') continue - if commlevel==0: # copy if we're not in comment - if t==';' and not quotelevel: + if commlevel == 0: + # copy if we're not in comment + if t == ';' and not quotelevel: newtext.append(''.join(newline)) newline=[] else: @@ -443,7 +458,7 @@ #level of comments should be 0 at the end of the file if newline: newtext.append('\n'.join(newline)) - if commlevel>0: + if commlevel > 0: raise NexusError('Nexus formatting error: unmatched [') return newtext @@ -455,37 +470,35 @@ Lines are adjusted so that no linebreaks occur within a commandline (except matrix command line) """ - formatted_lines=[] + formatted_lines = [] for l in lines: #Convert line endings - l=l.replace('\r\n','\n').replace('\r','\n').strip() + l = l.replace('\r\n', '\n').replace('\r', '\n').strip() if l.lower().startswith('matrix'): formatted_lines.append(l) else: - l=l.replace('\n',' ') + l = l.replace('\n', ' ') if l: formatted_lines.append(l) return formatted_lines -def _replace_parenthesized_ambigs(seq,rev_ambig_values): +def _replace_parenthesized_ambigs(seq, rev_ambig_values): """Replaces ambigs in xxx(ACG)xxx format by IUPAC ambiguity code.""" - opening=seq.find('(') - while opening>-1: - closing=seq.find(')') - if closing<0: + opening = seq.find('(') + while opening > -1: + closing = seq.find(')') + if closing < 0: raise NexusError('Missing closing parenthesis in: '+seq) - elif closing 0: try: options = options.replace('=', ' = ').split() - valued_indices=[(n-1,n,n+1) for n in range(len(options)) if options[n]=='=' and n!=0 and n!=len((options))] + valued_indices = [(n-1, n, n+1) for n in range(len(options)) + if options[n] == '=' and n != 0 and n != len((options))] indices = [] for sl in valued_indices: indices.extend(sl) @@ -526,47 +541,47 @@ class Block(object): """Represent a NEXUS block with block name and list of commandlines.""" - def __init__(self,title=None): - self.title=title - self.commandlines=[] + def __init__(self, title=None): + self.title = title + self.commandlines = [] class Nexus(object): def __init__(self, input=None): - self.ntax=0 # number of taxa - self.nchar=0 # number of characters - self.unaltered_taxlabels=[] # taxlabels as the appear in the input file (incl. duplicates, etc.) - self.taxlabels=[] # labels for taxa, ordered by their id - self.charlabels=None # ... and for characters - self.statelabels=None # ... and for states - self.datatype='dna' # (standard), dna, rna, nucleotide, protein - self.respectcase=False # case sensitivity - self.missing='?' # symbol for missing characters - self.gap='-' # symbol for gap - self.symbols=None # set of symbols - self.equate=None # set of symbol synonyms - self.matchchar=None # matching char for matrix representation - self.labels=None # left, right, no - self.transpose=False # whether matrix is transposed - self.interleave=False # whether matrix is interleaved - self.tokens=False # unsupported - self.eliminate=None # unsupported - self.matrix=None # ... - self.unknown_blocks=[] # blocks we don't care about - self.taxsets={} - self.charsets={} - self.charpartitions={} - self.taxpartitions={} - self.trees=[] # list of Trees (instances of Tree class) - self.translate=None # Dict to translate taxon <-> taxon numbers - self.structured=[] # structured input representation - self.set={} # dict of the set command to set various options - self.options={} # dict of the options command in the data block - self.codonposset=None # name of the charpartition that defines codon positions + self.ntax = 0 # number of taxa + self.nchar = 0 # number of characters + self.unaltered_taxlabels = [] # taxlabels as the appear in the input file (incl. duplicates, etc.) + self.taxlabels = [] # labels for taxa, ordered by their id + self.charlabels = None # ... and for characters + self.statelabels = None # ... and for states + self.datatype = 'dna' # (standard), dna, rna, nucleotide, protein + self.respectcase = False # case sensitivity + self.missing = '?' # symbol for missing characters + self.gap = '-' # symbol for gap + self.symbols = None # set of symbols + self.equate = None # set of symbol synonyms + self.matchchar = None # matching char for matrix representation + self.labels = None # left, right, no + self.transpose = False # whether matrix is transposed + self.interleave = False # whether matrix is interleaved + self.tokens = False # unsupported + self.eliminate = None # unsupported + self.matrix = None # ... + self.unknown_blocks = [] # blocks we don't care about + self.taxsets = {} + self.charsets = {} + self.charpartitions = {} + self.taxpartitions = {} + self.trees = [] # list of Trees (instances of Tree class) + self.translate = None # Dict to translate taxon <-> taxon numbers + self.structured = [] # structured input representation + self.set = {} # dict of the set command to set various options + self.options = {} # dict of the options command in the data block + self.codonposset = None # name of the charpartition that defines codon positions # some defaults - self.options['gapmode']='missing' + self.options['gapmode'] = 'missing' if input: self.read(input) @@ -577,13 +592,13 @@ """Included for backwards compatibility (DEPRECATED).""" return self.taxlabels - def set_original_taxon_order(self,value): + def set_original_taxon_order(self, value): """Included for backwards compatibility (DEPRECATED).""" - self.taxlabels=value + self.taxlabels = value - original_taxon_order=property(get_original_taxon_order,set_original_taxon_order) + original_taxon_order = property(get_original_taxon_order, set_original_taxon_order) - def read(self,input): + def read(self, input): """Read and parse NEXUS input (a filename, file-handle, or string).""" # 1. Assume we have the name of a file in the execution dir or a @@ -593,30 +608,30 @@ with File.as_handle(input, 'rU') as fp: file_contents = fp.read() self.filename = getattr(fp, 'name', 'Unknown_nexus_file') - except (TypeError,IOError,AttributeError): + except (TypeError, IOError, AttributeError): #2 Assume we have a string from a fh.read() if isinstance(input, basestring): file_contents = input - self.filename='input_string' + self.filename = 'input_string' else: - print input.strip()[:50] + print(input.strip()[:50]) raise NexusError('Unrecognized input: %s ...' % input[:100]) - file_contents=file_contents.strip() + file_contents = file_contents.strip() if file_contents.startswith('#NEXUS'): - file_contents=file_contents[6:] - commandlines=_get_command_lines(file_contents) + file_contents = file_contents[6:] + commandlines = _get_command_lines(file_contents) # get rid of stupid 'NEXUS token - in merged treefiles, this might appear multiple times' - for i,cl in enumerate(commandlines): + for i, cl in enumerate(commandlines): try: - if cl[:6].upper()=='#NEXUS': - commandlines[i]=cl[6:].strip() + if cl[:6].upper() == '#NEXUS': + commandlines[i] = cl[6:].strip() except: pass # now loop through blocks (we parse only data in known blocks, thus ignoring non-block commands nexus_block_gen = self._get_nexus_block(commandlines) - while 1: + while True: try: - title, contents = nexus_block_gen.next() + title, contents = next(nexus_block_gen) except StopIteration: break if title in KNOWN_NEXUS_BLOCKS: @@ -624,150 +639,150 @@ else: self._unknown_nexus_block(title, contents) - def _get_nexus_block(self,file_contents): + def _get_nexus_block(self, file_contents): """Generator for looping through Nexus blocks.""" - inblock=False - blocklines=[] + inblock = False + blocklines = [] while file_contents: - cl=file_contents.pop(0) + cl = file_contents.pop(0) if cl.lower().startswith('begin'): if not inblock: - inblock=True - title=cl.split()[1].lower() + inblock = True + title = cl.split()[1].lower() else: raise NexusError('Illegal block nesting in block %s' % title) elif cl.lower().startswith('end'): if inblock: - inblock=False - yield title,blocklines - blocklines=[] + inblock = False + yield title, blocklines + blocklines = [] else: raise NexusError('Unmatched \'end\'.') elif inblock: blocklines.append(cl) - def _unknown_nexus_block(self,title, contents): + def _unknown_nexus_block(self, title, contents): block = Block() block.commandlines.append(contents) block.title = title self.unknown_blocks.append(block) - def _parse_nexus_block(self,title, contents): + def _parse_nexus_block(self, title, contents): """Parse a known Nexus Block (PRIVATE).""" # attached the structered block representation self._apply_block_structure(title, contents) #now check for taxa,characters,data blocks. If this stuff is defined more than once #the later occurences will override the previous ones. - block=self.structured[-1] + block = self.structured[-1] for line in block.commandlines: try: - getattr(self,'_'+line.command)(line.options) + getattr(self, '_' + line.command)(line.options) except AttributeError: - raise raise NexusError('Unknown command: %s ' % line.command) - def _title(self,options): + def _title(self, options): pass def _link(self, options): pass - def _dimensions(self,options): + def _dimensions(self, options): if 'ntax' in options: - self.ntax=eval(options['ntax']) + self.ntax = eval(options['ntax']) if 'nchar' in options: - self.nchar=eval(options['nchar']) + self.nchar = eval(options['nchar']) - def _format(self,options): + def _format(self, options): # print options # we first need to test respectcase, then symbols (which depends on respectcase) # then datatype (which, if standard, depends on symbols and respectcase in order to generate # dicts for ambiguous values and alphabet if 'respectcase' in options: - self.respectcase=True + self.respectcase = True # adjust symbols to for respectcase if 'symbols' in options: - self.symbols=options['symbols'] + self.symbols = options['symbols'] if (self.symbols.startswith('"') and self.symbols.endswith('"')) or\ (self.symbold.startswith("'") and self.symbols.endswith("'")): - self.symbols=self.symbols[1:-1].replace(' ','') + self.symbols = self.symbols[1:-1].replace(' ', '') if not self.respectcase: - self.symbols=self.symbols.lower()+self.symbols.upper() - self.symbols=list(set(self.symbols)) + self.symbols = self.symbols.lower() + self.symbols.upper() + self.symbols = list(set(self.symbols)) if 'datatype' in options: - self.datatype=options['datatype'].lower() - if self.datatype=='dna' or self.datatype=='nucleotide': - self.alphabet=copy.deepcopy(IUPAC.ambiguous_dna) - self.ambiguous_values=copy.deepcopy(IUPACData.ambiguous_dna_values) - self.unambiguous_letters=copy.deepcopy(IUPACData.unambiguous_dna_letters) - elif self.datatype=='rna': - self.alphabet=copy.deepcopy(IUPAC.ambiguous_rna) - self.ambiguous_values=copy.deepcopy(IUPACData.ambiguous_rna_values) - self.unambiguous_letters=copy.deepcopy(IUPACData.unambiguous_rna_letters) - elif self.datatype=='protein': - self.alphabet=copy.deepcopy(IUPAC.protein) - self.ambiguous_values={'B':'DN','Z':'EQ','X':copy.deepcopy(IUPACData.protein_letters)} # that's how PAUP handles it - self.unambiguous_letters=copy.deepcopy(IUPACData.protein_letters)+'*' # stop-codon - elif self.datatype=='standard': + self.datatype = options['datatype'].lower() + if self.datatype == 'dna' or self.datatype == 'nucleotide': + self.alphabet = IUPAC.IUPACAmbiguousDNA() # fresh instance! + self.ambiguous_values = IUPACData.ambiguous_dna_values.copy() + self.unambiguous_letters = IUPACData.unambiguous_dna_letters + elif self.datatype == 'rna': + self.alphabet = IUPAC.IUPACAmbiguousDNA() # fresh instance! + self.ambiguous_values = IUPACData.ambiguous_rna_values.copy() + self.unambiguous_letters = IUPACData.unambiguous_rna_letters + elif self.datatype == 'protein': + #TODO - Should this not be ExtendedIUPACProtein? + self.alphabet = IUPAC.IUPACProtein() # fresh instance + self.ambiguous_values = {'B':'DN', 'Z':'EQ', 'X':IUPACData.protein_letters} + # that's how PAUP handles it + self.unambiguous_letters = IUPACData.protein_letters + '*' # stop-codon + elif self.datatype == 'standard': raise NexusError('Datatype standard is not yet supported.') - #self.alphabet=None - #self.ambiguous_values={} + #self.alphabet = None + #self.ambiguous_values = {} #if not self.symbols: - # self.symbols='01' # if nothing else defined, then 0 and 1 are the default states - #self.unambiguous_letters=self.symbols + # self.symbols = '01' # if nothing else defined, then 0 and 1 are the default states + #self.unambiguous_letters = self.symbols else: - raise NexusError('Unsupported datatype: '+self.datatype) - self.valid_characters=''.join(self.ambiguous_values)+self.unambiguous_letters + raise NexusError('Unsupported datatype: ' + self.datatype) + self.valid_characters = ''.join(self.ambiguous_values) + self.unambiguous_letters if not self.respectcase: - self.valid_characters=self.valid_characters.lower()+self.valid_characters.upper() + self.valid_characters = self.valid_characters.lower() + self.valid_characters.upper() #we have to sort the reverse ambig coding dict key characters: #to be sure that it's 'ACGT':'N' and not 'GTCA':'N' - rev=dict((i[1],i[0]) for i in self.ambiguous_values.iteritems() if i[0]!='X') - self.rev_ambiguous_values={} - for (k,v) in rev.iteritems(): - key=[c for c in k] - key.sort() - self.rev_ambiguous_values[''.join(key)]=v + rev=dict((i[1], i[0]) for i in self.ambiguous_values.items() if i[0]!='X') + self.rev_ambiguous_values = {} + for (k, v) in rev.items(): + key = sorted(c for c in k) + self.rev_ambiguous_values[''.join(key)] = v #overwrite symbols for datype rna,dna,nucleotide - if self.datatype in ['dna','rna','nucleotide']: - self.symbols=self.alphabet.letters + if self.datatype in ['dna', 'rna', 'nucleotide']: + self.symbols = self.alphabet.letters if self.missing not in self.ambiguous_values: - self.ambiguous_values[self.missing]=self.unambiguous_letters+self.gap - self.ambiguous_values[self.gap]=self.gap - elif self.datatype=='standard': + self.ambiguous_values[self.missing] = self.unambiguous_letters+self.gap + self.ambiguous_values[self.gap] = self.gap + elif self.datatype == 'standard': if not self.symbols: - self.symbols=['1','0'] + self.symbols = ['1', '0'] if 'missing' in options: - self.missing=options['missing'][0] + self.missing = options['missing'][0] if 'gap' in options: - self.gap=options['gap'][0] + self.gap = options['gap'][0] if 'equate' in options: - self.equate=options['equate'] + self.equate = options['equate'] if 'matchchar' in options: - self.matchchar=options['matchchar'][0] + self.matchchar = options['matchchar'][0] if 'labels' in options: - self.labels=options['labels'] + self.labels = options['labels'] if 'transpose' in options: raise NexusError('TRANSPOSE is not supported!') - self.transpose=True + self.transpose = True if 'interleave' in options: - if options['interleave'] is None or options['interleave'].lower()=='yes': - self.interleave=True + if options['interleave'] is None or options['interleave'].lower() == 'yes': + self.interleave = True if 'tokens' in options: - self.tokens=True + self.tokens = True if 'notokens' in options: - self.tokens=False + self.tokens = False - def _set(self,options): - self.set=options + def _set(self, options): + self.set = options - def _options(self,options): - self.options=options + def _options(self, options): + self.options = options - def _eliminate(self,options): - self.eliminate=options + def _eliminate(self, options): + self.eliminate = options - def _taxlabels(self,options): + def _taxlabels(self, options): """Get taxon labels (PRIVATE). As the taxon names are already in the matrix, this is superfluous @@ -776,358 +791,357 @@ taxon names easier. """ pass - #self.taxlabels=[] - #opts=CharBuffer(options) + #self.taxlabels = [] + #opts = CharBuffer(options) #while True: - # taxon=quotestrip(opts.next_word()) + # taxon = quotestrip(opts.next_word()) # if not taxon: # break # self.taxlabels.append(taxon) - def _check_taxlabels(self,taxon): + def _check_taxlabels(self, taxon): """Check for presence of taxon in self.taxlabels.""" # According to NEXUS standard, underscores shall be treated as spaces..., # so checking for identity is more difficult - nextaxa=dict([(t.replace(' ','_'),t) for t in self.taxlabels]) - nexid=taxon.replace(' ','_') + nextaxa = dict((t.replace(' ', '_'), t) for t in self.taxlabels) + nexid = taxon.replace(' ', '_') return nextaxa.get(nexid) - def _charlabels(self,options): - self.charlabels={} - opts=CharBuffer(options) + def _charlabels(self, options): + self.charlabels = {} + opts = CharBuffer(options) while True: - try: - # get id and state - w=opts.next_word() - if w is None: # McClade saves and reads charlabel-lists with terminal comma?! - break - identifier=self._resolve(w,set_type=CHARSET) - state=quotestrip(opts.next_word()) - self.charlabels[identifier]=state - # check for comma or end of command - c=opts.next_nonwhitespace() - if c is None: - break - elif c!=',': - raise NexusError('Missing \',\' in line %s.' % options) - except NexusError: - raise - except: - raise NexusError('Format error in line %s.' % options) + # get id and state + w = opts.next_word() + if w is None: # McClade saves and reads charlabel-lists with terminal comma?! + break + identifier = self._resolve(w, set_type=CHARSET) + state = quotestrip(opts.next_word()) + self.charlabels[identifier] = state + # check for comma or end of command + c = opts.next_nonwhitespace() + if c is None: + break + elif c != ',': + raise NexusError('Missing \',\' in line %s.' % options) - def _charstatelabels(self,options): + def _charstatelabels(self, options): # warning: charstatelabels supports only charlabels-syntax! self._charlabels(options) - def _statelabels(self,options): - #self.charlabels=options + def _statelabels(self, options): + #self.charlabels = options #print 'Command statelabels is not supported and will be ignored.' pass - def _matrix(self,options): + def _matrix(self, options): if not self.ntax or not self.nchar: raise NexusError('Dimensions must be specified before matrix!') - self.matrix={} - taxcount=0 - first_matrix_block=True + self.matrix = {} + taxcount = 0 + first_matrix_block = True #eliminate empty lines and leading/trailing whitespace - lines=[l.strip() for l in options.split('\n') if l.strip()!=''] - lineiter=iter(lines) - while 1: + lines = [l.strip() for l in options.split('\n') if l.strip() != ''] + lineiter = iter(lines) + while True: try: - l=lineiter.next() + l = next(lineiter) except StopIteration: - if taxcountself.ntax: + elif taxcount > self.ntax: raise NexusError('Too many taxa in matrix.') else: break # count the taxa and check for interleaved matrix - taxcount+=1 + taxcount += 1 ##print taxcount - if taxcount>self.ntax: + if taxcount > self.ntax: if not self.interleave: raise NexusError('Too many taxa in matrix - should matrix be interleaved?') else: - taxcount=1 - first_matrix_block=False + taxcount = 1 + first_matrix_block = False #get taxon name and sequence - linechars=CharBuffer(l) - id=quotestrip(linechars.next_word()) - l=linechars.rest().strip() - chars='' + linechars = CharBuffer(l) + id = quotestrip(linechars.next_word()) + l = linechars.rest().strip() + chars = '' if self.interleave: #interleaved matrix #print 'In interleave' if l: - chars=''.join(l.split()) + chars = ''.join(l.split()) else: - chars=''.join(lineiter.next().split()) + chars = ''.join(next(lineiter).split()) else: #non-interleaved matrix - chars=''.join(l.split()) + chars = ''.join(l.split()) while len(chars)1: + codonname = [n for n in self.charpartitions if n not in prev_partitions] + if codonname == [] or len(codonname) > 1: raise NexusError('Formatting Error in codonposset: %s ' % options) else: - self.codonposset=codonname[0] + self.codonposset = codonname[0] - def _codeset(self,options): + def _codeset(self, options): pass def _charpartition(self, options): - charpartition={} - quotelevel=False - opts=CharBuffer(options) - name=self._name_n_vector(opts) + charpartition = {} + quotelevel = False + opts = CharBuffer(options) + name = self._name_n_vector(opts) if not name: raise NexusError('Formatting error in charpartition: %s ' % options) # now collect thesubbpartitions and parse them # subpartitons separated by commas - which unfortunately could be part of a quoted identifier... - sub='' + sub = '' while True: - w=opts.next() - if w is None or (w==',' and not quotelevel): - subname,subindices=self._get_indices(sub,set_type=CHARSET,separator=':') - charpartition[subname]=_make_unique(subindices) - sub='' + w = next(opts) + if w is None or (w == ',' and not quotelevel): + subname, subindices = self._get_indices(sub, set_type=CHARSET, separator=':') + charpartition[subname] = _make_unique(subindices) + sub = '' if w is None: break else: - if w=="'": - quotelevel=not quotelevel - sub+=w + if w == "'": + quotelevel = not quotelevel + sub += w self.charpartitions[name]=charpartition - def _get_indices(self,options,set_type=CHARSET,separator='='): + def _get_indices(self, options, set_type=CHARSET, separator='='): """Parse the taxset/charset specification (PRIVATE). e.g. '1 2 3 - 5 dog cat 10 - 20 \\ 3' --> [0,1,2,3,4,'dog','cat',9,12,15,18] """ - opts=CharBuffer(options) - name=self._name_n_vector(opts,separator=separator) - indices=self._parse_list(opts,set_type=set_type) + opts = CharBuffer(options) + name = self._name_n_vector(opts, separator=separator) + indices = self._parse_list(opts, set_type=set_type) if indices is None: raise NexusError('Formatting error in line: %s ' % options) - return name,indices + return name, indices - def _name_n_vector(self,opts,separator='='): + def _name_n_vector(self, opts, separator='='): """Extract name and check that it's not in vector format.""" - rest=opts.rest() - name=opts.next_word() + rest = opts.rest() + name = opts.next_word() # we ignore * before names - if name=='*': - name=opts.next_word() + if name == '*': + name = opts.next_word() if not name: raise NexusError('Formatting error in line: %s ' % rest) - name=quotestrip(name) - if opts.peek_nonwhitespace=='(': - open=opts.next_nonwhitespace() - qualifier=open.next_word() - close=opts.next_nonwhitespace() - if qualifier.lower()=='vector': + name = quotestrip(name) + if opts.peek_nonwhitespace == '(': + open = opts.next_nonwhitespace() + qualifier = open.next_word() + close = opts.next_nonwhitespace() + if qualifier.lower() == 'vector': raise NexusError('Unsupported VECTOR format in line %s' % (opts)) - elif qualifier.lower()!='standard': + elif qualifier.lower() != 'standard': raise NexusError('Unknown qualifier %s in line %s' % (qualifier, opts)) - if opts.next_nonwhitespace()!=separator: + if opts.next_nonwhitespace() != separator: raise NexusError('Formatting error in line: %s ' % rest) return name - def _parse_list(self,options_buffer,set_type): + def _parse_list(self, options_buffer, set_type): """Parse a NEXUS list (PRIVATE). e.g. [1, 2, 4-8\\2, dog, cat] --> [1,2,4,6,8,17,21], (assuming dog is taxon no. 17 and cat is taxon no. 21). """ - plain_list=[] + plain_list = [] if options_buffer.peek_nonwhitespace(): - try: # capture all possible exceptions and treat them as formatting erros, if they are not NexusError + try: + # capture all possible exceptions and treat them as formatting + # errors, if they are not NexusError while True: - identifier=options_buffer.next_word() # next list element - if not identifier: # end of list? + identifier = options_buffer.next_word() # next list element + if not identifier: # end of list? break - start=self._resolve(identifier,set_type=set_type) - if options_buffer.peek_nonwhitespace()=='-': # followd by - - end=start - step=1 + start = self._resolve(identifier, set_type=set_type) + if options_buffer.peek_nonwhitespace() == '-': # followd by - + end = start + step = 1 # get hyphen and end of range - hyphen=options_buffer.next_nonwhitespace() - end=self._resolve(options_buffer.next_word(),set_type=set_type) - if set_type==CHARSET: - if options_buffer.peek_nonwhitespace()=='\\': # followd by \ - backslash=options_buffer.next_nonwhitespace() - step=int(options_buffer.next_word()) # get backslash and step - plain_list.extend(range(start,end+1,step)) + hyphen = options_buffer.next_nonwhitespace() + end = self._resolve(options_buffer.next_word(), set_type=set_type) + if set_type == CHARSET: + if options_buffer.peek_nonwhitespace() == '\\': # followd by \ + backslash = options_buffer.next_nonwhitespace() + step = int(options_buffer.next_word()) # get backslash and step + plain_list.extend(range(start, end+1, step)) else: - if type(start)==list or type(end)==list: + if isinstance(start, list) or isinstance(end, list): raise NexusError('Name if character sets not allowed in range definition: %s' % identifier) - start=self.taxlabels.index(start) - end=self.taxlabels.index(end) - taxrange=self.taxlabels[start:end+1] + start = self.taxlabels.index(start) + end = self.taxlabels.index(end) + taxrange = self.taxlabels[start:end+1] plain_list.extend(taxrange) else: - if type(start)==list: # start was the name of charset or taxset + if isinstance(start, list): # start was the name of charset or taxset plain_list.extend(start) else: # start was an ordinary identifier plain_list.append(start) @@ -1137,7 +1151,7 @@ return None return plain_list - def _resolve(self,identifier,set_type=None): + def _resolve(self, identifier, set_type=None): """Translate identifier in list into character/taxon index. Characters (which are referred to by their index in Nexus.py): @@ -1150,16 +1164,16 @@ Names are returned unchanged (if plain taxon identifiers), or the names in the corresponding taxon set is returned. """ - identifier=quotestrip(identifier) + identifier = quotestrip(identifier) if not set_type: raise NexusError('INTERNAL ERROR: Need type to resolve identifier.') - if set_type==CHARSET: + if set_type == CHARSET: try: - n=int(identifier) + n = int(identifier) except ValueError: - if self.charlabels and identifier in self.charlabels.itervalues(): + if self.charlabels and identifier in self.charlabels.values(): for k in self.charlabels: - if self.charlabels[k]==identifier: + if self.charlabels[k] == identifier: return k elif self.charsets and identifier in self.charsets: return self.charsets[identifier] @@ -1167,16 +1181,16 @@ raise NexusError('Unknown character identifier: %s' % identifier) else: - if n<=self.nchar: + if n <= self.nchar: return n-1 else: raise NexusError('Illegal character identifier: %d>nchar (=%d).' - % (identifier,self.nchar)) - elif set_type==TAXSET: + % (identifier, self.nchar)) + elif set_type == TAXSET: try: - n=int(identifier) + n = int(identifier) except ValueError: - taxlabels_id=self._check_taxlabels(identifier) + taxlabels_id = self._check_taxlabels(identifier) if taxlabels_id: return taxlabels_id elif self.taxsets and identifier in self.taxsets: @@ -1185,11 +1199,11 @@ raise NexusError('Unknown taxon identifier: %s' % identifier) else: - if n>0 and n<=self.ntax: + if n > 0 and n <= self.ntax: return self.taxlabels[n-1] else: raise NexusError('Illegal taxon identifier: %d>ntax (=%d).' - % (identifier,self.ntax)) + % (identifier, self.ntax)) else: raise NexusError('Unknown set specification: %s.'% set_type) @@ -1209,8 +1223,9 @@ #Not implemented pass - def write_nexus_data_partitions(self, matrix=None, filename=None, blocksize=None, interleave=False, - exclude=[], delete=[], charpartition=None, comment='',mrbayes=False): + def write_nexus_data_partitions(self, matrix=None, filename=None, blocksize=None, + interleave=False, exclude=[], delete=[], + charpartition=None, comment='', mrbayes=False): """Writes a nexus file for each partition in charpartition. Only non-excluded characters and non-deleted taxa are included, @@ -1218,39 +1233,39 @@ """ if not matrix: - matrix=self.matrix + matrix = self.matrix if not matrix: return if not filename: - filename=self.filename + filename = self.filename if charpartition: - pfilenames={} + pfilenames = {} for p in charpartition: - total_exclude=[]+exclude - total_exclude.extend([c for c in range(self.nchar) if c not in charpartition[p]]) - total_exclude=_make_unique(total_exclude) - pcomment=comment+'\nPartition: '+p+'\n' - dot=filename.rfind('.') - if dot>0: - pfilename=filename[:dot]+'_'+p+'.data' + total_exclude = [] + exclude + total_exclude.extend(c for c in range(self.nchar) if c not in charpartition[p]) + total_exclude = _make_unique(total_exclude) + pcomment = comment + '\nPartition: ' + p + '\n' + dot = filename.rfind('.') + if dot > 0: + pfilename = filename[:dot] + '_' + p + '.data' else: - pfilename=filename+'_'+p - pfilenames[p]=pfilename - self.write_nexus_data(filename=pfilename,matrix=matrix,blocksize=blocksize, - interleave=interleave,exclude=total_exclude,delete=delete,comment=pcomment,append_sets=False, - mrbayes=mrbayes) + pfilename = filename+'_'+p + pfilenames[p] = pfilename + self.write_nexus_data(filename=pfilename, matrix=matrix, blocksize=blocksize, + interleave=interleave, exclude=total_exclude, delete=delete, + comment=pcomment, append_sets=False, mrbayes=mrbayes) return pfilenames else: fn=self.filename+'.data' - self.write_nexus_data(filename=fn,matrix=matrix,blocksize=blocksize,interleave=interleave, - exclude=exclude,delete=delete,comment=comment,append_sets=False, - mrbayes=mrbayes) + self.write_nexus_data(filename=fn, matrix=matrix, blocksize=blocksize, + interleave=interleave, exclude=exclude, delete=delete, + comment=comment, append_sets=False, mrbayes=mrbayes) return fn def write_nexus_data(self, filename=None, matrix=None, exclude=[], delete=[], - blocksize=None, interleave=False, interleave_by_partition=False, - comment=None,omit_NEXUS=False,append_sets=True,mrbayes=False, - codons_block=True): + blocksize=None, interleave=False, interleave_by_partition=False, + comment=None, omit_NEXUS=False, append_sets=True, mrbayes=False, + codons_block=True): """Writes a nexus file with data and sets block to a file or handle. Character sets and partitions are appended by default, and are @@ -1268,11 +1283,11 @@ Returns the filename/handle used to write the data. """ if not matrix: - matrix=self.matrix + matrix = self.matrix if not matrix: return if not filename: - filename=self.filename + filename = self.filename if [t for t in delete if not self._check_taxlabels(t)]: raise NexusError('Unknown taxa: %s' % ', '.join(set(delete).difference(set(self.taxlabels)))) @@ -1280,177 +1295,181 @@ if not interleave_by_partition in self.charpartitions: raise NexusError('Unknown partition: %r' % interleave_by_partition) else: - partition=self.charpartitions[interleave_by_partition] + partition = self.charpartitions[interleave_by_partition] # we need to sort the partition names by starting position before we exclude characters - names=_sort_keys_by_values(partition) - newpartition={} + names = _sort_keys_by_values(partition) + newpartition = {} for p in partition: - newpartition[p]=[c for c in partition[p] if c not in exclude] + newpartition[p] = [c for c in partition[p] if c not in exclude] # how many taxa and how many characters are left? - undelete=[taxon for taxon in self.taxlabels if taxon in matrix and taxon not in delete] - cropped_matrix=_seqmatrix2strmatrix(self.crop_matrix(matrix,exclude=exclude,delete=delete)) - ntax_adjusted=len(undelete) - nchar_adjusted=len(cropped_matrix[undelete[0]]) - if not undelete or (undelete and undelete[0]==''): + undelete = [taxon for taxon in self.taxlabels if taxon in matrix and taxon not in delete] + cropped_matrix = _seqmatrix2strmatrix(self.crop_matrix(matrix, exclude=exclude, delete=delete)) + ntax_adjusted = len(undelete) + nchar_adjusted = len(cropped_matrix[undelete[0]]) + if not undelete or (undelete and undelete[0] == ''): return with File.as_handle(filename, mode='w') as fh: if not omit_NEXUS: fh.write('#NEXUS\n') if comment: - fh.write('['+comment+']\n') + fh.write('[' + comment + ']\n') fh.write('begin data;\n') fh.write('\tdimensions ntax=%d nchar=%d;\n' % (ntax_adjusted, nchar_adjusted)) - fh.write('\tformat datatype='+self.datatype) + fh.write('\tformat datatype=' + self.datatype) if self.respectcase: fh.write(' respectcase') if self.missing: - fh.write(' missing='+self.missing) + fh.write(' missing=' + self.missing) if self.gap: - fh.write(' gap='+self.gap) + fh.write(' gap=' + self.gap) if self.matchchar: - fh.write(' matchchar='+self.matchchar) + fh.write(' matchchar=' + self.matchchar) if self.labels: - fh.write(' labels='+self.labels) + fh.write(' labels=' + self.labels) if self.equate: - fh.write(' equate='+self.equate) + fh.write(' equate=' + self.equate) if interleave or interleave_by_partition: fh.write(' interleave') fh.write(';\n') #if self.taxlabels: # fh.write('taxlabels '+' '.join(self.taxlabels)+';\n') if self.charlabels: - newcharlabels=self._adjust_charlabels(exclude=exclude) - clkeys=sorted(newcharlabels) - fh.write('charlabels '+', '.join(["%s %s" % (k+1,safename(newcharlabels[k])) for k in clkeys])+';\n') + newcharlabels = self._adjust_charlabels(exclude=exclude) + clkeys = sorted(newcharlabels) + fh.write('charlabels ' + + ', '.join("%s %s" % (k+1, safename(newcharlabels[k])) for k in clkeys) + + ';\n') fh.write('matrix\n') if not blocksize: if interleave: - blocksize=70 + blocksize = 70 else: - blocksize=self.nchar + blocksize = self.nchar # delete deleted taxa and ecxclude excluded characters... - namelength=max([len(safename(t,mrbayes=mrbayes)) for t in undelete]) + namelength = max(len(safename(t, mrbayes=mrbayes)) for t in undelete) if interleave_by_partition: # interleave by partitions, but adjust partitions with regard to excluded characters - seek=0 + seek = 0 for p in names: - fh.write('[%s: %s]\n' % (interleave_by_partition,p)) - if len(newpartition[p])>0: + fh.write('[%s: %s]\n' % (interleave_by_partition, p)) + if len(newpartition[p]) > 0: for taxon in undelete: - fh.write(safename(taxon,mrbayes=mrbayes).ljust(namelength+1)) + fh.write(safename(taxon, mrbayes=mrbayes).ljust(namelength+1)) fh.write(cropped_matrix[taxon][seek:seek+len(newpartition[p])]+'\n') fh.write('\n') else: fh.write('[empty]\n\n') - seek+=len(newpartition[p]) + seek += len(newpartition[p]) elif interleave: - for seek in range(0,nchar_adjusted,blocksize): + for seek in range(0, nchar_adjusted, blocksize): for taxon in undelete: - fh.write(safename(taxon,mrbayes=mrbayes).ljust(namelength+1)) + fh.write(safename(taxon, mrbayes=mrbayes).ljust(namelength+1)) fh.write(cropped_matrix[taxon][seek:seek+blocksize]+'\n') fh.write('\n') else: for taxon in undelete: if blocksize'+safename(taxon)+'\n') - for i in range(0, len(str(self.matrix[taxon])), width): - fh.write(str(self.matrix[taxon])[i:i+width] + '\n') - fh.close() + filename = self.filename+'.fas' + with open(filename, 'w') as fh: + for taxon in self.taxlabels: + fh.write('>' + safename(taxon) + '\n') + for i in range(0, len(str(self.matrix[taxon])), width): + fh.write(str(self.matrix[taxon])[i:i+width] + '\n') return filename def export_phylip(self, filename=None): @@ -1459,296 +1478,290 @@ Note that this writes a relaxed PHYLIP format file, where the names are not truncated, nor checked for invalid characters.""" if not filename: - if '.' in self.filename and self.filename.split('.')[-1].lower() in ['paup','nexus','nex','dat']: - filename='.'.join(self.filename.split('.')[:-1])+'.phy' + if '.' in self.filename and self.filename.split('.')[-1].lower() in ['paup', 'nexus', 'nex', 'dat']: + filename = '.'.join(self.filename.split('.')[:-1])+'.phy' else: - filename=self.filename+'.phy' - fh=open(filename,'w') - fh.write('%d %d\n' % (self.ntax,self.nchar)) - for taxon in self.taxlabels: - fh.write('%s %s\n' % (safename(taxon), str(self.matrix[taxon]))) - fh.close() + filename = self.filename+'.phy' + with open(filename, 'w') as fh: + fh.write('%d %d\n' % (self.ntax, self.nchar)) + for taxon in self.taxlabels: + fh.write('%s %s\n' % (safename(taxon), str(self.matrix[taxon]))) return filename - def constant(self,matrix=None,delete=[],exclude=[]): + def constant(self, matrix=None, delete=[], exclude=[]): """Return a list with all constant characters.""" if not matrix: - matrix=self.matrix - undelete=[t for t in self.taxlabels if t in matrix and t not in delete] + matrix = self.matrix + undelete = [t for t in self.taxlabels if t in matrix and t not in delete] if not undelete: return None - elif len(undelete)==1: + elif len(undelete) == 1: return [x for x in range(len(matrix[undelete[0]])) if x not in exclude] # get the first sequence and expand all ambiguous values - constant=[(x,self.ambiguous_values.get(n.upper(),n.upper())) for - x,n in enumerate(str(matrix[undelete[0]])) if x not in exclude] + constant = [(x, self.ambiguous_values.get(n.upper(), n.upper())) for + x, n in enumerate(str(matrix[undelete[0]])) if x not in exclude] for taxon in undelete[1:]: - newconstant=[] + newconstant = [] for site in constant: #print '%d (paup=%d)' % (site[0],site[0]+1), - seqsite=matrix[taxon][site[0]].upper() + seqsite = matrix[taxon][site[0]].upper() #print seqsite,'checked against',site[1],'\t', - if seqsite==self.missing or (seqsite==self.gap and self.options['gapmode'].lower()=='missing') or seqsite==site[1]: + if seqsite == self.missing \ + or (seqsite == self.gap and self.options['gapmode'].lower() == 'missing') \ + or seqsite == site[1]: # missing or same as before -> ok newconstant.append(site) - elif seqsite in site[1] or site[1]==self.missing or (self.options['gapmode'].lower()=='missing' and site[1]==self.gap): + elif seqsite in site[1] \ + or site[1] == self.missing \ + or (self.options['gapmode'].lower() == 'missing' and site[1] == self.gap): # subset of an ambig or only missing in previous -> take subset - newconstant.append((site[0],self.ambiguous_values.get(seqsite,seqsite))) - elif seqsite in self.ambiguous_values: # is it an ambig: check the intersection with prev. values + newconstant.append((site[0], self.ambiguous_values.get(seqsite, seqsite))) + elif seqsite in self.ambiguous_values: + # is it an ambig: check the intersection with prev. values intersect = set(self.ambiguous_values[seqsite]).intersection(set(site[1])) if intersect: - newconstant.append((site[0],''.join(intersect))) + newconstant.append((site[0], ''.join(intersect))) # print 'ok' #else: # print 'failed' #else: # print 'failed' - constant=newconstant - cpos=[s[0] for s in constant] + constant = newconstant + cpos = [s[0] for s in constant] return cpos - def cstatus(self,site,delete=[],narrow=True): + def cstatus(self, site, delete=[], narrow=True): """Summarize character. narrow=True: paup-mode (a c ? --> ac; ? ? ? --> ?) narrow=false: (a c ? --> a c g t -; ? ? ? --> a c g t -) """ - undelete=[t for t in self.taxlabels if t not in delete] + undelete = [t for t in self.taxlabels if t not in delete] if not undelete: return None - cstatus=[] + cstatus = [] for t in undelete: - c=self.matrix[t][site].upper() - if self.options.get('gapmode')=='missing' and c==self.gap: - c=self.missing - if narrow and c==self.missing: + c = self.matrix[t][site].upper() + if self.options.get('gapmode') == 'missing' and c == self.gap: + c = self.missing + if narrow and c == self.missing: if c not in cstatus: cstatus.append(c) else: - cstatus.extend([b for b in self.ambiguous_values[c] if b not in cstatus]) + cstatus.extend(b for b in self.ambiguous_values[c] if b not in cstatus) if self.missing in cstatus and narrow and len(cstatus)>1: - cstatus=[c for c in cstatus if c!=self.missing] + cstatus = [c for c in cstatus if c != self.missing] cstatus.sort() return cstatus - def weighted_stepmatrix(self,name='your_name_here',exclude=[],delete=[]): + def weighted_stepmatrix(self, name='your_name_here', exclude=[], delete=[]): """Calculates a stepmatrix for weighted parsimony. See Wheeler (1990), Cladistics 6:269-275 and Felsenstein (1981), Biol. J. Linn. Soc. 16:183-196 """ - m=StepMatrix(self.unambiguous_letters,self.gap) + m = StepMatrix(self.unambiguous_letters, self.gap) for site in [s for s in range(self.nchar) if s not in exclude]: - cstatus=self.cstatus(site,delete) - for i,b1 in enumerate(cstatus[:-1]): + cstatus = self.cstatus(site, delete) + for i, b1 in enumerate(cstatus[:-1]): for b2 in cstatus[i+1:]: - m.add(b1.upper(),b2.upper(),1) + m.add(b1.upper(), b2.upper(), 1) return m.transformation().weighting().smprint(name=name) - def crop_matrix(self,matrix=None, delete=[], exclude=[]): + def crop_matrix(self, matrix=None, delete=[], exclude=[]): """Return a matrix without deleted taxa and excluded characters.""" if not matrix: - matrix=self.matrix + matrix = self.matrix if [t for t in delete if not self._check_taxlabels(t)]: raise NexusError('Unknown taxa: %s' % ', '.join(set(delete).difference(self.taxlabels))) - if exclude!=[]: - undelete=[t for t in self.taxlabels if t in matrix and t not in delete] + if exclude != []: + undelete = [t for t in self.taxlabels if t in matrix and t not in delete] if not undelete: return {} - m=[str(matrix[k]) for k in undelete] - zipped_m=zip(*m) - sitesm=[s for i,s in enumerate(zipped_m) if i not in exclude] - if sitesm==[]: - return dict([(t,Seq('',self.alphabet)) for t in undelete]) - else: - zipped_sitesm=zip(*sitesm) - m=[Seq(s,self.alphabet) for s in map(''.join,zipped_sitesm)] - return dict(zip(undelete,m)) + m = [str(matrix[k]) for k in undelete] + sitesm = [s for i, s in enumerate(zip(*m)) if i not in exclude] + if sitesm == []: + return dict((t, Seq('', self.alphabet)) for t in undelete) + else: + m = [Seq(s, self.alphabet) for s in (''.join(x) for x in zip(*sitesm))] + return dict(zip(undelete, m)) else: - return dict([(t,matrix[t]) for t in self.taxlabels if t in matrix and t not in delete]) + return dict((t, matrix[t]) for t in self.taxlabels if t in matrix and t not in delete) - def bootstrap(self,matrix=None,delete=[],exclude=[]): + def bootstrap(self, matrix=None, delete=[], exclude=[]): """Return a bootstrapped matrix.""" if not matrix: - matrix=self.matrix - seqobjects=isinstance(matrix[matrix.keys()[0]],Seq) # remember if Seq objects - cm=self.crop_matrix(delete=delete,exclude=exclude) # crop data out + matrix = self.matrix + seqobjects = isinstance(matrix[list(matrix.keys())[0]], Seq) # remember if Seq objects + cm = self.crop_matrix(delete=delete, exclude=exclude) # crop data out if not cm: # everything deleted? return {} - elif len(cm[cm.keys()[0]])==0: # everything excluded? + elif not cm[list(cm.keys())[0]]: # everything excluded? return cm - undelete=[t for t in self.taxlabels if t in cm] + undelete = [t for t in self.taxlabels if t in cm] if seqobjects: - sitesm=zip(*[str(cm[t]) for t in undelete]) - alphabet=matrix[matrix.keys()[0]].alphabet + sitesm = list(zip(*[str(cm[t]) for t in undelete])) + alphabet = matrix[list(matrix.keys())[0]].alphabet else: - sitesm=zip(*[cm[t] for t in undelete]) - bootstrapsitesm=[sitesm[random.randint(0,len(sitesm)-1)] for i in range(len(sitesm))] - bootstrapseqs=map(''.join,zip(*bootstrapsitesm)) + sitesm = list(zip(*[cm[t] for t in undelete])) + bootstrapsitesm = [sitesm[random.randint(0, len(sitesm)-1)] for i in range(len(sitesm))] + bootstrapseqs = [''.join(x) for x in zip(*bootstrapsitesm)] if seqobjects: - bootstrapseqs=[Seq(s,alphabet) for s in bootstrapseqs] - return dict(zip(undelete,bootstrapseqs)) + bootstrapseqs = [Seq(s, alphabet) for s in bootstrapseqs] + return dict(zip(undelete, bootstrapseqs)) - def add_sequence(self,name,sequence): + def add_sequence(self, name, sequence): """Adds a sequence (string) to the matrix.""" if not name: raise NexusError('New sequence must have a name') - diff=self.nchar-len(sequence) - if diff<0: - self.insert_gap(self.nchar,-diff) - elif diff>0: - sequence+=self.missing*diff + diff = self.nchar-len(sequence) + if diff < 0: + self.insert_gap(self.nchar, -diff) + elif diff > 0: + sequence += self.missing*diff if name in self.taxlabels: - unique_name=_unique_label(self.taxlabels,name) + unique_name = _unique_label(self.taxlabels, name) #print "WARNING: Sequence name %s is already present. Sequence was added as %s." % (name,unique_name) else: - unique_name=name + unique_name = name assert unique_name not in self.matrix, "ERROR. There is a discrepancy between taxlabels and matrix keys. Report this as a bug." - self.matrix[unique_name]=Seq(sequence,self.alphabet) - self.ntax+=1 + self.matrix[unique_name] = Seq(sequence, self.alphabet) + self.ntax += 1 self.taxlabels.append(unique_name) self.unaltered_taxlabels.append(name) - def insert_gap(self,pos,n=1,leftgreedy=False): + def insert_gap(self, pos, n=1, leftgreedy=False): """Add a gap into the matrix and adjust charsets and partitions. pos=0: first position pos=nchar: last position """ - def _adjust(set,x,d,leftgreedy=False): + def _adjust(set, x, d, leftgreedy=False): """Adjusts character sets if gaps are inserted, taking care of new gaps within a coherent character set.""" # if 3 gaps are inserted at pos. 9 in a set that looks like 1 2 3 8 9 10 11 13 14 15 # then the adjusted set will be 1 2 3 8 9 10 11 12 13 14 15 16 17 18 # but inserting into position 8 it will stay like 1 2 3 11 12 13 14 15 16 17 18 set.sort() - addpos=0 - for i,c in enumerate(set): - if c>=x: - set[i]=c+d + addpos = 0 + for i, c in enumerate(set): + if c >= x: + set[i] = c + d # if we add gaps within a group of characters, we want the gap position included in this group - if c==x: + if c == x: if leftgreedy or (i>0 and set[i-1]==c-1): - addpos=i - if addpos>0: - set[addpos:addpos]=range(x,x+d) + addpos = i + if addpos > 0: + set[addpos:addpos] = list(range(x, x+d)) return set - if pos<0 or pos>self.nchar: + if pos < 0 or pos > self.nchar: raise NexusError('Illegal gap position: %d' % pos) - if n==0: + if n == 0: return - if self.taxlabels: - #python 2.3 does not support zip(*[]) - sitesm=zip(*[str(self.matrix[t]) for t in self.taxlabels]) - else: - sitesm=[] - sitesm[pos:pos]=[['-']*len(self.taxlabels)]*n - # #self.matrix=dict([(taxon,Seq(map(''.join,zip(*sitesm))[i],self.alphabet)) for\ - # i,taxon in enumerate(self.taxlabels)]) - zipped=zip(*sitesm) - mapped=map(''.join,zipped) - listed=[(taxon,Seq(mapped[i],self.alphabet)) for i,taxon in enumerate(self.taxlabels)] - self.matrix=dict(listed) - self.nchar+=n + sitesm = list(zip(*[str(self.matrix[t]) for t in self.taxlabels])) + sitesm[pos:pos] = [['-']*len(self.taxlabels)] * n + mapped = [''.join(x) for x in zip(*sitesm)] + listed = [(taxon, Seq(mapped[i], self.alphabet)) for i, taxon in enumerate(self.taxlabels)] + self.matrix = dict(listed) + self.nchar += n # now adjust character sets - for i,s in self.charsets.iteritems(): - self.charsets[i]=_adjust(s,pos,n,leftgreedy=leftgreedy) + for i, s in self.charsets.items(): + self.charsets[i] = _adjust(s, pos, n, leftgreedy=leftgreedy) for p in self.charpartitions: - for sp,s in self.charpartitions[p].iteritems(): - self.charpartitions[p][sp]=_adjust(s,pos,n,leftgreedy=leftgreedy) + for sp, s in self.charpartitions[p].items(): + self.charpartitions[p][sp] = _adjust(s, pos, n, leftgreedy=leftgreedy) # now adjust character state labels - self.charlabels=self._adjust_charlabels(insert=[pos]*n) + self.charlabels = self._adjust_charlabels(insert=[pos]*n) return self.charlabels - def _adjust_charlabels(self,exclude=None,insert=None): + def _adjust_charlabels(self, exclude=None, insert=None): """Return adjusted indices of self.charlabels if characters are excluded or inserted.""" if exclude and insert: raise NexusError('Can\'t exclude and insert at the same time') if not self.charlabels: return None - labels=sorted(self.charlabels) - newcharlabels={} + labels = sorted(self.charlabels) + newcharlabels = {} if exclude: exclude.sort() - exclude.append(sys.maxint) - excount=0 + exclude.append(sys.maxsize) + excount = 0 for c in labels: if not c in exclude: - while c>exclude[excount]: - excount+=1 - newcharlabels[c-excount]=self.charlabels[c] + while c > exclude[excount]: + excount += 1 + newcharlabels[c-excount] = self.charlabels[c] elif insert: insert.sort() - insert.append(sys.maxint) - icount=0 + insert.append(sys.maxsize) + icount = 0 for c in labels: - while c>=insert[icount]: - icount+=1 - newcharlabels[c+icount]=self.charlabels[c] + while c >= insert[icount]: + icount += 1 + newcharlabels[c+icount] = self.charlabels[c] else: return self.charlabels return newcharlabels - def invert(self,charlist): + def invert(self, charlist): """Returns all character indices that are not in charlist.""" return [c for c in range(self.nchar) if c not in charlist] - def gaponly(self,include_missing=False): + def gaponly(self, include_missing=False): """Return gap-only sites.""" - gap=set(self.gap) + gap = set(self.gap) if include_missing: gap.add(self.missing) - sitesm=zip(*[str(self.matrix[t]) for t in self.taxlabels]) - gaponly=[i for i,site in enumerate(sitesm) if set(site).issubset(gap)] - return gaponly + sitesm = zip(*[str(self.matrix[t]) for t in self.taxlabels]) + return [i for i, site in enumerate(sitesm) if set(site).issubset(gap)] - def terminal_gap_to_missing(self,missing=None,skip_n=True): + def terminal_gap_to_missing(self, missing=None, skip_n=True): """Replaces all terminal gaps with missing character. Mixtures like ???------??------- are properly resolved.""" if not missing: - missing=self.missing - replace=[self.missing,self.gap] + missing = self.missing + replace = [self.missing, self.gap] if not skip_n: - replace.extend(['n','N']) + replace.extend(['n', 'N']) for taxon in self.taxlabels: - sequence=str(self.matrix[taxon]) - length=len(sequence) - start,end=get_start_end(sequence,skiplist=replace) - if start==-1 and end==-1: - sequence=missing*length + sequence = str(self.matrix[taxon]) + length = len(sequence) + start, end = get_start_end(sequence, skiplist=replace) + if start == -1 and end == -1: + sequence = missing*length else: - sequence=sequence[:end+1]+missing*(length-end-1) - sequence=start*missing+sequence[start:] + sequence = sequence[:end+1] + missing*(length-end-1) + sequence = start*missing + sequence[start:] assert length==len(sequence), 'Illegal sequence manipulation in Nexus.terminal_gap_to_missing in taxon %s' % taxon - self.matrix[taxon]=Seq(sequence,self.alphabet) + self.matrix[taxon] = Seq(sequence, self.alphabet) try: import cnexus except ImportError: def _get_command_lines(file_contents): - lines=_kill_comments_and_break_lines(file_contents) - commandlines=_adjust_lines(lines) + lines = _kill_comments_and_break_lines(file_contents) + commandlines = _adjust_lines(lines) return commandlines else: def _get_command_lines(file_contents): - decommented=cnexus.scanfile(file_contents) + decommented = cnexus.scanfile(file_contents) #check for unmatched parentheses - if decommented=='[' or decommented==']': + if decommented == '[' or decommented == ']': raise NexusError('Unmatched %s' % decommented) # cnexus can't return lists, so in analogy we separate # commandlines with chr(7) (a character that shouldn't be part of a # nexus file under normal circumstances) - commandlines=_adjust_lines(decommented.split(chr(7))) + commandlines = _adjust_lines(decommented.split(chr(7))) return commandlines diff -Nru python-biopython-1.62/Bio/Nexus/Nodes.py python-biopython-1.63/Bio/Nexus/Nodes.py --- python-biopython-1.62/Bio/Nexus/Nodes.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Nexus/Nodes.py 2013-12-05 14:10:43.000000000 +0000 @@ -38,7 +38,7 @@ def all_ids(self): """Return a list of all node ids.""" - return self.chain.keys() + return list(self.chain.keys()) def add(self,node,prev=None): """Attaches node to another.""" @@ -53,7 +53,7 @@ self.chain[id]=node return id - def collapse(self,id): + def collapse(self, id): """Deletes node from chain and relinks successors to predecessor.""" if id not in self.chain: raise ChainException('Unknown ID: '+str(id)) @@ -67,14 +67,14 @@ self.kill(id) return node - def kill(self,id): + def kill(self, id): """Kills a node from chain without caring to what it is connected.""" if id not in self.chain: raise ChainException('Unknown ID: '+str(id)) else: del self.chain[id] - def unlink(self,id): + def unlink(self, id): """Disconnects node from his predecessor.""" if id not in self.chain: raise ChainException('Unknown ID: '+str(id)) @@ -85,7 +85,7 @@ self.chain[id].prev=None return prev_id - def link(self, parent,child): + def link(self, parent, child): """Connects son to parent.""" if child not in self.chain: raise ChainException('Unknown ID: '+str(child)) @@ -96,26 +96,26 @@ self.chain[parent].succ.append(child) self.chain[child].set_prev(parent) - def is_parent_of(self,parent,grandchild): + def is_parent_of(self, parent, grandchild): """Check if grandchild is a subnode of parent.""" if grandchild==parent or grandchild in self.chain[parent].get_succ(): return True else: for sn in self.chain[parent].get_succ(): - if self.is_parent_of(sn,grandchild): + if self.is_parent_of(sn, grandchild): return True else: return False - def trace(self,start,finish): + def trace(self, start, finish): """Returns a list of all node_ids between two nodes (excluding start, including end).""" if start not in self.chain or finish not in self.chain: raise NodeException('Unknown node.') - if not self.is_parent_of(start,finish) or start==finish: + if not self.is_parent_of(start, finish) or start==finish: return [] for sn in self.chain[start].get_succ(): - if self.is_parent_of(sn,finish): - return [sn]+self.trace(sn,finish) + if self.is_parent_of(sn, finish): + return [sn]+self.trace(sn, finish) class Node(object): @@ -128,7 +128,7 @@ self.prev=None self.succ=[] - def set_id(self,id): + def set_id(self, id): """Sets the id of a node, if not set yet.""" if self.id is not None: raise NodeException('Node id cannot be changed.') @@ -146,24 +146,24 @@ """Returns the id of the node's predecessor.""" return self.prev - def add_succ(self,id): + def add_succ(self, id): """Adds a node id to the node's successors.""" - if isinstance(id,type([])): + if isinstance(id, type([])): self.succ.extend(id) else: self.succ.append(id) - def remove_succ(self,id): + def remove_succ(self, id): """Removes a node id from the node's successors.""" self.succ.remove(id) - def set_succ(self,new_succ): + def set_succ(self, new_succ): """Sets the node's successors.""" - if not isinstance(new_succ,type([])): + if not isinstance(new_succ, type([])): raise NodeException('Node successor must be of list type.') self.succ=new_succ - def set_prev(self,id): + def set_prev(self, id): """Sets the node's predecessor.""" self.prev=id @@ -171,6 +171,6 @@ """Returns a node's data.""" return self.data - def set_data(self,data): + def set_data(self, data): """Sets a node's data.""" self.data=data diff -Nru python-biopython-1.62/Bio/Nexus/Trees.py python-biopython-1.63/Bio/Nexus/Trees.py --- python-biopython-1.62/Bio/Nexus/Trees.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Nexus/Trees.py 2013-12-05 14:10:43.000000000 +0000 @@ -12,9 +12,11 @@ nodes). """ +from __future__ import print_function + import random import sys -import Nodes +from . import Nodes PRECISION_BRANCHLENGTH=6 PRECISION_SUPPORT=6 @@ -61,14 +63,14 @@ self.root = self.add(root) if tree: # use the tree we have # if Tree is called from outside Nexus parser, we need to get rid of linebreaks, etc - tree=tree.strip().replace('\n','').replace('\r','') + tree=tree.strip().replace('\n', '').replace('\r', '') # there's discrepancy whether newick allows semicolons et the end tree=tree.rstrip(';') subtree_info, base_info = self._parse(tree) root.data = self._add_nodedata(root.data, [[], base_info]) - self._add_subtree(parent_id=root.id,tree=subtree_info) + self._add_subtree(parent_id=root.id, tree=subtree_info) - def _parse(self,tree): + def _parse(self, tree): """Parses (a,b,c...)[[[xx]:]yy] into subcomponents and travels down recursively.""" #Remove any leading/trailing white space - want any string starting #with " (..." should be recognised as a leaf, "(..." @@ -80,15 +82,15 @@ nodecomment=tree.find(NODECOMMENT_START) colon=tree.find(':') if colon==-1 and nodecomment==-1: # none - return [tree,[None]] + return [tree, [None]] elif colon==-1 and nodecomment>-1: # only special comment - return [tree[:nodecomment],self._get_values(tree[nodecomment:])] + return [tree[:nodecomment], self._get_values(tree[nodecomment:])] elif colon>-1 and nodecomment==-1: # only numerical values - return [tree[:colon],self._get_values(tree[colon+1:])] + return [tree[:colon], self._get_values(tree[colon+1:])] elif colon < nodecomment: # taxon name ends at first colon or with special comment - return [tree[:colon],self._get_values(tree[colon+1:])] + return [tree[:colon], self._get_values(tree[colon+1:])] else: - return [tree[:nodecomment],self._get_values(tree[nodecomment:])] + return [tree[:nodecomment], self._get_values(tree[nodecomment:])] else: closing=tree.rfind(')') val=self._get_values(tree[closing+1:]) @@ -97,7 +99,7 @@ subtrees=[] plevel=0 prev=1 - for p in range(1,closing): + for p in range(1, closing): if tree[p]=='(': plevel+=1 elif tree[p]==')': @@ -107,7 +109,7 @@ prev=p+1 subtrees.append(tree[prev:closing]) subclades=[self._parse(subtree) for subtree in subtrees] - return [subclades,val] + return [subclades, val] def _add_subtree(self,parent_id=None,tree=None): """Adds leaf or tree (in newick format) to a parent_id.""" @@ -116,19 +118,19 @@ for st in tree: nd=self.dataclass() nd = self._add_nodedata(nd, st) - if type(st[0])==list: # it's a subtree + if isinstance(st[0], list): # it's a subtree sn=Nodes.Node(nd) - self.add(sn,parent_id) - self._add_subtree(sn.id,st[0]) + self.add(sn, parent_id) + self._add_subtree(sn.id, st[0]) else: # it's a leaf nd.taxon=st[0] leaf=Nodes.Node(nd) - self.add(leaf,parent_id) + self.add(leaf, parent_id) def _add_nodedata(self, nd, st): """Add data to the node parsed from the comments, taxon and support. """ - if isinstance(st[1][-1],str) and st[1][-1].startswith(NODECOMMENT_START): + if isinstance(st[1][-1], str) and st[1][-1].startswith(NODECOMMENT_START): nd.comment=st[1].pop(-1) # if the first element is a string, it's the subtree node taxon elif isinstance(st[1][0], str): @@ -188,7 +190,7 @@ for sn in self._walk(n): yield sn - def node(self,node_id): + def node(self, node_id): """Return the instance of node_id. node = node(self,node_id) @@ -214,20 +216,20 @@ if parent_data.taxon: node.data.taxon=parent_data.taxon+str(i) node.data.branchlength=branchlength - ids.append(self.add(node,parent_id)) + ids.append(self.add(node, parent_id)) return ids - def search_taxon(self,taxon): + def search_taxon(self, taxon): """Returns the first matching taxon in self.data.taxon. Not restricted to terminal nodes. node_id = search_taxon(self,taxon) """ - for id,node in self.chain.iteritems(): + for id, node in self.chain.items(): if node.data.taxon==taxon: return id return None - def prune(self,taxon): + def prune(self, taxon): """Prunes a terminal taxon from the tree. id_of_previous_node = prune(self,taxon) @@ -281,15 +283,15 @@ """Return a list of all terminal nodes.""" return [i for i in self.all_ids() if self.node(i).succ==[]] - def is_terminal(self,node): + def is_terminal(self, node): """Returns True if node is a terminal node.""" return self.node(node).succ==[] - def is_internal(self,node): + def is_internal(self, node): """Returns True if node is an internal node.""" return len(self.node(node).succ)>0 - def is_preterminal(self,node): + def is_preterminal(self, node): """Returns True if all successors of a node are terminal ones.""" if self.is_terminal(node): return False not in [self.is_terminal(n) for n in self.node(node).succ] @@ -313,9 +315,9 @@ genera=[] for t in taxa: if space_equals_underscore: - t=t.replace(' ','_') + t=t.replace(' ', '_') try: - genus=t.split('_',1)[0] + genus=t.split('_', 1)[0] except: genus='None' if genus not in genera: @@ -347,7 +349,7 @@ node=self.node(node).prev return blen - def set_subtree(self,node): + def set_subtree(self, node): """Return subtree as a set of nested sets. sets = set_subtree(self,node) @@ -357,16 +359,16 @@ return self.node(node).data.taxon else: try: - return frozenset([self.set_subtree(n) for n in self.node(node).succ]) + return frozenset(self.set_subtree(n) for n in self.node(node).succ) except: - print node - print self.node(node).succ + print(node) + print(self.node(node).succ) for n in self.node(node).succ: - print n, self.set_subtree(n) - print [self.set_subtree(n) for n in self.node(node).succ] + print("%s %s" % (n, self.set_subtree(n))) + print([self.set_subtree(n) for n in self.node(node).succ]) raise - def is_identical(self,tree2): + def is_identical(self, tree2): """Compare tree and tree2 for identity. result = is_identical(self,tree2) @@ -384,55 +386,55 @@ missing1=set(tree2.get_taxa())-set(self.get_taxa()) if strict and (missing1 or missing2): if missing1: - print 'Taxon/taxa %s is/are missing in tree %s' % (','.join(missing1) , self.name) + print('Taxon/taxa %s is/are missing in tree %s' % (','.join(missing1), self.name)) if missing2: - print 'Taxon/taxa %s is/are missing in tree %s' % (','.join(missing2) , tree2.name) + print('Taxon/taxa %s is/are missing in tree %s' % (','.join(missing2), tree2.name)) raise TreeError('Can\'t compare trees with different taxon compositions.') - t1=[(set(self.get_taxa(n)),self.node(n).data.support) for n in self.all_ids() if + t1=[(set(self.get_taxa(n)), self.node(n).data.support) for n in self.all_ids() if self.node(n).succ and (self.node(n).data and self.node(n).data.support and self.node(n).data.support>=threshold)] - t2=[(set(tree2.get_taxa(n)),tree2.node(n).data.support) for n in tree2.all_ids() if + t2=[(set(tree2.get_taxa(n)), tree2.node(n).data.support) for n in tree2.all_ids() if tree2.node(n).succ and (tree2.node(n).data and tree2.node(n).data.support and tree2.node(n).data.support>=threshold)] conflict=[] - for (st1,sup1) in t1: - for (st2,sup2) in t2: + for (st1, sup1) in t1: + for (st2, sup2) in t2: if not st1.issubset(st2) and not st2.issubset(st1): # don't hiccup on upstream nodes - intersect,notin1,notin2=st1 & st2, st2-st1, st1-st2 # all three are non-empty sets + intersect, notin1, notin2=st1 & st2, st2-st1, st1-st2 # all three are non-empty sets # if notin1==missing1 or notin2==missing2 <==> st1.issubset(st2) or st2.issubset(st1) ??? if intersect and not (notin1.issubset(missing1) or notin2.issubset(missing2)): # omit conflicts due to missing taxa - conflict.append((st1,sup1,st2,sup2,intersect,notin1,notin2)) + conflict.append((st1, sup1, st2, sup2, intersect, notin1, notin2)) return conflict - def common_ancestor(self,node1,node2): + def common_ancestor(self, node1, node2): """Return the common ancestor that connects two nodes. node_id = common_ancestor(self,node1,node2) """ - l1=[self.root]+self.trace(self.root,node1) - l2=[self.root]+self.trace(self.root,node2) + l1=[self.root]+self.trace(self.root, node1) + l2=[self.root]+self.trace(self.root, node2) return [n for n in l1 if n in l2][-1] - def distance(self,node1,node2): + def distance(self, node1, node2): """Add and return the sum of the branchlengths between two nodes. dist = distance(self,node1,node2) """ - ca=self.common_ancestor(node1,node2) - return self.sum_branchlength(ca,node1)+self.sum_branchlength(ca,node2) + ca=self.common_ancestor(node1, node2) + return self.sum_branchlength(ca, node1)+self.sum_branchlength(ca, node2) - def is_monophyletic(self,taxon_list): + def is_monophyletic(self, taxon_list): """Return node_id of common ancestor if taxon_list is monophyletic, -1 otherwise. result = is_monophyletic(self,taxon_list) """ - if isinstance(taxon_list,str): + if isinstance(taxon_list, str): taxon_set=set([taxon_list]) else: taxon_set=set(taxon_list) node_id=self.root - while 1: + while True: subclade_taxa=set(self.get_taxa(node_id)) if subclade_taxa==taxon_set: # are we there? return node_id @@ -470,7 +472,7 @@ self.node(n).data.support=self.node(n).data.branchlength self.node(n).data.branchlength=0.0 - def convert_absolute_support(self,nrep): + def convert_absolute_support(self, nrep): """Convert absolute support (clade-count) to rel. frequencies. Some software (e.g. PHYLIP consense) just calculate how often clades appear, instead of @@ -509,11 +511,11 @@ # bifurcate randomly at terminal nodes until ntax is reached while len(terminals)1: @@ -760,16 +761,16 @@ # no outgroup specified: use the smallest clade of the root if outgroup is None: try: - succnodes=self.node(self.root).succ - smallest=min([(len(self.get_taxa(n)),n) for n in succnodes]) - outgroup=self.get_taxa(smallest[1]) + succnodes = self.node(self.root).succ + smallest = min((len(self.get_taxa(n)), n) for n in succnodes) + outgroup = self.get_taxa(smallest[1]) except: raise TreeError("Error determining outgroup.") else: # root with user specified outgroup self.root_with_outgroup(outgroup) if bstrees: # calculate consensus - constree=consensus(bstrees,threshold=threshold,outgroup=outgroup) + constree=consensus(bstrees, threshold=threshold, outgroup=outgroup) else: if not constree.has_support(): constree.branchlength2support() @@ -798,13 +799,12 @@ for t in trees: c+=1 #if c%100==0: - # print c + # print(c) if alltaxa!=set(t.get_taxa()): raise TreeError('Trees for consensus must contain the same taxa') t.root_with_outgroup(outgroup=outgroup) for st_node in t._walk(t.root): - subclade_taxa=t.get_taxa(st_node) - subclade_taxa.sort() + subclade_taxa=sorted(t.get_taxa(st_node)) subclade_taxa=str(subclade_taxa) # lists are not hashable if subclade_taxa in clades: clades[subclade_taxa]+=float(t.weight)/total @@ -815,13 +815,13 @@ #else: # countclades[subclade_taxa]=t.weight # weed out clades below threshold - delclades=[c for c,p in clades.iteritems() if round(p,3)>> for (res, property) in iter(map): - ... print res, property + ... print(res, property) @return: iterator """ @@ -133,3 +135,4 @@ if isinstance(res_id, int): ent_id=(chain_id, (' ', res_id, ' '), atom_name, icode) return ent_id + diff -Nru python-biopython-1.62/Bio/PDB/Atom.py python-biopython-1.63/Bio/PDB/Atom.py --- python-biopython-1.62/Bio/PDB/Atom.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PDB/Atom.py 2013-12-05 14:10:43.000000000 +0000 @@ -124,7 +124,7 @@ @type other: L{Atom} """ diff=self.coord-other.coord - return numpy.sqrt(numpy.dot(diff,diff)) + return numpy.sqrt(numpy.dot(diff, diff)) # set methods @@ -262,8 +262,8 @@ Apply rotation and translation to the atomic coordinates. Example: - >>> rotation=rotmat(pi, Vector(1,0,0)) - >>> translation=array((0,0,1), 'f') + >>> rotation=rotmat(pi, Vector(1, 0, 0)) + >>> translation=array((0, 0, 1), 'f') >>> atom.transform(rotation, translation) @param rot: A right multiplying rotation matrix @@ -281,8 +281,8 @@ @return: coordinates as 3D vector @rtype: Vector """ - x,y,z=self.coord - return Vector(x,y,z) + x, y, z=self.coord + return Vector(x, y, z) def copy(self): """ @@ -333,3 +333,4 @@ if occupancy>self.last_occupancy: self.last_occupancy=occupancy self.disordered_select(altloc) + diff -Nru python-biopython-1.62/Bio/PDB/DSSP.py python-biopython-1.63/Bio/PDB/DSSP.py --- python-biopython-1.62/Bio/PDB/DSSP.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PDB/DSSP.py 2013-12-05 14:10:43.000000000 +0000 @@ -6,7 +6,7 @@ """Use the DSSP program to calculate secondary structure and accessibility. You need to have a working version of DSSP (and a license, free for academic -use) in order to use this. For DSSP, see U{http://www.cmbi.kun.nl/gv/dssp/}. +use) in order to use this. For DSSP, see U{http://swift.cmbi.ru.nl/gv/dssp/}. The DSSP codes for secondary structure used here are: @@ -20,10 +20,12 @@ - - None """ -from __future__ import with_statement +from __future__ import print_function + +__docformat__ = "epytext en" import re -from StringIO import StringIO +from Bio._py3k import StringIO import subprocess from Bio.Data import SCOPData @@ -114,7 +116,6 @@ @param filename: the DSSP output file @type filename: string """ - handle = open(filename, "r") with open(filename, "r") as handle: return _make_dssp_dict(handle) @@ -123,15 +124,15 @@ Return a DSSP dictionary that maps (chainid, resid) to aa, ss and accessibility, from an open DSSP file object. - @param filename: the open DSSP output file - @type filename: file + @param handle: the open DSSP output file handle + @type handle: file """ dssp = {} start = 0 keys = [] for l in handle.readlines(): sl = l.split() - if not sl: + if len(sl) < 2: continue if sl[1] == "RESIDUE": # Start parsing from here @@ -153,7 +154,7 @@ acc = int(l[34:38]) phi = float(l[103:109]) psi = float(l[109:115]) - except ValueError, exc: + except ValueError as exc: # DSSP output breaks its own format when there are >9999 # residues, since only 4 digits are allocated to the seq num # field. See 3kic chain T res 321, 1vsy chain T res 6077. @@ -186,7 +187,7 @@ >>> model = structure[0] >>> dssp = DSSP(model, "1MOT.pdb") >>> # DSSP data is accessed by a tuple (chain_id, res_id) - >>> a_key = dssp.keys()[2] + >>> a_key = list(dssp.keys())[2] >>> # residue object, secondary structure, solvent accessibility, >>> # relative accessiblity, phi, psi >>> dssp[a_key] @@ -328,11 +329,11 @@ d = DSSP(model, sys.argv[1]) for r in d: - print r - print "Handled", len(d), "residues" - print d.keys() + print(r) + print("Handled %i residues" % len(d)) + print(d.keys()) if ('A', 1) in d: - print d[('A', 1)] - print s[0]['A'][1].xtra + print(d[('A', 1)]) + print(s[0]['A'][1].xtra) # Secondary structure - print ''.join(d[key][1] for key in d.keys()) + print(''.join(item[1] for item in d)) diff -Nru python-biopython-1.62/Bio/PDB/Entity.py python-biopython-1.63/Bio/PDB/Entity.py --- python-biopython-1.62/Bio/PDB/Entity.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PDB/Entity.py 2013-12-05 14:10:43.000000000 +0000 @@ -156,8 +156,8 @@ Apply rotation and translation to the atomic coordinates. Example: - >>> rotation=rotmat(pi, Vector(1,0,0)) - >>> translation=array((0,0,1), 'f') + >>> rotation=rotmat(pi, Vector(1, 0, 0)) + >>> translation=array((0, 0, 1), 'f') >>> entity.transform(rotation, translation) @param rot: A right multiplying rotation matrix @@ -280,10 +280,8 @@ def disordered_get_id_list(self): "Return a list of id's." - l=self.child_dict.keys() # sort id list alphabetically - l.sort() - return l + return sorted(self.child_dict) def disordered_get(self, id=None): """Get the child object associated with id. @@ -296,4 +294,5 @@ def disordered_get_list(self): "Return list of children." - return self.child_dict.values() + return list(self.child_dict.values()) + diff -Nru python-biopython-1.62/Bio/PDB/FragmentMapper.py python-biopython-1.63/Bio/PDB/FragmentMapper.py --- python-biopython-1.62/Bio/PDB/FragmentMapper.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PDB/FragmentMapper.py 2013-12-05 14:10:43.000000000 +0000 @@ -30,6 +30,8 @@ >>> fragment = fm[residue] """ +from __future__ import print_function + import numpy from Bio.SVDSuperimposer import SVDSuperimposer @@ -62,27 +64,26 @@ @type dir: string """ filename=(dir+"/"+_FRAGMENT_FILE) % (size, length) - fp=open(filename, "r") - flist=[] - # ID of fragment=rank in spec file - fid=0 - for l in fp.readlines(): - # skip comment and blank lines - if l[0]=="*" or l[0]=="\n": - continue - sl=l.split() - if sl[1]=="------": - # Start of fragment definition - f=Fragment(length, fid) - flist.append(f) - # increase fragment id (rank) - fid+=1 - continue - # Add CA coord to Fragment - coord=numpy.array(map(float, sl[0:3])) - # XXX= dummy residue name - f.add_residue("XXX", coord) - fp.close() + with open(filename, "r") as fp: + flist=[] + # ID of fragment=rank in spec file + fid=0 + for l in fp.readlines(): + # skip comment and blank lines + if l[0]=="*" or l[0]=="\n": + continue + sl=l.split() + if sl[1]=="------": + # Start of fragment definition + f=Fragment(length, fid) + flist.append(f) + # increase fragment id (rank) + fid+=1 + continue + # Add CA coord to Fragment + coord = numpy.array([float(x) for x in sl[0:3]]) + # XXX= dummy residue name + f.add_residue("XXX", coord) return flist @@ -284,7 +285,7 @@ index=i-self.edge assert(index>=0) fd[res]=mflist[index] - except PDBException, why: + except PDBException as why: if why == 'CHAINBREAK': # Funny polypeptide - skip pass @@ -323,16 +324,12 @@ import sys - p=PDBParser() - s=p.get_structure("X", sys.argv[1]) - - m=s[0] - fm=FragmentMapper(m, 10, 5, "levitt_data") + p = PDBParser() + s = p.get_structure("X", sys.argv[1]) + m = s[0] + fm = FragmentMapper(m, 10, 5, "levitt_data") for r in Selection.unfold_entities(m, "R"): - - print r, + print("%s:" % r) if r in fm: - print fm[r] - else: - print + print(fm[r]) diff -Nru python-biopython-1.62/Bio/PDB/HSExposure.py python-biopython-1.63/Bio/PDB/HSExposure.py --- python-biopython-1.62/Bio/PDB/HSExposure.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PDB/HSExposure.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,6 +5,8 @@ """Half-sphere exposure and coordination number calculation.""" +from __future__ import print_function + import warnings from math import pi @@ -207,20 +209,19 @@ if len(self.ca_cb_list)==0: warnings.warn("Nothing to draw.", RuntimeWarning) return - fp=open(filename, "w") - fp.write("from pymol.cgo import *\n") - fp.write("from pymol import cmd\n") - fp.write("obj=[\n") - fp.write("BEGIN, LINES,\n") - fp.write("COLOR, %.2f, %.2f, %.2f,\n" % (1.0, 1.0, 1.0)) - for (ca, cb) in self.ca_cb_list: - x,y,z=ca.get_array() - fp.write("VERTEX, %.2f, %.2f, %.2f,\n" % (x,y,z)) - x,y,z=cb.get_array() - fp.write("VERTEX, %.2f, %.2f, %.2f,\n" % (x,y,z)) - fp.write("END]\n") - fp.write("cmd.load_cgo(obj, 'HS')\n") - fp.close() + with open(filename, "w") as fp: + fp.write("from pymol.cgo import *\n") + fp.write("from pymol import cmd\n") + fp.write("obj=[\n") + fp.write("BEGIN, LINES,\n") + fp.write("COLOR, %.2f, %.2f, %.2f,\n" % (1.0, 1.0, 1.0)) + for (ca, cb) in self.ca_cb_list: + x, y, z=ca.get_array() + fp.write("VERTEX, %.2f, %.2f, %.2f,\n" % (x, y, z)) + x, y, z=cb.get_array() + fp.write("VERTEX, %.2f, %.2f, %.2f,\n" % (x, y, z)) + fp.write("END]\n") + fp.write("cmd.load_cgo(obj, 'HS')\n") class HSExposureCB(_AbstractHSExposure): @@ -324,22 +325,22 @@ hse=HSExposureCA(model, radius=RADIUS, offset=OFFSET) for l in hse: - print l - print + print(l) + print("") hse=HSExposureCB(model, radius=RADIUS, offset=OFFSET) for l in hse: - print l - print + print(l) + print("") hse=ExposureCN(model, radius=RADIUS, offset=OFFSET) for l in hse: - print l - print + print(l) + print("") for c in model: for r in c: try: - print r.xtra['PCB_CB_ANGLE'] + print(r.xtra['PCB_CB_ANGLE']) except: pass diff -Nru python-biopython-1.62/Bio/PDB/MMCIF2Dict.py python-biopython-1.63/Bio/PDB/MMCIF2Dict.py --- python-biopython-1.62/Bio/PDB/MMCIF2Dict.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PDB/MMCIF2Dict.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,43 +5,46 @@ """Turn an mmCIF file into a dictionary.""" +from __future__ import print_function + +from Bio._py3k import input as _input + import shlex class MMCIF2Dict(dict): def __init__(self, filename): - handle = open(filename) - loop_flag = False - key = None - tokens = self._tokenize(handle) - token = tokens.next() - self[token[0:5]]=token[5:] - for token in tokens: - if token=="loop_": - loop_flag = True - keys = [] - i = 0 - n = 0 - continue - elif loop_flag: - if token.startswith("_"): - if i > 0: - loop_flag = False + with open(filename) as handle: + loop_flag = False + key = None + tokens = self._tokenize(handle) + token = next(tokens) + self[token[0:5]]=token[5:] + for token in tokens: + if token=="loop_": + loop_flag = True + keys = [] + i = 0 + n = 0 + continue + elif loop_flag: + if token.startswith("_"): + if i > 0: + loop_flag = False + else: + self[token] = [] + keys.append(token) + n += 1 + continue else: - self[token] = [] - keys.append(token) - n += 1 + self[keys[i%n]].append(token) + i+=1 continue + if key is None: + key = token else: - self[keys[i%n]].append(token) - i+=1 - continue - if key is None: - key = token - else: - self[key] = token - key = None - handle.close() + self[key] = token + key = None def _tokenize(self, handle): for line in handle: @@ -66,28 +69,28 @@ import sys if len(sys.argv)!=2: - print "Usage: python MMCIF2Dict filename." + print("Usage: python MMCIF2Dict filename.") filename=sys.argv[1] mmcif_dict = MMCIF2Dict(filename) entry = "" - print "Now type a key ('q' to end, 'k' for a list of all keys):" + print("Now type a key ('q' to end, 'k' for a list of all keys):") while(entry != "q"): - entry = raw_input("MMCIF dictionary key ==> ") + entry = _input("MMCIF dictionary key ==> ") if entry == "q": sys.exit() if entry == "k": for key in mmcif_dict: - print key + print(key) continue try: value=mmcif_dict[entry] if isinstance(value, list): for item in value: - print item + print(item) else: - print value + print(value) except KeyError: - print "No such key found." + print("No such key found.") diff -Nru python-biopython-1.62/Bio/PDB/MMCIFParser.py python-biopython-1.63/Bio/PDB/MMCIFParser.py --- python-biopython-1.62/Bio/PDB/MMCIFParser.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PDB/MMCIFParser.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,10 +5,14 @@ """mmCIF parser""" +from __future__ import print_function + from string import ascii_letters import numpy +from Bio._py3k import range + from Bio.PDB.MMCIF2Dict import MMCIF2Dict from Bio.PDB.StructureBuilder import StructureBuilder from Bio.PDB.PDBExceptions import PDBConstructionException @@ -31,9 +35,9 @@ element_list = None seq_id_list=mmcif_dict["_atom_site.label_seq_id"] chain_id_list=mmcif_dict["_atom_site.label_asym_id"] - x_list=map(float, mmcif_dict["_atom_site.Cartn_x"]) - y_list=map(float, mmcif_dict["_atom_site.Cartn_y"]) - z_list=map(float, mmcif_dict["_atom_site.Cartn_z"]) + x_list = [float(x) for x in mmcif_dict["_atom_site.Cartn_x"]] + y_list = [float(x) for x in mmcif_dict["_atom_site.Cartn_y"]] + z_list = [float(x) for x in mmcif_dict["_atom_site.Cartn_z"]] alt_list=mmcif_dict["_atom_site.label_alt_id"] b_factor_list=mmcif_dict["_atom_site.B_iso_or_equiv"] occupancy_list=mmcif_dict["_atom_site.occupancy"] @@ -73,7 +77,7 @@ # so serial_id means the Model ID specified in the file current_model_id = 0 current_serial_id = 0 - for i in xrange(0, len(atom_id_list)): + for i in range(0, len(atom_id_list)): x=x_list[i] y=y_list[i] z=z_list[i] @@ -128,7 +132,7 @@ if aniso_flag==1: u=(aniso_u11[i], aniso_u12[i], aniso_u13[i], aniso_u22[i], aniso_u23[i], aniso_u33[i]) - mapped_anisou=map(float, u) + mapped_anisou = [float(x) for x in u] anisou_array=numpy.array(mapped_anisou, 'f') structure_builder.set_anisou(anisou_array) # Now try to set the cell @@ -165,7 +169,7 @@ import sys if len(sys.argv) != 2: - print "Usage: python MMCIFparser.py filename" + print("Usage: python MMCIFparser.py filename") raise SystemExit filename=sys.argv[1] @@ -174,7 +178,7 @@ structure=p.get_structure("test", filename) for model in structure.get_list(): - print model + print(model) for chain in model.get_list(): - print chain - print "Found %d residues." % len(chain.get_list()) + print(chain) + print("Found %d residues." % len(chain.get_list())) diff -Nru python-biopython-1.62/Bio/PDB/NACCESS.py python-biopython-1.63/Bio/PDB/NACCESS.py --- python-biopython-1.62/Bio/PDB/NACCESS.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PDB/NACCESS.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,8 +5,12 @@ # NACCESS interface adapted from Bio/PDB/DSSP.py +from __future__ import print_function + import os import tempfile +import shutil +import subprocess from Bio.PDB.PDBIO import PDBIO from Bio.PDB.AbstractPropertyMap import AbstractResiduePropertyMap, AbstractAtomPropertyMap @@ -22,52 +26,51 @@ """ -def run_naccess(model, pdb_file, probe_size = None, z_slice = None, - naccess = 'naccess', temp_path = '/tmp/'): +def run_naccess(model, pdb_file, probe_size=None, z_slice=None, + naccess='naccess', temp_path='/tmp/'): - # make temp directory; chdir to temp directory, - # as NACCESS writes to current working directory - tmp_path = tempfile.mktemp(dir = temp_path) - os.mkdir(tmp_path) - old_dir = os.getcwd() - os.chdir(tmp_path) + # make temp directory; + tmp_path = tempfile.mkdtemp(dir=temp_path) # file name must end with '.pdb' to work with NACCESS # -> create temp file of existing pdb # or write model to temp file - tmp_pdb_file = tempfile.mktemp('.pdb', dir = tmp_path) + handle, tmp_pdb_file = tempfile.mkstemp('.pdb', dir=tmp_path) + os.close(handle) if pdb_file: - os.system('cp %s %s' % (pdb_file, tmp_pdb_file)) + pdb_file = os.path.abspath(pdb_file) + shutil.copy(pdb_file, tmp_pdb_file) else: writer = PDBIO() writer.set_structure(model.get_parent()) writer.save(tmp_pdb_file) + # chdir to temp directory, as NACCESS writes to current working directory + old_dir = os.getcwd() + os.chdir(tmp_path) + # create the command line and run # catch standard out & err - command = '%s %s ' % (naccess, tmp_pdb_file) + command = [naccess, tmp_pdb_file] if probe_size: - command += '-p %s ' % probe_size + command.extend(['-p', probe_size]) if z_slice: - command += '-z %s ' % z_slice - in_, out, err = os.popen3(command) - in_.close() - stdout = out.readlines() - out.close() - stderr = err.readlines() - err.close() + command.extend(['-z', z_slice]) + + p = subprocess.Popen(command, universal_newlines=True, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + out, err = p.communicate() + os.chdir(old_dir) # get the output, then delete the temp directory rsa_file = tmp_pdb_file[:-4] + '.rsa' - rf = open(rsa_file) - rsa_data = rf.readlines() - rf.close() + with open(rsa_file) as rf: + rsa_data = rf.readlines() asa_file = tmp_pdb_file[:-4] + '.asa' - af = open(asa_file) - asa_data = af.readlines() - af.close() - os.chdir(old_dir) - os.system('rm -rf %s >& /dev/null' % tmp_path) + with open(asa_file) as af: + asa_data = af.readlines() + + shutil.rmtree(tmp_path, ignore_errors=True) return rsa_data, asa_data @@ -92,7 +95,7 @@ 'non_polar_abs': float(line[55:61]), 'non_polar_rel': float(line[62:67]), 'all_polar_abs': float(line[68:74]), - 'all_polar_rel': float(line[75:80]) } + 'all_polar_rel': float(line[75:80])} return naccess_rel_dict @@ -118,20 +121,21 @@ class NACCESS(AbstractResiduePropertyMap): - def __init__(self, model, pdb_file = None, - naccess_binary = 'naccess', tmp_directory = '/tmp'): - res_data, atm_data = run_naccess(model, pdb_file, naccess = naccess_binary, - temp_path = tmp_directory) + def __init__(self, model, pdb_file=None, + naccess_binary='naccess', tmp_directory='/tmp'): + res_data, atm_data = run_naccess(model, pdb_file, + naccess=naccess_binary, + temp_path=tmp_directory) naccess_dict = process_rsa_data(res_data) res_list = [] - property_dict={} - property_keys=[] - property_list=[] + property_dict = {} + property_keys = [] + property_list = [] # Now create a dictionary that maps Residue objects to accessibility for chain in model: - chain_id=chain.get_id() + chain_id = chain.get_id() for res in chain: - res_id=res.get_id() + res_id = res.get_id() if (chain_id, res_id) in naccess_dict: item = naccess_dict[(chain_id, res_id)] res_name = item['res_name'] @@ -139,24 +143,24 @@ property_dict[(chain_id, res_id)] = item property_keys.append((chain_id, res_id)) property_list.append((res, item)) - res.xtra["EXP_NACCESS"]=item + res.xtra["EXP_NACCESS"] = item else: pass AbstractResiduePropertyMap.__init__(self, property_dict, property_keys, - property_list) + property_list) class NACCESS_atomic(AbstractAtomPropertyMap): - def __init__(self, model, pdb_file = None, - naccess_binary = 'naccess', tmp_directory = '/tmp'): - res_data, atm_data = run_naccess(model, pdb_file, naccess = naccess_binary, - temp_path = tmp_directory) + def __init__(self, model, pdb_file=None, + naccess_binary='naccess', tmp_directory='/tmp'): + res_data, atm_data = run_naccess(model, pdb_file, + naccess=naccess_binary, + temp_path=tmp_directory) self.naccess_atom_dict = process_asa_data(atm_data) - atom_list = [] - property_dict={} - property_keys=[] - property_list=[] + property_dict = {} + property_keys = [] + property_list = [] # Now create a dictionary that maps Atom objects to accessibility for chain in model: chain_id = chain.get_id() @@ -164,25 +168,25 @@ res_id = residue.get_id() for atom in residue: atom_id = atom.get_id() - full_id=(chain_id, res_id, atom_id) + full_id = (chain_id, res_id, atom_id) if full_id in self.naccess_atom_dict: asa = self.naccess_atom_dict[full_id] - property_dict[full_id]=asa + property_dict[full_id] = asa property_keys.append((full_id)) property_list.append((atom, asa)) - atom.xtra['EXP_NACCESS']=asa - AbstractAtomPropertyMap.__init__(self, property_dict, property_keys, - property_list) + atom.xtra['EXP_NACCESS'] = asa + AbstractAtomPropertyMap.__init__(self, property_dict, + property_keys, property_list) -if __name__=="__main__": +if __name__ == "__main__": import sys from Bio.PDB import PDBParser - p=PDBParser() - s=p.get_structure('X', sys.argv[1]) - model=s[0] + p = PDBParser() + s = p.get_structure('X', sys.argv[1]) + model = s[0] n = NACCESS(model, sys.argv[1]) - for e in n.get_iterator(): - print e + for e in n: + print(e) diff -Nru python-biopython-1.62/Bio/PDB/NeighborSearch.py python-biopython-1.63/Bio/PDB/NeighborSearch.py --- python-biopython-1.62/Bio/PDB/NeighborSearch.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PDB/NeighborSearch.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,6 +5,8 @@ """Fast atom neighbor lookup using a KD tree (implemented in C++).""" +from __future__ import print_function + import numpy from Bio.KDTree import KDTree @@ -133,7 +135,5 @@ for i in range(0, 20): #Make a list of 100 atoms al = [Atom() for j in range(100)] - - ns=NeighborSearch(al) - - print "Found ", len(ns.search_all(5.0)) + ns = NeighborSearch(al) + print("Found %i" % len(ns.search_all(5.0))) diff -Nru python-biopython-1.62/Bio/PDB/PDBIO.py python-biopython-1.63/Bio/PDB/PDBIO.py --- python-biopython-1.62/Bio/PDB/PDBIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PDB/PDBIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,6 +5,8 @@ """Output of PDB files.""" +from Bio._py3k import basestring + from Bio.PDB.StructureBuilder import StructureBuilder # To allow saving of chains, residues, etc.. from Bio.Data.IUPACData import atom_weights # Allowed Elements @@ -229,12 +231,11 @@ io.set_structure(s) io.save("out1.pdb") - fp=open("out2.pdb", "w") - s1=p.get_structure("test1", sys.argv[1]) - s2=p.get_structure("test2", sys.argv[2]) - io=PDBIO(1) - io.set_structure(s1) - io.save(fp) - io.set_structure(s2) - io.save(fp, write_end=1) - fp.close() + with open("out2.pdb", "w") as fp: + s1=p.get_structure("test1", sys.argv[1]) + s2=p.get_structure("test2", sys.argv[2]) + io=PDBIO(1) + io.set_structure(s1) + io.save(fp) + io.set_structure(s2) + io.save(fp, write_end=1) diff -Nru python-biopython-1.62/Bio/PDB/PDBList.py python-biopython-1.63/Bio/PDB/PDBList.py --- python-biopython-1.62/Bio/PDB/PDBList.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PDB/PDBList.py 2013-12-05 14:10:43.000000000 +0000 @@ -20,15 +20,16 @@ """ Access the PDB over the internet (e.g. to download structures). """ -# For using with statement in Python 2.5 or Jython -from __future__ import with_statement +from __future__ import print_function import contextlib import gzip import os import shutil -import urllib -from urllib2 import urlopen as _urlopen # urllib made too many FTP conn's + +#Importing these functions with leading underscore as not intended for reuse +from Bio._py3k import urlopen as _urlopen +from Bio._py3k import urlretrieve as _urlretrieve class PDBList(object): @@ -125,7 +126,7 @@ PDB entries and some annotation to them. Returns a list of PDB codes in the index file. """ - print "retrieving index file. Takes about 5 MB." + print("retrieving index file. Takes about 5 MB.") url = self.pdb_server + '/pub/pdb/derived_data/index/entries.idx' with contextlib.closing(_urlopen(url)) as handle: all_entries = [line[:4] for line in handle.readlines()[2:] @@ -205,12 +206,12 @@ # Skip download if the file already exists if not self.overwrite: if os.path.exists(final_file): - print "Structure exists: '%s' " % final_file + print("Structure exists: '%s' " % final_file) return final_file # Retrieve the file - print "Downloading PDB structure '%s'..." % pdb_code - urllib.urlretrieve(url, filename) + print("Downloading PDB structure '%s'..." % pdb_code) + _urlretrieve(url, filename) # Uncompress the archive, delete when done #Can't use context manager with gzip.open until Python 2.7 @@ -238,7 +239,7 @@ try: self.retrieve_pdb_file(pdb_code) except Exception: - print 'error %s\n' % pdb_code + print('error %s\n' % pdb_code) # you can insert here some more log notes that # something has gone wrong. @@ -259,11 +260,11 @@ try: shutil.move(old_file, new_file) except Exception: - print "Could not move %s to obsolete folder" % old_file + print("Could not move %s to obsolete folder" % old_file) elif os.path.isfile(new_file): - print "Obsolete file %s already moved" % old_file + print("Obsolete file %s already moved" % old_file) else: - print "Obsolete file %s is missing" % old_file + print("Obsolete file %s is missing" % old_file) def download_entire_pdb(self, listfile=None): """Retrieve all PDB entries not present in the local PDB copy. @@ -299,9 +300,9 @@ """Retrieves a (big) file containing all the sequences of PDB entries and writes it to a file. """ - print "Retrieving sequence file (takes about 15 MB)." + print("Retrieving sequence file (takes about 15 MB).") url = self.pdb_server + '/pub/pdb/derived_data/pdb_seqres.txt' - urllib.urlretrieve(url, savefile) + _urlretrieve(url, savefile) if __name__ == '__main__': @@ -324,7 +325,7 @@ -d A single directory will be used as , not a tree. -o Overwrite existing structure files. """ - print doc + print(doc) if len(sys.argv) > 2: pdb_path = sys.argv[2] @@ -344,7 +345,7 @@ if len(sys.argv) > 1: if sys.argv[1] == 'update': # update PDB - print "updating local PDB at " + pdb_path + print("updating local PDB at " + pdb_path) pl.update_pdb() elif sys.argv[1] == 'all': diff -Nru python-biopython-1.62/Bio/PDB/PDBParser.py python-biopython-1.63/Bio/PDB/PDBParser.py --- python-biopython-1.62/Bio/PDB/PDBParser.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PDB/PDBParser.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,8 +5,7 @@ """Parser for PDB files.""" -# For using with statement in Python 2.5 or Jython -from __future__ import with_statement +from __future__ import print_function import warnings @@ -215,24 +214,24 @@ current_resname = resname try: structure_builder.init_residue(resname, hetero_flag, resseq, icode) - except PDBConstructionException, message: + except PDBConstructionException as message: self._handle_PDB_exception(message, global_line_counter) elif current_residue_id != residue_id or current_resname != resname: current_residue_id = residue_id current_resname = resname try: structure_builder.init_residue(resname, hetero_flag, resseq, icode) - except PDBConstructionException, message: + except PDBConstructionException as message: self._handle_PDB_exception(message, global_line_counter) # init atom try: structure_builder.init_atom(name, coord, bfactor, occupancy, altloc, fullname, serial_number, element) - except PDBConstructionException, message: + except PDBConstructionException as message: self._handle_PDB_exception(message, global_line_counter) elif record_type == "ANISOU": - anisou = map(float, (line[28:35], line[35:42], line[43:49], - line[49:56], line[56:63], line[63:70])) + anisou = [float(x) for x in (line[28:35], line[35:42], line[43:49], + line[49:56], line[56:63], line[63:70])] # U's are scaled by 10^4 anisou_array = (numpy.array(anisou, "f") / 10000.0).astype("f") structure_builder.set_anisou(anisou_array) @@ -258,15 +257,15 @@ current_residue_id = None elif record_type == "SIGUIJ": # standard deviation of anisotropic B factor - siguij = map(float, (line[28:35], line[35:42], line[42:49], - line[49:56], line[56:63], line[63:70])) + siguij = [float(x) for x in (line[28:35], line[35:42], line[42:49], + line[49:56], line[56:63], line[63:70])] # U sigma's are scaled by 10^4 siguij_array = (numpy.array(siguij, "f") / 10000.0).astype("f") structure_builder.set_siguij(siguij_array) elif record_type == "SIGATM": # standard deviation of atomic positions - sigatm = map(float, (line[30:38], line[38:45], line[46:54], - line[54:60], line[60:66])) + sigatm = [float(x) for x in (line[30:38], line[38:45], line[46:54], + line[54:60], line[60:66])] sigatm_array = numpy.array(sigatm, "f") structure_builder.set_sigatm(sigatm_array) local_line_counter += 1 @@ -308,10 +307,10 @@ p = c.get_parent() assert(p is m) for r in c: - print r + print(r) p = r.get_parent() assert(p is c) for a in r: p = a.get_parent() if not p is r: - print p, r + print("%s %s" % (p, r)) diff -Nru python-biopython-1.62/Bio/PDB/PSEA.py python-biopython-1.63/Bio/PDB/PSEA.py --- python-biopython-1.62/Bio/PDB/PSEA.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PDB/PSEA.py 2013-12-05 14:10:43.000000000 +0000 @@ -41,17 +41,16 @@ fname=run_psea(pname) start=0 ss="" - fp=open(fname, 'r') - for l in fp.readlines(): - if l[0:6]==">p-sea": - start=1 - continue - if not start: - continue - if l[0]=="\n": - break - ss=ss+l[0:-1] - fp.close() + with open(fname, 'r') as fp: + for l in fp.readlines(): + if l[0:6]==">p-sea": + start=1 + continue + if not start: + continue + if l[0]=="\n": + break + ss=ss+l[0:-1] return ss diff -Nru python-biopython-1.62/Bio/PDB/Polypeptide.py python-biopython-1.63/Bio/PDB/Polypeptide.py --- python-biopython-1.62/Bio/PDB/Polypeptide.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PDB/Polypeptide.py 2013-12-05 14:10:43.000000000 +0000 @@ -12,7 +12,7 @@ >>> structure = PDBParser().get_structure('2BEG', 'PDB/2BEG.pdb') >>> ppb=PPBuilder() >>> for pp in ppb.build_peptides(structure): - ... print pp.get_sequence() + ... print(pp.get_sequence()) LVFFAEDVGSNKGAIIGLMVGGVVIA LVFFAEDVGSNKGAIIGLMVGGVVIA LVFFAEDVGSNKGAIIGLMVGGVVIA @@ -27,7 +27,7 @@ >>> structure = PDBParser().get_structure('1A8O', 'PDB/1A8O.pdb') >>> ppb=PPBuilder() >>> for pp in ppb.build_peptides(structure): - ... print pp.get_sequence() + ... print(pp.get_sequence()) DIRQGPKEPFRDYVDRFYKTLRAEQASQEVKNW TETLLVQNANPDCKTILKALGPGATLEE TACQG @@ -35,10 +35,10 @@ If you want to, you can include non-standard amino acids in the peptides: >>> for pp in ppb.build_peptides(structure, aa_only=False): - ... print pp.get_sequence() - ... print pp.get_sequence()[0], pp[0].get_resname() - ... print pp.get_sequence()[-7], pp[-7].get_resname() - ... print pp.get_sequence()[-6], pp[-6].get_resname() + ... print(pp.get_sequence()) + ... print("%s %s" % (pp.get_sequence()[0], pp[0].get_resname())) + ... print("%s %s" % (pp.get_sequence()[-7], pp[-7].get_resname())) + ... print("%s %s" % (pp.get_sequence()[-6], pp[-6].get_resname())) MDIRQGPKEPFRDYVDRFYKTLRAEQASQEVKNWMTETLLVQNANPDCKTILKALGPGATLEEMMTACQG M MSE M MSE @@ -48,6 +48,9 @@ last residues) have been shown as M (methionine) by the get_sequence method. """ +from __future__ import print_function +from Bio._py3k import basestring + import warnings from Bio.Alphabet import generic_protein @@ -351,9 +354,9 @@ for chain in chain_list: chain_it=iter(chain) try: - prev_res = chain_it.next() + prev_res = next(chain_it) while not accept(prev_res, aa_only): - prev_res = chain_it.next() + prev_res = next(chain_it) except StopIteration: #No interesting residues at all in this chain continue @@ -460,24 +463,25 @@ ppb=PPBuilder() - print "C-N" + print("C-N") for pp in ppb.build_peptides(s): - print pp.get_sequence() + print(pp.get_sequence()) for pp in ppb.build_peptides(s[0]): - print pp.get_sequence() + print(pp.get_sequence()) for pp in ppb.build_peptides(s[0]["A"]): - print pp.get_sequence() + print(pp.get_sequence()) for pp in ppb.build_peptides(s): for phi, psi in pp.get_phi_psi_list(): - print phi, psi + print("%f %f" % (phi, psi)) ppb=CaPPBuilder() - print "CA-CA" + print("CA-CA") for pp in ppb.build_peptides(s): - print pp.get_sequence() + print(pp.get_sequence()) for pp in ppb.build_peptides(s[0]): - print pp.get_sequence() + print(pp.get_sequence()) for pp in ppb.build_peptides(s[0]["A"]): - print pp.get_sequence() + print(pp.get_sequence()) + diff -Nru python-biopython-1.62/Bio/PDB/ResidueDepth.py python-biopython-1.63/Bio/PDB/ResidueDepth.py --- python-biopython-1.62/Bio/PDB/ResidueDepth.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PDB/ResidueDepth.py 2013-12-05 14:10:43.000000000 +0000 @@ -15,7 +15,7 @@ Residue Depth: >>> rd = ResidueDepth(model, pdb_file) - >>> print rd[(chain_id, res_id)] + >>> print(rd[(chain_id, res_id)]) Direct MSMS interface: @@ -39,6 +39,8 @@ >>> rd = residue_depth(residue, surface) """ +from __future__ import print_function + import os import tempfile @@ -53,16 +55,15 @@ """ Read the vertex list into a Numeric array. """ - fp=open(filename, "r") - vertex_list=[] - for l in fp.readlines(): - sl=l.split() - if not len(sl)==9: - # skip header - continue - vl=map(float, sl[0:3]) - vertex_list.append(vl) - fp.close() + with open(filename, "r") as fp: + vertex_list=[] + for l in fp.readlines(): + sl=l.split() + if not len(sl)==9: + # skip header + continue + vl = [float(x) for x in sl[0:3]] + vertex_list.append(vl) return numpy.array(vertex_list) @@ -173,4 +174,4 @@ rd=ResidueDepth(model, sys.argv[1]) for item in rd: - print item + print(item) diff -Nru python-biopython-1.62/Bio/PDB/Selection.py python-biopython-1.63/Bio/PDB/Selection.py --- python-biopython-1.62/Bio/PDB/Selection.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PDB/Selection.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,6 +5,8 @@ """Selection of atoms, residues, etc.""" +from __future__ import print_function + import itertools from Bio.PDB.Atom import Atom @@ -79,9 +81,9 @@ def _test(): """Run the Bio.PDB.Selection module's doctests (PRIVATE).""" import doctest - print "Running doctests ..." + print("Running doctests ...") doctest.testmod() - print "Done" + print("Done") if __name__ == "__main__": diff -Nru python-biopython-1.62/Bio/PDB/StructureAlignment.py python-biopython-1.63/Bio/PDB/StructureAlignment.py --- python-biopython-1.62/Bio/PDB/StructureAlignment.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PDB/StructureAlignment.py 2013-12-05 14:10:43.000000000 +0000 @@ -7,6 +7,8 @@ file. """ +from __future__ import print_function + from Bio.Data import SCOPData from Bio.PDB import Selection @@ -43,7 +45,7 @@ aa2=column[sj] if aa1!="-": # Position in seq1 is not - - while 1: + while True: # Loop until an aa is found r1=rl1[p1] p1=p1+1 @@ -54,7 +56,7 @@ r1=None if aa2!="-": # Position in seq2 is not - - while 1: + while True: # Loop until an aa is found r2=rl2[p2] p2=p2+1 @@ -103,10 +105,10 @@ from Bio.PDB import PDBParser if len(sys.argv) != 4: - print "Expects three arguments," - print " - FASTA alignment filename (expect two sequences)" - print " - PDB file one" - print " - PDB file two" + print("Expects three arguments,") + print(" - FASTA alignment filename (expect two sequences)") + print(" - PDB file one") + print(" - PDB file two") sys.exit() # The alignment @@ -128,5 +130,5 @@ al=StructureAlignment(fa, m1, m2) # Print aligned pairs (r is None if gap) - for (r1,r2) in al.get_iterator(): - print r1, r2 + for (r1, r2) in al.get_iterator(): + print("%s %s" % (r1, r2)) diff -Nru python-biopython-1.62/Bio/PDB/StructureBuilder.py python-biopython-1.63/Bio/PDB/StructureBuilder.py --- python-biopython-1.62/Bio/PDB/StructureBuilder.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PDB/StructureBuilder.py 2013-12-05 14:10:43.000000000 +0000 @@ -69,7 +69,7 @@ o id - int o serial_num - int """ - self.model=Model(model_id,serial_num) + self.model=Model(model_id, serial_num) self.structure.add(self.model) def init_chain(self, chain_id): diff -Nru python-biopython-1.62/Bio/PDB/Superimposer.py python-biopython-1.63/Bio/PDB/Superimposer.py --- python-biopython-1.62/Bio/PDB/Superimposer.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PDB/Superimposer.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,6 +5,8 @@ """Superimpose two structures.""" +from __future__ import print_function + import numpy from Bio.SVDSuperimposer import SVDSuperimposer @@ -78,7 +80,7 @@ sup.set_atoms(fixed, moving) - print sup.rotran - print sup.rms + print(sup.rotran) + print(sup.rms) sup.apply(moving) diff -Nru python-biopython-1.62/Bio/PDB/Vector.py python-biopython-1.63/Bio/PDB/Vector.py --- python-biopython-1.62/Bio/PDB/Vector.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PDB/Vector.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,6 +5,8 @@ """Vector class, including rotation-related functions.""" +from __future__ import print_function + import numpy @@ -20,33 +22,33 @@ angle=numpy.arccos(t) if angle<1e-15: # Angle is 0 - return 0.0, Vector(1,0,0) + return 0.0, Vector(1, 0, 0) elif anglem11 and m00>m22: x=numpy.sqrt(m00-m11-m22+0.5) - y=m[0,1]/(2*x) - z=m[0,2]/(2*x) + y=m[0, 1]/(2*x) + z=m[0, 2]/(2*x) elif m11>m00 and m11>m22: y=numpy.sqrt(m11-m00-m22+0.5) - x=m[0,1]/(2*y) - z=m[1,2]/(2*y) + x=m[0, 1]/(2*y) + z=m[1, 2]/(2*y) else: z=numpy.sqrt(m22-m00-m11+0.5) - x=m[0,2]/(2*z) - y=m[1,2]/(2*z) - axis=Vector(x,y,z) + x=m[0, 2]/(2*z) + y=m[1, 2]/(2*z) + axis=Vector(x, y, z) axis.normalize() return numpy.pi, axis @@ -76,7 +78,7 @@ Example: - >>> m=rotaxis(pi, Vector(1,0,0)) + >>> m=rotaxis(pi, Vector(1, 0, 0)) >>> rotated_vector=any_vector.left_multiply(m) @type theta: float @@ -93,33 +95,34 @@ c=numpy.cos(theta) s=numpy.sin(theta) t=1-c - x,y,z=vector.get_array() - rot=numpy.zeros((3,3)) + x, y, z=vector.get_array() + rot=numpy.zeros((3, 3)) # 1st row - rot[0,0]=t*x*x+c - rot[0,1]=t*x*y-s*z - rot[0,2]=t*x*z+s*y + rot[0, 0]=t*x*x+c + rot[0, 1]=t*x*y-s*z + rot[0, 2]=t*x*z+s*y # 2nd row - rot[1,0]=t*x*y+s*z - rot[1,1]=t*y*y+c - rot[1,2]=t*y*z-s*x + rot[1, 0]=t*x*y+s*z + rot[1, 1]=t*y*y+c + rot[1, 2]=t*y*z-s*x # 3rd row - rot[2,0]=t*x*z-s*y - rot[2,1]=t*y*z+s*x - rot[2,2]=t*z*z+c + rot[2, 0]=t*x*z-s*y + rot[2, 1]=t*y*z+s*x + rot[2, 2]=t*z*z+c return rot rotaxis=rotaxis2m -def refmat(p,q): +def refmat(p, q): """ Return a (left multiplying) matrix that mirrors p onto q. Example: - >>> mirror=refmat(p,q) + >>> mirror=refmat(p, q) >>> qq=p.left_multiply(mirror) - >>> print q, qq # q and qq should be the same + >>> print(q) + >>> print(qq) # q and qq should be the same @type p,q: L{Vector} @return: The mirror operation, a 3x3 Numeric array. @@ -137,13 +140,14 @@ return ref -def rotmat(p,q): +def rotmat(p, q): """ Return a (left multiplying) matrix that rotates p onto q. Example: - >>> r=rotmat(p,q) - >>> print q, p.left_multiply(r) + >>> r=rotmat(p, q) + >>> print(q) + >>> print(p.left_multiply(r)) @param p: moving vector @type p: L{Vector} @@ -215,8 +219,8 @@ self._ar=numpy.array((x, y, z), 'd') def __repr__(self): - x,y,z=self._ar - return "" % (x,y,z) + x, y, z=self._ar + return "" % (x, y, z) def __neg__(self): "Return Vector(-x, -y, -z)" @@ -251,12 +255,12 @@ def __pow__(self, other): "Return VectorxVector (cross product) or Vectorxscalar" if isinstance(other, Vector): - a,b,c=self._ar - d,e,f=other._ar - c1=numpy.linalg.det(numpy.array(((b,c), (e,f)))) - c2=-numpy.linalg.det(numpy.array(((a,c), (d,f)))) - c3=numpy.linalg.det(numpy.array(((a,b), (d,e)))) - return Vector(c1,c2,c3) + a, b, c=self._ar + d, e, f=other._ar + c1=numpy.linalg.det(numpy.array(((b, c), (e, f)))) + c2=-numpy.linalg.det(numpy.array(((a, c), (d, f)))) + c3=numpy.linalg.det(numpy.array(((a, b), (d, e)))) + return Vector(c1, c2, c3) else: a=self._ar*numpy.array(other) return Vector(a) @@ -294,8 +298,8 @@ n2=other.norm() c=(self*other)/(n1*n2) # Take care of roundoff errors - c=min(c,1) - c=max(-1,c) + c=min(c, 1) + c=max(-1, c) return numpy.arccos(c) def get_array(self): @@ -320,59 +324,59 @@ from numpy.random import random - v1=Vector(0,0,1) - v2=Vector(0,0,0) - v3=Vector(0,1,0) - v4=Vector(1,1,0) + v1=Vector(0, 0, 1) + v2=Vector(0, 0, 0) + v3=Vector(0, 1, 0) + v4=Vector(1, 1, 0) v4.normalize() - print v4 + print(v4) - print calc_angle(v1, v2, v3) + print(calc_angle(v1, v2, v3)) dih=calc_dihedral(v1, v2, v3, v4) # Test dihedral sign assert(dih>0) - print "DIHEDRAL ", dih + print("DIHEDRAL %f" % dih) ref=refmat(v1, v3) rot=rotmat(v1, v3) - print v3 - print v1.left_multiply(ref) - print v1.left_multiply(rot) - print v1.right_multiply(numpy.transpose(rot)) + print(v3) + print(v1.left_multiply(ref)) + print(v1.left_multiply(rot)) + print(v1.right_multiply(numpy.transpose(rot))) # - - print v1-v2 - print v1-1 - print v1+(1,2,3) + print(v1-v2) + print(v1-1) + print(v1+(1, 2, 3)) # + - print v1+v2 - print v1+3 - print v1-(1,2,3) + print(v1+v2) + print(v1+3) + print(v1-(1, 2, 3)) # * - print v1*v2 + print(v1*v2) # / - print v1/2 - print v1/(1,2,3) + print(v1/2) + print(v1/(1, 2, 3)) # ** - print v1**v2 - print v1**2 - print v1**(1,2,3) + print(v1**v2) + print(v1**2) + print(v1**(1, 2, 3)) # norm - print v1.norm() + print(v1.norm()) # norm squared - print v1.normsq() + print(v1.normsq()) # setitem v1[2]=10 - print v1 + print(v1) # getitem - print v1[2] + print(v1[2]) - print numpy.array(v1) + print(numpy.array(v1)) - print "ROT" + print("ROT") angle=random()*numpy.pi axis=Vector(random(3)-random(3)) @@ -382,6 +386,7 @@ cangle, caxis=m2rotaxis(m) - print angle-cangle - print axis-caxis - print + print(angle-cangle) + print(axis-caxis) + print("") + diff -Nru python-biopython-1.62/Bio/PDB/__init__.py python-biopython-1.63/Bio/PDB/__init__.py --- python-biopython-1.62/Bio/PDB/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PDB/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -12,63 +12,63 @@ """ # Get a Structure object from a PDB file -from PDBParser import PDBParser +from .PDBParser import PDBParser try: # Get a Structure object from an mmCIF file - from MMCIFParser import MMCIFParser + from .MMCIFParser import MMCIFParser except: # Not compiled I guess pass # Download from the PDB -from PDBList import PDBList +from .PDBList import PDBList # Parse PDB header directly -from parse_pdb_header import parse_pdb_header +from .parse_pdb_header import parse_pdb_header # Find connected polypeptides in a Structure -from Polypeptide import PPBuilder, CaPPBuilder, is_aa, standard_aa_names +from .Polypeptide import PPBuilder, CaPPBuilder, is_aa, standard_aa_names # This is also useful :-) from Bio.Data.SCOPData import protein_letters_3to1 # IO of PDB files (including flexible selective output) -from PDBIO import PDBIO, Select +from .PDBIO import PDBIO, Select # Some methods to eg. get a list of Residues # from a list of Atoms. -import Selection +from . import Selection # Superimpose atom sets -from Superimposer import Superimposer +from .Superimposer import Superimposer # 3D vector class -from Vector import Vector, calc_angle, calc_dihedral, refmat, rotmat, rotaxis -from Vector import vector_to_axis, m2rotaxis, rotaxis2m +from .Vector import Vector, calc_angle, calc_dihedral, refmat, rotmat, rotaxis +from .Vector import vector_to_axis, m2rotaxis, rotaxis2m # Alignment module -from StructureAlignment import StructureAlignment +from .StructureAlignment import StructureAlignment # DSSP handle # (secondary structure and solvent accessible area calculation) -from DSSP import DSSP, make_dssp_dict +from .DSSP import DSSP, make_dssp_dict # Residue depth: # distance of residue atoms from solvent accessible surface -from ResidueDepth import ResidueDepth, get_surface +from .ResidueDepth import ResidueDepth, get_surface # Calculation of Half Sphere Solvent Exposure -from HSExposure import HSExposureCA, HSExposureCB, ExposureCN +from .HSExposure import HSExposureCA, HSExposureCB, ExposureCN # Kolodny et al.'s backbone libraries -from FragmentMapper import FragmentMapper +from .FragmentMapper import FragmentMapper # Write out chain(start-end) to PDB file -from Dice import extract +from .Dice import extract # Fast atom neighbor search # Depends on KDTree C++ module try: - from NeighborSearch import NeighborSearch + from .NeighborSearch import NeighborSearch except ImportError: pass diff -Nru python-biopython-1.62/Bio/PDB/parse_pdb_header.py python-biopython-1.63/Bio/PDB/parse_pdb_header.py --- python-biopython-1.62/Bio/PDB/parse_pdb_header.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PDB/parse_pdb_header.py 2013-12-05 14:10:43.000000000 +0000 @@ -23,8 +23,8 @@ """Parse the header of a PDB file.""" -# For 'with' on Python 2.5/Jython 2.5 -from __future__ import with_statement +from __future__ import print_function + import re from Bio import File @@ -34,9 +34,9 @@ # JRNL AUTH L.CHEN,M.DOI,F.S.MATHEWS,A.Y.CHISTOSERDOV, 2BBK 7 journal="" for l in inl: - if re.search("\AJRNL",l): + if re.search("\AJRNL", l): journal+=l[19:72].lower() - journal=re.sub("\s\s+"," ",journal) + journal=re.sub("\s\s+", " ", journal) return journal @@ -46,10 +46,10 @@ references=[] actref="" for l in inl: - if re.search("\AREMARK 1",l): - if re.search("\AREMARK 1 REFERENCE",l): + if re.search("\AREMARK 1", l): + if re.search("\AREMARK 1 REFERENCE", l): if actref!="": - actref=re.sub("\s\s+"," ",actref) + actref=re.sub("\s\s+", " ", actref) if actref!=" ": references.append(actref) actref="" @@ -57,7 +57,7 @@ actref+=l[19:72].lower() if actref!="": - actref=re.sub("\s\s+"," ",actref) + actref=re.sub("\s\s+", " ", actref) if actref!=" ": references.append(actref) return references @@ -73,8 +73,8 @@ else: century=1900 date=str(century+year)+"-" - all_months=['xxx','Jan','Feb','Mar','Apr','May','Jun','Jul', - 'Aug','Sep','Oct','Nov','Dec'] + all_months=['xxx', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', + 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] month=str(all_months.index(pdb_date[3:6])) if len(month)==1: month = '0'+month @@ -84,12 +84,12 @@ def _chop_end_codes(line): """Chops lines ending with ' 1CSA 14' and the like.""" - return re.sub("\s\s\s\s+[\w]{4}.\s+\d*\Z","",line) + return re.sub("\s\s\s\s+[\w]{4}.\s+\d*\Z", "", line) def _chop_end_misc(line): """Chops lines ending with ' 14-JUL-97 1CSA' and the like.""" - return re.sub("\s\s\s\s+.*\Z","",line) + return re.sub("\s\s\s\s+.*\Z", "", line) def _nice_case(line): @@ -152,12 +152,12 @@ last_src_key="misc" for hh in header: - h=re.sub("[\s\n\r]*\Z","",hh) # chop linebreaks off + h=re.sub("[\s\n\r]*\Z", "", hh) # chop linebreaks off #key=re.sub("\s.+\s*","",h) key = h[:6].strip() #tail=re.sub("\A\w+\s+\d*\s*","",h) tail = h[10:].strip() - # print key+":"+tail + # print("%s:%s" % (key, tail) # From here, all the keys from the header are being parsed if key=="TITLE": @@ -167,22 +167,22 @@ else: dict['name']=name elif key=="HEADER": - rr=re.search("\d\d-\w\w\w-\d\d",tail) + rr=re.search("\d\d-\w\w\w-\d\d", tail) if rr is not None: dict['deposition_date']=_format_date(_nice_case(rr.group())) head=_chop_end_misc(tail).lower() dict['head']=head elif key=="COMPND": - tt=re.sub("\;\s*\Z","",_chop_end_codes(tail)).lower() + tt=re.sub("\;\s*\Z", "", _chop_end_codes(tail)).lower() # look for E.C. numbers in COMPND lines - rec = re.search('\d+\.\d+\.\d+\.\d+',tt) + rec = re.search('\d+\.\d+\.\d+\.\d+', tt) if rec: dict['compound'][comp_molid]['ec_number']=rec.group() - tt=re.sub("\((e\.c\.)*\d+\.\d+\.\d+\.\d+\)","",tt) + tt=re.sub("\((e\.c\.)*\d+\.\d+\.\d+\.\d+\)", "", tt) tok=tt.split(":") if len(tok)>=2: ckey=tok[0] - cval=re.sub("\A\s*","",tok[1]) + cval=re.sub("\A\s*", "", tok[1]) if ckey=='mol_id': dict['compound'][cval]={'misc':''} comp_molid=cval @@ -193,12 +193,12 @@ else: dict['compound'][comp_molid][last_comp_key]+=tok[0]+" " elif key=="SOURCE": - tt=re.sub("\;\s*\Z","",_chop_end_codes(tail)).lower() + tt=re.sub("\;\s*\Z", "", _chop_end_codes(tail)).lower() tok=tt.split(":") - # print tok + # print(tok) if len(tok)>=2: ckey=tok[0] - cval=re.sub("\A\s*","",tok[1]) + cval=re.sub("\A\s*", "", tok[1]) if ckey=='mol_id': dict['source'][cval]={'misc':''} comp_molid=cval @@ -217,7 +217,7 @@ elif key=="EXPDTA": expd=_chop_end_codes(tail) # chop junk at end of lines for some structures - expd=re.sub('\s\s\s\s\s\s\s.*\Z','',expd) + expd=re.sub('\s\s\s\s\s\s\s.*\Z', '', expd) # if re.search('\Anmr',expd,re.IGNORECASE): expd='nmr' # if re.search('x-ray diffraction',expd,re.IGNORECASE): expd='x-ray diffraction' dict['structure_method']=expd.lower() @@ -225,11 +225,11 @@ # make Annotation entries out of these!!! pass elif key=="REVDAT": - rr=re.search("\d\d-\w\w\w-\d\d",tail) + rr=re.search("\d\d-\w\w\w-\d\d", tail) if rr is not None: dict['release_date']=_format_date(_nice_case(rr.group())) elif key=="JRNL": - # print key,tail + # print("%s:%s" % (key, tail)) if 'journal' in dict: dict['journal']+=tail else: @@ -241,16 +241,16 @@ else: dict['author']=auth elif key=="REMARK": - if re.search("REMARK 2 RESOLUTION.",hh): - r=_chop_end_codes(re.sub("REMARK 2 RESOLUTION.",'',hh)) - r=re.sub("\s+ANGSTROM.*","",r) + if re.search("REMARK 2 RESOLUTION.", hh): + r=_chop_end_codes(re.sub("REMARK 2 RESOLUTION.", '', hh)) + r=re.sub("\s+ANGSTROM.*", "", r) try: dict['resolution']=float(r) except: - #print 'nonstandard resolution',r + #print('nonstandard resolution %r' % r) dict['resolution']=None else: - # print key + # print(key) pass if dict['structure_method']=='unknown': if dict['resolution']>0.0: @@ -262,12 +262,11 @@ # some data and returns it as a dictionary. import sys filename = sys.argv[1] - handle = open(filename,'r') - data_dict = parse_pdb_header(handle) - handle.close() + with open(filename, 'r') as handle: + data_dict = parse_pdb_header(handle) # print the dictionary - for k, y in data_dict.iteritems(): - print "-"*40 - print k - print y + for k, y in data_dict.items(): + print("-"*40) + print(k) + print(y) diff -Nru python-biopython-1.62/Bio/ParserSupport.py python-biopython-1.63/Bio/ParserSupport.py --- python-biopython-1.62/Bio/ParserSupport.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/ParserSupport.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,16 +3,14 @@ # license. Please see the LICENSE file that should have been included # as part of this package. -"""Code to support writing parsers (OBSOLETE). - - +"""Code to support writing parsers (DEPRECATED). Classes: AbstractParser Base class for parsers. AbstractConsumer Base class of all Consumers. TaggingConsumer Consumer that tags output with its event. For debugging EventGenerator Generate Biopython Events from Martel XML output - (note that Martel is now DEPRECATED) + (note that Martel has been removed) Functions: safe_readline Read a line from a handle, with check for EOF. @@ -25,10 +23,10 @@ """ - +from Bio import BiopythonDeprecationWarning import warnings -warnings.warn("The module Bio.ParserSupport is now obsolete, and will be deprecated and removed in a future release of Biopython.", PendingDeprecationWarning) - +warnings.warn("Bio.ParserSupport is now deprecated will be removed in a " + "future release of Biopython.", BiopythonDeprecationWarning) import sys try: @@ -37,7 +35,8 @@ #Python 3, see http://bugs.python.org/issue8206 InstanceType = object from types import MethodType -import StringIO + +from Bio._py3k import StringIO from Bio import File @@ -59,14 +58,11 @@ raise NotImplementedError("Please implement in a derived class") def parse_str(self, string): - return self.parse(StringIO.StringIO(string)) + return self.parse(StringIO(string)) def parse_file(self, filename): - h = open(filename) - try: + with open(filename) as h: retval = self.parse(h) - finally: - h.close() return retval @@ -298,7 +294,7 @@ """ nlines = 0 - while 1: + while True: line = safe_readline(uhandle) # If I've failed the condition, then stop reading the line. if _fails_conditions(*(line,), **keywds): @@ -320,7 +316,7 @@ """ nlines = 0 - while 1: + while True: line = safe_readline(uhandle) # If I've met the condition, then stop reading the line. if not _fails_conditions(*(line,), **keywds): diff -Nru python-biopython-1.62/Bio/Pathway/Rep/Graph.py python-biopython-1.63/Bio/Pathway/Rep/Graph.py --- python-biopython-1.62/Bio/Pathway/Rep/Graph.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Pathway/Rep/Graph.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,6 +5,8 @@ # get set abstraction for graph representation +from functools import reduce + class Graph(object): """A directed graph abstraction with labeled edges.""" @@ -29,23 +31,20 @@ return not self.__eq__(g) def __repr__(self): - """Returns an unique string representation of this graph.""" + """Returns a unique string representation of this graph.""" s = "" def __str__(self): """Returns a concise string description of this graph.""" - nodenum = len(self._adjacency_list.keys()) - edgenum = reduce(lambda x,y: x+y, - map(len, self._adjacency_list.values())) - labelnum = len(self._label_map.keys()) + nodenum = len(self._adjacency_list) + edgenum = reduce(lambda x, y: x+y, + [len(v) for v in self._adjacency_list.values()]) + labelnum = len(self._label_map) return " node: " + str(source)) if to not in self._adjacency_list: raise ValueError("Unknown node: " + str(to)) - if (source,to) in self._edge_map: + if (source, to) in self._edge_map: raise ValueError(str(source) + " -> " + str(to) + " exists") self._adjacency_list[source].add(to) if label not in self._label_map: self._label_map[label] = set() - self._label_map[label].add((source,to)) - self._edge_map[(source,to)] = label + self._label_map[label].add((source, to)) + self._edge_map[(source, to)] = label def child_edges(self, parent): """Returns a list of (child, label) pairs for parent.""" if parent not in self._adjacency_list: raise ValueError("Unknown node: " + str(parent)) - return [(x, self._edge_map[(parent,x)]) + return [(x, self._edge_map[(parent, x)]) for x in sorted(self._adjacency_list[parent])] def children(self, parent): @@ -89,18 +88,18 @@ def labels(self): """Returns a list of all the edge labels in this graph.""" - return self._label_map.keys() + return list(self._label_map.keys()) def nodes(self): """Returns a list of the nodes in this graph.""" - return self._adjacency_list.keys() + return list(self._adjacency_list.keys()) def parent_edges(self, child): """Returns a list of (parent, label) pairs for child.""" if child not in self._adjacency_list: raise ValueError("Unknown node: " + str(child)) parents = [] - for parent, children in self._adjacency_list.iteritems(): + for parent, children in self._adjacency_list.items(): for x in children: if x is child: parents.append((parent, self._edge_map[(parent, child)])) @@ -108,7 +107,7 @@ def parents(self, child): """Returns a list of unique parents for child.""" - return sorted(set([x[0] for x in self.parent_edges(child)])) + return sorted(set(x[0] for x in self.parent_edges(child))) def remove_node(self, node): """Removes node and all edges connected to it.""" @@ -121,7 +120,7 @@ self._adjacency_list[n] = set(x for x in self._adjacency_list[n] if x is not node) # remove all refering pairs in label map - for label in self._label_map.keys(): + for label in list(self._label_map.keys()): # we're editing this! lm = set(x for x in self._label_map[label] if (x[0] is not node) and (x[1] is not node)) # remove the entry completely if the label is now unused @@ -130,7 +129,7 @@ else: del self._label_map[label] # remove all refering entries in edge map - for edge in self._edge_map.keys(): + for edge in list(self._edge_map.keys()): # we're editing this! if edge[0] is node or edge[1] is node: del self._edge_map[edge] diff -Nru python-biopython-1.62/Bio/Pathway/Rep/MultiGraph.py python-biopython-1.63/Bio/Pathway/Rep/MultiGraph.py --- python-biopython-1.62/Bio/Pathway/Rep/MultiGraph.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Pathway/Rep/MultiGraph.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,6 +5,8 @@ # get set abstraction for graph representation +from functools import reduce + #TODO - Subclass graph? class MultiGraph(object): @@ -28,19 +30,18 @@ return not self.__eq__(g) def __repr__(self): - """Returns an unique string representation of this graph.""" + """Returns a unique string representation of this graph.""" s = "" def __str__(self): """Returns a concise string description of this graph.""" nodenum = len(self._adjacency_list) - edgenum = reduce(lambda x,y: x+y, - map(len, self._adjacency_list.values())) + edgenum = reduce(lambda x, y: x+y, + [len(v) for v in self._adjacency_list.values()]) labelnum = len(self._label_map) return " node: " + str(child)) parents = [] - for parent, children in self._adjacency_list.iteritems(): + for parent, children in self._adjacency_list.items(): for x in children: if x[0] is child: parents.append((parent, x[1])) @@ -101,7 +102,7 @@ def parents(self, child): """Returns a list of unique parents for child.""" - return sorted(set([x[0] for x in self.parent_edges(child)])) + return sorted(set(x[0] for x in self.parent_edges(child))) def remove_node(self, node): """Removes node and all edges connected to it.""" @@ -114,7 +115,7 @@ self._adjacency_list[n] = set(x for x in self._adjacency_list[n] if x[0] is not node) # remove all refering pairs in label map - for label in self._label_map.keys(): + for label in list(self._label_map.keys()): # we're editing this! lm = set(x for x in self._label_map[label] if (x[0] is not node) and (x[1] is not node)) # remove the entry completely if the label is now unused diff -Nru python-biopython-1.62/Bio/Pathway/__init__.py python-biopython-1.63/Bio/Pathway/__init__.py --- python-biopython-1.62/Bio/Pathway/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Pathway/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -30,6 +30,8 @@ Comments and feature requests are most welcome. """ +from functools import reduce + from Bio.Pathway.Rep.MultiGraph import * @@ -72,7 +74,7 @@ # enforce invariants on reactants: self.reactants = reactants.copy() # loop over original, edit the copy - for r, value in reactants.iteritems(): + for r, value in reactants.items(): if value == 0: del self.reactants[r] self.catalysts = sorted(set(catalysts)) @@ -99,7 +101,7 @@ def __repr__(self): """Returns a debugging string representation of self.""" return "Reaction(" + \ - ",".join(map(repr,[self.reactants, + ",".join(map(repr, [self.reactants, self.catalysts, self.data, self.reversible])) + ")" @@ -142,7 +144,7 @@ def species(self): """Returns a list of all Species involved in self.""" - return self.reactants.keys() + return list(self.reactants.keys()) class System(object): @@ -162,7 +164,7 @@ def __repr__(self): """Returns a debugging string representation of self.""" - return "System(" + ",".join(map(repr,self.__reactions)) + ")" + return "System(" + ",".join(map(repr, self.__reactions)) + ")" def __str__(self): """Returns a string representation of self.""" @@ -188,7 +190,7 @@ def species(self): """Returns a list of the species in this system.""" - return sorted(set(reduce(lambda s,x: s + x, + return sorted(set(reduce(lambda s, x: s + x, [x.species() for x in self.reactions()], []))) def stochiometry(self): diff -Nru python-biopython-1.62/Bio/Phylo/Applications/_Fasttree.py python-biopython-1.63/Bio/Phylo/Applications/_Fasttree.py --- python-biopython-1.62/Bio/Phylo/Applications/_Fasttree.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Phylo/Applications/_Fasttree.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,6 +3,8 @@ # Please see the LICENSE file that should have been included as part of this # package. """Command-line wrapper for tree inference program Fasttree.""" +from __future__ import print_function + __docformat__ = "restructuredtext en" from Bio.Application import _Option, _Switch, _Argument, AbstractCommandline @@ -38,10 +40,10 @@ >>> import _Fasttree >>> fasttree_exe = r"C:\FasttreeWin32\fasttree.exe" >>> cmd = _Fasttree.FastTreeCommandline(fasttree_exe, input=r'C:\Input\ExampleAlignment.fsa', out='C:\Output\ExampleTree.tree') - >>> print cmd + >>> print(cmd) >>> out, err = cmd() - >>> print out - >>> print err + >>> print(out) + >>> print(err) Usage advice: the only parameters needed are (fasttree_exe, input='' out='') @@ -500,3 +502,4 @@ ] AbstractCommandline.__init__(self, cmd, **kwargs) + diff -Nru python-biopython-1.62/Bio/Phylo/Applications/_Phyml.py python-biopython-1.63/Bio/Phylo/Applications/_Phyml.py --- python-biopython-1.62/Bio/Phylo/Applications/_Phyml.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Phylo/Applications/_Phyml.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,6 +5,8 @@ """Command-line wrapper for the tree inference program PhyML.""" __docformat__ = "restructuredtext en" +from Bio._py3k import basestring + from Bio.Application import _Option, _Switch, AbstractCommandline diff -Nru python-biopython-1.62/Bio/Phylo/Applications/_Raxml.py python-biopython-1.63/Bio/Phylo/Applications/_Raxml.py --- python-biopython-1.62/Bio/Phylo/Applications/_Raxml.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Phylo/Applications/_Raxml.py 2013-12-05 14:10:43.000000000 +0000 @@ -7,6 +7,9 @@ Derived from the help page for RAxML version 7.3 by Alexandros Stamatakis, but should work for any version 7.X (and probably earlier for most options). """ +from __future__ import print_function +from Bio._py3k import basestring + __docformat__ = "restructuredtext en" from Bio.Application import _Option, _Switch, AbstractCommandline @@ -24,7 +27,7 @@ >>> from Bio.Phylo.Applications import RaxmlCommandline >>> raxml_cline = RaxmlCommandline(sequences="Tests/Phylip/interlaced2.phy", ... model="PROTCATWAG", name="interlaced2") - >>> print raxml_cline + >>> print(raxml_cline) raxmlHPC -m PROTCATWAG -n interlaced2 -p 10000 -s Tests/Phylip/interlaced2.phy You would typically run the command line with raxml_cline() or via @@ -368,3 +371,4 @@ # ENH: enforce -s, -n and -m if not self.parsimony_seed: self.parsimony_seed = 10000 + diff -Nru python-biopython-1.62/Bio/Phylo/Applications/__init__.py python-biopython-1.63/Bio/Phylo/Applications/__init__.py --- python-biopython-1.62/Bio/Phylo/Applications/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Phylo/Applications/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,9 +5,9 @@ """Phylogenetics command line tool wrappers.""" __docformat__ = "restructuredtext en" -from _Phyml import PhymlCommandline -from _Raxml import RaxmlCommandline -from _Fasttree import FastTreeCommandline +from ._Phyml import PhymlCommandline +from ._Raxml import RaxmlCommandline +from ._Fasttree import FastTreeCommandline #Make this explicit, then they show up in the API docs __all__ = ["PhymlCommandline", diff -Nru python-biopython-1.62/Bio/Phylo/BaseTree.py python-biopython-1.63/Bio/Phylo/BaseTree.py --- python-biopython-1.62/Bio/Phylo/BaseTree.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Phylo/BaseTree.py 2013-12-05 14:10:43.000000000 +0000 @@ -10,6 +10,11 @@ """ __docformat__ = "restructuredtext en" +from Bio._py3k import zip +from Bio._py3k import filter +from Bio._py3k import basestring +from Bio._py3k import unicode + import collections import copy import itertools @@ -57,7 +62,7 @@ singles = [] lists = [] # Sort attributes for consistent results - for attrname, child in sorted(elem.__dict__.iteritems(), + for attrname, child in sorted(elem.__dict__.items(), key=lambda kv: kv[0]): if child is None: continue @@ -115,7 +120,7 @@ return False else: kwa_copy = kwargs - for key, pattern in kwa_copy.iteritems(): + for key, pattern in kwa_copy.items(): # Nodes must match all other specified attributes if not hasattr(node, key): return False @@ -230,7 +235,7 @@ return "%s=%s" % (key, val) return u'%s(%s)' % (self.__class__.__name__, ', '.join(pair_as_kwarg_string(key, val) - for key, val in self.__dict__.iteritems() + for key, val in self.__dict__.items() if val is not None and type(val) in (str, int, float, bool, unicode) )) @@ -260,14 +265,14 @@ order_func = order_opts[order] except KeyError: raise ValueError("Invalid order '%s'; must be one of: %s" - % (order, tuple(order_opts.keys()))) + % (order, tuple(order_opts))) if follow_attrs: get_children = _sorted_attrs root = self else: get_children = lambda elem: elem.clades root = self.root - return itertools.ifilter(filter_func, order_func(root, get_children)) + return filter(filter_func, order_func(root, get_children)) def find_any(self, *args, **kwargs): """Return the first element found by find_elements(), or None. @@ -277,7 +282,7 @@ """ hits = self.find_elements(*args, **kwargs) try: - return hits.next() + return next(hits) except StopIteration: return None @@ -320,7 +325,7 @@ >>> from Bio.Phylo.IO import PhyloXMIO >>> phx = PhyloXMLIO.read('phyloxml_examples.xml') >>> matches = phx.phylogenies[5].find_elements(code='OCTVU') - >>> matches.next() + >>> next(matches) Taxonomy(code='OCTVU', scientific_name='Octopus vulgaris') """ @@ -413,7 +418,7 @@ if p is None: raise ValueError("target %s is not in this tree" % repr(t)) mrca = self.root - for level in itertools.izip(*paths): + for level in zip(*paths): ref = level[0] for other in level[1:]: if ref is not other: @@ -871,7 +876,7 @@ tips = self.get_terminals() for tip in tips: self.root_with_outgroup(tip) - new_max = max(self.depths().iteritems(), key=lambda nd: nd[1]) + new_max = max(self.depths().items(), key=lambda nd: nd[1]) if new_max[1] > max_distance: tip1 = tip tip2 = new_max[0] @@ -912,7 +917,7 @@ as an output file format. """ if format_spec: - from StringIO import StringIO + from Bio._py3k import StringIO from Bio.Phylo import _io handle = StringIO() _io.write([self], handle, format_spec) @@ -1013,14 +1018,17 @@ """Number of clades directy under the root.""" return len(self.clades) - def __nonzero__(self): - """Boolean value of an instance of this class. + #Python 3: + def __bool__(self): + """Boolean value of an instance of this class (True). NB: If this method is not defined, but ``__len__`` is, then the object is considered true if the result of ``__len__()`` is nonzero. We want Clade instances to always be considered True. """ return True + #Python 2: + __nonzero__ = __bool__ def __str__(self): if self.name: @@ -1122,11 +1130,8 @@ len(hexstr) == 7 ), "need a 24-bit hexadecimal string, e.g. #000000" - def unpack(cc): - return int('0x'+cc, base=16) - RGB = hexstr[1:3], hexstr[3:5], hexstr[5:] - return cls(*map(unpack, RGB)) + return cls(*[int('0x'+cc, base=16) for cc in RGB]) @classmethod def from_name(cls, colorname): diff -Nru python-biopython-1.62/Bio/Phylo/CDAOIO.py python-biopython-1.63/Bio/Phylo/CDAOIO.py --- python-biopython-1.62/Bio/Phylo/CDAOIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Phylo/CDAOIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -21,19 +21,21 @@ __docformat__ = "restructuredtext en" -from cStringIO import StringIO +from Bio._py3k import StringIO from Bio.Phylo import CDAO -from _cdao_owl import cdao_elements, cdao_namespaces, resolve_uri +from ._cdao_owl import cdao_elements, cdao_namespaces, resolve_uri import os -import urlparse class CDAOError(Exception): """Exception raised when CDAO object construction cannot continue.""" pass -try: +try: import rdflib + rdfver = rdflib.__version__ + if rdfver[0] in ["1", "2"] or (rdfver in ["3.0.0", "3.1.0", "3.2.0"]): + raise CDAOError('Support for CDAO tree format requires RDFlib v3.2.1 or later.') except ImportError: raise CDAOError('Support for CDAO tree format requires RDFlib.') @@ -48,7 +50,7 @@ def qUri(x): return resolve_uri(x, namespaces=RDF_NAMESPACES) - + def format_label(x): return x.replace('_', ' ') @@ -94,50 +96,50 @@ """Parse the text stream this object was initialized with.""" self.parse_handle_to_graph(**kwargs) return self.parse_graph() - + def parse_handle_to_graph(self, rooted=False, parse_format='turtle', context=None, **kwargs): '''Parse self.handle into RDF model self.model.''' - + if self.graph is None: self.graph = rdflib.Graph() graph = self.graph - + for k, v in RDF_NAMESPACES.items(): graph.bind(k, v) - + self.rooted = rooted - + if 'base_uri' in kwargs: base_uri = kwargs['base_uri'] else: base_uri = "file://"+os.path.abspath(self.handle.name) - + graph.parse(file=self.handle, publicID=base_uri, format=parse_format) - + return self.parse_graph(graph, context=context) - - + + def parse_graph(self, graph=None, context=None): '''Generator that yields CDAO.Tree instances from an RDF model.''' - + if graph is None: graph = self.graph - + # look up branch lengths/TUs for all nodes self.get_node_info(graph, context=context) - + for root_node in self.tree_roots: clade = self.parse_children(root_node) - + yield CDAO.Tree(root=clade, rooted=self.rooted) - - + + def new_clade(self, node): '''Returns a CDAO.Clade object for a given named node.''' - + result = self.node_info[node] - + kwargs = {} if 'branch_length' in result: kwargs['branch_length'] = result['branch_length'] @@ -145,21 +147,21 @@ kwargs['name'] = result['label'].replace('_', ' ') if 'confidence' in result: kwargs['confidence'] = result['confidence'] - + clade = CDAO.Clade(**kwargs) - + return clade - - + + def get_node_info(self, graph, context=None): '''Creates a dictionary containing information about all nodes in the tree.''' - + self.node_info = {} self.obj_info = {} self.children = {} self.nodes = set() self.tree_roots = set() - + assignments = { qUri('cdao:has_Parent'): 'parent', qUri('cdao:belongs_to_Edge_as_Child'): 'edge', @@ -169,21 +171,21 @@ qUri('rdfs:label'): 'label', qUri('cdao:has_Support_Value'): 'confidence', } - + for s, v, o in graph: # process each RDF triple in the graph sequentially - + s, v, o = str(s), str(v), str(o) - + if not s in self.obj_info: self.obj_info[s] = {} this = self.obj_info[s] - + try: # if the predicate is one we care about, store information for later this[assignments[v]] = o except KeyError: pass - + if v == qUri('rdf:type'): if o in (qUri('cdao:AncestralNode'), qUri('cdao:TerminalNode')): # this is a tree node; store it in set of all nodes @@ -191,12 +193,12 @@ if v == qUri('cdao:has_Root'): # this is a tree; store its root in set of all tree roots self.tree_roots.add(o) - + for node in self.nodes: # for each node, look up all information needed to create a CDAO.Clade self.node_info[node] = {} node_info = self.node_info[node] - + obj = self.obj_info[node] if 'edge' in obj: # if this object points to an edge, we need a branch length from @@ -212,7 +214,7 @@ tu = self.obj_info[obj['tu']] if 'label' in tu: node_info['label'] = tu['label'] - + if 'parent' in obj: # store this node as a child of its parent, if it has one, # so that the tree can be traversed from parent to children @@ -220,18 +222,18 @@ if not parent in self.children: self.children[parent] = [] self.children[parent].append(node) - - + + def parse_children(self, node): - '''Return a CDAO.Clade, and calls itself recursively for each child, - traversing the entire tree and creating a nested structure of CDAO.Clade + '''Return a CDAO.Clade, and calls itself recursively for each child, + traversing the entire tree and creating a nested structure of CDAO.Clade objects.''' - + clade = self.new_clade(node) - + children = self.children[node] if node in self.children else [] clade.clades = [self.parse_children(child_node) for child_node in children] - + return clade @@ -244,30 +246,30 @@ def __init__(self, trees): self.trees = trees - + self.node_counter = 0 self.edge_counter = 0 self.tu_counter = 0 self.tree_counter = 0 - def write(self, handle, tree_uri='', record_complete_ancestry=False, + def write(self, handle, tree_uri='', record_complete_ancestry=False, rooted=False, **kwargs): """Write this instance's trees to a file handle.""" - + self.rooted = rooted self.record_complete_ancestry = record_complete_ancestry - + if tree_uri and not tree_uri.endswith('/'): tree_uri += '/' - + trees = self.trees - + if tree_uri: handle.write('@base <%s>\n' % tree_uri) for k, v in self.prefixes.items(): - handle.write('@prefix %s: <%s> .\n' % (k,v)) + handle.write('@prefix %s: <%s> .\n' % (k, v)) handle.write('<%s> a owl:Ontology .\n' % self.prefixes['cdao']) - - + + for tree in trees: self.tree_counter += 1 self.tree_uri = 'tree%s' @@ -276,8 +278,8 @@ statements = self.process_clade(first_clade, root=tree) for stmt in statements: self.add_stmt_to_handle(handle, stmt) - - + + def add_stmt_to_handle(self, handle, stmt): # apply URI prefixes stmt_strings = [] @@ -295,41 +297,41 @@ elif isinstance(part, rdflib.Literal): stmt_strings.append(part.n3()) - + else: stmt_strings.append(str(part)) - + handle.write('%s .\n' % ' '.join(stmt_strings)) - + def process_clade(self, clade, parent=None, root=False): '''recursively generate triples describing a tree of clades''' - + self.node_counter += 1 clade.uri = 'node%s' % str(self.node_counter).zfill(ZEROES) if parent: clade.ancestors = parent.ancestors + [parent.uri] else: clade.ancestors = [] - + nUri = lambda s: rdflib.URIRef(s)#':%s' % s pUri = lambda s: rdflib.URIRef(qUri(s)) tree_id = nUri('') - + statements = [] - + if not root is False: # create a cdao:RootedTree with reference to the tree root tree_type = pUri('cdao:RootedTree') if self.rooted else pUri('cdao:UnrootedTree') - + statements += [ (tree_id, pUri('rdf:type'), tree_type), (tree_id, pUri('cdao:has_Root'), nUri(clade.uri)), ] - + try: tree_attributes = root.attributes except AttributeError: tree_attributes = [] - + for predicate, obj in tree_attributes: statements.append((tree_id, predicate, obj)) - + if clade.name: # create TU self.tu_counter += 1 @@ -340,20 +342,20 @@ (nUri(clade.uri), pUri('cdao:represents_TU'), nUri(tu_uri)), (nUri(tu_uri), pUri('rdfs:label'), rdflib.Literal(format_label(clade.name))), ] - + try: tu_attributes = clade.tu_attributes except AttributeError: tu_attributes = [] - + for predicate, obj in tu_attributes: yield (nUri(tu_uri), predicate, obj) - + # create this node node_type = 'cdao:TerminalNode' if clade.is_terminal() else 'cdao:AncestralNode' statements += [ (nUri(clade.uri), pUri('rdf:type'), pUri(node_type)), (nUri(clade.uri), pUri('cdao:belongs_to_Tree'), tree_id), ] - + if not parent is None: # create edge from the parent node to this node self.edge_counter += 1 @@ -368,43 +370,43 @@ (nUri(clade.uri), pUri('cdao:has_Parent'), nUri(parent.uri)), (nUri(parent.uri), pUri('cdao:belongs_to_Edge_as_Parent'), nUri(edge_uri)), ] - + if hasattr(clade, 'confidence') and not clade.confidence is None: confidence = rdflib.Literal(clade.confidence, datatype='http://www.w3.org/2001/XMLSchema#decimal') - + statements += [(nUri(clade.uri), pUri('cdao:has_Support_Value'), confidence)] - - + + if self.record_complete_ancestry and len(clade.ancestors) > 0: statements += [(nUri(clade.uri), pUri('cdao:has_Ancestor'), nUri(ancestor)) for ancestor in clade.ancestors] - + if not clade.branch_length is None: # add branch length edge_ann_uri = 'edge_annotation%s' % str(self.edge_counter).zfill(ZEROES) - + branch_length = rdflib.Literal(clade.branch_length, datatype=rdflib.URIRef('http://www.w3.org/2001/XMLSchema#decimal')) statements += [ (nUri(edge_ann_uri), pUri('rdf:type'), pUri('cdao:EdgeLength')), (nUri(edge_uri), pUri('cdao:has_Annotation'), nUri(edge_ann_uri)), (nUri(edge_ann_uri), pUri('cdao:has_Value'), branch_length), ] - + try: edge_attributes = clade.edge_attributes except AttributeError: edge_attributes = [] - + for predicate, obj in edge_attributes: yield (nUri(edge_uri), predicate, obj) - + for stmt in statements: yield stmt - + try: clade_attributes = clade.attributes except AttributeError: clade_attributes = [] - + for predicate, obj in clade_attributes: yield (nUri(clade.uri), predicate, obj) - + if not clade.is_terminal(): for new_clade in clade.clades: for stmt in self.process_clade(new_clade, parent=clade, root=False): diff -Nru python-biopython-1.62/Bio/Phylo/NeXMLIO.py python-biopython-1.63/Bio/Phylo/NeXMLIO.py --- python-biopython-1.62/Bio/Phylo/NeXMLIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Phylo/NeXMLIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -12,12 +12,12 @@ """ __docformat__ = "restructuredtext en" -from cStringIO import StringIO +from Bio._py3k import StringIO from Bio.Phylo import NeXML from xml.dom import minidom import sys -from _cdao_owl import cdao_elements, cdao_namespaces, resolve_uri +from ._cdao_owl import cdao_elements, cdao_namespaces, resolve_uri #For speed try to use cElementTree rather than ElementTree @@ -54,7 +54,7 @@ def register_namespace(prefix, uri): ElementTree._namespace_map[uri] = prefix -for prefix, uri in NAMESPACES.iteritems(): +for prefix, uri in NAMESPACES.items(): register_namespace(prefix, uri) @@ -180,14 +180,16 @@ # if no root specified, start the recursive tree creation function # with the first node that's not a child of any other nodes rooted = False - possible_roots = (node.attrib['id'] for node in nodes if node.attrib['id'] in srcs and not node.attrib['id'] in tars) - root = possible_roots.next() + possible_roots = (node.attrib['id'] for node in nodes + if node.attrib['id'] in srcs + and not node.attrib['id'] in tars) + root = next(possible_roots) else: rooted = True yield NeXML.Tree(root=self._make_tree(root, node_dict, node_children), rooted=rooted) - - + + @classmethod def _make_tree(cls, node, node_dict, children): '''Return a NeXML.Clade, and calls itself recursively for each child, @@ -290,15 +292,15 @@ if not parent is None: edge_id = self.new_label('edge') attrib={ - 'id':edge_id, 'source':parent.node_id, 'target':node_id, - 'length':str(clade.branch_length), - 'typeof':convert_uri('cdao:Edge'), + 'id': edge_id, 'source': parent.node_id, 'target': node_id, + 'length': str(clade.branch_length), + 'typeof': convert_uri('cdao:Edge'), } if hasattr(clade, 'confidence') and not clade.confidence is None: attrib.update({ - 'property':convert_uri('cdao:has_Support_Value'), - 'datatype':'xsd:float', - 'content':'%1.2f' % clade.confidence, + 'property': convert_uri('cdao:has_Support_Value'), + 'datatype': 'xsd:float', + 'content': '%1.2f' % clade.confidence, }) node = ElementTree.SubElement(tree, 'edge', **attrib) diff -Nru python-biopython-1.62/Bio/Phylo/NewickIO.py python-biopython-1.63/Bio/Phylo/NewickIO.py --- python-biopython-1.62/Bio/Phylo/NewickIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Phylo/NewickIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -12,7 +12,7 @@ __docformat__ = "restructuredtext en" import re -from cStringIO import StringIO +from Bio._py3k import StringIO from Bio.Phylo import Newick @@ -33,7 +33,7 @@ (r"\;", 'semicolon'), (r"\n", 'newline'), ] -tokenizer = re.compile('(%s)' % '|'.join([token[0] for token in tokens])) +tokenizer = re.compile('(%s)' % '|'.join(token[0] for token in tokens)) token_dict = dict((name, re.compile(token)) for (token, name) in tokens) @@ -186,7 +186,7 @@ # if ; token broke out of for loop, there should be no remaining tokens try: - next_token = tokens.next() + next_token = next(tokens) raise NewickError('Text after semicolon in Newick tree: %s' % next_token.group()) except StopIteration: diff -Nru python-biopython-1.62/Bio/Phylo/NexusIO.py python-biopython-1.63/Bio/Phylo/NexusIO.py --- python-biopython-1.62/Bio/Phylo/NexusIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Phylo/NexusIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -68,7 +68,7 @@ for idx, nwk in enumerate( writer.to_strings(plain=False, plain_newick=True, **kwargs))] - tax_labels = map(str, chain(*(t.get_terminals() for t in trees))) + tax_labels = [str(x) for x in chain(*(t.get_terminals() for t in trees))] text = NEX_TEMPLATE % { 'count': len(tax_labels), 'labels': ' '.join(tax_labels), diff -Nru python-biopython-1.62/Bio/Phylo/PAML/_paml.py python-biopython-1.63/Bio/Phylo/PAML/_paml.py --- python-biopython-1.62/Bio/Phylo/PAML/_paml.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Phylo/PAML/_paml.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,6 +3,8 @@ # license. Please see the LICENSE file that should have been included # as part of this package. +from __future__ import print_function + import os import subprocess @@ -66,7 +68,7 @@ def print_options(self): """Print out all of the options and their current settings.""" for option in self._options.items(): - print "%s = %s" % (option[0], option[1]) + print("%s = %s" % (option[0], option[1])) def set_options(self, **kwargs): """Set the value of an option. @@ -89,7 +91,7 @@ def get_all_options(self): """Return the values of all the options.""" - return self._options.items() + return list(self._options.items()) def _set_rel_paths(self): """Convert all file/directory locations to paths relative to the current working directory. diff -Nru python-biopython-1.62/Bio/Phylo/PAML/_parse_codeml.py python-biopython-1.63/Bio/Phylo/PAML/_parse_codeml.py --- python-biopython-1.62/Bio/Phylo/PAML/_parse_codeml.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Phylo/PAML/_parse_codeml.py 2013-12-05 14:10:43.000000000 +0000 @@ -187,7 +187,7 @@ # "lnL(ntime: 19 np: 22): -2021.348300 +0.000000" if "lnL(ntime:" in line and len(line_floats) > 0: results["lnL"] = line_floats[0] - np_res = re.match("lnL\(ntime:\s+\d+\s+np:\s+(\d+)\)",line) + np_res = re.match("lnL\(ntime:\s+\d+\s+np:\s+(\d+)\)", line) if np_res is not None: num_params = int(np_res.group(1)) # Get parameter list. This can be useful for specifying starting @@ -337,7 +337,7 @@ float_model_params = [] for param in model_params: float_model_params.append((param[0], _nan_float(param[1]))) - parameters = dict(parameters.items() + float_model_params) + parameters.update(dict(float_model_params)) if len(parameters) > 0: results["parameters"] = parameters return results diff -Nru python-biopython-1.62/Bio/Phylo/PAML/_parse_yn00.py python-biopython-1.63/Bio/Phylo/PAML/_parse_yn00.py --- python-biopython-1.62/Bio/Phylo/PAML/_parse_yn00.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Phylo/PAML/_parse_yn00.py 2013-12-05 14:10:43.000000000 +0000 @@ -19,7 +19,7 @@ # Find all floating point numbers in this line line_floats_res = re.findall("-*\d+\.\d+", line) line_floats = [float(val) for val in line_floats_res] - matrix_row_res = re.match("(.+)\s{5,15}",line) + matrix_row_res = re.match("(.+)\s{5,15}", line) if matrix_row_res is not None: seq_name = matrix_row_res.group(1).strip() sequences.append(seq_name) diff -Nru python-biopython-1.62/Bio/Phylo/PAML/baseml.py python-biopython-1.63/Bio/Phylo/PAML/baseml.py --- python-biopython-1.62/Bio/Phylo/PAML/baseml.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Phylo/PAML/baseml.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,13 +3,10 @@ # license. Please see the LICENSE file that should have been included # as part of this package. -# For using with statement in Python 2.5 or Jython -from __future__ import with_statement - import os import os.path -from _paml import Paml, _relpath -import _parse_baseml +from ._paml import Paml, _relpath +from . import _parse_baseml class BasemlError(EnvironmentError): @@ -104,7 +101,7 @@ with open(ctl_file) as ctl_handle: for line in ctl_handle: line = line.strip() - uncommented = line.split("*",1)[0] + uncommented = line.split("*", 1)[0] if uncommented != "": if "=" not in uncommented: raise AttributeError( @@ -141,8 +138,8 @@ except: converted_value = value temp_options[option] = converted_value - for option in self._options.keys(): - if option in temp_options.keys(): + for option in self._options: + if option in temp_options: self._options[option] = temp_options[option] else: self._options[option] = None @@ -185,9 +182,8 @@ results = {} if not os.path.exists(results_file): raise IOError("Results file does not exist.") - handle = open(results_file) - lines = handle.readlines() - handle.close() + with open(results_file) as handle: + lines = handle.readlines() (results, num_params) = _parse_baseml.parse_basics(lines, results) results = _parse_baseml.parse_parameters(lines, results, num_params) if results.get("version") is None: diff -Nru python-biopython-1.62/Bio/Phylo/PAML/codeml.py python-biopython-1.63/Bio/Phylo/PAML/codeml.py --- python-biopython-1.62/Bio/Phylo/PAML/codeml.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Phylo/PAML/codeml.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,13 +3,12 @@ # license. Please see the LICENSE file that should have been included # as part of this package. -# For using with statement in Python 2.5 or Jython -from __future__ import with_statement +from __future__ import print_function import os import os.path -from _paml import Paml, _relpath -import _parse_codeml +from ._paml import Paml, _relpath +from . import _parse_codeml class CodemlError(EnvironmentError): @@ -89,7 +88,7 @@ # NSsites is stored in Python as a list but in the # control file it is specified as a series of numbers # separated by spaces. - NSsites = " ".join([str(site) for site in option[1]]) + NSsites = " ".join(str(site) for site in option[1]) ctl_handle.write("%s = %s\n" % (option[0], NSsites)) else: ctl_handle.write("%s = %s\n" % (option[0], option[1])) @@ -104,7 +103,7 @@ with open(ctl_file) as ctl_handle: for line in ctl_handle: line = line.strip() - uncommented = line.split("*",1)[0] + uncommented = line.split("*", 1)[0] if uncommented != "": if "=" not in uncommented: raise AttributeError( @@ -141,8 +140,8 @@ except: converted_value = value temp_options[option] = converted_value - for option in self._options.keys(): - if option in temp_options.keys(): + for option in self._options: + if option in temp_options: self._options[option] = temp_options[option] else: self._options[option] = None @@ -154,10 +153,10 @@ # NSsites is stored in Python as a list but in the # control file it is specified as a series of numbers # separated by spaces. - NSsites = " ".join([str(site) for site in option[1]]) - print "%s = %s" % (option[0], NSsites) + NSsites = " ".join(str(site) for site in option[1]) + print("%s = %s" % (option[0], NSsites)) else: - print "%s = %s" % (option[0], option[1]) + print("%s = %s" % (option[0], option[1])) def _set_rel_paths(self): """Convert all file/directory locations to paths relative to the current working directory. @@ -197,9 +196,8 @@ results = {} if not os.path.exists(results_file): raise IOError("Results file does not exist.") - handle = open(results_file) - lines = handle.readlines() - handle.close() + with open(results_file) as handle: + lines = handle.readlines() (results, multi_models, multi_genes) = _parse_codeml.parse_basics(lines, results) results = _parse_codeml.parse_nssites(lines, results, multi_models, diff -Nru python-biopython-1.62/Bio/Phylo/PAML/yn00.py python-biopython-1.63/Bio/Phylo/PAML/yn00.py --- python-biopython-1.62/Bio/Phylo/PAML/yn00.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Phylo/PAML/yn00.py 2013-12-05 14:10:43.000000000 +0000 @@ -4,8 +4,8 @@ # as part of this package. import os.path -from _paml import Paml -import _parse_yn00 +from ._paml import Paml +from . import _parse_yn00 #TODO - Restore use of with statement for closing handles automatically #after dropping Python 2.4 @@ -43,8 +43,7 @@ """ # Make sure all paths are relative to the working directory self._set_rel_paths() - if True: # Dummy statement to preserve indentation for diff - ctl_handle = open(self.ctl_file, 'w') + with open(self.ctl_file, 'w') as ctl_handle: ctl_handle.write("seqfile = %s\n" % self._rel_alignment) ctl_handle.write("outfile = %s\n" % self._rel_out_file) for option in self._options.items(): @@ -54,7 +53,6 @@ # commented out. continue ctl_handle.write("%s = %s\n" % (option[0], option[1])) - ctl_handle.close() def read_ctl_file(self, ctl_file): """Parse a control file and load the options into the yn00 instance. @@ -63,40 +61,37 @@ if not os.path.isfile(ctl_file): raise IOError("File not found: %r" % ctl_file) else: - ctl_handle = open(ctl_file) - for line in ctl_handle: - line = line.strip() - uncommented = line.split("*",1)[0] - if uncommented != "": - if "=" not in uncommented: - ctl_handle.close() - raise AttributeError( - "Malformed line in control file:\n%r" % line) - (option, value) = uncommented.split("=") - option = option.strip() - value = value.strip() - if option == "seqfile": - self.alignment = value - elif option == "outfile": - self.out_file = value - elif option not in self._options: - ctl_handle.close() - raise KeyError("Invalid option: %s" % option) - else: - if "." in value or "e-" in value: - try: - converted_value = float(value) - except: - converted_value = value + with open(ctl_file) as ctl_handle: + for line in ctl_handle: + line = line.strip() + uncommented = line.split("*", 1)[0] + if uncommented != "": + if "=" not in uncommented: + raise AttributeError( + "Malformed line in control file:\n%r" % line) + (option, value) = uncommented.split("=") + option = option.strip() + value = value.strip() + if option == "seqfile": + self.alignment = value + elif option == "outfile": + self.out_file = value + elif option not in self._options: + raise KeyError("Invalid option: %s" % option) else: - try: - converted_value = int(value) - except: - converted_value = value - temp_options[option] = converted_value - ctl_handle.close() - for option in self._options.keys(): - if option in temp_options.keys(): + if "." in value or "e-" in value: + try: + converted_value = float(value) + except: + converted_value = value + else: + try: + converted_value = int(value) + except: + converted_value = value + temp_options[option] = converted_value + for option in self._options: + if option in temp_options: self._options[option] = temp_options[option] else: self._options[option] = None @@ -116,9 +111,8 @@ results = {} if not os.path.exists(results_file): raise IOError("Results file does not exist.") - handle = open(results_file) - lines = handle.readlines() - handle.close() + with open(results_file) as handle: + lines = handle.readlines() for line_num in range(len(lines)): line = lines[line_num] if "(A) Nei-Gojobori (1986) method" in line: diff -Nru python-biopython-1.62/Bio/Phylo/PhyloXML.py python-biopython-1.63/Bio/Phylo/PhyloXML.py --- python-biopython-1.62/Bio/Phylo/PhyloXML.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Phylo/PhyloXML.py 2013-12-05 14:10:43.000000000 +0000 @@ -17,6 +17,8 @@ import re import warnings +from Bio._py3k import basestring + from Bio import Alphabet from Bio.Align import MultipleSeqAlignment from Bio.Seq import Seq @@ -223,7 +225,7 @@ return False seqs = self._filter_search(is_aligned_seq, 'preorder', True) try: - first_seq = seqs.next() + first_seq = next(seqs) except StopIteration: # No aligned sequences were found --> empty MSA return MultipleSeqAlignment([]) @@ -761,15 +763,16 @@ self.confidence = confidence def items(self): - return [(k, v) for k, v in self.__dict__.iteritems() if v is not None] + return [(k, v) for k, v in self.__dict__.items() if v is not None] def keys(self): - return [k for k, v in self.__dict__.iteritems() if v is not None] + return [k for k, v in self.__dict__.items() if v is not None] def values(self): - return [v for v in self.__dict__.itervalues() if v is not None] + return [v for v in self.__dict__.values() if v is not None] def __len__(self): + #TODO - Better way to do this? return len(self.values()) def __getitem__(self, key): @@ -1118,7 +1121,7 @@ """ def clean_dict(dct): """Remove None-valued items from a dictionary.""" - return dict((key, val) for key, val in dct.iteritems() + return dict((key, val) for key, val in dct.items() if val is not None) seqrec = SeqRecord(Seq(self.mol_seq.value, self.get_alphabet()), diff -Nru python-biopython-1.62/Bio/Phylo/PhyloXMLIO.py python-biopython-1.63/Bio/Phylo/PhyloXMLIO.py --- python-biopython-1.62/Bio/Phylo/PhyloXMLIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Phylo/PhyloXMLIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -20,6 +20,9 @@ import sys +from Bio._py3k import basestring +from Bio._py3k import unicode + from Bio.Phylo import PhyloXML as PX #For speed try to use cElementTree rather than ElementTree @@ -50,7 +53,7 @@ def register_namespace(prefix, uri): ElementTree._namespace_map[uri] = prefix -for prefix, uri in NAMESPACES.iteritems(): +for prefix, uri in NAMESPACES.items(): register_namespace(prefix, uri) @@ -215,9 +218,9 @@ def _str2bool(text): - if text == 'true': + if text == 'true' or text=='1': return True - if text == 'false': + if text == 'false' or text=='0': return False raise ValueError('String could not be converted to boolean: ' + text) @@ -284,7 +287,7 @@ def __init__(self, file): # Get an iterable context for XML parsing events context = iter(ElementTree.iterparse(file, events=('start', 'end'))) - event, root = context.next() + event, root = next(context) self.root = root self.context = context @@ -374,8 +377,8 @@ 'reference': 'references', 'property': 'properties', } - _clade_tracked_tags = set(_clade_complex_types + _clade_list_types.keys() - + ['branch_length', 'name', 'node_id', 'width']) + _clade_tracked_tags = set(_clade_complex_types).union(_clade_list_types.keys()).union( + ['branch_length', 'name', 'node_id', 'width']) def _parse_clade(self, parent): """Parse a Clade node and its children, recursively.""" diff -Nru python-biopython-1.62/Bio/Phylo/_io.py python-biopython-1.63/Bio/Phylo/_io.py --- python-biopython-1.62/Bio/Phylo/_io.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Phylo/_io.py 2013-12-05 14:10:43.000000000 +0000 @@ -8,8 +8,8 @@ This API follows the same semantics as Biopython's `SeqIO` and `AlignIO`. """ -# For with on Python/Jython 2.5 -from __future__ import with_statement +from __future__ import print_function + __docformat__ = "restructuredtext en" from Bio import File @@ -46,7 +46,7 @@ >>> trees = parse('../../Tests/PhyloXML/apaf.xml', 'phyloxml') >>> for tree in trees: - ... print tree.rooted + ... print(tree.rooted) True """ with File.as_handle(file, 'r') as fp: @@ -62,11 +62,11 @@ """ try: tree_gen = parse(file, format, **kwargs) - tree = tree_gen.next() + tree = next(tree_gen) except StopIteration: raise ValueError("There are no trees in this file.") try: - tree_gen.next() + next(tree_gen) except StopIteration: return tree else: @@ -88,3 +88,4 @@ """Convert between two tree file formats.""" trees = parse(in_file, in_format, **parse_args) return write(trees, out_file, out_format, **kwargs) + diff -Nru python-biopython-1.62/Bio/Phylo/_utils.py python-biopython-1.63/Bio/Phylo/_utils.py --- python-biopython-1.62/Bio/Phylo/_utils.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Phylo/_utils.py 2013-12-05 14:10:43.000000000 +0000 @@ -136,7 +136,19 @@ "Install NetworkX if you want to use to_networkx.") G = to_networkx(tree) - Gi = networkx.convert_node_labels_to_integers(G, discard_old_labels=False) + try: + # NetworkX version 1.8 or later (2013-01-20) + Gi = networkx.convert_node_labels_to_integers(G, + label_attribute='label') + int_labels = {} + for integer, nodeattrs in Gi.node.items(): + int_labels[nodeattrs['label']] = integer + except TypeError: + # Older NetworkX versions (before 1.8) + Gi = networkx.convert_node_labels_to_integers(G, + discard_old_labels=False) + int_labels = Gi.node_labels + try: posi = networkx.graphviz_layout(Gi, prog, args=args) except ImportError: @@ -144,6 +156,7 @@ "Install PyGraphviz or pydot if you want to use draw_graphviz.") def get_label_mapping(G, selection): + """Apply the user-specified node relabeling.""" for node in G.nodes(): if (selection is None) or (node in selection): try: @@ -157,7 +170,7 @@ labels = dict(get_label_mapping(G, set(kwargs['nodelist']))) else: labels = dict(get_label_mapping(G, None)) - kwargs['nodelist'] = labels.keys() + kwargs['nodelist'] = list(labels.keys()) if 'edge_color' not in kwargs: kwargs['edge_color'] = [isinstance(e[2], dict) and e[2].get('color', 'k') or 'k' @@ -167,7 +180,7 @@ e[2].get('width', 1.0) or 1.0 for e in G.edges(data=True)] - posn = dict((n, posi[Gi.node_labels[n]]) for n in G) + posn = dict((n, posi[int_labels[n]]) for n in G) networkx.draw(G, posn, labels=labels, node_color=node_color, **kwargs) @@ -203,14 +216,14 @@ """Create a mapping of each clade to its column position.""" depths = tree.depths() # If there are no branch lengths, assume unit branch lengths - if not max(depths.itervalues()): + if not max(depths.values()): depths = tree.depths(unit_branch_lengths=True) # Potential drawing overflow due to rounding -- 1 char per tree layer fudge_margin = int(math.ceil(math.log(len(taxa), 2))) cols_per_branch_unit = ((drawing_width - fudge_margin) - / float(max(depths.itervalues()))) + / float(max(depths.values()))) return dict((clade, int(round(blen*cols_per_branch_unit + 0.5))) - for clade, blen in depths.iteritems()) + for clade, blen in depths.items()) def get_row_positions(tree): positions = dict((taxon, 2*idx) for idx, taxon in enumerate(taxa)) @@ -357,7 +370,7 @@ """ depths = tree.depths() # If there are no branch lengths, assume unit branch lengths - if not max(depths.itervalues()): + if not max(depths.values()): depths = tree.depths(unit_branch_lengths=True) return depths @@ -406,12 +419,12 @@ axes.hlines(y_here, x_start, x_here, color=color, lw=lw) elif (use_linecollection==True and orientation=='horizontal'): horizontal_linecollections.append(mpcollections.LineCollection( - [[(x_start,y_here), (x_here,y_here)]], color=color, lw=lw),) + [[(x_start, y_here), (x_here, y_here)]], color=color, lw=lw),) elif (use_linecollection==False and orientation=='vertical'): axes.vlines(x_here, y_bot, y_top, color=color) elif (use_linecollection==True and orientation=='vertical'): vertical_linecollections.append(mpcollections.LineCollection( - [[(x_here,y_bot), (x_here,y_top)]], color=color, lw=lw),) + [[(x_here, y_bot), (x_here, y_top)]], color=color, lw=lw),) def draw_clade(clade, x_start, color, lw): """Recursively draw a tree, down from the given clade.""" @@ -424,7 +437,7 @@ lw = clade.width * plt.rcParams['lines.linewidth'] # Draw a horizontal line from start to here draw_clade_lines(use_linecollection=True, orientation='horizontal', - y_here=y_here, x_start=x_start, x_here=x_here, color='black', lw=lw) + y_here=y_here, x_start=x_start, x_here=x_here, color=color, lw=lw) # Add node/taxon labels label = label_func(clade) if label not in (None, clade.__class__.__name__): @@ -440,7 +453,7 @@ y_bot = y_posns[clade.clades[-1]] # Only apply widths to horizontal lines, like Archaeopteryx draw_clade_lines(use_linecollection=True, orientation='vertical', - x_here=x_here, y_bot=y_bot, y_top=y_top, color='black', lw=lw) + x_here=x_here, y_bot=y_bot, y_top=y_top, color=color, lw=lw) # Draw descendents for child in clade: draw_clade(child, x_here, color, lw) @@ -461,14 +474,14 @@ axes.set_xlabel('branch length') axes.set_ylabel('taxa') # Add margins around the tree to prevent overlapping the axes - xmax = max(x_posns.itervalues()) + xmax = max(x_posns.values()) axes.set_xlim(-0.05 * xmax, 1.25 * xmax) # Also invert the y-axis (origin at the top) # Add a small vertical margin, but avoid including 0 and N+1 on the y axis - axes.set_ylim(max(y_posns.itervalues()) + 0.8, 0.2) + axes.set_ylim(max(y_posns.values()) + 0.8, 0.2) # Parse and process key word arguments as pyplot options - for key, value in kwargs.iteritems(): + for key, value in kwargs.items(): try: # Check that the pyplot option input is iterable, as required [i for i in value] diff -Nru python-biopython-1.62/Bio/PopGen/Async/Local.py python-biopython-1.63/Bio/PopGen/Async/Local.py --- python-biopython-1.62/Bio/PopGen/Async/Local.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PopGen/Async/Local.py 2013-12-05 14:10:43.000000000 +0000 @@ -11,14 +11,14 @@ from Bio.PopGen.Async import Async -import thread +import threading class Local(Async): '''Execution on Local machine. ''' - def __init__(self, num_cores = 1): + def __init__(self, num_cores=1): '''Constructor. parameters: @@ -41,7 +41,7 @@ self.waiting.append((id, hook, parameters, input_files)) if self.cores_used < self.num_cores: self.cores_used += 1 - thread.start_new_thread(self.start_work, ()) + threading.Thread(target=self.start_work).run() self.access_ds.release() def start_work(self): diff -Nru python-biopython-1.62/Bio/PopGen/Async/__init__.py python-biopython-1.63/Bio/PopGen/Async/__init__.py --- python-biopython-1.62/Bio/PopGen/Async/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PopGen/Async/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -10,7 +10,7 @@ ''' import os -import thread +import threading class Async(object): @@ -32,7 +32,7 @@ self.done = {} self.id = 0 self.hooks = {} - self.access_ds = thread.allocate_lock() + self.access_ds = threading.Lock() def run_program(self, program, parameters, input_files): '''Runs a program. @@ -96,7 +96,7 @@ ''' def __init__(self): - self.file_list=[] + self.file_list = [] def get_File_list(self): '''Returns the list of available files. @@ -117,7 +117,7 @@ walk_list = os.walk(directory) for dir, dir_list, file_list in walk_list: for file in file_list: - self.file_list.append(file[len(directory)+1:]) + self.file_list.append(file[len(directory) + 1:]) def get_file(self, name): return open(self.directory + os.sep + name) diff -Nru python-biopython-1.62/Bio/PopGen/FDist/Async.py python-biopython-1.63/Bio/PopGen/FDist/Async.py --- python-biopython-1.62/Bio/PopGen/FDist/Async.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PopGen/FDist/Async.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,21 +3,19 @@ # license. Please see the LICENSE file that should have been included # as part of this package. - -""" -This modules allows for asynchronous execution of Fdist and - spliting of loads. +"""Asynchronous execution of Fdist and spliting of loads. FDistAsync Allows for the execution of FDist. SplitFDist splits a single Fdist execution in several, taking advantage - of multi-core architectures. - +of multi-core architectures. """ +from __future__ import print_function + import os import shutil -import thread +import threading from time import sleep from Bio.PopGen.Async import Local from Bio.PopGen.FDist.Controller import FDistController @@ -27,7 +25,7 @@ """Asynchronous FDist execution. """ - def __init__(self, fdist_dir = "", ext = None): + def __init__(self, fdist_dir="", ext=None): """Constructor. Parameters: @@ -57,9 +55,9 @@ beta = parameters.get('beta', (0.25, 0.25)) max_freq = parameters.get('max_freq', 0.99) fst = self.run_fdist(npops, nsamples, fst, sample_size, - mut, num_sims, data_dir, - is_dominant, theta, beta, - max_freq) + mut, num_sims, data_dir, + is_dominant, theta, beta, + max_freq) output_files = {} output_files['out.dat'] = open(data_dir + os.sep + 'out.dat', 'r') return fst, output_files @@ -76,8 +74,8 @@ Each SplitFDist object can only be used to run a single FDist simulation. """ - def __init__(self, report_fun = None, - num_thr = 2, split_size = 1000, fdist_dir = '', ext = None): + def __init__(self, report_fun=None, + num_thr=2, split_size=1000, fdist_dir='', ext=None): """Constructor. Parameters: @@ -108,22 +106,20 @@ while(True): sleep(1) self.async.access_ds.acquire() - keys = self.async.done.keys()[:] + keys = list(self.async.done.keys()) #copy it self.async.access_ds.release() for done in keys: self.async.access_ds.acquire() fst, files = self.async.done[done] del self.async.done[done] out_dat = files['out.dat'] - f = open(self.data_dir + os.sep + 'out.dat','a') - f.writelines(out_dat.readlines()) - f.close() + with open(self.data_dir + os.sep + 'out.dat', 'a') as f: + f.writelines(out_dat.readlines()) out_dat.close() self.async.access_ds.release() for file in os.listdir(self.parts[done]): os.remove(self.parts[done] + os.sep + file) os.rmdir(self.parts[done]) - #print fst, out_dat if self.report_fun: self.report_fun(fst) self.async.access_ds.acquire() @@ -131,9 +127,6 @@ and len(self.async.done) == 0: break self.async.access_ds.release() - #print 'R', self.async.running - #print 'W', self.async.waiting - #print 'R', self.async.running def acquire(self): """Allows the external acquisition of the lock. @@ -147,9 +140,9 @@ #You can only run a fdist case at a time def run_fdist(self, npops, nsamples, fst, sample_size, - mut = 0, num_sims = 20000, data_dir='.', - is_dominant = False, theta = 0.06, beta = (0.25, 0.25), - max_freq = 0.99): + mut=0, num_sims=20000, data_dir='.', + is_dominant=False, theta=0.06, beta=(0.25, 0.25), + max_freq=0.99): """Runs FDist. Parameters can be seen on FDistController.run_fdist. @@ -157,7 +150,7 @@ It will split a single execution in several parts and create separated data directories. """ - num_parts = num_sims/self.split_size + num_parts = num_sims // self.split_size self.parts = {} self.data_dir = data_dir for directory in range(num_parts): @@ -182,4 +175,4 @@ 'max_freq' : max_freq }, {}) self.parts[id] = full_path - thread.start_new_thread(self.monitor, ()) + threading.Thread(target=self.monitor).run() diff -Nru python-biopython-1.62/Bio/PopGen/FDist/Controller.py python-biopython-1.63/Bio/PopGen/FDist/Controller.py --- python-biopython-1.62/Bio/PopGen/FDist/Controller.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PopGen/FDist/Controller.py 2013-12-05 14:10:43.000000000 +0000 @@ -19,11 +19,6 @@ from time import strftime, clock #from logging import debug -if sys.version_info[0] == 3: - maxint = sys.maxsize -else: - maxint = sys.maxint - def my_float(f): #Because of Jython, mostly @@ -117,11 +112,10 @@ Parameter: data_dir - data directory """ - inf = open(data_dir + os.sep + 'INTFILE', 'w') - for i in range(98): - inf.write(str(randint(-maxint + 1, maxint - 1)) + '\n') - inf.write('8\n') - inf.close() + with open(data_dir + os.sep + 'INTFILE', 'w') as inf: + for i in range(98): + inf.write(str(randint(-sys.maxsize + 1, sys.maxsize - 1)) + '\n') + inf.write('8\n') def run_fdist(self, npops, nsamples, fst, sample_size, mut=0, num_sims=50000, data_dir='.', @@ -159,20 +153,19 @@ else: config_name = "fdist_params2.dat" - f = open(data_dir + os.sep + config_name, 'w') - f.write(str(npops) + '\n') - f.write(str(nsamples) + '\n') - f.write(str(fst) + '\n') - f.write(str(sample_size) + '\n') - if is_dominant: - f.write(str(theta) + '\n') - else: - f.write(str(mut) + '\n') - f.write(str(num_sims) + '\n') - if is_dominant: - f.write("%f %f\n" % beta) - f.write("%f\n" % max_freq) - f.close() + with open(data_dir + os.sep + config_name, 'w') as f: + f.write(str(npops) + '\n') + f.write(str(nsamples) + '\n') + f.write(str(fst) + '\n') + f.write(str(sample_size) + '\n') + if is_dominant: + f.write(str(theta) + '\n') + else: + f.write(str(mut) + '\n') + f.write(str(num_sims) + '\n') + if is_dominant: + f.write("%f %f\n" % beta) + f.write("%f\n" % max_freq) self._generate_intfile(data_dir) @@ -256,19 +249,16 @@ "data_fst_outfile out.cpl out.dat", str(ci), str(smooth)])) - f = open(data_dir + os.sep + 'out.cpl') - conf_lines = [] - l = f.readline() - try: - while l != '': - conf_lines.append( - tuple(map(lambda x: my_float(x), - l.rstrip().split(' ')))) - l = f.readline() - except ValueError: - f.close() - return [] - f.close() + with open(data_dir + os.sep + 'out.cpl') as f: + conf_lines = [] + l = f.readline() + try: + while l != '': + conf_lines.append( + tuple(my_float(x) for x in l.rstrip().split(' '))) + l = f.readline() + except ValueError: + return [] return conf_lines def run_pv(self, out_file='probs.dat', data_dir='.', @@ -293,9 +283,6 @@ universal_newlines=True) proc.communicate('data_fst_outfile ' + out_file + ' out.dat\n' + str(smooth) + '\n') - pvf = open(data_dir + os.sep + out_file, 'r') - result = map(lambda x: tuple(map(lambda y: - my_float(y), x.rstrip().split(' '))), - pvf.readlines()) - pvf.close() + with open(data_dir + os.sep + out_file, 'r') as pvf: + result = [tuple(my_float(y) for y in x.rstrip().split(' ')) for x in pvf.readlines()] return result diff -Nru python-biopython-1.62/Bio/PopGen/FDist/Utils.py python-biopython-1.63/Bio/PopGen/FDist/Utils.py --- python-biopython-1.62/Bio/PopGen/FDist/Utils.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PopGen/FDist/Utils.py 2013-12-05 14:10:43.000000000 +0000 @@ -4,6 +4,8 @@ # as part of this package. +from __future__ import print_function + from Bio.PopGen.GenePop import FileParser import Bio.PopGen.FDist @@ -106,7 +108,7 @@ for al in lParser[1][loci_pos]: if al is not None: loci[loci_pos].add(al) - curr_pop[loci_pos][al]= curr_pop[loci_pos].get(al,0)+1 + curr_pop[loci_pos][al]= curr_pop[loci_pos].get(al, 0)+1 else: pops.append(curr_pop) num_pops += 1 @@ -118,8 +120,7 @@ pops.append(curr_pop) fd_rec.num_pops = num_pops for loci_pos in range(num_loci): - alleles = list(loci[loci_pos]) - alleles.sort() + alleles = sorted(loci[loci_pos]) loci_rec = [len(alleles), []] for pop in pops: pop_rec = [] diff -Nru python-biopython-1.62/Bio/PopGen/FDist/__init__.py python-biopython-1.63/Bio/PopGen/FDist/__init__.py --- python-biopython-1.62/Bio/PopGen/FDist/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PopGen/FDist/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -27,17 +27,17 @@ handle is a file-like object that contains a FDist record. """ record = Record() - record.data_org = int(str(handle.next()).rstrip()) - record.num_pops = int(str(handle.next()).rstrip()) - record.num_loci = int(str(handle.next()).rstrip()) + record.data_org = int(str(next(handle)).rstrip()) + record.num_pops = int(str(next(handle)).rstrip()) + record.num_loci = int(str(next(handle)).rstrip()) for i in range(record.num_loci): - handle.next() - num_alleles = int(str(handle.next()).rstrip()) + next(handle) + num_alleles = int(str(next(handle)).rstrip()) pops_data = [] if record.data_org==0: for j in range(record.num_pops): - line_comp = str(handle.next()).rstrip().split(' ') - pop_dist = map(lambda x: int(x), line_comp) + line_comp = str(next(handle)).rstrip().split(' ') + pop_dist = [int(x) for x in line_comp] pops_data.append(pop_dist) else: raise NotImplementedError('1/alleles by rows not implemented') diff -Nru python-biopython-1.62/Bio/PopGen/GenePop/Controller.py python-biopython-1.63/Bio/PopGen/GenePop/Controller.py --- python-biopython-1.62/Bio/PopGen/GenePop/Controller.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PopGen/GenePop/Controller.py 2013-12-05 14:10:43.000000000 +0000 @@ -12,6 +12,8 @@ import re import shutil +import sys # for checking if under Python 2 + from Bio.Application import AbstractCommandline, _Argument @@ -41,16 +43,16 @@ if 'No data' in l: return None, None l = f.readline() - alleles = filter(lambda x: x != '', f.readline().rstrip().split(" ")) - alleles = map(lambda x: _gp_int(x), alleles) + alleles = [x for x in f.readline().rstrip().split(" ") if x != ''] + alleles = [_gp_int(x) for x in alleles] l = f.readline().rstrip() table = [] while l != "": - line = filter(lambda x: x != '', l.split(" ")) + line = [x for x in l.split(" ") if x != ''] try: table.append( (line[0], - map(lambda x: _gp_float(x), line[1:-1]), + [_gp_float(x) for x in line[1:-1]], _gp_int(line[-1]))) except ValueError: table.append( @@ -68,7 +70,7 @@ l = f.readline().rstrip() l = f.readline().rstrip() while '===' not in l and '---' not in l and l != "": - toks = filter(lambda x: x != "", l.split(" ")) + toks = [x for x in l.split(" ") if x != ""] line = [] for i in range(len(toks)): try: @@ -85,8 +87,7 @@ l = f.readline().rstrip() while l != "": matrix.append( - map(lambda x: _gp_float(x), - filter(lambda y: y != "", l.split(" ")))) + [_gp_float(x) for x in [y for y in l.split(" ") if y != ""]]) l = f.readline().rstrip() return matrix @@ -96,10 +97,10 @@ header = f.readline().rstrip() if '---' in header or '===' in header: header = f.readline().rstrip() - nlines = len(filter(lambda x:x != '', header.split(' '))) - 1 + nlines = len([x for x in header.split(' ') if x != '']) - 1 for line_pop in range(nlines): l = f.readline().rstrip() - vals = filter(lambda x:x != '', l.split(' ')[1:]) + vals = [x for x in l.split(' ')[1:] if x != ''] clean_vals = [] for val in vals: try: @@ -122,7 +123,7 @@ stream.readline() stream.readline() stream.readline() - table = _read_table(stream,[str,_gp_float,_gp_float,_gp_float,_gp_float,_gp_int,str]) + table = _read_table(stream, [str, _gp_float, _gp_float, _gp_float, _gp_float, _gp_int, str]) #loci might mean pop if hook="Locus " loci = {} for entry in table: @@ -145,9 +146,14 @@ The generator function is expected to yield a tuple, while consuming input """ - def __init__(self, func, stream, fname): + def __init__(self, func, fname, handle=None): self.func = func - self.stream = stream + if handle is None: + self.stream = open(fname) + else: + # For special cases where calling code wants to + # seek into the file before starting: + self.stream = handle self.fname = fname self.done = False @@ -157,9 +163,19 @@ raise StopIteration return self - def next(self): + def __next__(self): return self.func(self) + if sys.version_info[0] < 3: + def next(self): + """Deprecated Python 2 style alias for Python 3 style __next__ method.""" + import warnings + from Bio import BiopythonDeprecationWarning + warnings.warn("Please use next(my_iterator) instead of my_iterator.next(), " + "the .next() method is deprecated and will be removed in a " + "future release of Biopython.", BiopythonDeprecationWarning) + return self.__next__() + def __del__(self): self.stream.close() try: @@ -206,8 +222,8 @@ Example set_menu([6,1]) = get all F statistics (menu 6.1) """ - self.set_parameter("command", "MenuOptions="+ - ".".join(map(lambda x:str(x),option_list))) + self.set_parameter("command", "MenuOptions=" + + ".".join(str(x) for x in option_list)) def set_input(self, fname): """Sets the input file name. @@ -279,12 +295,11 @@ """ opts = self._get_opts(dememorization, batches, iterations, enum_test) self._run_genepop([ext], [1, type], fname, opts) - f = open(fname + ext) def hw_func(self): return _hw_func(self.stream, False) - return _FileIterator(hw_func, f, fname + ext) + return _FileIterator(hw_func, fname + ext) def _test_global_hz_both(self, fname, type, ext, enum_test = True, dememorization = 10000, batches = 20, @@ -309,28 +324,26 @@ def hw_pop_func(self): return _read_table(self.stream, [str, _gp_float, _gp_float, _gp_float]) - f1 = open(fname + ext) - l = f1.readline() - while "by population" not in l: + with open(fname + ext) as f1: l = f1.readline() - pop_p = _read_table(f1, [str, _gp_float, _gp_float, _gp_float]) - f2 = open(fname + ext) - l = f2.readline() - while "by locus" not in l: + while "by population" not in l: + l = f1.readline() + pop_p = _read_table(f1, [str, _gp_float, _gp_float, _gp_float]) + with open(fname + ext) as f2: l = f2.readline() - loc_p = _read_table(f2, [str, _gp_float, _gp_float, _gp_float]) - f = open(fname + ext) - l = f.readline() - while "all locus" not in l: + while "by locus" not in l: + l = f2.readline() + loc_p = _read_table(f2, [str, _gp_float, _gp_float, _gp_float]) + with open(fname + ext) as f: l = f.readline() - f.readline() - f.readline() - f.readline() - f.readline() - l = f.readline().rstrip() - p, se, switches = tuple(map(lambda x: _gp_float(x), - filter(lambda y: y != "",l.split(" ")))) - f.close() + while "all locus" not in l: + l = f.readline() + f.readline() + f.readline() + f.readline() + f.readline() + l = f.readline().rstrip() + p, se, switches = tuple(_gp_float(x) for x in [y for y in l.split(" ") if y != ""]) return pop_p, loc_p, (p, se, switches) #1.1 @@ -391,9 +404,8 @@ return _hw_func(self.stream, False, True) shutil.copyfile(fname+".P", fname+".P2") - f1 = open(fname + ".P") - f2 = open(fname + ".P2") - return _FileIterator(hw_prob_loci_func, f1, fname + ".P"), _FileIterator(hw_prob_pop_func, f2, fname + ".P2") + + return _FileIterator(hw_prob_loci_func, fname + ".P"), _FileIterator(hw_prob_pop_func, fname + ".P2") #1.4 def test_global_hz_deficiency(self, fname, enum_test = True, @@ -447,7 +459,7 @@ if l == "": self.done = True raise StopIteration - toks = filter(lambda x: x != "", l.split(" ")) + toks = [x for x in l.split(" ") if x != ""] pop, locus1, locus2 = toks[0], toks[1], toks[2] if not hasattr(self, "start_locus1"): start_locus1, start_locus2 = locus1, locus2 @@ -464,7 +476,7 @@ if l == "": self.done = True raise StopIteration - toks = filter(lambda x: x != "", l.split(" ")) + toks = [x for x in l.split(" ") if x != ""] locus1, locus2 = toks[0], toks[2] try: chi2, df, p = _gp_float(toks[3]), _gp_int(toks[4]), _gp_float(toks[5]) @@ -483,7 +495,7 @@ l = f2.readline() while "----" not in l: l = f2.readline() - return _FileIterator(ld_pop_func, f1, fname+".DIS"), _FileIterator(ld_func, f2, fname + ".DI2") + return _FileIterator(ld_pop_func, fname+".DIS", f1), _FileIterator(ld_func, fname + ".DI2", f2) #2.2 def create_contingency_tables(self, fname): @@ -512,9 +524,8 @@ #4 def estimate_nm(self, fname): self._run_genepop(["PRI"], [4], fname) - f = open(fname + ".PRI") - lines = f.readlines() # Small file, it is ok - f.close() + with open(fname + ".PRI") as f: + lines = f.readlines() # Small file, it is ok for line in lines: m = re.search("Mean sample size: ([.0-9]+)", line) if m is not None: @@ -568,21 +579,20 @@ Will create a file called fname.INF """ - self._run_genepop(["INF"], [5,1], fname) + self._run_genepop(["INF"], [5, 1], fname) #First pass, general information #num_loci = None #num_pops = None - #f = open(fname + ".INF") - #l = f.readline() - #while (num_loci is None or num_pops is None) and l != '': - # m = re.search("Number of populations detected : ([0-9+])", l) - # if m is not None: - # num_pops = _gp_int(m.group(1)) - # m = re.search("Number of loci detected : ([0-9+])", l) - # if m is not None: - # num_loci = _gp_int(m.group(1)) - # l = f.readline() - #f.close() + #with open(fname + ".INF") as f: + #l = f.readline() + #while (num_loci is None or num_pops is None) and l != '': + #m = re.search("Number of populations detected : ([0-9+])", l) + #if m is not None: + #num_pops = _gp_int(m.group(1)) + #m = re.search("Number of loci detected : ([0-9+])", l) + #if m is not None: + #num_loci = _gp_int(m.group(1)) + #l = f.readline() def pop_parser(self): if hasattr(self, "old_line"): @@ -622,7 +632,7 @@ l = self.stream.readline() while l != "\n": - m2 = re.match(" +([0-9]+) , ([0-9]+) *([0-9]+) *(.+)",l) + m2 = re.match(" +([0-9]+) , ([0-9]+) *([0-9]+) *(.+)", l) if m2 is not None: geno_list.append((_gp_int(m2.group(1)), _gp_int(m2.group(2)), _gp_int(m2.group(3)), _gp_float(m2.group(4)))) @@ -648,8 +658,7 @@ freq_fis={} overall_fis = None while "----" not in l: - vals = filter(lambda x: x!='', - l.rstrip().split(' ')) + vals = [x for x in l.rstrip().split(' ') if x!=''] if vals[0]=="Tot": overall_fis = _gp_int(vals[1]), \ _gp_float(vals[2]), _gp_float(vals[3]) @@ -676,24 +685,21 @@ self.done = True raise StopIteration - popf = open(fname + ".INF") shutil.copyfile(fname + ".INF", fname + ".IN2") - locf = open(fname + ".IN2") - pop_iter = _FileIterator(pop_parser, popf, fname + ".INF") - locus_iter = _FileIterator(locus_parser, locf, fname + ".IN2") + pop_iter = _FileIterator(pop_parser, fname + ".INF") + locus_iter = _FileIterator(locus_parser, fname + ".IN2") return (pop_iter, locus_iter) def _calc_diversities_fis(self, fname, ext): - self._run_genepop([ext], [5,2], fname) - f = open(fname + ext) - l = f.readline() - while l != "": - l = l.rstrip() - if l.startswith("Statistics per sample over all loci with at least two individuals typed"): - avg_fis = _read_table(f, [str, _gp_float, _gp_float, _gp_float]) - avg_Qintra = _read_table(f, [str, _gp_float]) + self._run_genepop([ext], [5, 2], fname) + with open(fname + ext) as f: l = f.readline() - f.close() + while l != "": + l = l.rstrip() + if l.startswith("Statistics per sample over all loci with at least two individuals typed"): + avg_fis = _read_table(f, [str, _gp_float, _gp_float, _gp_float]) + avg_Qintra = _read_table(f, [str, _gp_float]) + l = f.readline() def fis_func(self): l = self.stream.readline() @@ -708,15 +714,14 @@ self.stream.readline() fis_table = _read_table(self.stream, [str, _gp_float, _gp_float, _gp_float]) self.stream.readline() - avg_qinter, avg_fis = tuple(map(lambda x: _gp_float(x), - filter(lambda y:y != "", self.stream.readline().split(" ")))) + avg_qinter, avg_fis = tuple(_gp_float(x) for x in + [y for y in self.stream.readline().split(" ") if y != ""]) return locus, fis_table, avg_qinter, avg_fis l = self.stream.readline() self.done = True raise StopIteration - dvf = open(fname + ext) - return _FileIterator(fis_func, dvf, fname + ext), avg_fis, avg_Qintra + return _FileIterator(fis_func, fname + ext), avg_fis, avg_Qintra #5.2 def calc_diversities_fis_with_identity(self, fname): @@ -742,27 +747,25 @@ This does not return the genotype frequencies. """ - self._run_genepop([".FST"], [6,1], fname) - f = open(fname + ".FST") - l = f.readline() - while l != '': - if l.startswith(' All:'): - toks=filter(lambda x:x!="", l.rstrip().split(' ')) - try: - allFis = _gp_float(toks[1]) - except ValueError: - allFis = None - try: - allFst = _gp_float(toks[2]) - except ValueError: - allFst = None - try: - allFit = _gp_float(toks[3]) - except ValueError: - allFit = None + self._run_genepop([".FST"], [6, 1], fname) + with open(fname + ".FST") as f: l = f.readline() - f.close() - f = open(fname + ".FST") + while l != '': + if l.startswith(' All:'): + toks = [x for x in l.rstrip().split(' ') if x != ""] + try: + allFis = _gp_float(toks[1]) + except ValueError: + allFis = None + try: + allFst = _gp_float(toks[2]) + except ValueError: + allFst = None + try: + allFit = _gp_float(toks[3]) + except ValueError: + allFit = None + l = f.readline() def proc(self): if hasattr(self, "last_line"): @@ -801,19 +804,18 @@ self.stream.close() self.done = True raise StopIteration - return (allFis, allFst, allFit), _FileIterator(proc , f, fname + ".FST") + return (allFis, allFst, allFit), _FileIterator(proc, fname + ".FST") #6.2 def calc_fst_pair(self, fname): - self._run_genepop([".ST2", ".MIG"], [6,2], fname) - f = open(fname + ".ST2") - l = f.readline() - while l != "": - l = l.rstrip() - if l.startswith("Estimates for all loci"): - avg_fst = _read_headed_triangle_matrix(f) + self._run_genepop([".ST2", ".MIG"], [6, 2], fname) + with open(fname + ".ST2") as f: l = f.readline() - f.close() + while l != "": + l = l.rstrip() + if l.startswith("Estimates for all loci"): + avg_fst = _read_headed_triangle_matrix(f) + l = f.readline() def loci_func(self): l = self.stream.readline() @@ -828,9 +830,8 @@ self.done = True raise StopIteration - stf = open(fname + ".ST2") os.remove(fname + ".MIG") - return _FileIterator(loci_func, stf, fname + ".ST2"), avg_fst + return _FileIterator(loci_func, fname + ".ST2"), avg_fst #6.3 def calc_rho_all(self, fname): @@ -843,33 +844,32 @@ def _calc_ibd(self, fname, sub, stat="a", scale="Log", min_dist=0.00001): """Calculates isolation by distance statistics """ - self._run_genepop([".GRA", ".MIG", ".ISO"], [6,sub], + self._run_genepop([".GRA", ".MIG", ".ISO"], [6, sub], fname, opts = { - "MinimalDistance" : min_dist, - "GeographicScale" : scale, - "IsolBDstatistic" : stat, + "MinimalDistance": min_dist, + "GeographicScale": scale, + "IsolBDstatistic": stat, }) - f = open(fname + ".ISO") - f.readline() - f.readline() - f.readline() - f.readline() - estimate = _read_triangle_matrix(f) - f.readline() - f.readline() - distance = _read_triangle_matrix(f) - f.readline() - match = re.match("a = (.+), b = (.+)", f.readline().rstrip()) - a = _gp_float(match.group(1)) - b = _gp_float(match.group(2)) - f.readline() - f.readline() - match = re.match(" b=(.+)", f.readline().rstrip()) - bb = _gp_float(match.group(1)) - match = re.match(".*\[(.+) ; (.+)\]", f.readline().rstrip()) - bblow = _gp_float(match.group(1)) - bbhigh = _gp_float(match.group(2)) - f.close() + with open(fname + ".ISO") as f: + f.readline() + f.readline() + f.readline() + f.readline() + estimate = _read_triangle_matrix(f) + f.readline() + f.readline() + distance = _read_triangle_matrix(f) + f.readline() + match = re.match("a = (.+), b = (.+)", f.readline().rstrip()) + a = _gp_float(match.group(1)) + b = _gp_float(match.group(2)) + f.readline() + f.readline() + match = re.match(" b=(.+)", f.readline().rstrip()) + bb = _gp_float(match.group(1)) + match = re.match(".*\[(.+) ; (.+)\]", f.readline().rstrip()) + bblow = _gp_float(match.group(1)) + bbhigh = _gp_float(match.group(2)) os.remove(fname + ".MIG") os.remove(fname + ".GRA") os.remove(fname + ".ISO") diff -Nru python-biopython-1.62/Bio/PopGen/GenePop/EasyController.py python-biopython-1.63/Bio/PopGen/GenePop/EasyController.py --- python-biopython-1.62/Bio/PopGen/GenePop/EasyController.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PopGen/GenePop/EasyController.py 2013-12-05 14:10:43.000000000 +0000 @@ -10,7 +10,7 @@ """ -from Controller import GenePopController +from .Controller import GenePopController from Bio.PopGen import GenePop @@ -28,9 +28,8 @@ self.__allele_frequency = {} # More caches like this needed! def get_basic_info(self): - f=open(self._fname) - rec = GenePop.read(f) - f.close() + with open(self._fname) as f: + rec = GenePop.read(f) return rec.pop_list, rec.loci_list def test_hw_pop(self, pop_pos, test_type = "probability"): @@ -41,8 +40,8 @@ else: loci_res, hw_res, fisher_full = self._controller.test_pop_hz_prob(self._fname, ".P") for i in range(pop_pos-1): - hw_res.next() - return hw_res.next() + next(hw_res) + return next(hw_res) def test_hw_global(self, test_type = "deficiency", enum_test = True, dememorization = 10000, batches = 20, iterations = 5000): @@ -111,7 +110,7 @@ geno_freqs = self._controller.calc_allele_genotype_freqs(self._fname) pop_iter, loc_iter = geno_freqs pop_iter = list(pop_iter) - return pop_iter[pop_pos][1][locus_name][2].keys() + return list(pop_iter[pop_pos][1][locus_name][2].keys()) def get_alleles_all_pops(self, locus_name): """Returns the alleles for a certain population and locus. diff -Nru python-biopython-1.62/Bio/PopGen/GenePop/FileParser.py python-biopython-1.63/Bio/PopGen/GenePop/FileParser.py --- python-biopython-1.62/Bio/PopGen/GenePop/FileParser.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PopGen/GenePop/FileParser.py 2013-12-05 14:10:43.000000000 +0000 @@ -68,6 +68,12 @@ self.fname = fname self.start_read() + def __del__(self): + try: + self._handle.close() + except AttributeError: + pass + def __str__(self): """Returns (reconstructs) a GenePop textual representation. @@ -191,28 +197,67 @@ fname - file to be created with population removed """ old_rec = read(self.fname) - f = open(fname, "w") - f.write(self.comment_line + "\n") - for locus in old_rec.loci_list: - f.write(locus + "\n") - curr_pop = 0 - l_parser = old_rec.get_individual() - start_pop = True - while l_parser: - if curr_pop == pos: - old_rec.skip_population() - curr_pop += 1 - else: - if l_parser is True: + with open(fname, "w") as f: + f.write(self.comment_line + "\n") + for locus in old_rec.loci_list: + f.write(locus + "\n") + curr_pop = 0 + l_parser = old_rec.get_individual() + start_pop = True + while l_parser: + if curr_pop == pos: + old_rec.skip_population() curr_pop += 1 - start_pop = True else: - if start_pop: - f.write("POP\n") - start_pop = False + if l_parser is True: + curr_pop += 1 + start_pop = True + else: + if start_pop: + f.write("POP\n") + start_pop = False + name, markers = l_parser + f.write(name + ",") + for marker in markers: + f.write(' ') + for al in marker: + if al is None: + al = '0' + aStr = str(al) + while len(aStr)<3: + aStr = "".join(['0', aStr]) + f.write(aStr) + f.write('\n') + + l_parser = old_rec.get_individual() + + def remove_locus_by_position(self, pos, fname): + """Removes a locus by position. + + pos - position + fname - file to be created with locus removed + """ + old_rec = read(self.fname) + with open(fname, "w") as f: + f.write(self.comment_line + "\n") + loci_list = old_rec.loci_list + del loci_list[pos] + for locus in loci_list: + f.write(locus + "\n") + l_parser = old_rec.get_individual() + f.write("POP\n") + while l_parser: + if l_parser is True: + f.write("POP\n") + else: name, markers = l_parser f.write(name + ",") + marker_pos = 0 for marker in markers: + if marker_pos == pos: + marker_pos += 1 + continue + marker_pos += 1 f.write(' ') for al in marker: if al is None: @@ -223,48 +268,7 @@ f.write(aStr) f.write('\n') - l_parser = old_rec.get_individual() - f.close() - - def remove_locus_by_position(self, pos, fname): - """Removes a locus by position. - - pos - position - fname - file to be created with locus removed - """ - old_rec = read(self.fname) - f = open(fname, "w") - f.write(self.comment_line + "\n") - loci_list = old_rec.loci_list - del loci_list[pos] - for locus in loci_list: - f.write(locus + "\n") - l_parser = old_rec.get_individual() - f.write("POP\n") - while l_parser: - if l_parser is True: - f.write("POP\n") - else: - name, markers = l_parser - f.write(name + ",") - marker_pos = 0 - for marker in markers: - if marker_pos == pos: - marker_pos += 1 - continue - marker_pos += 1 - f.write(' ') - for al in marker: - if al is None: - al = '0' - aStr = str(al) - while len(aStr)<3: - aStr = "".join(['0', aStr]) - f.write(aStr) - f.write('\n') - - l_parser = old_rec.get_individual() - f.close() + l_parser = old_rec.get_individual() def remove_loci_by_position(self, positions, fname): """Removes a set of loci by position. @@ -273,43 +277,42 @@ fname - file to be created with locus removed """ old_rec = read(self.fname) - f = open(fname, "w") - f.write(self.comment_line + "\n") - loci_list = old_rec.loci_list - positions.sort() - positions.reverse() - posSet = set() - for pos in positions: - del loci_list[pos] - posSet.add(pos) - for locus in loci_list: - f.write(locus + "\n") - l_parser = old_rec.get_individual() - f.write("POP\n") - while l_parser: - if l_parser is True: - f.write("POP\n") - else: - name, markers = l_parser - f.write(name + ",") - marker_pos = 0 - for marker in markers: - if marker_pos in posSet: + with open(fname, "w") as f: + f.write(self.comment_line + "\n") + loci_list = old_rec.loci_list + positions.sort() + positions.reverse() + posSet = set() + for pos in positions: + del loci_list[pos] + posSet.add(pos) + for locus in loci_list: + f.write(locus + "\n") + l_parser = old_rec.get_individual() + f.write("POP\n") + while l_parser: + if l_parser is True: + f.write("POP\n") + else: + name, markers = l_parser + f.write(name + ",") + marker_pos = 0 + for marker in markers: + if marker_pos in posSet: + marker_pos += 1 + continue marker_pos += 1 - continue - marker_pos += 1 - f.write(' ') - for al in marker: - if al is None: - al = '0' - aStr = str(al) - while len(aStr)<3: - aStr = "".join(['0', aStr]) - f.write(aStr) - f.write('\n') + f.write(' ') + for al in marker: + if al is None: + al = '0' + aStr = str(al) + while len(aStr)<3: + aStr = "".join(['0', aStr]) + f.write(aStr) + f.write('\n') - l_parser = old_rec.get_individual() - f.close() + l_parser = old_rec.get_individual() def remove_locus_by_name(self, name, fname): """Removes a locus by name. diff -Nru python-biopython-1.62/Bio/PopGen/GenePop/__init__.py python-biopython-1.63/Bio/PopGen/GenePop/__init__.py --- python-biopython-1.62/Bio/PopGen/GenePop/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PopGen/GenePop/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -51,11 +51,11 @@ handle is a file-like object that contains a GenePop record. """ record = Record() - record.comment_line = str(handle.next()).rstrip() + record.comment_line = str(next(handle)).rstrip() #We can now have one loci per line or all loci in a single line #separated by either space or comma+space... #We will remove all commas on loci... that should not be a problem - sample_loci_line = str(handle.next()).rstrip().replace(',', '') + sample_loci_line = str(next(handle)).rstrip().replace(',', '') all_loci = sample_loci_line.split(' ') record.loci_list.extend(all_loci) for line in handle: diff -Nru python-biopython-1.62/Bio/PopGen/SimCoal/Async.py python-biopython-1.63/Bio/PopGen/SimCoal/Async.py --- python-biopython-1.62/Bio/PopGen/SimCoal/Async.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PopGen/SimCoal/Async.py 2013-12-05 14:10:43.000000000 +0000 @@ -10,7 +10,7 @@ import os -import Cache +from . import Cache class SimCoalCache(Cache.SimCoalCache): @@ -25,8 +25,7 @@ f = inputFiles[parFile] text = f.read() f.close() - w = open(os.sep.join([self.data_dir, 'SimCoal', 'runs', parFile]), 'w') - w.write(text) - w.close() + with open(os.sep.join([self.data_dir, 'SimCoal', 'runs', parFile]), 'w') as w: + w.write(text) self.run_simcoal(parFile, numSims, ploydi) return 0, None diff -Nru python-biopython-1.62/Bio/PopGen/SimCoal/Cache.py python-biopython-1.63/Bio/PopGen/SimCoal/Cache.py --- python-biopython-1.62/Bio/PopGen/SimCoal/Cache.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PopGen/SimCoal/Cache.py 2013-12-05 14:10:43.000000000 +0000 @@ -8,7 +8,7 @@ import os import tarfile -from Controller import SimCoalController +from .Controller import SimCoalController class SimCoalCache(object): diff -Nru python-biopython-1.62/Bio/PopGen/SimCoal/Template.py python-biopython-1.63/Bio/PopGen/SimCoal/Template.py --- python-biopython-1.62/Bio/PopGen/SimCoal/Template.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/PopGen/SimCoal/Template.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,8 +3,11 @@ # license. Please see the LICENSE file that should have been included # as part of this package. +from __future__ import print_function + from os import sep import re +from functools import reduce from Bio.PopGen.SimCoal import builtin_tpl_dir @@ -34,12 +37,11 @@ #reg = re.compile('\?' + name, re.MULTILINE) #template = re.sub(reg, str(val), template) template = template.replace('?'+name, str(val)) - f = open(f_name + '.par', 'w') - #executed_template = template - executed_template = exec_template(template) - clean_template = executed_template.replace('\r\n','\n').replace('\n\n','\n') - f.write(clean_template) - f.close() + with open(f_name + '.par', 'w') as f: + #executed_template = template + executed_template = exec_template(template) + clean_template = executed_template.replace('\r\n', '\n').replace('\n\n', '\n') + f.write(clean_template) return [f_name] else: name, rng = para_list[0] @@ -156,15 +158,15 @@ ''' if tp_dir is None: #Internal Template - f = open(sep.join([builtin_tpl_dir, model + '.par']), 'r') + filename = sep.join([builtin_tpl_dir, model + '.par']) else: #External template - f = open(sep.join([tp_dir, model + '.par']), 'r') - l = f.readline() - while l!='': - stream.write(l) + filename = sep.join([tp_dir, model + '.par']) + with open(filename, 'r') as f: l = f.readline() - f.close() + while l!='': + stream.write(l) + l = f.readline() def _gen_loci(stream, loci): @@ -173,8 +175,7 @@ stream.write('//Per Block: Data type, No. of loci, Recombination rate to the right-side locus, plus optional parameters\n') for locus in loci: stream.write(' '.join([locus[0]] + - map(lambda x: str(x), list(locus[1]) - )) + '\n') + [str(x) for x in list(locus[1])]) + '\n') def get_chr_template(stream, chrs): @@ -217,13 +218,10 @@ get_demography_template, chrs from get_chr_template and params from generate_model). ''' - stream = open(out_dir + sep + 'tmp.par', 'w') - get_demography_template(stream, model, tp_dir) - get_chr_template(stream, chrs) - stream.close() - #par_stream = open(out_dir + sep + 'tmp.par', 'r') - #print par_stream.read() - #par_stream.close() - par_stream = open(out_dir + sep + 'tmp.par', 'r') - generate_model(par_stream, model, params, out_dir = out_dir) - par_stream.close() + with open(out_dir + sep + 'tmp.par', 'w') as stream: + get_demography_template(stream, model, tp_dir) + get_chr_template(stream, chrs) + #with open(out_dir + sep + 'tmp.par', 'r') as par_stream: + #print par_stream.read() + with open(out_dir + sep + 'tmp.par', 'r') as par_stream: + generate_model(par_stream, model, params, out_dir = out_dir) diff -Nru python-biopython-1.62/Bio/Restriction/PrintFormat.py python-biopython-1.63/Bio/Restriction/PrintFormat.py --- python-biopython-1.62/Bio/Restriction/PrintFormat.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Restriction/PrintFormat.py 2013-12-05 14:10:43.000000000 +0000 @@ -8,7 +8,12 @@ # as part of this package. # +from __future__ import print_function + import re + +from Bio._py3k import range + from Bio.Restriction import RanaConfig as RanaConf """ @@ -29,7 +34,7 @@ >>> handle.close() >>> dct = AllEnzymes.search(pBR322.seq) >>> new = PrintFormat() - >>> new.print_that(dct, '\n my pBR322 analysis\n\n','\n no site :\n\n') + >>> new.print_that(dct, '\n my pBR322 analysis\n\n', '\n no site :\n\n') my pBR322 analysis @@ -110,12 +115,12 @@ if not dct: dct = self.results ls, nc = [], [] - for k, v in dct.iteritems(): + for k, v in dct.items(): if v: - ls.append((k,v)) + ls.append((k, v)) else: nc.append(k) - print self.make_format(ls, title, nc, s1) + print(self.make_format(ls, title, nc, s1)) return def make_format(self, cut=[], title='', nc=[], s1=''): @@ -124,11 +129,11 @@ Virtual method. Here to be pointed to one of the _make_* methods. You can as well create a new method and point make_format to it.""" - return self._make_list(cut,title, nc,s1) + return self._make_list(cut, title, nc, s1) ###### _make_* methods to be used with the virtual method make_format - def _make_list(self, ls,title, nc,s1): + def _make_list(self, ls, title, nc, s1): """PF._make_number(ls,title, nc,s1) -> string. return a string of form: @@ -144,7 +149,7 @@ s1 is the sentence before the non cutting enzymes.""" return self._make_list_only(ls, title) + self._make_nocut_only(nc, s1) - def _make_map(self, ls,title, nc,s1): + def _make_map(self, ls, title, nc, s1): """PF._make_number(ls,title, nc,s1) -> string. return a string of form: @@ -163,7 +168,7 @@ s1 is the sentence before the non cutting enzymes.""" return self._make_map_only(ls, title) + self._make_nocut_only(nc, s1) - def _make_number(self, ls,title, nc,s1): + def _make_number(self, ls, title, nc, s1): """PF._make_number(ls,title, nc,s1) -> string. title. @@ -181,9 +186,9 @@ title is the title. nc is a list of non cutting enzymes. s1 is the sentence before the non cutting enzymes.""" - return self._make_number_only(ls, title)+self._make_nocut_only(nc,s1) + return self._make_number_only(ls, title)+self._make_nocut_only(nc, s1) - def _make_nocut(self, ls,title, nc,s1): + def _make_nocut(self, ls, title, nc, s1): """PF._make_nocut(ls,title, nc,s1) -> string. return a formatted string of the non cutting enzymes. @@ -257,7 +262,7 @@ Non cutting enzymes are not included.""" if not ls: return title - ls.sort(lambda x,y : cmp(len(x[1]), len(y[1]))) + ls.sort(lambda x, y : cmp(len(x[1]), len(y[1]))) iterator = iter(ls) cur_len = 1 new_sect = [] @@ -268,7 +273,7 @@ title = self.__next_section(new_sect, title) new_sect, cur_len = [(name, sites)], l continue - new_sect.append((name,sites)) + new_sect.append((name, sites)) title += "\n\nenzymes which cut %i times :\n\n"%cur_len return self.__next_section(new_sect, title) @@ -291,8 +296,7 @@ """ if not ls: return title - resultKeys = [str(x) for x,y in ls] - resultKeys.sort() + resultKeys = sorted(str(x) for x, y in ls) map = title or '' enzymemap = {} for (enzyme, cut) in ls: @@ -301,11 +305,10 @@ enzymemap[c].append(str(enzyme)) else: enzymemap[c] = [str(enzyme)] - mapping = enzymemap.keys() - mapping.sort() + mapping = sorted(enzymemap.keys()) cutloc = {} x, counter, length = 0, 0, len(self.sequence) - for x in xrange(60, length, 60): + for x in range(60, length, 60): counter = x - 60 l=[] for key in mapping: @@ -323,14 +326,14 @@ base, counter = 0, 0 emptyline = ' ' * 60 Join = ''.join - for base in xrange(60, length, 60): + for base in range(60, length, 60): counter = base - 60 line = emptyline for key in cutloc[counter]: s = '' if key == base: for n in enzymemap[key]: - s = ' '.join((s,n)) + s = ' '.join((s, n)) l = line[0:59] lineo = Join((l, str(key), s, '\n')) line2 = Join((l, a, '\n')) @@ -338,17 +341,17 @@ map = Join((map, linetot)) break for n in enzymemap[key]: - s = ' '.join((s,n)) + s = ' '.join((s, n)) k = key%60 lineo = Join((line[0:(k-1)], str(key), s, '\n')) line = Join((line[0:(k-1)], a, line[k:])) line2 = Join((line[0:(k-1)], a, line[k:], '\n')) - linetot = Join((lineo,line2)) - map = Join((map,linetot)) - mapunit = '\n'.join((sequence[counter : base],a * 60, + linetot = Join((lineo, line2)) + map = Join((map, linetot)) + mapunit = '\n'.join((sequence[counter : base], a * 60, revsequence[counter : base], Join((str.ljust(str(counter+1), 15), ' '* 30, - str.rjust(str(base), 15),'\n\n')) + str.rjust(str(base), 15), '\n\n')) )) map = Join((map, mapunit)) line = ' '* 60 @@ -356,29 +359,29 @@ s = '' if key == length: for n in enzymemap[key]: - s = Join((s,' ',n)) + s = Join((s, ' ', n)) l = line[0:(length-1)] - lineo = Join((l,str(key),s,'\n')) - line2 = Join((l,a,'\n')) + lineo = Join((l, str(key), s, '\n')) + line2 = Join((l, a, '\n')) linetot = Join((lineo, line2)) map = Join((map, linetot)) break for n in enzymemap[key]: - s = Join((s,' ',n)) + s = Join((s, ' ', n)) k = key%60 - lineo = Join((line[0:(k-1)],str(key),s,'\n')) - line = Join((line[0:(k-1)],a,line[k:])) - line2 = Join((line[0:(k-1)],a,line[k:],'\n')) - linetot = Join((lineo,line2)) - map = Join((map,linetot)) + lineo = Join((line[0:(k-1)], str(key), s, '\n')) + line = Join((line[0:(k-1)], a, line[k:])) + line2 = Join((line[0:(k-1)], a, line[k:], '\n')) + linetot = Join((lineo, line2)) + map = Join((map, linetot)) mapunit = '' mapunit = Join((sequence[base : length], '\n')) mapunit = Join((mapunit, a * (length-base), '\n')) - mapunit = Join((mapunit,revsequence[base:length], '\n')) + mapunit = Join((mapunit, revsequence[base:length], '\n')) mapunit = Join((mapunit, Join((str.ljust(str(base+1), 15), ' '*( - length-base-30),str.rjust(str(length), 15), + length-base-30), str.rjust(str(length), 15), '\n\n')))) - map = Join((map,mapunit)) + map = Join((map, mapunit)) return map ###### private method to do lists: @@ -404,7 +407,7 @@ several, Join = '', ''.join for name, sites in ls: stringsite = '' - l = Join((', '.join([str(site) for site in sites]), '.')) + l = Join((', '.join(str(site) for site in sites), '.')) if len(l) > linesize: # # cut where appropriate and add the indentation @@ -414,5 +417,6 @@ else: stringsite = l into = Join((into, - str(name).ljust(self.NameWidth),' : ',stringsite,'\n')) + str(name).ljust(self.NameWidth), ' : ', stringsite, '\n')) return into + diff -Nru python-biopython-1.62/Bio/Restriction/Restriction.py python-biopython-1.63/Bio/Restriction/Restriction.py --- python-biopython-1.62/Bio/Restriction/Restriction.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Restriction/Restriction.py 2013-12-05 14:10:43.000000000 +0000 @@ -78,6 +78,11 @@ ---------------------------------------------------------------------------- """ +from __future__ import print_function +from Bio._py3k import zip +from Bio._py3k import filter +from Bio._py3k import range + import re import itertools @@ -247,7 +252,7 @@ # super(RestrictionType, cls).__init__(cls, name, bases, dct) try : cls.compsite = re.compile(cls.compsite) - except Exception, err : + except Exception as err : raise ValueError("Problem with regular expression, re.compiled(%s)" % repr(cls.compsite)) @@ -473,9 +478,8 @@ @classmethod def all_suppliers(self): """RE.all_suppliers -> print all the suppliers of R""" - supply = [x[0] for x in suppliers_dict.itervalues()] - supply.sort() - print ",\n".join(supply) + supply = sorted(x[0] for x in suppliers_dict.values()) + print(",\n".join(supply)) return @classmethod @@ -534,8 +538,7 @@ neoschizomer <=> same site, different position of restriction.""" if not batch: batch = AllEnzymes - r = [x for x in batch if self >> x] - r.sort() + r = sorted(x for x in batch if self >> x) return r @classmethod @@ -833,8 +836,8 @@ implement the search method for palindromic and non palindromic enzyme. """ - siteloc = self.dna.finditer(self.compsite,self.size) - self.results = [r for s,g in siteloc for r in self._modify(s)] + siteloc = self.dna.finditer(self.compsite, self.size) + self.results = [r for s, g in siteloc for r in self._modify(s)] if self.results: self._drop() return self.results @@ -1008,7 +1011,7 @@ # # if more than one site add them. # - fragments += [d[r[x]:r[x+1]] for x in xrange(length)] + fragments += [d[r[x]:r[x+1]] for x in range(length)] # # LAST site to END of the sequence. # @@ -1026,7 +1029,7 @@ # # add the others. # - fragments += [d[r[x]:r[x+1]] for x in xrange(length)] + fragments += [d[r[x]:r[x+1]] for x in range(length)] return tuple(fragments) catalyze = catalyse @@ -1080,8 +1083,7 @@ list of all the enzymes that share compatible end with RE.""" if not batch: batch = AllEnzymes - r = [x for x in iter(AllEnzymes) if x.is_blunt()] - r.sort() + r = sorted(x for x in iter(AllEnzymes) if x.is_blunt()) return r @staticmethod @@ -1129,7 +1131,7 @@ # # if more than one site add them. # - fragments += [d[r[x]:r[x+1]] for x in xrange(length)] + fragments += [d[r[x]:r[x+1]] for x in range(length)] # # LAST site to END of the sequence. # @@ -1147,7 +1149,7 @@ # # add the others. # - fragments += [d[r[x]:r[x+1]] for x in xrange(length)] + fragments += [d[r[x]:r[x+1]] for x in range(length)] return tuple(fragments) catalyze = catalyse @@ -1201,8 +1203,7 @@ list of all the enzymes that share compatible end with RE.""" if not batch: batch = AllEnzymes - r = [x for x in iter(AllEnzymes) if x.is_5overhang() and x % self] - r.sort() + r = sorted(x for x in iter(AllEnzymes) if x.is_5overhang() and x % self) return r @classmethod @@ -1253,7 +1254,7 @@ # # if more than one site add them. # - fragments += [d[r[x]:r[x+1]] for x in xrange(length)] + fragments += [d[r[x]:r[x+1]] for x in range(length)] # # LAST site to END of the sequence. # @@ -1271,7 +1272,7 @@ # # add the others. # - fragments += [d[r[x]:r[x+1]] for x in xrange(length)] + fragments += [d[r[x]:r[x+1]] for x in range(length)] return tuple(fragments) catalyze = catalyse @@ -1325,8 +1326,7 @@ list of all the enzymes that share compatible end with RE.""" if not batch: batch = AllEnzymes - r = [x for x in iter(AllEnzymes) if x.is_3overhang() and x % self] - r.sort() + r = sorted(x for x in iter(AllEnzymes) if x.is_3overhang() and x % self) return r @classmethod @@ -1635,7 +1635,7 @@ re = site + (f5-length)*'N' + '^_N' else: raise ValueError('%s.easyrepr() : error f5=%i' - % (self.name,f5)) + % (self.name, f5)) else: if f3 == 0: if f5 == 0: @@ -1776,10 +1776,8 @@ @classmethod def suppliers(self): """RE.suppliers() -> print the suppliers of RE.""" - supply = suppliers_dict.items() - for k,v in supply: - if k in self.suppl: - print v[0]+',' + for s in self.suppliers_dict(): + print(s + ',') return @classmethod @@ -1787,7 +1785,7 @@ """RE.supplier_list() -> list. list of the supplier names for RE.""" - return [v[0] for k,v in suppliers_dict.items() if k in self.suppl] + return [v[0] for k, v in suppliers_dict.items() if k in self.suppl] @classmethod def buffers(self, supplier): @@ -1899,7 +1897,7 @@ the new batch will contains only the enzymes for which func return True.""" - d = [x for x in itertools.ifilter(func, self)] + d = [x for x in filter(func, self)] new = RestrictionBatch() new._data = dict(zip(d, [True]*len(d))) return new @@ -1922,8 +1920,7 @@ return a sorted list of the suppliers which have been used to create the batch.""" - suppl_list = [suppliers_dict[x][0] for x in self.suppliers] - suppl_list.sort() + suppl_list = sorted(suppliers_dict[x][0] for x in self.suppliers) return suppl_list def __iadd__(self, other): @@ -2002,7 +1999,7 @@ else: continue return True - d = [k for k in itertools.ifilter(splittest, self)] + d = [k for k in filter(splittest, self)] new = RestrictionBatch() new._data = dict(zip(d, [True]*len(d))) return new @@ -2011,8 +2008,7 @@ """B.elements() -> tuple. give all the names of the enzymes in B sorted alphabetically.""" - l = [str(e) for e in self] - l.sort() + l = sorted(str(e) for e in self) return l def as_string(self): @@ -2026,14 +2022,14 @@ """B.suppl_codes() -> dict letter code for the suppliers""" - supply = dict([(k,v[0]) for k,v in suppliers_dict.iteritems()]) + supply = dict((k, v[0]) for k, v in suppliers_dict.items()) return supply @classmethod def show_codes(self): """B.show_codes() -> letter codes for the suppliers""" - supply = [' = '.join(i) for i in self.suppl_codes().iteritems()] - print '\n'.join(supply) + supply = [' = '.join(i) for i in self.suppl_codes().items()] + print('\n'.join(supply)) return def search(self, dna, linear=True): @@ -2056,14 +2052,14 @@ else: self.already_mapped = str(dna), linear fseq = FormattedSeq(dna, linear) - self.mapping = dict([(x, x.search(fseq)) for x in self]) + self.mapping = dict((x, x.search(fseq)) for x in self) return self.mapping elif isinstance(dna, FormattedSeq): if (str(dna), dna.linear) == self.already_mapped: return self.mapping else: self.already_mapped = str(dna), dna.linear - self.mapping = dict([(x, x.search(dna)) for x in self]) + self.mapping = dict((x, x.search(dna)) for x in self) return self.mapping raise TypeError("Expected Seq or MutableSeq instance, got %s instead" %type(dna)) @@ -2094,7 +2090,7 @@ def __repr__(self): return 'Analysis(%s,%s,%s)'%\ - (repr(self.rb),repr(self.sequence),self.linear) + (repr(self.rb), repr(self.sequence), self.linear) def _sub_set(self, wanted): """A._sub_set(other_set) -> dict. @@ -2104,7 +2100,7 @@ screen the results through wanted set. Keep only the results for which the enzymes is in wanted set. """ - return dict([(k,v) for k,v in self.mapping.iteritems() if k in wanted]) + return dict((k, v) for k, v in self.mapping.items() if k in wanted) def _boundaries(self, start, end): """A._boundaries(start, end) -> tuple. @@ -2154,7 +2150,7 @@ """ if not dct: dct = self.mapping - print + print("") return PrintFormat.print_that(self, dct, title, s1) def change(self, **what): @@ -2168,7 +2164,7 @@ you expect. In which case, you can settle back to a 80 columns shell or try to change self.Cmodulo and self.PrefWidth in PrintFormat until you get it right.""" - for k,v in what.iteritems(): + for k, v in what.items(): if k in ('NameWidth', 'ConsoleWidth'): setattr(self, k, v) self.Cmodulo = self.ConsoleWidth % self.NameWidth @@ -2204,7 +2200,7 @@ Only the enzymes which have a 3'overhang restriction site.""" if not dct: dct = self.mapping - return dict([(k,v) for k,v in dct.iteritems() if k.is_blunt()]) + return dict((k, v) for k, v in dct.items() if k.is_blunt()) def overhang5(self, dct=None): """A.overhang5([dct]) -> dict. @@ -2212,7 +2208,7 @@ Only the enzymes which have a 5' overhang restriction site.""" if not dct: dct = self.mapping - return dict([(k,v) for k,v in dct.iteritems() if k.is_5overhang()]) + return dict((k, v) for k, v in dct.items() if k.is_5overhang()) def overhang3(self, dct=None): """A.Overhang3([dct]) -> dict. @@ -2220,7 +2216,7 @@ Only the enzymes which have a 3'overhang restriction site.""" if not dct: dct = self.mapping - return dict([(k,v) for k,v in dct.iteritems() if k.is_3overhang()]) + return dict((k, v) for k, v in dct.items() if k.is_3overhang()) def defined(self, dct=None): """A.defined([dct]) -> dict. @@ -2228,7 +2224,7 @@ Only the enzymes that have a defined restriction site in Rebase.""" if not dct: dct = self.mapping - return dict([(k,v) for k,v in dct.iteritems() if k.is_defined()]) + return dict((k, v) for k, v in dct.items() if k.is_defined()) def with_sites(self, dct=None): """A.with_sites([dct]) -> dict. @@ -2236,7 +2232,7 @@ Enzymes which have at least one site in the sequence.""" if not dct: dct = self.mapping - return dict([(k,v) for k,v in dct.iteritems() if v]) + return dict((k, v) for k, v in dct.items() if v) def without_site(self, dct=None): """A.without_site([dct]) -> dict. @@ -2244,7 +2240,7 @@ Enzymes which have no site in the sequence.""" if not dct: dct = self.mapping - return dict([(k,v) for k,v in dct.iteritems() if not v]) + return dict((k, v) for k, v in dct.items() if not v) def with_N_sites(self, N, dct=None): """A.With_N_Sites(N [, dct]) -> dict. @@ -2252,12 +2248,12 @@ Enzymes which cut N times the sequence.""" if not dct: dct = self.mapping - return dict([(k,v) for k,v in dct.iteritems()if len(v) == N]) + return dict((k, v) for k, v in dct.items()if len(v) == N) def with_number_list(self, list, dct= None): if not dct: dct = self.mapping - return dict([(k,v) for k,v in dct.iteritems() if len(v) in list]) + return dict((k, v) for k, v in dct.items() if len(v) in list) def with_name(self, names, dct=None): """A.with_name(list_of_names [, dct]) -> @@ -2265,11 +2261,11 @@ Limit the search to the enzymes named in list_of_names.""" for i, enzyme in enumerate(names): if not enzyme in AllEnzymes: - print "no data for the enzyme:", str(name) + print("no data for the enzyme: %s" % name) del names[i] if not dct: return RestrictionBatch(names).search(self.sequence) - return dict([(n, dct[n]) for n in names if n in dct]) + return dict((n, dct[n]) for n in names if n in dct) def with_site_size(self, site_size, dct=None): """A.with_site_size(site_size [, dct]) -> @@ -2278,7 +2274,7 @@ sites = [name for name in self if name.size == site_size] if not dct: return RestrictionBatch(sites).search(self.sequence) - return dict([(k,v) for k,v in dct.iteritems() if k in site_size]) + return dict((k, v) for k, v in dct.items() if k in site_size) def only_between(self, start, end, dct=None): """A.only_between(start, end[, dct]) -> dict. @@ -2288,7 +2284,7 @@ if not dct: dct = self.mapping d = dict(dct) - for key, sites in dct.iteritems(): + for key, sites in dct.items(): if not sites: del d[key] continue @@ -2309,7 +2305,7 @@ d = {} if not dct: dct = self.mapping - for key, sites in dct.iteritems(): + for key, sites in dct.items(): for site in sites: if test(start, end, site): d[key] = sites @@ -2340,7 +2336,7 @@ if not dct: dct = self.mapping d = dict(dct) - for key, sites in dct.iteritems(): + for key, sites in dct.items(): if not sites: del d[key] continue @@ -2361,7 +2357,7 @@ if not dct: dct = self.mapping d = {} - for key, sites in dct.iteritems(): + for key, sites in dct.items(): for site in sites: if test(start, end, site): continue @@ -2404,7 +2400,7 @@ # CommOnly = RestrictionBatch() # commercial enzymes NonComm = RestrictionBatch() # not available commercially -for TYPE, (bases, enzymes) in typedict.iteritems(): +for TYPE, (bases, enzymes) in typedict.items(): # # The keys are the pseudo-types TYPE (stored as type1, type2...) # The names are not important and are only present to differentiate @@ -2422,7 +2418,7 @@ # # First eval the bases. # - bases = tuple([eval(x) for x in bases]) + bases = tuple(eval(x) for x in bases) # # now create the particular value of RestrictionType for the classes # in enzymes. @@ -2458,5 +2454,5 @@ #Scoping changed in Python 3, the variable isn't leaked pass locals().update(dict(zip(names, AllEnzymes))) -__all__=['FormattedSeq', 'Analysis', 'RestrictionBatch','AllEnzymes','CommOnly','NonComm']+names +__all__=['FormattedSeq', 'Analysis', 'RestrictionBatch', 'AllEnzymes', 'CommOnly', 'NonComm']+names del k, enzymes, TYPE, bases, names diff -Nru python-biopython-1.62/Bio/Restriction/Restriction_Dictionary.py python-biopython-1.63/Bio/Restriction/Restriction_Dictionary.py --- python-biopython-1.62/Bio/Restriction/Restriction_Dictionary.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Restriction/Restriction_Dictionary.py 2013-12-05 14:10:43.000000000 +0000 @@ -20,16610 +20,17153 @@ rest_dict = {} def _temp(): return { - 'compsite' : '(?PTTATAA)|(?PTTATAA)', - 'results' : None, - 'site' : 'TTATAA', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'TTATAA'), - 'ovhgseq' : '', + 'compsite': '(?PTTATAA)', + 'results': None, + 'site': 'TTATAA', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (3, -3, None, None, 'TTATAA'), + 'ovhgseq': '', } rest_dict['AanI'] = _temp() def _temp(): return { - 'compsite' : '(?PCACCTGC)|(?PGCAGGTG)', - 'results' : None, - 'site' : 'CACCTGC', - 'substrat' : 'DNA', - 'fst3' : 8, - 'fst5' : 11, - 'freq' : 16384, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (11, 8, None, None, 'CACCTGC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PCACCTGC)|(?PGCAGGTG)', + 'results': None, + 'site': 'CACCTGC', + 'substrat': 'DNA', + 'fst3': 8, + 'fst5': 11, + 'freq': 16384, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (11, 8, None, None, 'CACCTGC'), + 'ovhgseq': 'NNNN', } rest_dict['AarI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAC......GTC)|(?PGAC......GTC)', - 'results' : None, - 'site' : 'GACNNNNNNGTC', - 'substrat' : 'DNA', - 'fst3' : -7, - 'fst5' : 7, - 'freq' : 4096, - 'size' : 12, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (7, -7, None, None, 'GACNNNNNNGTC'), - 'ovhgseq' : 'NN', + 'compsite': '(?PGAC......GTC)', + 'results': None, + 'site': 'GACNNNNNNGTC', + 'substrat': 'DNA', + 'fst3': -7, + 'fst5': 7, + 'freq': 4096, + 'size': 12, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (7, -7, None, None, 'GACNNNNNNGTC'), + 'ovhgseq': 'NN', } rest_dict['AasI'] = _temp() def _temp(): return { - 'compsite' : '(?PAGGCCT)|(?PAGGCCT)', - 'results' : None, - 'site' : 'AGGCCT', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('O',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'AGGCCT'), - 'ovhgseq' : '', - } -rest_dict['AatI'] = _temp() + 'compsite': '(?PGACGTC)', + 'results': None, + 'site': 'GACGTC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('F', 'I', 'K', 'M', 'N', 'R'), + 'scd5': None, + 'charac': (5, -5, None, None, 'GACGTC'), + 'ovhgseq': 'ACGT', + } +rest_dict['AatII'] = _temp() def _temp(): return { - 'compsite' : '(?PGACGTC)|(?PGACGTC)', - 'results' : None, - 'site' : 'GACGTC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('F', 'I', 'K', 'M', 'N', 'O', 'R', 'V'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GACGTC'), - 'ovhgseq' : 'ACGT', - } -rest_dict['AatII'] = _temp() + 'compsite': '(?PC)|(?PG)', + 'results': None, + 'site': 'C', + 'substrat': 'DNA', + 'fst3': 9, + 'fst5': 12, + 'freq': 4, + 'size': 1, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (12, 9, None, None, 'C'), + 'ovhgseq': 'NN', + } +rest_dict['AbaSI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCTCGAGG)|(?PCCTCGAGG)', - 'results' : None, - 'site' : 'CCTCGAGG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 65536, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CCTCGAGG'), - 'ovhgseq' : 'TCGA', + 'compsite': '(?PCCTCGAGG)', + 'results': None, + 'site': 'CCTCGAGG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (2, -2, None, None, 'CCTCGAGG'), + 'ovhgseq': 'TCGA', } rest_dict['AbsI'] = _temp() def _temp(): return { - 'compsite' : '(?PTGCGCA)|(?PTGCGCA)', - 'results' : None, - 'site' : 'TGCGCA', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'TGCGCA'), - 'ovhgseq' : '', + 'compsite': '(?PTGCGCA)', + 'results': None, + 'site': 'TGCGCA', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (3, -3, None, None, 'TGCGCA'), + 'ovhgseq': '', } rest_dict['Acc16I'] = _temp() def _temp(): return { - 'compsite' : '(?PACCTGC)|(?PGCAGGT)', - 'results' : None, - 'site' : 'ACCTGC', - 'substrat' : 'DNA', - 'fst3' : 8, - 'fst5' : 10, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (10, 8, None, None, 'ACCTGC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PACCTGC)|(?PGCAGGT)', + 'results': None, + 'site': 'ACCTGC', + 'substrat': 'DNA', + 'fst3': 8, + 'fst5': 10, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (10, 8, None, None, 'ACCTGC'), + 'ovhgseq': 'NNNN', } rest_dict['Acc36I'] = _temp() def _temp(): return { - 'compsite' : '(?PGGTACC)|(?PGGTACC)', - 'results' : None, - 'site' : 'GGTACC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F', 'I', 'N', 'R', 'V', 'W'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGTACC'), - 'ovhgseq' : 'GTAC', + 'compsite': '(?PGGTACC)', + 'results': None, + 'site': 'GGTACC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F', 'I', 'N', 'R'), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGTACC'), + 'ovhgseq': 'GTAC', } rest_dict['Acc65I'] = _temp() def _temp(): return { - 'compsite' : '(?PGG[CT][AG]CC)|(?PGG[CT][AG]CC)', - 'results' : None, - 'site' : 'GGYRCC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGYRCC'), - 'ovhgseq' : 'GYRC', + 'compsite': '(?PGG[CT][AG]CC)', + 'results': None, + 'site': 'GGYRCC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGYRCC'), + 'ovhgseq': 'GYRC', } rest_dict['AccB1I'] = _temp() def _temp(): return { - 'compsite' : '(?PCCA.....TGG)|(?PCCA.....TGG)', - 'results' : None, - 'site' : 'CCANNNNNTGG', - 'substrat' : 'DNA', - 'fst3' : -7, - 'fst5' : 7, - 'freq' : 4096, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : None, - 'suppl' : ('I', 'R', 'V'), - 'scd5' : None, - 'charac' : (7, -7, None, None, 'CCANNNNNTGG'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PCCA.....TGG)', + 'results': None, + 'site': 'CCANNNNNTGG', + 'substrat': 'DNA', + 'fst3': -7, + 'fst5': 7, + 'freq': 4096, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (7, -7, None, None, 'CCANNNNNTGG'), + 'ovhgseq': 'NNN', } rest_dict['AccB7I'] = _temp() def _temp(): return { - 'compsite' : '(?PCCGCTC)|(?PGAGCGG)', - 'results' : None, - 'site' : 'CCGCTC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'CCGCTC'), - 'ovhgseq' : '', + 'compsite': '(?PCCGCTC)|(?PGAGCGG)', + 'results': None, + 'site': 'CCGCTC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (3, -3, None, None, 'CCGCTC'), + 'ovhgseq': '', } rest_dict['AccBSI'] = _temp() def _temp(): return { - 'compsite' : '(?PGT[AC][GT]AC)|(?PGT[AC][GT]AC)', - 'results' : None, - 'site' : 'GTMKAC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('B', 'J', 'K', 'M', 'N', 'O', 'R', 'S', 'U', 'W', 'X'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GTMKAC'), - 'ovhgseq' : 'MK', + 'compsite': '(?PGT[AC][GT]AC)', + 'results': None, + 'site': 'GTMKAC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('B', 'J', 'K', 'M', 'N', 'Q', 'R', 'S', 'U', 'X'), + 'scd5': None, + 'charac': (2, -2, None, None, 'GTMKAC'), + 'ovhgseq': 'MK', } rest_dict['AccI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGCG)|(?PCGCG)', - 'results' : None, - 'site' : 'CGCG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('J', 'K'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CGCG'), - 'ovhgseq' : '', + 'compsite': '(?PCGCG)', + 'results': None, + 'site': 'CGCG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('J', 'K'), + 'scd5': None, + 'charac': (2, -2, None, None, 'CGCG'), + 'ovhgseq': '', } rest_dict['AccII'] = _temp() def _temp(): return { - 'compsite' : '(?PTCCGGA)|(?PTCCGGA)', - 'results' : None, - 'site' : 'TCCGGA', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('J', 'K', 'R', 'W'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'TCCGGA'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?PTCCGGA)', + 'results': None, + 'site': 'TCCGGA', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('J', 'K', 'R'), + 'scd5': None, + 'charac': (1, -1, None, None, 'TCCGGA'), + 'ovhgseq': 'CCGG', } rest_dict['AccIII'] = _temp() def _temp(): return { - 'compsite' : '(?PCAGCTC)|(?PGAGCTG)', - 'results' : None, - 'site' : 'CAGCTC', - 'substrat' : 'DNA', - 'fst3' : 11, - 'fst5' : 13, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (13, 11, None, None, 'CAGCTC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PCAGCTC)|(?PGAGCTG)', + 'results': None, + 'site': 'CAGCTC', + 'substrat': 'DNA', + 'fst3': 11, + 'fst5': 13, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (13, 11, None, None, 'CAGCTC'), + 'ovhgseq': 'NNNN', } rest_dict['AceIII'] = _temp() def _temp(): return { - 'compsite' : '(?PCCGC)|(?PGCGG)', - 'results' : None, - 'site' : 'CCGC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCGC'), - 'ovhgseq' : 'CG', + 'compsite': '(?PCCGC)|(?PGCGG)', + 'results': None, + 'site': 'CCGC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCGC'), + 'ovhgseq': 'CG', } rest_dict['AciI'] = _temp() def _temp(): return { - 'compsite' : '(?PAACGTT)|(?PAACGTT)', - 'results' : None, - 'site' : 'AACGTT', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('I', 'N', 'V'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'AACGTT'), - 'ovhgseq' : 'CG', + 'compsite': '(?PAACGTT)', + 'results': None, + 'site': 'AACGTT', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('I', 'N'), + 'scd5': None, + 'charac': (2, -2, None, None, 'AACGTT'), + 'ovhgseq': 'CG', } rest_dict['AclI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGATC)|(?PGATCC)', - 'results' : None, - 'site' : 'GGATC', - 'substrat' : 'DNA', - 'fst3' : 5, - 'fst5' : 9, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (9, 5, None, None, 'GGATC'), - 'ovhgseq' : 'N', + 'compsite': '(?PGGATC)|(?PGATCC)', + 'results': None, + 'site': 'GGATC', + 'substrat': 'DNA', + 'fst3': 5, + 'fst5': 9, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (9, 5, None, None, 'GGATC'), + 'ovhgseq': 'N', } rest_dict['AclWI'] = _temp() def _temp(): return { - 'compsite' : '(?P[CT]GGCC[AG])|(?P[CT]GGCC[AG])', - 'results' : None, - 'site' : 'YGGCCR', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'YGGCCR'), - 'ovhgseq' : 'GGCC', + 'compsite': '(?P[CT]GGCC[AG])', + 'results': None, + 'site': 'YGGCCR', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (1, -1, None, None, 'YGGCCR'), + 'ovhgseq': 'GGCC', } rest_dict['AcoI'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]AATT[CT])|(?P[AG]AATT[CT])', - 'results' : None, - 'site' : 'RAATTY', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'RAATTY'), - 'ovhgseq' : 'AATT', + 'compsite': '(?P[AG]AATT[CT])', + 'results': None, + 'site': 'RAATTY', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (1, -1, None, None, 'RAATTY'), + 'ovhgseq': 'AATT', } rest_dict['AcsI'] = _temp() def _temp(): return { - 'compsite' : '(?PCTGAAG)|(?PCTTCAG)', - 'results' : None, - 'site' : 'CTGAAG', - 'substrat' : 'DNA', - 'fst3' : 14, - 'fst5' : 22, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('I', 'N'), - 'scd5' : None, - 'charac' : (22, 14, None, None, 'CTGAAG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PCTGAAG)|(?PCTTCAG)', + 'results': None, + 'site': 'CTGAAG', + 'substrat': 'DNA', + 'fst3': 14, + 'fst5': 22, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('I', 'N'), + 'scd5': None, + 'charac': (22, 14, None, None, 'CTGAAG'), + 'ovhgseq': 'NN', } rest_dict['AcuI'] = _temp() def _temp(): return { - 'compsite' : '(?PCACGTG)|(?PCACGTG)', - 'results' : None, - 'site' : 'CACGTG', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('Q', 'X'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'CACGTG'), - 'ovhgseq' : '', + 'compsite': '(?PCACGTG)', + 'results': None, + 'site': 'CACGTG', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('Q', 'X'), + 'scd5': None, + 'charac': (3, -3, None, None, 'CACGTG'), + 'ovhgseq': '', } rest_dict['AcvI'] = _temp() def _temp(): return { - 'compsite' : '(?PG[AG]CG[CT]C)|(?PG[AG]CG[CT]C)', - 'results' : None, - 'site' : 'GRCGYC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('J', 'M'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GRCGYC'), - 'ovhgseq' : 'CG', + 'compsite': '(?PG[AG]CG[CT]C)', + 'results': None, + 'site': 'GRCGYC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('J',), + 'scd5': None, + 'charac': (2, -2, None, None, 'GRCGYC'), + 'ovhgseq': 'CG', } rest_dict['AcyI'] = _temp() def _temp(): return { - 'compsite' : '(?PCAC...GTG)|(?PCAC...GTG)', - 'results' : None, - 'site' : 'CACNNNGTG', - 'substrat' : 'DNA', - 'fst3' : -6, - 'fst5' : 6, - 'freq' : 4096, - 'size' : 9, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (6, -6, None, None, 'CACNNNGTG'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PCAC...GTG)', + 'results': None, + 'site': 'CACNNNGTG', + 'substrat': 'DNA', + 'fst3': -6, + 'fst5': 6, + 'freq': 4096, + 'size': 9, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (6, -6, None, None, 'CACNNNGTG'), + 'ovhgseq': 'NNN', } rest_dict['AdeI'] = _temp() def _temp(): return { - 'compsite' : '(?PGTAC)|(?PGTAC)', - 'results' : None, - 'site' : 'GTAC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('K',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GTAC'), - 'ovhgseq' : '', + 'compsite': '(?PGTAC)', + 'results': None, + 'site': 'GTAC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('B', 'K'), + 'scd5': None, + 'charac': (2, -2, None, None, 'GTAC'), + 'ovhgseq': '', } rest_dict['AfaI'] = _temp() def _temp(): return { - 'compsite' : '(?PAGCGCT)|(?PAGCGCT)', - 'results' : None, - 'site' : 'AGCGCT', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I', 'N'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'AGCGCT'), - 'ovhgseq' : '', + 'compsite': '(?PAGCGCT)', + 'results': None, + 'site': 'AGCGCT', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I', 'N'), + 'scd5': None, + 'charac': (3, -3, None, None, 'AGCGCT'), + 'ovhgseq': '', } rest_dict['AfeI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC.......GG)|(?PCC.......GG)', - 'results' : None, - 'site' : 'CCNNNNNNNGG', - 'substrat' : 'DNA', - 'fst3' : -7, - 'fst5' : 7, - 'freq' : 256, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : None, - 'suppl' : ('V',), - 'scd5' : None, - 'charac' : (7, -7, None, None, 'CCNNNNNNNGG'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PCC.......GG)', + 'results': None, + 'site': 'CCNNNNNNNGG', + 'substrat': 'DNA', + 'fst3': -7, + 'fst5': 7, + 'freq': 256, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': ('V',), + 'scd5': None, + 'charac': (7, -7, None, None, 'CCNNNNNNNGG'), + 'ovhgseq': 'NNN', } rest_dict['AfiI'] = _temp() def _temp(): return { - 'compsite' : '(?PCTTAAG)|(?PCTTAAG)', - 'results' : None, - 'site' : 'CTTAAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('J', 'K', 'N'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTTAAG'), - 'ovhgseq' : 'TTAA', + 'compsite': '(?PCTTAAG)', + 'results': None, + 'site': 'CTTAAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('J', 'K', 'N'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CTTAAG'), + 'ovhgseq': 'TTAA', } rest_dict['AflII'] = _temp() def _temp(): return { - 'compsite' : '(?PAC[AG][CT]GT)|(?PAC[AG][CT]GT)', - 'results' : None, - 'site' : 'ACRYGT', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('M', 'N', 'W'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'ACRYGT'), - 'ovhgseq' : 'CRYG', + 'compsite': '(?PAC[AG][CT]GT)', + 'results': None, + 'site': 'ACRYGT', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('M', 'N'), + 'scd5': None, + 'charac': (1, -1, None, None, 'ACRYGT'), + 'ovhgseq': 'CRYG', } rest_dict['AflIII'] = _temp() def _temp(): return { - 'compsite' : '(?PACCGGT)|(?PACCGGT)', - 'results' : None, - 'site' : 'ACCGGT', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('J', 'N', 'R'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'ACCGGT'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?PACCGGT)', + 'results': None, + 'site': 'ACCGGT', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('J', 'N', 'R'), + 'scd5': None, + 'charac': (1, -1, None, None, 'ACCGGT'), + 'ovhgseq': 'CCGG', } rest_dict['AgeI'] = _temp() def _temp(): return { - 'compsite' : '(?PTT[CG]AA)|(?PTT[CG]AA)', - 'results' : None, - 'site' : 'TTSAA', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 1, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'TTSAA'), - 'ovhgseq' : 'S', + 'compsite': '(?PTT[CG]AA)', + 'results': None, + 'site': 'TTSAA', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (3, -3, None, None, 'TTSAA'), + 'ovhgseq': 'S', } rest_dict['AgsI'] = _temp() def _temp(): return { - 'compsite' : '(?PTTTAAA)|(?PTTTAAA)', - 'results' : None, - 'site' : 'TTTAAA', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'TTTAAA'), - 'ovhgseq' : '', + 'compsite': '(?PTTTAAA)', + 'results': None, + 'site': 'TTTAAA', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (3, -3, None, None, 'TTTAAA'), + 'ovhgseq': '', } rest_dict['AhaIII'] = _temp() def _temp(): return { - 'compsite' : '(?PGAC.....GTC)|(?PGAC.....GTC)', - 'results' : None, - 'site' : 'GACNNNNNGTC', - 'substrat' : 'DNA', - 'fst3' : -6, - 'fst5' : 6, - 'freq' : 4096, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 1, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (6, -6, None, None, 'GACNNNNNGTC'), - 'ovhgseq' : 'N', + 'compsite': '(?PGAC.....GTC)', + 'results': None, + 'site': 'GACNNNNNGTC', + 'substrat': 'DNA', + 'fst3': -6, + 'fst5': 6, + 'freq': 4096, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (6, -6, None, None, 'GACNNNNNGTC'), + 'ovhgseq': 'N', } rest_dict['AhdI'] = _temp() def _temp(): return { - 'compsite' : '(?PACTAGT)|(?PACTAGT)', - 'results' : None, - 'site' : 'ACTAGT', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'ACTAGT'), - 'ovhgseq' : 'CTAG', + 'compsite': '(?PACTAGT)', + 'results': None, + 'site': 'ACTAGT', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'ACTAGT'), + 'ovhgseq': 'CTAG', } rest_dict['AhlI'] = _temp() def _temp(): return { - 'compsite' : '(?PCACGTC)|(?PGACGTG)', - 'results' : None, - 'site' : 'CACGTC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'CACGTC'), - 'ovhgseq' : '', + 'compsite': '(?PCACGTC)|(?PGACGTG)', + 'results': None, + 'site': 'CACGTC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (3, -3, None, None, 'CACGTC'), + 'ovhgseq': '', } rest_dict['AjiI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC[AT]GG)|(?PCC[AT]GG)', - 'results' : None, - 'site' : 'CCWGG', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -5, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'CCWGG'), - 'ovhgseq' : 'CCWGG', + 'compsite': '(?PCC[AT]GG)', + 'results': None, + 'site': 'CCWGG', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (0, 0, None, None, 'CCWGG'), + 'ovhgseq': 'CCWGG', } rest_dict['AjnI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAA.......TTGG)|(?PCCAA.......TTC)', - 'results' : None, - 'site' : 'GAANNNNNNNTTGG', - 'substrat' : 'DNA', - 'fst3' : -26, - 'fst5' : -7, - 'freq' : 16384, - 'size' : 14, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 5, - 'scd3' : 6, - 'suppl' : ('F',), - 'scd5' : 25, - 'charac' : (-7, -26, 25, 6, 'GAANNNNNNNTTGG'), - 'ovhgseq' : 'NNNNN', + 'compsite': '(?PGAA.......TTGG)|(?PCCAA.......TTC)', + 'results': None, + 'site': 'GAANNNNNNNTTGG', + 'substrat': 'DNA', + 'fst3': -26, + 'fst5': -7, + 'freq': 16384, + 'size': 14, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 5, + 'scd3': 6, + 'suppl': ('F',), + 'scd5': 25, + 'charac': (-7, -26, 25, 6, 'GAANNNNNNNTTGG'), + 'ovhgseq': 'NNNNN', } rest_dict['AjuI'] = _temp() def _temp(): return { - 'compsite' : '(?PCAC....GTG)|(?PCAC....GTG)', - 'results' : None, - 'site' : 'CACNNNNGTG', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 10, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'CACNNNNGTG'), - 'ovhgseq' : '', + 'compsite': '(?PCAC....GTG)', + 'results': None, + 'site': 'CACNNNNGTG', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 10, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (5, -5, None, None, 'CACNNNNGTG'), + 'ovhgseq': '', } rest_dict['AleI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCA......TGC)|(?PGCA......TGC)', - 'results' : None, - 'site' : 'GCANNNNNNTGC', - 'substrat' : 'DNA', - 'fst3' : -24, - 'fst5' : -10, - 'freq' : 4096, - 'size' : 12, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : 10, - 'suppl' : ('F',), - 'scd5' : 24, - 'charac' : (-10, -24, 24, 10, 'GCANNNNNNTGC'), - 'ovhgseq' : 'NN', + 'compsite': '(?PGCA......TGC)', + 'results': None, + 'site': 'GCANNNNNNTGC', + 'substrat': 'DNA', + 'fst3': -24, + 'fst5': -10, + 'freq': 4096, + 'size': 12, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': 10, + 'suppl': ('F',), + 'scd5': 24, + 'charac': (-10, -24, 24, 10, 'GCANNNNNNTGC'), + 'ovhgseq': 'NN', } rest_dict['AlfI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAAC......TCC)|(?PGGA......GTTC)', - 'results' : None, - 'site' : 'GAACNNNNNNTCC', - 'substrat' : 'DNA', - 'fst3' : -25, - 'fst5' : -7, - 'freq' : 16384, - 'size' : 13, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 5, - 'scd3' : 7, - 'suppl' : ('F',), - 'scd5' : 25, - 'charac' : (-7, -25, 25, 7, 'GAACNNNNNNTCC'), - 'ovhgseq' : 'NNNNN', + 'compsite': '(?PGAAC......TCC)|(?PGGA......GTTC)', + 'results': None, + 'site': 'GAACNNNNNNTCC', + 'substrat': 'DNA', + 'fst3': -25, + 'fst5': -7, + 'freq': 16384, + 'size': 13, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 5, + 'scd3': 7, + 'suppl': ('F',), + 'scd5': 25, + 'charac': (-7, -25, 25, 7, 'GAACNNNNNNTCC'), + 'ovhgseq': 'NNNNN', } rest_dict['AloI'] = _temp() def _temp(): return { - 'compsite' : '(?PAGCT)|(?PAGCT)', - 'results' : None, - 'site' : 'AGCT', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'AGCT'), - 'ovhgseq' : '', + 'compsite': '(?PAGCT)', + 'results': None, + 'site': 'AGCT', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (2, -2, None, None, 'AGCT'), + 'ovhgseq': '', } rest_dict['AluBI'] = _temp() def _temp(): return { - 'compsite' : '(?PAGCT)|(?PAGCT)', - 'results' : None, - 'site' : 'AGCT', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('B', 'C', 'F', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'AGCT'), - 'ovhgseq' : '', + 'compsite': '(?PAGCT)', + 'results': None, + 'site': 'AGCT', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('B', 'C', 'F', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'X', 'Y'), + 'scd5': None, + 'charac': (2, -2, None, None, 'AGCT'), + 'ovhgseq': '', } rest_dict['AluI'] = _temp() def _temp(): return { - 'compsite' : '(?PG[AT]GC[AT]C)|(?PG[AT]GC[AT]C)', - 'results' : None, - 'site' : 'GWGCWC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GWGCWC'), - 'ovhgseq' : 'WGCW', + 'compsite': '(?PG[AT]GC[AT]C)', + 'results': None, + 'site': 'GWGCWC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (5, -5, None, None, 'GWGCWC'), + 'ovhgseq': 'WGCW', } rest_dict['Alw21I'] = _temp() def _temp(): return { - 'compsite' : '(?PGTCTC)|(?PGAGAC)', - 'results' : None, - 'site' : 'GTCTC', - 'substrat' : 'DNA', - 'fst3' : 5, - 'fst5' : 6, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (6, 5, None, None, 'GTCTC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PGTCTC)|(?PGAGAC)', + 'results': None, + 'site': 'GTCTC', + 'substrat': 'DNA', + 'fst3': 5, + 'fst5': 6, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (6, 5, None, None, 'GTCTC'), + 'ovhgseq': 'NNNN', } rest_dict['Alw26I'] = _temp() def _temp(): return { - 'compsite' : '(?PGTGCAC)|(?PGTGCAC)', - 'results' : None, - 'site' : 'GTGCAC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F', 'J', 'O', 'R'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GTGCAC'), - 'ovhgseq' : 'TGCA', + 'compsite': '(?PGTGCAC)', + 'results': None, + 'site': 'GTGCAC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F', 'J'), + 'scd5': None, + 'charac': (1, -1, None, None, 'GTGCAC'), + 'ovhgseq': 'TGCA', } rest_dict['Alw44I'] = _temp() def _temp(): return { - 'compsite' : '(?PGAAA[CT].....[AG]TG)|(?PCA[CT].....[AG]TTTC)', - 'results' : None, - 'site' : 'GAAAYNNNNNRTG', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 16384, - 'size' : 13, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'GAAAYNNNNNRTG'), - 'ovhgseq' : None, + 'compsite': '(?PGAAA[CT].....[AG]TG)|(?PCA[CT].....[AG]TTTC)', + 'results': None, + 'site': 'GAAAYNNNNNRTG', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 16384, + 'size': 13, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'GAAAYNNNNNRTG'), + 'ovhgseq': None, } rest_dict['AlwFI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGATC)|(?PGATCC)', - 'results' : None, - 'site' : 'GGATC', - 'substrat' : 'DNA', - 'fst3' : 5, - 'fst5' : 9, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (9, 5, None, None, 'GGATC'), - 'ovhgseq' : 'N', + 'compsite': '(?PGGATC)|(?PGATCC)', + 'results': None, + 'site': 'GGATC', + 'substrat': 'DNA', + 'fst3': 5, + 'fst5': 9, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (9, 5, None, None, 'GGATC'), + 'ovhgseq': 'N', } rest_dict['AlwI'] = _temp() def _temp(): return { - 'compsite' : '(?PCAG...CTG)|(?PCAG...CTG)', - 'results' : None, - 'site' : 'CAGNNNCTG', - 'substrat' : 'DNA', - 'fst3' : -6, - 'fst5' : 6, - 'freq' : 4096, - 'size' : 9, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (6, -6, None, None, 'CAGNNNCTG'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PCAG...CTG)', + 'results': None, + 'site': 'CAGNNNCTG', + 'substrat': 'DNA', + 'fst3': -6, + 'fst5': 6, + 'freq': 4096, + 'size': 9, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (6, -6, None, None, 'CAGNNNCTG'), + 'ovhgseq': 'NNN', } rest_dict['AlwNI'] = _temp() def _temp(): return { - 'compsite' : '(?PC[CT]CG[AG]G)|(?PC[CT]CG[AG]G)', - 'results' : None, - 'site' : 'CYCGRG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CYCGRG'), - 'ovhgseq' : 'YCGR', + 'compsite': '(?PC[CT]CG[AG]G)', + 'results': None, + 'site': 'CYCGRG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CYCGRG'), + 'ovhgseq': 'YCGR', } rest_dict['Ama87I'] = _temp() def _temp(): return { - 'compsite' : '(?PTCCGGA)|(?PTCCGGA)', - 'results' : None, - 'site' : 'TCCGGA', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('K',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'TCCGGA'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?PTCCGGA)', + 'results': None, + 'site': 'TCCGGA', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('K',), + 'scd5': None, + 'charac': (1, -1, None, None, 'TCCGGA'), + 'ovhgseq': 'CCGG', } rest_dict['Aor13HI'] = _temp() def _temp(): return { - 'compsite' : '(?PAGCGCT)|(?PAGCGCT)', - 'results' : None, - 'site' : 'AGCGCT', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('K',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'AGCGCT'), - 'ovhgseq' : '', + 'compsite': '(?PAGCGCT)', + 'results': None, + 'site': 'AGCGCT', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('K',), + 'scd5': None, + 'charac': (3, -3, None, None, 'AGCGCT'), + 'ovhgseq': '', } rest_dict['Aor51HI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCA.....TGC)|(?PGCA.....TGC)', - 'results' : None, - 'site' : 'GCANNNNNTGC', - 'substrat' : 'DNA', - 'fst3' : -8, - 'fst5' : 8, - 'freq' : 4096, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 5, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (8, -8, None, None, 'GCANNNNNTGC'), - 'ovhgseq' : 'NNNNN', + 'compsite': '(?PGGCC)', + 'results': None, + 'site': 'GGCC', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (0, 0, None, None, 'GGCC'), + 'ovhgseq': 'GGCC', + } +rest_dict['AoxI'] = _temp() + +def _temp(): + return { + 'compsite': '(?PGCA.....TGC)', + 'results': None, + 'site': 'GCANNNNNTGC', + 'substrat': 'DNA', + 'fst3': -8, + 'fst5': 8, + 'freq': 4096, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 5, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (8, -8, None, None, 'GCANNNNNTGC'), + 'ovhgseq': 'NNNNN', } rest_dict['ApaBI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGGCCC)|(?PGGGCCC)', - 'results' : None, - 'site' : 'GGGCCC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('B', 'F', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'W', 'X'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GGGCCC'), - 'ovhgseq' : 'GGCC', + 'compsite': '(?PGGGCCC)', + 'results': None, + 'site': 'GGGCCC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('B', 'F', 'I', 'J', 'K', 'M', 'N', 'Q', 'R', 'S', 'U', 'V', 'X'), + 'scd5': None, + 'charac': (5, -5, None, None, 'GGGCCC'), + 'ovhgseq': 'GGCC', } rest_dict['ApaI'] = _temp() def _temp(): return { - 'compsite' : '(?PGTGCAC)|(?PGTGCAC)', - 'results' : None, - 'site' : 'GTGCAC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('C', 'K', 'N', 'U'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GTGCAC'), - 'ovhgseq' : 'TGCA', + 'compsite': '(?PGTGCAC)', + 'results': None, + 'site': 'GTGCAC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('C', 'K', 'N', 'U'), + 'scd5': None, + 'charac': (1, -1, None, None, 'GTGCAC'), + 'ovhgseq': 'TGCA', } rest_dict['ApaLI'] = _temp() def _temp(): return { - 'compsite' : '(?PGC[AT]GC)|(?PGC[AT]GC)', - 'results' : None, - 'site' : 'GCWGC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GCWGC'), - 'ovhgseq' : 'CWG', + 'compsite': '(?PGC[AT]GC)', + 'results': None, + 'site': 'GCWGC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GCWGC'), + 'ovhgseq': 'CWG', } rest_dict['ApeKI'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]AATT[CT])|(?P[AG]AATT[CT])', - 'results' : None, - 'site' : 'RAATTY', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'RAATTY'), - 'ovhgseq' : 'AATT', + 'compsite': '(?P[AG]AATT[CT])', + 'results': None, + 'site': 'RAATTY', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'RAATTY'), + 'ovhgseq': 'AATT', } rest_dict['ApoI'] = _temp() def _temp(): return { - 'compsite' : '(?PATCGAC)|(?PGTCGAT)', - 'results' : None, - 'site' : 'ATCGAC', - 'substrat' : 'DNA', - 'fst3' : 18, - 'fst5' : 26, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (26, 18, None, None, 'ATCGAC'), - 'ovhgseq' : 'NN', + 'compsite': '(?PATCGAC)|(?PGTCGAT)', + 'results': None, + 'site': 'ATCGAC', + 'substrat': 'DNA', + 'fst3': 18, + 'fst5': 26, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (26, 18, None, None, 'ATCGAC'), + 'ovhgseq': 'NN', } rest_dict['ApyPI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCCG.AC)|(?PGT.CGGC)', - 'results' : None, - 'site' : 'GCCGNAC', - 'substrat' : 'DNA', - 'fst3' : 18, - 'fst5' : 27, - 'freq' : 4096, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (27, 18, None, None, 'GCCGNAC'), - 'ovhgseq' : 'NN', + 'compsite': '(?PGCCG.AC)|(?PGT.CGGC)', + 'results': None, + 'site': 'GCCGNAC', + 'substrat': 'DNA', + 'fst3': 18, + 'fst5': 27, + 'freq': 4096, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (27, 18, None, None, 'GCCGNAC'), + 'ovhgseq': 'NN', } rest_dict['AquII'] = _temp() def _temp(): return { - 'compsite' : '(?PGAGGAG)|(?PCTCCTC)', - 'results' : None, - 'site' : 'GAGGAG', - 'substrat' : 'DNA', - 'fst3' : 18, - 'fst5' : 26, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (26, 18, None, None, 'GAGGAG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PGAGGAG)|(?PCTCCTC)', + 'results': None, + 'site': 'GAGGAG', + 'substrat': 'DNA', + 'fst3': 18, + 'fst5': 26, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (26, 18, None, None, 'GAGGAG'), + 'ovhgseq': 'NN', } rest_dict['AquIII'] = _temp() def _temp(): return { - 'compsite' : '(?PG[AG]GGAAG)|(?PCTTCC[CT]C)', - 'results' : None, - 'site' : 'GRGGAAG', - 'substrat' : 'DNA', - 'fst3' : 17, - 'fst5' : 26, - 'freq' : 8192, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (26, 17, None, None, 'GRGGAAG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PG[AG]GGAAG)|(?PCTTCC[CT]C)', + 'results': None, + 'site': 'GRGGAAG', + 'substrat': 'DNA', + 'fst3': 17, + 'fst5': 26, + 'freq': 8192, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (26, 17, None, None, 'GRGGAAG'), + 'ovhgseq': 'NN', } rest_dict['AquIV'] = _temp() def _temp(): return { - 'compsite' : '(?PGAC......TT[CT]G)|(?PC[AG]AA......GTC)', - 'results' : None, - 'site' : 'GACNNNNNNTTYG', - 'substrat' : 'DNA', - 'fst3' : -26, - 'fst5' : -8, - 'freq' : 8192, - 'size' : 13, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 5, - 'scd3' : 6, - 'suppl' : ('I',), - 'scd5' : 24, - 'charac' : (-8, -26, 24, 6, 'GACNNNNNNTTYG'), - 'ovhgseq' : 'NNNNN', + 'compsite': '(?PGAC......TT[CT]G)|(?PC[AG]AA......GTC)', + 'results': None, + 'site': 'GACNNNNNNTTYG', + 'substrat': 'DNA', + 'fst3': -26, + 'fst5': -8, + 'freq': 8192, + 'size': 13, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 5, + 'scd3': 6, + 'suppl': ('I',), + 'scd5': 24, + 'charac': (-8, -26, 24, 6, 'GACNNNNNNTTYG'), + 'ovhgseq': 'NNNNN', } rest_dict['ArsI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGCGCGCC)|(?PGGCGCGCC)', - 'results' : None, - 'site' : 'GGCGCGCC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 65536, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N', 'W'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GGCGCGCC'), - 'ovhgseq' : 'CGCG', + 'compsite': '(?PGGCGCGCC)', + 'results': None, + 'site': 'GGCGCGCC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (2, -2, None, None, 'GGCGCGCC'), + 'ovhgseq': 'CGCG', } rest_dict['AscI'] = _temp() def _temp(): return { - 'compsite' : '(?PATTAAT)|(?PATTAAT)', - 'results' : None, - 'site' : 'ATTAAT', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('J', 'N', 'O'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'ATTAAT'), - 'ovhgseq' : 'TA', + 'compsite': '(?PATTAAT)', + 'results': None, + 'site': 'ATTAAT', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('J', 'N', 'O'), + 'scd5': None, + 'charac': (2, -2, None, None, 'ATTAAT'), + 'ovhgseq': 'TA', } rest_dict['AseI'] = _temp() def _temp(): return { - 'compsite' : '(?PGATC)|(?PGATC)', - 'results' : None, - 'site' : 'GATC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GATC'), - 'ovhgseq' : 'AT', + 'compsite': '(?PGATC)', + 'results': None, + 'site': 'GATC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (1, -1, None, None, 'GATC'), + 'ovhgseq': 'AT', } rest_dict['Asi256I'] = _temp() def _temp(): return { - 'compsite' : '(?PACCGGT)|(?PACCGGT)', - 'results' : None, - 'site' : 'ACCGGT', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'ACCGGT'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?PACCGGT)', + 'results': None, + 'site': 'ACCGGT', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'ACCGGT'), + 'ovhgseq': 'CCGG', } rest_dict['AsiGI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCGATCGC)|(?PGCGATCGC)', - 'results' : None, - 'site' : 'GCGATCGC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 65536, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GCGATCGC'), - 'ovhgseq' : 'AT', + 'compsite': '(?PGCGATCGC)', + 'results': None, + 'site': 'GCGATCGC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('I', 'N'), + 'scd5': None, + 'charac': (5, -5, None, None, 'GCGATCGC'), + 'ovhgseq': 'AT', } rest_dict['AsiSI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAA....TTC)|(?PGAA....TTC)', - 'results' : None, - 'site' : 'GAANNNNTTC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 10, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('M',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GAANNNNTTC'), - 'ovhgseq' : '', + 'compsite': '(?PGAA....TTC)', + 'results': None, + 'site': 'GAANNNNTTC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 10, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('M',), + 'scd5': None, + 'charac': (5, -5, None, None, 'GAANNNNTTC'), + 'ovhgseq': '', } rest_dict['Asp700I'] = _temp() def _temp(): return { - 'compsite' : '(?PGGTACC)|(?PGGTACC)', - 'results' : None, - 'site' : 'GGTACC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('M',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGTACC'), - 'ovhgseq' : 'GTAC', + 'compsite': '(?PGGTACC)', + 'results': None, + 'site': 'GGTACC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('M',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGTACC'), + 'ovhgseq': 'GTAC', } rest_dict['Asp718I'] = _temp() def _temp(): return { - 'compsite' : '(?PCCTAGG)|(?PCCTAGG)', - 'results' : None, - 'site' : 'CCTAGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCTAGG'), - 'ovhgseq' : 'CTAG', + 'compsite': '(?PCCTAGG)', + 'results': None, + 'site': 'CCTAGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCTAGG'), + 'ovhgseq': 'CTAG', } rest_dict['AspA2I'] = _temp() def _temp(): return { - 'compsite' : '(?PGCCGC)|(?PGCGGC)', - 'results' : None, - 'site' : 'GCCGC', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'GCCGC'), - 'ovhgseq' : None, - } -rest_dict['AspCNI'] = _temp() - -def _temp(): - return { - 'compsite' : '(?PGAC.....GTC)|(?PGAC.....GTC)', - 'results' : None, - 'site' : 'GACNNNNNGTC', - 'substrat' : 'DNA', - 'fst3' : -6, - 'fst5' : 6, - 'freq' : 4096, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 1, - 'scd3' : None, - 'suppl' : ('M',), - 'scd5' : None, - 'charac' : (6, -6, None, None, 'GACNNNNNGTC'), - 'ovhgseq' : 'N', - } -rest_dict['AspEI'] = _temp() - -def _temp(): - return { - 'compsite' : '(?PGAC...GTC)|(?PGAC...GTC)', - 'results' : None, - 'site' : 'GACNNNGTC', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 4096, - 'size' : 9, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('M',), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'GACNNNGTC'), - 'ovhgseq' : 'N', - } -rest_dict['AspI'] = _temp() - -def _temp(): - return { - 'compsite' : '(?PGCGC)|(?PGCGC)', - 'results' : None, - 'site' : 'GCGC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GCGC'), - 'ovhgseq' : 'CG', + 'compsite': '(?P[CT][CG]C.[CG])|(?P[CG].G[CG][AG])', + 'results': None, + 'site': 'YSCNS', + 'substrat': 'DNA', + 'fst3': 12, + 'fst5': 13, + 'freq': 32, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (13, 12, None, None, 'YSCNS'), + 'ovhgseq': 'NNNN', + } +rest_dict['AspBHI'] = _temp() + +def _temp(): + return { + 'compsite': '(?PGCGC)', + 'results': None, + 'site': 'GCGC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (3, -3, None, None, 'GCGC'), + 'ovhgseq': 'CG', } rest_dict['AspLEI'] = _temp() def _temp(): return { - 'compsite' : '(?PGG.CC)|(?PGG.CC)', - 'results' : None, - 'site' : 'GGNCC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGNCC'), - 'ovhgseq' : 'GNC', + 'compsite': '(?PGG.CC)', + 'results': None, + 'site': 'GGNCC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGNCC'), + 'ovhgseq': 'GNC', } rest_dict['AspS9I'] = _temp() def _temp(): return { - 'compsite' : '(?PAGTACT)|(?PAGTACT)', - 'results' : None, - 'site' : 'AGTACT', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('U',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'AGTACT'), - 'ovhgseq' : '', + 'compsite': '(?PAGTACT)', + 'results': None, + 'site': 'AGTACT', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('U',), + 'scd5': None, + 'charac': (3, -3, None, None, 'AGTACT'), + 'ovhgseq': '', } rest_dict['AssI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC[CG]GG)|(?PCC[CG]GG)', - 'results' : None, - 'site' : 'CCSGG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CCSGG'), - 'ovhgseq' : 'S', + 'compsite': '(?PCC[CG]GG)', + 'results': None, + 'site': 'CCSGG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (2, -2, None, None, 'CCSGG'), + 'ovhgseq': 'S', } rest_dict['AsuC2I'] = _temp() def _temp(): return { - 'compsite' : '(?PGGTGA)|(?PTCACC)', - 'results' : None, - 'site' : 'GGTGA', - 'substrat' : 'DNA', - 'fst3' : 7, - 'fst5' : 13, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 1, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (13, 7, None, None, 'GGTGA'), - 'ovhgseq' : 'N', + 'compsite': '(?PGGTGA)|(?PTCACC)', + 'results': None, + 'site': 'GGTGA', + 'substrat': 'DNA', + 'fst3': 7, + 'fst5': 13, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (13, 7, None, None, 'GGTGA'), + 'ovhgseq': 'N', } rest_dict['AsuHPI'] = _temp() def _temp(): return { - 'compsite' : '(?PGG.CC)|(?PGG.CC)', - 'results' : None, - 'site' : 'GGNCC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGNCC'), - 'ovhgseq' : 'GNC', + 'compsite': '(?PGG.CC)', + 'results': None, + 'site': 'GGNCC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGNCC'), + 'ovhgseq': 'GNC', } rest_dict['AsuI'] = _temp() def _temp(): return { - 'compsite' : '(?PTTCGAA)|(?PTTCGAA)', - 'results' : None, - 'site' : 'TTCGAA', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('C',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'TTCGAA'), - 'ovhgseq' : 'CG', + 'compsite': '(?PTTCGAA)', + 'results': None, + 'site': 'TTCGAA', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('C',), + 'scd5': None, + 'charac': (2, -2, None, None, 'TTCGAA'), + 'ovhgseq': 'CG', } rest_dict['AsuII'] = _temp() def _temp(): return { - 'compsite' : '(?PGCTAGC)|(?PGCTAGC)', - 'results' : None, - 'site' : 'GCTAGC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GCTAGC'), - 'ovhgseq' : 'CTAG', + 'compsite': '(?PGCTAGC)', + 'results': None, + 'site': 'GCTAGC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'GCTAGC'), + 'ovhgseq': 'CTAG', } rest_dict['AsuNHI'] = _temp() def _temp(): return { - 'compsite' : '(?PC[CT]CG[AG]G)|(?PC[CT]CG[AG]G)', - 'results' : None, - 'site' : 'CYCGRG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('B', 'J', 'M', 'N', 'O', 'R', 'S', 'U', 'W', 'X'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CYCGRG'), - 'ovhgseq' : 'YCGR', + 'compsite': '(?PC[CT]CG[AG]G)', + 'results': None, + 'site': 'CYCGRG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('J', 'N', 'Q', 'R', 'U', 'X'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CYCGRG'), + 'ovhgseq': 'YCGR', } rest_dict['AvaI'] = _temp() def _temp(): return { - 'compsite' : '(?PGG[AT]CC)|(?PGG[AT]CC)', - 'results' : None, - 'site' : 'GGWCC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('J', 'K', 'M', 'N', 'R', 'S', 'W', 'Y'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGWCC'), - 'ovhgseq' : 'GWC', + 'compsite': '(?PGG[AT]CC)', + 'results': None, + 'site': 'GGWCC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('J', 'N', 'R', 'X', 'Y'), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGWCC'), + 'ovhgseq': 'GWC', } rest_dict['AvaII'] = _temp() def _temp(): return { - 'compsite' : '(?PATGCAT)|(?PATGCAT)', - 'results' : None, - 'site' : 'ATGCAT', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'ATGCAT'), - 'ovhgseq' : None, + 'compsite': '(?PATGCAT)', + 'results': None, + 'site': 'ATGCAT', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'ATGCAT'), + 'ovhgseq': None, } rest_dict['AvaIII'] = _temp() def _temp(): return { - 'compsite' : '(?PTGCGCA)|(?PTGCGCA)', - 'results' : None, - 'site' : 'TGCGCA', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('M',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'TGCGCA'), - 'ovhgseq' : '', - } -rest_dict['AviII'] = _temp() - -def _temp(): - return { - 'compsite' : '(?PCCTAGG)|(?PCCTAGG)', - 'results' : None, - 'site' : 'CCTAGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCTAGG'), - 'ovhgseq' : 'CTAG', + 'compsite': '(?PCCTAGG)', + 'results': None, + 'site': 'CCTAGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCTAGG'), + 'ovhgseq': 'CTAG', } rest_dict['AvrII'] = _temp() def _temp(): return { - 'compsite' : '(?PCCT.AGG)|(?PCCT.AGG)', - 'results' : None, - 'site' : 'CCTNAGG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('J',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CCTNAGG'), - 'ovhgseq' : 'TNA', + 'compsite': '(?PCCT.AGG)', + 'results': None, + 'site': 'CCTNAGG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('J',), + 'scd5': None, + 'charac': (2, -2, None, None, 'CCTNAGG'), + 'ovhgseq': 'TNA', } rest_dict['AxyI'] = _temp() def _temp(): return { - 'compsite' : '(?PG[GT]GC[AC]C)|(?PG[GT]GC[AC]C)', - 'results' : None, - 'site' : 'GKGCMC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GKGCMC'), - 'ovhgseq' : 'KGCM', + 'compsite': '(?PG[GT]GC[AC]C)', + 'results': None, + 'site': 'GKGCMC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (5, -5, None, None, 'GKGCMC'), + 'ovhgseq': 'KGCM', } rest_dict['BaeGI'] = _temp() def _temp(): return { - 'compsite' : '(?PAC....GTA[CT]C)|(?PG[AG]TAC....GT)', - 'results' : None, - 'site' : 'ACNNNNGTAYC', - 'substrat' : 'DNA', - 'fst3' : -26, - 'fst5' : -10, - 'freq' : 8192, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 5, - 'scd3' : 7, - 'suppl' : ('N',), - 'scd5' : 23, - 'charac' : (-10, -26, 23, 7, 'ACNNNNGTAYC'), - 'ovhgseq' : 'NNNNN', + 'compsite': '(?PAC....GTA[CT]C)|(?PG[AG]TAC....GT)', + 'results': None, + 'site': 'ACNNNNGTAYC', + 'substrat': 'DNA', + 'fst3': -26, + 'fst5': -10, + 'freq': 8192, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 5, + 'scd3': 7, + 'suppl': ('N',), + 'scd5': 23, + 'charac': (-10, -26, 23, 7, 'ACNNNNGTAYC'), + 'ovhgseq': 'NNNNN', } rest_dict['BaeI'] = _temp() def _temp(): return { - 'compsite' : '(?PTGGCCA)|(?PTGGCCA)', - 'results' : None, - 'site' : 'TGGCCA', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('J', 'K', 'R', 'X'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'TGGCCA'), - 'ovhgseq' : '', + 'compsite': '(?PTGGCCA)', + 'results': None, + 'site': 'TGGCCA', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('B', 'J', 'K', 'Q', 'R', 'X'), + 'scd5': None, + 'charac': (3, -3, None, None, 'TGGCCA'), + 'ovhgseq': '', } rest_dict['BalI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGATCC)|(?PGGATCC)', - 'results' : None, - 'site' : 'GGATCC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('B', 'C', 'F', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGATCC'), - 'ovhgseq' : 'GATC', + 'compsite': '(?PGGATCC)', + 'results': None, + 'site': 'GGATCC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('B', 'C', 'F', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'X', 'Y'), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGATCC'), + 'ovhgseq': 'GATC', } rest_dict['BamHI'] = _temp() def _temp(): return { - 'compsite' : '(?PGG[CT][AG]CC)|(?PGG[CT][AG]CC)', - 'results' : None, - 'site' : 'GGYRCC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N', 'O', 'R', 'U'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGYRCC'), - 'ovhgseq' : 'GYRC', + 'compsite': '(?PGG[CT][AG]CC)', + 'results': None, + 'site': 'GGYRCC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N', 'R', 'U'), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGYRCC'), + 'ovhgseq': 'GYRC', } rest_dict['BanI'] = _temp() def _temp(): return { - 'compsite' : '(?PG[AG]GC[CT]C)|(?PG[AG]GC[CT]C)', - 'results' : None, - 'site' : 'GRGCYC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('K', 'N', 'O', 'Q', 'R', 'W', 'X'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GRGCYC'), - 'ovhgseq' : 'RGCY', + 'compsite': '(?PG[AG]GC[CT]C)', + 'results': None, + 'site': 'GRGCYC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('K', 'N', 'X'), + 'scd5': None, + 'charac': (5, -5, None, None, 'GRGCYC'), + 'ovhgseq': 'RGCY', } rest_dict['BanII'] = _temp() def _temp(): return { - 'compsite' : '(?PATCGAT)|(?PATCGAT)', - 'results' : None, - 'site' : 'ATCGAT', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('O',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'ATCGAT'), - 'ovhgseq' : 'CG', - } -rest_dict['BanIII'] = _temp() - -def _temp(): - return { - 'compsite' : '(?PGAAG......TAC)|(?PGTA......CTTC)', - 'results' : None, - 'site' : 'GAAGNNNNNNTAC', - 'substrat' : 'DNA', - 'fst3' : -25, - 'fst5' : -7, - 'freq' : 16384, - 'size' : 13, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 5, - 'scd3' : 7, - 'suppl' : ('I',), - 'scd5' : 25, - 'charac' : (-7, -25, 25, 7, 'GAAGNNNNNNTAC'), - 'ovhgseq' : 'NNNNN', + 'compsite': '(?PGAAG......TAC)|(?PGTA......CTTC)', + 'results': None, + 'site': 'GAAGNNNNNNTAC', + 'substrat': 'DNA', + 'fst3': -25, + 'fst5': -7, + 'freq': 16384, + 'size': 13, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 5, + 'scd3': 7, + 'suppl': ('I',), + 'scd5': 25, + 'charac': (-7, -25, 25, 7, 'GAAGNNNNNNTAC'), + 'ovhgseq': 'NNNNN', } rest_dict['BarI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCA.....TGG)|(?PCCA.....TGG)', - 'results' : None, - 'site' : 'CCANNNNNTGG', - 'substrat' : 'DNA', - 'fst3' : -7, - 'fst5' : 7, - 'freq' : 4096, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : None, - 'suppl' : ('U',), - 'scd5' : None, - 'charac' : (7, -7, None, None, 'CCANNNNNTGG'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PCCA.....TGG)', + 'results': None, + 'site': 'CCANNNNNTGG', + 'substrat': 'DNA', + 'fst3': -7, + 'fst5': 7, + 'freq': 4096, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': ('U',), + 'scd5': None, + 'charac': (7, -7, None, None, 'CCANNNNNTGG'), + 'ovhgseq': 'NNN', } rest_dict['BasI'] = _temp() def _temp(): return { - 'compsite' : '(?PCACGAG)|(?PCTCGTG)', - 'results' : None, - 'site' : 'CACGAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CACGAG'), - 'ovhgseq' : 'ACGA', + 'compsite': '(?PCACGAG)|(?PCTCGTG)', + 'results': None, + 'site': 'CACGAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CACGAG'), + 'ovhgseq': 'ACGA', } rest_dict['BauI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGCGCC)|(?PGGCGCC)', - 'results' : None, - 'site' : 'GGCGCC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('K',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GGCGCC'), - 'ovhgseq' : 'GCGC', - } -rest_dict['BbeI'] = _temp() - -def _temp(): - return { - 'compsite' : '(?PGAAGAC)|(?PGTCTTC)', - 'results' : None, - 'site' : 'GAAGAC', - 'substrat' : 'DNA', - 'fst3' : 11, - 'fst5' : 13, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (13, 11, None, None, 'GAAGAC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PGAAGAC)|(?PGTCTTC)', + 'results': None, + 'site': 'GAAGAC', + 'substrat': 'DNA', + 'fst3': 11, + 'fst5': 13, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (13, 11, None, None, 'GAAGAC'), + 'ovhgseq': 'NNNN', } rest_dict['Bbr7I'] = _temp() def _temp(): return { - 'compsite' : '(?PCACGTG)|(?PCACGTG)', - 'results' : None, - 'site' : 'CACGTG', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('M', 'O'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'CACGTG'), - 'ovhgseq' : '', + 'compsite': '(?PCACGTG)', + 'results': None, + 'site': 'CACGTG', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('M',), + 'scd5': None, + 'charac': (3, -3, None, None, 'CACGTG'), + 'ovhgseq': '', } rest_dict['BbrPI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAAGAC)|(?PGTCTTC)', - 'results' : None, - 'site' : 'GAAGAC', - 'substrat' : 'DNA', - 'fst3' : 6, - 'fst5' : 8, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (8, 6, None, None, 'GAAGAC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PGAAGAC)|(?PGTCTTC)', + 'results': None, + 'site': 'GAAGAC', + 'substrat': 'DNA', + 'fst3': 6, + 'fst5': 8, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (8, 6, None, None, 'GAAGAC'), + 'ovhgseq': 'NNNN', } rest_dict['BbsI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCATGC)|(?PGCATGC)', - 'results' : None, - 'site' : 'GCATGC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('R',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GCATGC'), - 'ovhgseq' : 'CATG', - } -rest_dict['BbuI'] = _temp() - -def _temp(): - return { - 'compsite' : '(?PG[AT]GC[AT]C)|(?PG[AT]GC[AT]C)', - 'results' : None, - 'site' : 'GWGCWC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GWGCWC'), - 'ovhgseq' : 'WGCW', + 'compsite': '(?PG[AT]GC[AT]C)', + 'results': None, + 'site': 'GWGCWC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (5, -5, None, None, 'GWGCWC'), + 'ovhgseq': 'WGCW', } rest_dict['Bbv12I'] = _temp() def _temp(): return { - 'compsite' : '(?PCCTCAGC)|(?PGCTGAGG)', - 'results' : None, - 'site' : 'CCTCAGC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 16384, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CCTCAGC'), - 'ovhgseq' : 'TCA', + 'compsite': '(?PCCTCAGC)|(?PGCTGAGG)', + 'results': None, + 'site': 'CCTCAGC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 16384, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (2, -2, None, None, 'CCTCAGC'), + 'ovhgseq': 'TCA', } rest_dict['BbvCI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCAGC)|(?PGCTGC)', - 'results' : None, - 'site' : 'GCAGC', - 'substrat' : 'DNA', - 'fst3' : 12, - 'fst5' : 13, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (13, 12, None, None, 'GCAGC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PGCAGC)|(?PGCTGC)', + 'results': None, + 'site': 'GCAGC', + 'substrat': 'DNA', + 'fst3': 12, + 'fst5': 13, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (13, 12, None, None, 'GCAGC'), + 'ovhgseq': 'NNNN', } rest_dict['BbvI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAAGAC)|(?PGTCTTC)', - 'results' : None, - 'site' : 'GAAGAC', - 'substrat' : 'DNA', - 'fst3' : 6, - 'fst5' : 8, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (8, 6, None, None, 'GAAGAC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PGAAGAC)|(?PGTCTTC)', + 'results': None, + 'site': 'GAAGAC', + 'substrat': 'DNA', + 'fst3': 6, + 'fst5': 8, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (8, 6, None, None, 'GAAGAC'), + 'ovhgseq': 'NNNN', } rest_dict['BbvII'] = _temp() def _temp(): return { - 'compsite' : '(?PCCATC)|(?PGATGG)', - 'results' : None, - 'site' : 'CCATC', - 'substrat' : 'DNA', - 'fst3' : 5, - 'fst5' : 9, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (9, 5, None, None, 'CCATC'), - 'ovhgseq' : 'N', + 'compsite': '(?PCCATC)|(?PGATGG)', + 'results': None, + 'site': 'CCATC', + 'substrat': 'DNA', + 'fst3': 5, + 'fst5': 9, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (9, 5, None, None, 'CCATC'), + 'ovhgseq': 'N', } rest_dict['BccI'] = _temp() def _temp(): return { - 'compsite' : '(?PCTTGAG)|(?PCTCAAG)', - 'results' : None, - 'site' : 'CTTGAG', - 'substrat' : 'DNA', - 'fst3' : 14, - 'fst5' : 22, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (22, 14, None, None, 'CTTGAG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PCTTGAG)|(?PCTCAAG)', + 'results': None, + 'site': 'CTTGAG', + 'substrat': 'DNA', + 'fst3': 14, + 'fst5': 22, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (22, 14, None, None, 'CTTGAG'), + 'ovhgseq': 'NN', } rest_dict['Bce83I'] = _temp() def _temp(): return { - 'compsite' : '(?PACGGC)|(?PGCCGT)', - 'results' : None, - 'site' : 'ACGGC', - 'substrat' : 'DNA', - 'fst3' : 14, - 'fst5' : 17, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (17, 14, None, None, 'ACGGC'), - 'ovhgseq' : 'NN', + 'compsite': '(?PACGGC)|(?PGCCGT)', + 'results': None, + 'site': 'ACGGC', + 'substrat': 'DNA', + 'fst3': 14, + 'fst5': 17, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (17, 14, None, None, 'ACGGC'), + 'ovhgseq': 'NN', } rest_dict['BceAI'] = _temp() def _temp(): return { - 'compsite' : '(?PACGGC)|(?PGCCGT)', - 'results' : None, - 'site' : 'ACGGC', - 'substrat' : 'DNA', - 'fst3' : 13, - 'fst5' : 17, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (17, 13, None, None, 'ACGGC'), - 'ovhgseq' : 'N', + 'compsite': '(?PACGGC)|(?PGCCGT)', + 'results': None, + 'site': 'ACGGC', + 'substrat': 'DNA', + 'fst3': 13, + 'fst5': 17, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (17, 13, None, None, 'ACGGC'), + 'ovhgseq': 'N', } rest_dict['BcefI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGA......TGC)|(?PGCA......TCG)', - 'results' : None, - 'site' : 'CGANNNNNNTGC', - 'substrat' : 'DNA', - 'fst3' : -24, - 'fst5' : -10, - 'freq' : 4096, - 'size' : 12, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : 10, - 'suppl' : ('N',), - 'scd5' : 24, - 'charac' : (-10, -24, 24, 10, 'CGANNNNNNTGC'), - 'ovhgseq' : 'NN', + 'compsite': '(?PCGA......TGC)|(?PGCA......TCG)', + 'results': None, + 'site': 'CGANNNNNNTGC', + 'substrat': 'DNA', + 'fst3': -24, + 'fst5': -10, + 'freq': 4096, + 'size': 12, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': 10, + 'suppl': ('N',), + 'scd5': 24, + 'charac': (-10, -24, 24, 10, 'CGANNNNNNTGC'), + 'ovhgseq': 'NN', } rest_dict['BcgI'] = _temp() def _temp(): return { - 'compsite' : '(?PGTATCC)|(?PGGATAC)', - 'results' : None, - 'site' : 'GTATCC', - 'substrat' : 'DNA', - 'fst3' : 5, - 'fst5' : 12, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 1, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (12, 5, None, None, 'GTATCC'), - 'ovhgseq' : 'N', + 'compsite': '(?PCC[AT]GG)', + 'results': None, + 'site': 'CCWGG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('K',), + 'scd5': None, + 'charac': (2, -2, None, None, 'CCWGG'), + 'ovhgseq': 'W', + } +rest_dict['BciT130I'] = _temp() + +def _temp(): + return { + 'compsite': '(?PGTATCC)|(?PGGATAC)', + 'results': None, + 'site': 'GTATCC', + 'substrat': 'DNA', + 'fst3': 5, + 'fst5': 12, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (12, 5, None, None, 'GTATCC'), + 'ovhgseq': 'N', } rest_dict['BciVI'] = _temp() def _temp(): return { - 'compsite' : '(?PTGATCA)|(?PTGATCA)', - 'results' : None, - 'site' : 'TGATCA', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('C', 'F', 'J', 'M', 'N', 'O', 'R', 'S', 'U', 'W', 'Y'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'TGATCA'), - 'ovhgseq' : 'GATC', + 'compsite': '(?PTGATCA)', + 'results': None, + 'site': 'TGATCA', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('C', 'F', 'J', 'M', 'N', 'O', 'R', 'S', 'U', 'Y'), + 'scd5': None, + 'charac': (1, -1, None, None, 'TGATCA'), + 'ovhgseq': 'GATC', } rest_dict['BclI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC[CG]GG)|(?PCC[CG]GG)', - 'results' : None, - 'site' : 'CCSGG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('F', 'K'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CCSGG'), - 'ovhgseq' : 'S', + 'compsite': '(?PCC[CG]GG)', + 'results': None, + 'site': 'CCSGG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('F', 'K'), + 'scd5': None, + 'charac': (2, -2, None, None, 'CCSGG'), + 'ovhgseq': 'S', } rest_dict['BcnI'] = _temp() def _temp(): return { - 'compsite' : '(?PACTAGT)|(?PACTAGT)', - 'results' : None, - 'site' : 'ACTAGT', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'ACTAGT'), - 'ovhgseq' : 'CTAG', + 'compsite': '(?PGTCTC)|(?PGAGAC)', + 'results': None, + 'site': 'GTCTC', + 'substrat': 'DNA', + 'fst3': 5, + 'fst5': 6, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (6, 5, None, None, 'GTCTC'), + 'ovhgseq': 'NNNN', + } +rest_dict['BcoDI'] = _temp() + +def _temp(): + return { + 'compsite': '(?PACTAGT)', + 'results': None, + 'site': 'ACTAGT', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'ACTAGT'), + 'ovhgseq': 'CTAG', } rest_dict['BcuI'] = _temp() def _temp(): return { - 'compsite' : '(?PTGA......TCA)|(?PTGA......TCA)', - 'results' : None, - 'site' : 'TGANNNNNNTCA', - 'substrat' : 'DNA', - 'fst3' : -24, - 'fst5' : -10, - 'freq' : 4096, - 'size' : 12, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : 10, - 'suppl' : ('F',), - 'scd5' : 24, - 'charac' : (-10, -24, 24, 10, 'TGANNNNNNTCA'), - 'ovhgseq' : 'NN', + 'compsite': '(?PTGA......TCA)', + 'results': None, + 'site': 'TGANNNNNNTCA', + 'substrat': 'DNA', + 'fst3': -24, + 'fst5': -10, + 'freq': 4096, + 'size': 12, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': 10, + 'suppl': (), + 'scd5': 24, + 'charac': (-10, -24, 24, 10, 'TGANNNNNNTCA'), + 'ovhgseq': 'NN', } rest_dict['BdaI'] = _temp() def _temp(): return { - 'compsite' : '(?P[AT]CCGG[AT])|(?P[AT]CCGG[AT])', - 'results' : None, - 'site' : 'WCCGGW', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'WCCGGW'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?P[AT]CCGG[AT])', + 'results': None, + 'site': 'WCCGGW', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (1, -1, None, None, 'WCCGGW'), + 'ovhgseq': 'CCGG', } rest_dict['BetI'] = _temp() def _temp(): return { - 'compsite' : '(?PCTAG)|(?PCTAG)', - 'results' : None, - 'site' : 'CTAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTAG'), - 'ovhgseq' : 'TA', + 'compsite': '(?PCTAG)', + 'results': None, + 'site': 'CTAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CTAG'), + 'ovhgseq': 'TA', } rest_dict['BfaI'] = _temp() def _temp(): return { - 'compsite' : '(?PACTGGG)|(?PCCCAGT)', - 'results' : None, - 'site' : 'ACTGGG', - 'substrat' : 'DNA', - 'fst3' : 4, - 'fst5' : 11, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 1, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (11, 4, None, None, 'ACTGGG'), - 'ovhgseq' : 'N', + 'compsite': '(?PACTGGG)|(?PCCCAGT)', + 'results': None, + 'site': 'ACTGGG', + 'substrat': 'DNA', + 'fst3': 4, + 'fst5': 11, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (11, 4, None, None, 'ACTGGG'), + 'ovhgseq': 'N', } rest_dict['BfiI'] = _temp() def _temp(): return { - 'compsite' : '(?PCT[AG][CT]AG)|(?PCT[AG][CT]AG)', - 'results' : None, - 'site' : 'CTRYAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTRYAG'), - 'ovhgseq' : 'TRYA', + 'compsite': '(?PCT[AG][CT]AG)', + 'results': None, + 'site': 'CTRYAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CTRYAG'), + 'ovhgseq': 'TRYA', } rest_dict['BfmI'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]GCGC[CT])|(?P[AG]GCGC[CT])', - 'results' : None, - 'site' : 'RGCGCY', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'RGCGCY'), - 'ovhgseq' : 'GCGC', + 'compsite': '(?P[AG]GCGC[CT])', + 'results': None, + 'site': 'RGCGCY', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (5, -5, None, None, 'RGCGCY'), + 'ovhgseq': 'GCGC', } rest_dict['BfoI'] = _temp() def _temp(): return { - 'compsite' : '(?PCTTAAG)|(?PCTTAAG)', - 'results' : None, - 'site' : 'CTTAAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('M', 'O'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTTAAG'), - 'ovhgseq' : 'TTAA', + 'compsite': '(?PCTTAAG)', + 'results': None, + 'site': 'CTTAAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('M',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CTTAAG'), + 'ovhgseq': 'TTAA', } rest_dict['BfrI'] = _temp() def _temp(): return { - 'compsite' : '(?PACCTGC)|(?PGCAGGT)', - 'results' : None, - 'site' : 'ACCTGC', - 'substrat' : 'DNA', - 'fst3' : 8, - 'fst5' : 10, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (10, 8, None, None, 'ACCTGC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PACCTGC)|(?PGCAGGT)', + 'results': None, + 'site': 'ACCTGC', + 'substrat': 'DNA', + 'fst3': 8, + 'fst5': 10, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (10, 8, None, None, 'ACCTGC'), + 'ovhgseq': 'NNNN', } rest_dict['BfuAI'] = _temp() def _temp(): return { - 'compsite' : '(?PGATC)|(?PGATC)', - 'results' : None, - 'site' : 'GATC', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'GATC'), - 'ovhgseq' : 'GATC', + 'compsite': '(?PGATC)', + 'results': None, + 'site': 'GATC', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (0, 0, None, None, 'GATC'), + 'ovhgseq': 'GATC', } rest_dict['BfuCI'] = _temp() def _temp(): return { - 'compsite' : '(?PGTATCC)|(?PGGATAC)', - 'results' : None, - 'site' : 'GTATCC', - 'substrat' : 'DNA', - 'fst3' : 5, - 'fst5' : 12, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 1, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (12, 5, None, None, 'GTATCC'), - 'ovhgseq' : 'N', + 'compsite': '(?PGTATCC)|(?PGGATAC)', + 'results': None, + 'site': 'GTATCC', + 'substrat': 'DNA', + 'fst3': 5, + 'fst5': 12, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (12, 5, None, None, 'GTATCC'), + 'ovhgseq': 'N', } rest_dict['BfuI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCC.....GGC)|(?PGCC.....GGC)', - 'results' : None, - 'site' : 'GCCNNNNNGGC', - 'substrat' : 'DNA', - 'fst3' : -7, - 'fst5' : 7, - 'freq' : 4096, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : None, - 'suppl' : ('C', 'F', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (7, -7, None, None, 'GCCNNNNNGGC'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PGCC.....GGC)', + 'results': None, + 'site': 'GCCNNNNNGGC', + 'substrat': 'DNA', + 'fst3': -7, + 'fst5': 7, + 'freq': 4096, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': ('C', 'F', 'I', 'J', 'K', 'N', 'O', 'Q', 'R', 'U', 'V', 'X', 'Y'), + 'scd5': None, + 'charac': (7, -7, None, None, 'GCCNNNNNGGC'), + 'ovhgseq': 'NNN', } rest_dict['BglI'] = _temp() def _temp(): return { - 'compsite' : '(?PAGATCT)|(?PAGATCT)', - 'results' : None, - 'site' : 'AGATCT', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('B', 'C', 'F', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'AGATCT'), - 'ovhgseq' : 'GATC', + 'compsite': '(?PAGATCT)', + 'results': None, + 'site': 'AGATCT', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('B', 'C', 'F', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'X', 'Y'), + 'scd5': None, + 'charac': (1, -1, None, None, 'AGATCT'), + 'ovhgseq': 'GATC', } rest_dict['BglII'] = _temp() def _temp(): return { - 'compsite' : '(?PGGATC)|(?PGATCC)', - 'results' : None, - 'site' : 'GGATC', - 'substrat' : 'DNA', - 'fst3' : 5, - 'fst5' : 9, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (9, 5, None, None, 'GGATC'), - 'ovhgseq' : 'N', + 'compsite': '(?PGGATC)|(?PGATCC)', + 'results': None, + 'site': 'GGATC', + 'substrat': 'DNA', + 'fst3': 5, + 'fst5': 9, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (9, 5, None, None, 'GGATC'), + 'ovhgseq': 'N', } rest_dict['BinI'] = _temp() def _temp(): return { - 'compsite' : '(?PGC.GC)|(?PGC.GC)', - 'results' : None, - 'site' : 'GCNGC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GCNGC'), - 'ovhgseq' : 'N', + 'compsite': '(?PGC.GC)', + 'results': None, + 'site': 'GCNGC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (2, -2, None, None, 'GCNGC'), + 'ovhgseq': 'N', } rest_dict['BisI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCTAGG)|(?PCCTAGG)', - 'results' : None, - 'site' : 'CCTAGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('K', 'M', 'S'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCTAGG'), - 'ovhgseq' : 'CTAG', + 'compsite': '(?PCCTAGG)', + 'results': None, + 'site': 'CCTAGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('K', 'M', 'S'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCTAGG'), + 'ovhgseq': 'CTAG', } rest_dict['BlnI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCT.AGC)|(?PGCT.AGC)', - 'results' : None, - 'site' : 'GCTNAGC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GCTNAGC'), - 'ovhgseq' : 'TNA', + 'compsite': '(?PGCT.AGC)', + 'results': None, + 'site': 'GCTNAGC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (2, -2, None, None, 'GCTNAGC'), + 'ovhgseq': 'TNA', } rest_dict['BlpI'] = _temp() def _temp(): return { - 'compsite' : '(?PGC.GC)|(?PGC.GC)', - 'results' : None, - 'site' : 'GCNGC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 1, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GCNGC'), - 'ovhgseq' : 'N', + 'compsite': '(?PGC.GC)', + 'results': None, + 'site': 'GCNGC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (3, -3, None, None, 'GCNGC'), + 'ovhgseq': 'N', } rest_dict['BlsI'] = _temp() def _temp(): return { - 'compsite' : '(?PAGTACT)|(?PAGTACT)', - 'results' : None, - 'site' : 'AGTACT', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('V',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'AGTACT'), - 'ovhgseq' : '', + 'compsite': '(?PAGTACT)', + 'results': None, + 'site': 'AGTACT', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('V',), + 'scd5': None, + 'charac': (3, -3, None, None, 'AGTACT'), + 'ovhgseq': '', } rest_dict['BmcAI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC.GG)|(?PCC.GG)', - 'results' : None, - 'site' : 'CCNGG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CCNGG'), - 'ovhgseq' : 'N', + 'compsite': '(?PCC.GG)', + 'results': None, + 'site': 'CCNGG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (2, -2, None, None, 'CCNGG'), + 'ovhgseq': 'N', } rest_dict['Bme1390I'] = _temp() def _temp(): return { - 'compsite' : '(?PGG[AT]CC)|(?PGG[AT]CC)', - 'results' : None, - 'site' : 'GGWCC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGWCC'), - 'ovhgseq' : 'GWC', + 'compsite': '(?PGG[AT]CC)', + 'results': None, + 'site': 'GGWCC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGWCC'), + 'ovhgseq': 'GWC', } rest_dict['Bme18I'] = _temp() def _temp(): return { - 'compsite' : '(?PGAC.....GTC)|(?PGAC.....GTC)', - 'results' : None, - 'site' : 'GACNNNNNGTC', - 'substrat' : 'DNA', - 'fst3' : -6, - 'fst5' : 6, - 'freq' : 4096, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 1, - 'scd3' : None, - 'suppl' : ('V',), - 'scd5' : None, - 'charac' : (6, -6, None, None, 'GACNNNNNGTC'), - 'ovhgseq' : 'N', + 'compsite': '(?PC)|(?PG)', + 'results': None, + 'site': 'C', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 3, + 'freq': 4, + 'size': 1, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (3, 0, None, None, 'C'), + 'ovhgseq': 'NN', + } +rest_dict['BmeDI'] = _temp() + +def _temp(): + return { + 'compsite': '(?PGAC.....GTC)', + 'results': None, + 'site': 'GACNNNNNGTC', + 'substrat': 'DNA', + 'fst3': -6, + 'fst5': 6, + 'freq': 4096, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': ('V',), + 'scd5': None, + 'charac': (6, -6, None, None, 'GACNNNNNGTC'), + 'ovhgseq': 'N', } rest_dict['BmeRI'] = _temp() def _temp(): return { - 'compsite' : '(?PC[CT]CG[AG]G)|(?PC[CT]CG[AG]G)', - 'results' : None, - 'site' : 'CYCGRG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('K',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CYCGRG'), - 'ovhgseq' : 'YCGR', + 'compsite': '(?PC[CT]CG[AG]G)', + 'results': None, + 'site': 'CYCGRG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('B', 'K'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CYCGRG'), + 'ovhgseq': 'YCGR', } rest_dict['BmeT110I'] = _temp() def _temp(): return { - 'compsite' : '(?PCACGTC)|(?PGACGTG)', - 'results' : None, - 'site' : 'CACGTC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'CACGTC'), - 'ovhgseq' : '', + 'compsite': '(?PCACGTC)|(?PGACGTG)', + 'results': None, + 'site': 'CACGTC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (3, -3, None, None, 'CACGTC'), + 'ovhgseq': '', } rest_dict['BmgBI'] = _temp() def _temp(): return { - 'compsite' : '(?PG[GT]GCCC)|(?PGGGC[AC]C)', - 'results' : None, - 'site' : 'GKGCCC', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 2048, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'GKGCCC'), - 'ovhgseq' : None, + 'compsite': '(?PG[GT]GCCC)|(?PGGGC[AC]C)', + 'results': None, + 'site': 'GKGCCC', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 2048, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'GKGCCC'), + 'ovhgseq': None, } rest_dict['BmgI'] = _temp() def _temp(): return { - 'compsite' : '(?PGG.CC)|(?PGG.CC)', - 'results' : None, - 'site' : 'GGNCC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('K',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GGNCC'), - 'ovhgseq' : 'N', + 'compsite': '(?PGG.CC)', + 'results': None, + 'site': 'GGNCC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('K',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGNCC'), + 'ovhgseq': 'GNC', } rest_dict['BmgT120I'] = _temp() def _temp(): return { - 'compsite' : '(?PGG..CC)|(?PGG..CC)', - 'results' : None, - 'site' : 'GGNNCC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 256, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('V',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GGNNCC'), - 'ovhgseq' : '', + 'compsite': '(?PGG..CC)', + 'results': None, + 'site': 'GGNNCC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 256, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('V',), + 'scd5': None, + 'charac': (3, -3, None, None, 'GGNNCC'), + 'ovhgseq': '', } rest_dict['BmiI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC.GG)|(?PCC.GG)', - 'results' : None, - 'site' : 'CCNGG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('V',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CCNGG'), - 'ovhgseq' : 'N', + 'compsite': '(?PCC.GG)', + 'results': None, + 'site': 'CCNGG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('V',), + 'scd5': None, + 'charac': (2, -2, None, None, 'CCNGG'), + 'ovhgseq': 'N', } rest_dict['BmrFI'] = _temp() def _temp(): return { - 'compsite' : '(?PACTGGG)|(?PCCCAGT)', - 'results' : None, - 'site' : 'ACTGGG', - 'substrat' : 'DNA', - 'fst3' : 4, - 'fst5' : 11, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 1, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (11, 4, None, None, 'ACTGGG'), - 'ovhgseq' : 'N', + 'compsite': '(?PACTGGG)|(?PCCCAGT)', + 'results': None, + 'site': 'ACTGGG', + 'substrat': 'DNA', + 'fst3': 4, + 'fst5': 11, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (11, 4, None, None, 'ACTGGG'), + 'ovhgseq': 'N', } rest_dict['BmrI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCATC)|(?PGATGC)', - 'results' : None, - 'site' : 'GCATC', - 'substrat' : 'DNA', - 'fst3' : 9, - 'fst5' : 10, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (10, 9, None, None, 'GCATC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PGCATC)|(?PGATGC)', + 'results': None, + 'site': 'GCATC', + 'substrat': 'DNA', + 'fst3': 9, + 'fst5': 10, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (10, 9, None, None, 'GCATC'), + 'ovhgseq': 'NNNN', } rest_dict['BmsI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCTAGC)|(?PGCTAGC)', - 'results' : None, - 'site' : 'GCTAGC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('I', 'N', 'V'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GCTAGC'), - 'ovhgseq' : 'CTAG', + 'compsite': '(?PGCTAGC)', + 'results': None, + 'site': 'GCTAGC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('I', 'N', 'V'), + 'scd5': None, + 'charac': (5, -5, None, None, 'GCTAGC'), + 'ovhgseq': 'CTAG', } rest_dict['BmtI'] = _temp() def _temp(): return { - 'compsite' : '(?PACTGGG)|(?PCCCAGT)', - 'results' : None, - 'site' : 'ACTGGG', - 'substrat' : 'DNA', - 'fst3' : 4, - 'fst5' : 11, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 1, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (11, 4, None, None, 'ACTGGG'), - 'ovhgseq' : 'N', + 'compsite': '(?PACTGGG)|(?PCCCAGT)', + 'results': None, + 'site': 'ACTGGG', + 'substrat': 'DNA', + 'fst3': 4, + 'fst5': 11, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (11, 4, None, None, 'ACTGGG'), + 'ovhgseq': 'N', } rest_dict['BmuI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAC....GTC)|(?PGAC....GTC)', - 'results' : None, - 'site' : 'GACNNNNGTC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 10, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GACNNNNGTC'), - 'ovhgseq' : '', + 'compsite': '(?PGAC....GTC)', + 'results': None, + 'site': 'GACNNNNGTC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 10, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (5, -5, None, None, 'GACNNNNGTC'), + 'ovhgseq': '', } rest_dict['BoxI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAAGAC)|(?PGTCTTC)', - 'results' : None, - 'site' : 'GAAGAC', - 'substrat' : 'DNA', - 'fst3' : 6, - 'fst5' : 8, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (8, 6, None, None, 'GAAGAC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PGAAGAC)|(?PGTCTTC)', + 'results': None, + 'site': 'GAAGAC', + 'substrat': 'DNA', + 'fst3': 6, + 'fst5': 8, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (8, 6, None, None, 'GAAGAC'), + 'ovhgseq': 'NNNN', } rest_dict['BpiI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAG.....CTC)|(?PGAG.....CTC)', - 'results' : None, - 'site' : 'GAGNNNNNCTC', - 'substrat' : 'DNA', - 'fst3' : -24, - 'fst5' : -8, - 'freq' : 4096, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 5, - 'scd3' : 8, - 'suppl' : ('F',), - 'scd5' : 24, - 'charac' : (-8, -24, 24, 8, 'GAGNNNNNCTC'), - 'ovhgseq' : 'NNNNN', + 'compsite': '(?PGAG.....CTC)', + 'results': None, + 'site': 'GAGNNNNNCTC', + 'substrat': 'DNA', + 'fst3': -24, + 'fst5': -8, + 'freq': 4096, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 5, + 'scd3': 8, + 'suppl': ('F',), + 'scd5': 24, + 'charac': (-8, -24, 24, 8, 'GAGNNNNNCTC'), + 'ovhgseq': 'NNNNN', } rest_dict['BplI'] = _temp() def _temp(): return { - 'compsite' : '(?PCTGGAG)|(?PCTCCAG)', - 'results' : None, - 'site' : 'CTGGAG', - 'substrat' : 'DNA', - 'fst3' : 14, - 'fst5' : 22, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('I', 'N'), - 'scd5' : None, - 'charac' : (22, 14, None, None, 'CTGGAG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PCTGGAG)|(?PCTCCAG)', + 'results': None, + 'site': 'CTGGAG', + 'substrat': 'DNA', + 'fst3': 14, + 'fst5': 22, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('I', 'N'), + 'scd5': None, + 'charac': (22, 14, None, None, 'CTGGAG'), + 'ovhgseq': 'NN', } rest_dict['BpmI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCT.AGC)|(?PGCT.AGG)', - 'results' : None, - 'site' : 'CCTNAGC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('F', 'I', 'N', 'V'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CCTNAGC'), - 'ovhgseq' : 'TNA', + 'compsite': '(?PCCT.AGC)|(?PGCT.AGG)', + 'results': None, + 'site': 'CCTNAGC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('F', 'I', 'N', 'V'), + 'scd5': None, + 'charac': (2, -2, None, None, 'CCTNAGC'), + 'ovhgseq': 'TNA', } rest_dict['Bpu10I'] = _temp() def _temp(): return { - 'compsite' : '(?PGCT.AGC)|(?PGCT.AGC)', - 'results' : None, - 'site' : 'GCTNAGC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('F', 'K'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GCTNAGC'), - 'ovhgseq' : 'TNA', + 'compsite': '(?PGCT.AGC)', + 'results': None, + 'site': 'GCTNAGC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('F', 'K'), + 'scd5': None, + 'charac': (2, -2, None, None, 'GCTNAGC'), + 'ovhgseq': 'TNA', } rest_dict['Bpu1102I'] = _temp() def _temp(): return { - 'compsite' : '(?PTTCGAA)|(?PTTCGAA)', - 'results' : None, - 'site' : 'TTCGAA', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'TTCGAA'), - 'ovhgseq' : 'CG', + 'compsite': '(?PTTCGAA)', + 'results': None, + 'site': 'TTCGAA', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (2, -2, None, None, 'TTCGAA'), + 'ovhgseq': 'CG', } rest_dict['Bpu14I'] = _temp() def _temp(): return { - 'compsite' : '(?PGAAGAC)|(?PGTCTTC)', - 'results' : None, - 'site' : 'GAAGAC', - 'substrat' : 'DNA', - 'fst3' : 6, - 'fst5' : 8, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('M',), - 'scd5' : None, - 'charac' : (8, 6, None, None, 'GAAGAC'), - 'ovhgseq' : 'NNNN', - } -rest_dict['BpuAI'] = _temp() - -def _temp(): - return { - 'compsite' : '(?PCTTGAG)|(?PCTCAAG)', - 'results' : None, - 'site' : 'CTTGAG', - 'substrat' : 'DNA', - 'fst3' : 14, - 'fst5' : 22, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (22, 14, None, None, 'CTTGAG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PCTTGAG)|(?PCTCAAG)', + 'results': None, + 'site': 'CTTGAG', + 'substrat': 'DNA', + 'fst3': 14, + 'fst5': 22, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (22, 14, None, None, 'CTTGAG'), + 'ovhgseq': 'NN', } rest_dict['BpuEI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC[CG]GG)|(?PCC[CG]GG)', - 'results' : None, - 'site' : 'CCSGG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('V',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CCSGG'), - 'ovhgseq' : 'S', + 'compsite': '(?PCC[CG]GG)', + 'results': None, + 'site': 'CCSGG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('V',), + 'scd5': None, + 'charac': (2, -2, None, None, 'CCSGG'), + 'ovhgseq': 'S', } rest_dict['BpuMI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGATCG)|(?PCGATCG)', - 'results' : None, - 'site' : 'CGATCG', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('V',), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'CGATCG'), - 'ovhgseq' : 'AT', + 'compsite': '(?PCGATCG)', + 'results': None, + 'site': 'CGATCG', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('V',), + 'scd5': None, + 'charac': (4, -4, None, None, 'CGATCG'), + 'ovhgseq': 'AT', } rest_dict['BpvUI'] = _temp() def _temp(): return { - 'compsite' : '(?PATCGAT)|(?PATCGAT)', - 'results' : None, - 'site' : 'ATCGAT', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'ATCGAT'), - 'ovhgseq' : 'CG', + 'compsite': '(?PATCGAT)', + 'results': None, + 'site': 'ATCGAT', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (2, -2, None, None, 'ATCGAT'), + 'ovhgseq': 'CG', } rest_dict['Bsa29I'] = _temp() def _temp(): return { - 'compsite' : '(?P[CT]ACGT[AG])|(?P[CT]ACGT[AG])', - 'results' : None, - 'site' : 'YACGTR', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'YACGTR'), - 'ovhgseq' : '', + 'compsite': '(?P[CT]ACGT[AG])', + 'results': None, + 'site': 'YACGTR', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (3, -3, None, None, 'YACGTR'), + 'ovhgseq': '', } rest_dict['BsaAI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAT....ATC)|(?PGAT....ATC)', - 'results' : None, - 'site' : 'GATNNNNATC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 10, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GATNNNNATC'), - 'ovhgseq' : '', + 'compsite': '(?PGAT....ATC)', + 'results': None, + 'site': 'GATNNNNATC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 10, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (5, -5, None, None, 'GATNNNNATC'), + 'ovhgseq': '', } rest_dict['BsaBI'] = _temp() def _temp(): return { - 'compsite' : '(?PG[AG]CG[CT]C)|(?PG[AG]CG[CT]C)', - 'results' : None, - 'site' : 'GRCGYC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GRCGYC'), - 'ovhgseq' : 'CG', + 'compsite': '(?PG[AG]CG[CT]C)', + 'results': None, + 'site': 'GRCGYC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (2, -2, None, None, 'GRCGYC'), + 'ovhgseq': 'CG', } rest_dict['BsaHI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGTCTC)|(?PGAGACC)', - 'results' : None, - 'site' : 'GGTCTC', - 'substrat' : 'DNA', - 'fst3' : 5, - 'fst5' : 7, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (7, 5, None, None, 'GGTCTC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PGGTCTC)|(?PGAGACC)', + 'results': None, + 'site': 'GGTCTC', + 'substrat': 'DNA', + 'fst3': 5, + 'fst5': 7, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (7, 5, None, None, 'GGTCTC'), + 'ovhgseq': 'NNNN', } rest_dict['BsaI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC..GG)|(?PCC..GG)', - 'results' : None, - 'site' : 'CCNNGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCNNGG'), - 'ovhgseq' : 'CNNG', + 'compsite': '(?PCC..GG)', + 'results': None, + 'site': 'CCNNGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCNNGG'), + 'ovhgseq': 'CNNG', } rest_dict['BsaJI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAATGC)|(?PGCATTC)', - 'results' : None, - 'site' : 'GAATGC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 7, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('R',), - 'scd5' : None, - 'charac' : (7, -1, None, None, 'GAATGC'), - 'ovhgseq' : 'CN', - } -rest_dict['BsaMI'] = _temp() - -def _temp(): - return { - 'compsite' : '(?P[AT]CCGG[AT])|(?P[AT]CCGG[AT])', - 'results' : None, - 'site' : 'WCCGGW', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'WCCGGW'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?P[AT]CCGG[AT])', + 'results': None, + 'site': 'WCCGGW', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'WCCGGW'), + 'ovhgseq': 'CCGG', } rest_dict['BsaWI'] = _temp() def _temp(): return { - 'compsite' : '(?PAC.....CTCC)|(?PGGAG.....GT)', - 'results' : None, - 'site' : 'ACNNNNNCTCC', - 'substrat' : 'DNA', - 'fst3' : -23, - 'fst5' : -9, - 'freq' : 4096, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : 7, - 'suppl' : ('N',), - 'scd5' : 21, - 'charac' : (-9, -23, 21, 7, 'ACNNNNNCTCC'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PAC.....CTCC)|(?PGGAG.....GT)', + 'results': None, + 'site': 'ACNNNNNCTCC', + 'substrat': 'DNA', + 'fst3': -23, + 'fst5': -9, + 'freq': 4096, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': 7, + 'suppl': ('N',), + 'scd5': 21, + 'charac': (-9, -23, 21, 7, 'ACNNNNNCTCC'), + 'ovhgseq': 'NNN', } rest_dict['BsaXI'] = _temp() def _temp(): return { - 'compsite' : '(?PCAACAC)|(?PGTGTTG)', - 'results' : None, - 'site' : 'CAACAC', - 'substrat' : 'DNA', - 'fst3' : 19, - 'fst5' : 27, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (27, 19, None, None, 'CAACAC'), - 'ovhgseq' : 'NN', + 'compsite': '(?PCAACAC)|(?PGTGTTG)', + 'results': None, + 'site': 'CAACAC', + 'substrat': 'DNA', + 'fst3': 19, + 'fst5': 27, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (27, 19, None, None, 'CAACAC'), + 'ovhgseq': 'NN', } rest_dict['BsbI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC.......GG)|(?PCC.......GG)', - 'results' : None, - 'site' : 'CCNNNNNNNGG', - 'substrat' : 'DNA', - 'fst3' : -7, - 'fst5' : 7, - 'freq' : 256, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (7, -7, None, None, 'CCNNNNNNNGG'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PCC.......GG)', + 'results': None, + 'site': 'CCNNNNNNNGG', + 'substrat': 'DNA', + 'fst3': -7, + 'fst5': 7, + 'freq': 256, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (7, -7, None, None, 'CCNNNNNNNGG'), + 'ovhgseq': 'NNN', } rest_dict['Bsc4I'] = _temp() def _temp(): return { - 'compsite' : '(?PGCATC)|(?PGATGC)', - 'results' : None, - 'site' : 'GCATC', - 'substrat' : 'DNA', - 'fst3' : 6, - 'fst5' : 9, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (9, 6, None, None, 'GCATC'), - 'ovhgseq' : 'NN', + 'compsite': '(?PGCATC)|(?PGATGC)', + 'results': None, + 'site': 'GCATC', + 'substrat': 'DNA', + 'fst3': 6, + 'fst5': 9, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (9, 6, None, None, 'GCATC'), + 'ovhgseq': 'NN', } rest_dict['BscAI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCCGT)|(?PACGGG)', - 'results' : None, - 'site' : 'CCCGT', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'CCCGT'), - 'ovhgseq' : None, + 'compsite': '(?PCCCGT)|(?PACGGG)', + 'results': None, + 'site': 'CCCGT', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'CCCGT'), + 'ovhgseq': None, } rest_dict['BscGI'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]CCGG[CT])|(?P[AG]CCGG[CT])', - 'results' : None, - 'site' : 'RCCGGY', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'RCCGGY'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?P[AG]CCGG[CT])', + 'results': None, + 'site': 'RCCGGY', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'RCCGGY'), + 'ovhgseq': 'CCGG', } rest_dict['Bse118I'] = _temp() def _temp(): return { - 'compsite' : '(?PACTGG)|(?PCCAGT)', - 'results' : None, - 'site' : 'ACTGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 6, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (6, -1, None, None, 'ACTGG'), - 'ovhgseq' : 'GN', + 'compsite': '(?PACTGG)|(?PCCAGT)', + 'results': None, + 'site': 'ACTGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 6, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (6, -1, None, None, 'ACTGG'), + 'ovhgseq': 'GN', } rest_dict['Bse1I'] = _temp() def _temp(): return { - 'compsite' : '(?PCCT.AGG)|(?PCCT.AGG)', - 'results' : None, - 'site' : 'CCTNAGG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CCTNAGG'), - 'ovhgseq' : 'TNA', + 'compsite': '(?PCCT.AGG)', + 'results': None, + 'site': 'CCTNAGG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (2, -2, None, None, 'CCTNAGG'), + 'ovhgseq': 'TNA', } rest_dict['Bse21I'] = _temp() def _temp(): return { - 'compsite' : '(?PGCAATG)|(?PCATTGC)', - 'results' : None, - 'site' : 'GCAATG', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 8, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (8, 0, None, None, 'GCAATG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PGCAATG)|(?PCATTGC)', + 'results': None, + 'site': 'GCAATG', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 8, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (8, 0, None, None, 'GCAATG'), + 'ovhgseq': 'NN', } rest_dict['Bse3DI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAT....ATC)|(?PGAT....ATC)', - 'results' : None, - 'site' : 'GATNNNNATC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 10, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GATNNNNATC'), - 'ovhgseq' : '', + 'compsite': '(?PGAT....ATC)', + 'results': None, + 'site': 'GATNNNNATC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 10, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (5, -5, None, None, 'GATNNNNATC'), + 'ovhgseq': '', } rest_dict['Bse8I'] = _temp() def _temp(): return { - 'compsite' : '(?PTCCGGA)|(?PTCCGGA)', - 'results' : None, - 'site' : 'TCCGGA', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('C', 'M'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'TCCGGA'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?PTCCGGA)', + 'results': None, + 'site': 'TCCGGA', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('C', 'M'), + 'scd5': None, + 'charac': (1, -1, None, None, 'TCCGGA'), + 'ovhgseq': 'CCGG', } rest_dict['BseAI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC[AT]GG)|(?PCC[AT]GG)', - 'results' : None, - 'site' : 'CCWGG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('C',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CCWGG'), - 'ovhgseq' : 'W', + 'compsite': '(?PCC[AT]GG)', + 'results': None, + 'site': 'CCWGG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('C',), + 'scd5': None, + 'charac': (2, -2, None, None, 'CCWGG'), + 'ovhgseq': 'W', } rest_dict['BseBI'] = _temp() def _temp(): return { - 'compsite' : '(?PATCGAT)|(?PATCGAT)', - 'results' : None, - 'site' : 'ATCGAT', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('C',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'ATCGAT'), - 'ovhgseq' : 'CG', + 'compsite': '(?PATCGAT)', + 'results': None, + 'site': 'ATCGAT', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('C',), + 'scd5': None, + 'charac': (2, -2, None, None, 'ATCGAT'), + 'ovhgseq': 'CG', } rest_dict['BseCI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC..GG)|(?PCC..GG)', - 'results' : None, - 'site' : 'CCNNGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCNNGG'), - 'ovhgseq' : 'CNNG', + 'compsite': '(?PCC..GG)', + 'results': None, + 'site': 'CCNNGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCNNGG'), + 'ovhgseq': 'CNNG', } rest_dict['BseDI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGATG)|(?PCATCC)', - 'results' : None, - 'site' : 'GGATG', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 7, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (7, 0, None, None, 'GGATG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PGGATG)|(?PCATCC)', + 'results': None, + 'site': 'GGATG', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 7, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (7, 0, None, None, 'GGATG'), + 'ovhgseq': 'NN', } rest_dict['BseGI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAT....ATC)|(?PGAT....ATC)', - 'results' : None, - 'site' : 'GATNNNNATC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 10, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GATNNNNATC'), - 'ovhgseq' : '', + 'compsite': '(?PGAT....ATC)', + 'results': None, + 'site': 'GATNNNNATC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 10, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (5, -5, None, None, 'GATNNNNATC'), + 'ovhgseq': '', } rest_dict['BseJI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC.......GG)|(?PCC.......GG)', - 'results' : None, - 'site' : 'CCNNNNNNNGG', - 'substrat' : 'DNA', - 'fst3' : -7, - 'fst5' : 7, - 'freq' : 256, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (7, -7, None, None, 'CCNNNNNNNGG'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PCC.......GG)', + 'results': None, + 'site': 'CCNNNNNNNGG', + 'substrat': 'DNA', + 'fst3': -7, + 'fst5': 7, + 'freq': 256, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (7, -7, None, None, 'CCNNNNNNNGG'), + 'ovhgseq': 'NNN', } rest_dict['BseLI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCAATG)|(?PCATTGC)', - 'results' : None, - 'site' : 'GCAATG', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 8, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (8, 0, None, None, 'GCAATG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PGCAATG)|(?PCATTGC)', + 'results': None, + 'site': 'GCAATG', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 8, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (8, 0, None, None, 'GCAATG'), + 'ovhgseq': 'NN', } rest_dict['BseMI'] = _temp() def _temp(): return { - 'compsite' : '(?PCTCAG)|(?PCTGAG)', - 'results' : None, - 'site' : 'CTCAG', - 'substrat' : 'DNA', - 'fst3' : 8, - 'fst5' : 15, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (15, 8, None, None, 'CTCAG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PCTCAG)|(?PCTGAG)', + 'results': None, + 'site': 'CTCAG', + 'substrat': 'DNA', + 'fst3': 8, + 'fst5': 15, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (15, 8, None, None, 'CTCAG'), + 'ovhgseq': 'NN', } rest_dict['BseMII'] = _temp() def _temp(): return { - 'compsite' : '(?PACTGG)|(?PCCAGT)', - 'results' : None, - 'site' : 'ACTGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 6, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (6, -1, None, None, 'ACTGG'), - 'ovhgseq' : 'GN', + 'compsite': '(?PACTGG)|(?PCCAGT)', + 'results': None, + 'site': 'ACTGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 6, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (6, -1, None, None, 'ACTGG'), + 'ovhgseq': 'GN', } rest_dict['BseNI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCGCGC)|(?PGCGCGC)', - 'results' : None, - 'site' : 'GCGCGC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GCGCGC'), - 'ovhgseq' : 'CGCG', + 'compsite': '(?PGCGCGC)', + 'results': None, + 'site': 'GCGCGC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'GCGCGC'), + 'ovhgseq': 'CGCG', } rest_dict['BsePI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAGGAG)|(?PCTCCTC)', - 'results' : None, - 'site' : 'GAGGAG', - 'substrat' : 'DNA', - 'fst3' : 8, - 'fst5' : 16, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (16, 8, None, None, 'GAGGAG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PGAGGAG)|(?PCTCCTC)', + 'results': None, + 'site': 'GAGGAG', + 'substrat': 'DNA', + 'fst3': 8, + 'fst5': 16, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (16, 8, None, None, 'GAGGAG'), + 'ovhgseq': 'NN', } rest_dict['BseRI'] = _temp() def _temp(): return { - 'compsite' : '(?PG[GT]GC[AC]C)|(?PG[GT]GC[AC]C)', - 'results' : None, - 'site' : 'GKGCMC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GKGCMC'), - 'ovhgseq' : 'KGCM', + 'compsite': '(?PG[GT]GC[AC]C)', + 'results': None, + 'site': 'GKGCMC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (5, -5, None, None, 'GKGCMC'), + 'ovhgseq': 'KGCM', } rest_dict['BseSI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGGCCG)|(?PCGGCCG)', - 'results' : None, - 'site' : 'CGGCCG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CGGCCG'), - 'ovhgseq' : 'GGCC', + 'compsite': '(?PCGGCCG)', + 'results': None, + 'site': 'CGGCCG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CGGCCG'), + 'ovhgseq': 'GGCC', } rest_dict['BseX3I'] = _temp() def _temp(): return { - 'compsite' : '(?PGCAGC)|(?PGCTGC)', - 'results' : None, - 'site' : 'GCAGC', - 'substrat' : 'DNA', - 'fst3' : 12, - 'fst5' : 13, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (13, 12, None, None, 'GCAGC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PGCAGC)|(?PGCTGC)', + 'results': None, + 'site': 'GCAGC', + 'substrat': 'DNA', + 'fst3': 12, + 'fst5': 13, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (13, 12, None, None, 'GCAGC'), + 'ovhgseq': 'NNNN', } rest_dict['BseXI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCCAGC)|(?PGCTGGG)', - 'results' : None, - 'site' : 'CCCAGC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCCAGC'), - 'ovhgseq' : 'CCAG', + 'compsite': '(?PCCCAGC)|(?PGCTGGG)', + 'results': None, + 'site': 'CCCAGC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCCAGC'), + 'ovhgseq': 'CCAG', } rest_dict['BseYI'] = _temp() def _temp(): return { - 'compsite' : '(?PGTGCAG)|(?PCTGCAC)', - 'results' : None, - 'site' : 'GTGCAG', - 'substrat' : 'DNA', - 'fst3' : 14, - 'fst5' : 22, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (22, 14, None, None, 'GTGCAG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PGTGCAG)|(?PCTGCAC)', + 'results': None, + 'site': 'GTGCAG', + 'substrat': 'DNA', + 'fst3': 14, + 'fst5': 22, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (22, 14, None, None, 'GTGCAG'), + 'ovhgseq': 'NN', } rest_dict['BsgI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGCG)|(?PCGCG)', - 'results' : None, - 'site' : 'CGCG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CGCG'), - 'ovhgseq' : '', + 'compsite': '(?PCGCG)', + 'results': None, + 'site': 'CGCG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (2, -2, None, None, 'CGCG'), + 'ovhgseq': '', } rest_dict['Bsh1236I'] = _temp() def _temp(): return { - 'compsite' : '(?PCG[AG][CT]CG)|(?PCG[AG][CT]CG)', - 'results' : None, - 'site' : 'CGRYCG', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'CGRYCG'), - 'ovhgseq' : 'RY', + 'compsite': '(?PCG[AG][CT]CG)', + 'results': None, + 'site': 'CGRYCG', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (4, -4, None, None, 'CGRYCG'), + 'ovhgseq': 'RY', } rest_dict['Bsh1285I'] = _temp() def _temp(): return { - 'compsite' : '(?PGGCC)|(?PGGCC)', - 'results' : None, - 'site' : 'GGCC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('C',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GGCC'), - 'ovhgseq' : '', + 'compsite': '(?PGGCC)', + 'results': None, + 'site': 'GGCC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('C',), + 'scd5': None, + 'charac': (2, -2, None, None, 'GGCC'), + 'ovhgseq': '', } rest_dict['BshFI'] = _temp() def _temp(): return { - 'compsite' : '(?PGG[CT][AG]CC)|(?PGG[CT][AG]CC)', - 'results' : None, - 'site' : 'GGYRCC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGYRCC'), - 'ovhgseq' : 'GYRC', + 'compsite': '(?PGG[CT][AG]CC)', + 'results': None, + 'site': 'GGYRCC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGYRCC'), + 'ovhgseq': 'GYRC', } rest_dict['BshNI'] = _temp() def _temp(): return { - 'compsite' : '(?PACCGGT)|(?PACCGGT)', - 'results' : None, - 'site' : 'ACCGGT', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'ACCGGT'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?PACCGGT)', + 'results': None, + 'site': 'ACCGGT', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('B', 'F'), + 'scd5': None, + 'charac': (1, -1, None, None, 'ACCGGT'), + 'ovhgseq': 'CCGG', } rest_dict['BshTI'] = _temp() def _temp(): return { - 'compsite' : '(?PATCGAT)|(?PATCGAT)', - 'results' : None, - 'site' : 'ATCGAT', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('V',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'ATCGAT'), - 'ovhgseq' : 'CG', + 'compsite': '(?PATCGAT)', + 'results': None, + 'site': 'ATCGAT', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('V',), + 'scd5': None, + 'charac': (2, -2, None, None, 'ATCGAT'), + 'ovhgseq': 'CG', } rest_dict['BshVI'] = _temp() def _temp(): return { - 'compsite' : '(?PCG[AG][CT]CG)|(?PCG[AG][CT]CG)', - 'results' : None, - 'site' : 'CGRYCG', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'CGRYCG'), - 'ovhgseq' : 'RY', + 'compsite': '(?PCG[AG][CT]CG)', + 'results': None, + 'site': 'CGRYCG', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (4, -4, None, None, 'CGRYCG'), + 'ovhgseq': 'RY', } rest_dict['BsiEI'] = _temp() def _temp(): return { - 'compsite' : '(?PG[AT]GC[AT]C)|(?PG[AT]GC[AT]C)', - 'results' : None, - 'site' : 'GWGCWC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GWGCWC'), - 'ovhgseq' : 'WGCW', + 'compsite': '(?PG[AT]GC[AT]C)', + 'results': None, + 'site': 'GWGCWC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (5, -5, None, None, 'GWGCWC'), + 'ovhgseq': 'WGCW', } rest_dict['BsiHKAI'] = _temp() def _temp(): return { - 'compsite' : '(?PC[CT]CG[AG]G)|(?PC[CT]CG[AG]G)', - 'results' : None, - 'site' : 'CYCGRG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('Q', 'X'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CYCGRG'), - 'ovhgseq' : 'YCGR', + 'compsite': '(?PC[CT]CG[AG]G)', + 'results': None, + 'site': 'CYCGRG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('Q', 'X'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CYCGRG'), + 'ovhgseq': 'YCGR', } rest_dict['BsiHKCI'] = _temp() def _temp(): return { - 'compsite' : '(?PCACGAG)|(?PCTCGTG)', - 'results' : None, - 'site' : 'CACGAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CACGAG'), - 'ovhgseq' : 'ACGA', + 'compsite': '(?PCACGAG)|(?PCTCGTG)', + 'results': None, + 'site': 'CACGAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (1, -1, None, None, 'CACGAG'), + 'ovhgseq': 'ACGA', } rest_dict['BsiI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCGG)|(?PCCGG)', - 'results' : None, - 'site' : 'CCGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('C',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCGG'), - 'ovhgseq' : 'CG', + 'compsite': '(?PCCGG)', + 'results': None, + 'site': 'CCGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('C',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCGG'), + 'ovhgseq': 'CG', } rest_dict['BsiSI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGTACG)|(?PCGTACG)', - 'results' : None, - 'site' : 'CGTACG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('M', 'N', 'O'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CGTACG'), - 'ovhgseq' : 'GTAC', + 'compsite': '(?PCGTACG)', + 'results': None, + 'site': 'CGTACG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CGTACG'), + 'ovhgseq': 'GTAC', } rest_dict['BsiWI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC.......GG)|(?PCC.......GG)', - 'results' : None, - 'site' : 'CCNNNNNNNGG', - 'substrat' : 'DNA', - 'fst3' : -7, - 'fst5' : 7, - 'freq' : 256, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (7, -7, None, None, 'CCNNNNNNNGG'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PCC.......GG)', + 'results': None, + 'site': 'CCNNNNNNNGG', + 'substrat': 'DNA', + 'fst3': -7, + 'fst5': 7, + 'freq': 256, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (7, -7, None, None, 'CCNNNNNNNGG'), + 'ovhgseq': 'NNN', } rest_dict['BsiYI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGGAC)|(?PGTCCC)', - 'results' : None, - 'site' : 'GGGAC', - 'substrat' : 'DNA', - 'fst3' : 14, - 'fst5' : 15, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (15, 14, None, None, 'GGGAC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PGGGAC)|(?PGTCCC)', + 'results': None, + 'site': 'GGGAC', + 'substrat': 'DNA', + 'fst3': 14, + 'fst5': 15, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (15, 14, None, None, 'GGGAC'), + 'ovhgseq': 'NNNN', } rest_dict['BslFI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC.......GG)|(?PCC.......GG)', - 'results' : None, - 'site' : 'CCNNNNNNNGG', - 'substrat' : 'DNA', - 'fst3' : -7, - 'fst5' : 7, - 'freq' : 256, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : None, - 'suppl' : ('N', 'W'), - 'scd5' : None, - 'charac' : (7, -7, None, None, 'CCNNNNNNNGG'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PCC.......GG)', + 'results': None, + 'site': 'CCNNNNNNNGG', + 'substrat': 'DNA', + 'fst3': -7, + 'fst5': 7, + 'freq': 256, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (7, -7, None, None, 'CCNNNNNNNGG'), + 'ovhgseq': 'NNN', } rest_dict['BslI'] = _temp() def _temp(): return { - 'compsite' : '(?PGTCTC)|(?PGAGAC)', - 'results' : None, - 'site' : 'GTCTC', - 'substrat' : 'DNA', - 'fst3' : 5, - 'fst5' : 6, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (6, 5, None, None, 'GTCTC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PGTCTC)|(?PGAGAC)', + 'results': None, + 'site': 'GTCTC', + 'substrat': 'DNA', + 'fst3': 5, + 'fst5': 6, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (6, 5, None, None, 'GTCTC'), + 'ovhgseq': 'NNNN', } rest_dict['BsmAI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGTCTC)|(?PGAGACG)', - 'results' : None, - 'site' : 'CGTCTC', - 'substrat' : 'DNA', - 'fst3' : 5, - 'fst5' : 7, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (7, 5, None, None, 'CGTCTC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PCGTCTC)|(?PGAGACG)', + 'results': None, + 'site': 'CGTCTC', + 'substrat': 'DNA', + 'fst3': 5, + 'fst5': 7, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (7, 5, None, None, 'CGTCTC'), + 'ovhgseq': 'NNNN', } rest_dict['BsmBI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGGAC)|(?PGTCCC)', - 'results' : None, - 'site' : 'GGGAC', - 'substrat' : 'DNA', - 'fst3' : 14, - 'fst5' : 15, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (15, 14, None, None, 'GGGAC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PGGGAC)|(?PGTCCC)', + 'results': None, + 'site': 'GGGAC', + 'substrat': 'DNA', + 'fst3': 14, + 'fst5': 15, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (15, 14, None, None, 'GGGAC'), + 'ovhgseq': 'NNNN', } rest_dict['BsmFI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAATGC)|(?PGCATTC)', - 'results' : None, - 'site' : 'GAATGC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 7, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('J', 'M', 'N', 'O', 'S', 'W'), - 'scd5' : None, - 'charac' : (7, -1, None, None, 'GAATGC'), - 'ovhgseq' : 'CN', + 'compsite': '(?PGAATGC)|(?PGCATTC)', + 'results': None, + 'site': 'GAATGC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 7, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('J', 'M', 'N', 'S'), + 'scd5': None, + 'charac': (7, -1, None, None, 'GAATGC'), + 'ovhgseq': 'CN', } rest_dict['BsmI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGCC)|(?PGGCC)', - 'results' : None, - 'site' : 'GGCC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('V',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GGCC'), - 'ovhgseq' : '', + 'compsite': '(?PGGCC)', + 'results': None, + 'site': 'GGCC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('V',), + 'scd5': None, + 'charac': (2, -2, None, None, 'GGCC'), + 'ovhgseq': '', } rest_dict['BsnI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGTCTC)|(?PGAGACC)', - 'results' : None, - 'site' : 'GGTCTC', - 'substrat' : 'DNA', - 'fst3' : 5, - 'fst5' : 7, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (7, 5, None, None, 'GGTCTC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PGGTCTC)|(?PGAGACC)', + 'results': None, + 'site': 'GGTCTC', + 'substrat': 'DNA', + 'fst3': 5, + 'fst5': 7, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (7, 5, None, None, 'GGTCTC'), + 'ovhgseq': 'NNNN', } rest_dict['Bso31I'] = _temp() def _temp(): return { - 'compsite' : '(?PC[CT]CG[AG]G)|(?PC[CT]CG[AG]G)', - 'results' : None, - 'site' : 'CYCGRG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CYCGRG'), - 'ovhgseq' : 'YCGR', + 'compsite': '(?PC[CT]CG[AG]G)', + 'results': None, + 'site': 'CYCGRG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CYCGRG'), + 'ovhgseq': 'YCGR', } rest_dict['BsoBI'] = _temp() def _temp(): return { - 'compsite' : '(?PTTCGAA)|(?PTTCGAA)', - 'results' : None, - 'site' : 'TTCGAA', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'TTCGAA'), - 'ovhgseq' : 'CG', + 'compsite': '(?PTTCGAA)', + 'results': None, + 'site': 'TTCGAA', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (2, -2, None, None, 'TTCGAA'), + 'ovhgseq': 'CG', } rest_dict['Bsp119I'] = _temp() def _temp(): return { - 'compsite' : '(?PGGGCCC)|(?PGGGCCC)', - 'results' : None, - 'site' : 'GGGCCC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGGCCC'), - 'ovhgseq' : 'GGCC', + 'compsite': '(?PGGGCCC)', + 'results': None, + 'site': 'GGGCCC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGGCCC'), + 'ovhgseq': 'GGCC', } rest_dict['Bsp120I'] = _temp() def _temp(): return { - 'compsite' : '(?PG[AGT]GC[ACT]C)|(?PG[AGT]GC[ACT]C)', - 'results' : None, - 'site' : 'GDGCHC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 256, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('J', 'K', 'N', 'R'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GDGCHC'), - 'ovhgseq' : 'DGCH', + 'compsite': '(?PG[AGT]GC[ACT]C)', + 'results': None, + 'site': 'GDGCHC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 256, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('J', 'K', 'N'), + 'scd5': None, + 'charac': (5, -5, None, None, 'GDGCHC'), + 'ovhgseq': 'DGCH', } rest_dict['Bsp1286I'] = _temp() def _temp(): return { - 'compsite' : '(?PTCCGGA)|(?PTCCGGA)', - 'results' : None, - 'site' : 'TCCGGA', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'TCCGGA'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?PTCCGGA)', + 'results': None, + 'site': 'TCCGGA', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'TCCGGA'), + 'ovhgseq': 'CCGG', } rest_dict['Bsp13I'] = _temp() def _temp(): return { - 'compsite' : '(?PTGTACA)|(?PTGTACA)', - 'results' : None, - 'site' : 'TGTACA', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F', 'K'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'TGTACA'), - 'ovhgseq' : 'GTAC', + 'compsite': '(?PTGTACA)', + 'results': None, + 'site': 'TGTACA', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F', 'K'), + 'scd5': None, + 'charac': (1, -1, None, None, 'TGTACA'), + 'ovhgseq': 'GTAC', } rest_dict['Bsp1407I'] = _temp() def _temp(): return { - 'compsite' : '(?PGATC)|(?PGATC)', - 'results' : None, - 'site' : 'GATC', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'GATC'), - 'ovhgseq' : 'GATC', + 'compsite': '(?PGATC)', + 'results': None, + 'site': 'GATC', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (0, 0, None, None, 'GATC'), + 'ovhgseq': 'GATC', } rest_dict['Bsp143I'] = _temp() def _temp(): return { - 'compsite' : '(?PGCT.AGC)|(?PGCT.AGC)', - 'results' : None, - 'site' : 'GCTNAGC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GCTNAGC'), - 'ovhgseq' : 'TNA', + 'compsite': '(?PGCT.AGC)', + 'results': None, + 'site': 'GCTNAGC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (2, -2, None, None, 'GCTNAGC'), + 'ovhgseq': 'TNA', } rest_dict['Bsp1720I'] = _temp() def _temp(): return { - 'compsite' : '(?PCCATGG)|(?PCCATGG)', - 'results' : None, - 'site' : 'CCATGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCATGG'), - 'ovhgseq' : 'CATG', + 'compsite': '(?PCCATGG)', + 'results': None, + 'site': 'CCATGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCATGG'), + 'ovhgseq': 'CATG', } rest_dict['Bsp19I'] = _temp() def _temp(): return { - 'compsite' : '(?PGAC......TGG)|(?PCCA......GTC)', - 'results' : None, - 'site' : 'GACNNNNNNTGG', - 'substrat' : 'DNA', - 'fst3' : -25, - 'fst5' : -8, - 'freq' : 4096, - 'size' : 12, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 5, - 'scd3' : 7, - 'suppl' : (), - 'scd5' : 24, - 'charac' : (-8, -25, 24, 7, 'GACNNNNNNTGG'), - 'ovhgseq' : 'NNNNN', + 'compsite': '(?PGAC......TGG)|(?PCCA......GTC)', + 'results': None, + 'site': 'GACNNNNNNTGG', + 'substrat': 'DNA', + 'fst3': -25, + 'fst5': -8, + 'freq': 4096, + 'size': 12, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 5, + 'scd3': 7, + 'suppl': (), + 'scd5': 24, + 'charac': (-8, -25, 24, 7, 'GACNNNNNNTGG'), + 'ovhgseq': 'NNNNN', } rest_dict['Bsp24I'] = _temp() def _temp(): return { - 'compsite' : '(?PTCGCGA)|(?PTCGCGA)', - 'results' : None, - 'site' : 'TCGCGA', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'TCGCGA'), - 'ovhgseq' : '', + 'compsite': '(?PTCGCGA)', + 'results': None, + 'site': 'TCGCGA', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (3, -3, None, None, 'TCGCGA'), + 'ovhgseq': '', } rest_dict['Bsp68I'] = _temp() def _temp(): return { - 'compsite' : '(?PCCGC)|(?PGCGG)', - 'results' : None, - 'site' : 'CCGC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCGC'), - 'ovhgseq' : 'CG', + 'compsite': '(?PCCGC)|(?PGCGG)', + 'results': None, + 'site': 'CCGC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCGC'), + 'ovhgseq': 'CG', } rest_dict['BspACI'] = _temp() def _temp(): return { - 'compsite' : '(?PCTCAG)|(?PCTGAG)', - 'results' : None, - 'site' : 'CTCAG', - 'substrat' : 'DNA', - 'fst3' : 7, - 'fst5' : 14, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (14, 7, None, None, 'CTCAG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PCTCAG)|(?PCTGAG)', + 'results': None, + 'site': 'CTCAG', + 'substrat': 'DNA', + 'fst3': 7, + 'fst5': 14, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (14, 7, None, None, 'CTCAG'), + 'ovhgseq': 'NN', } rest_dict['BspCNI'] = _temp() def _temp(): return { - 'compsite' : '(?PGACTC)|(?PGAGTC)', - 'results' : None, - 'site' : 'GACTC', - 'substrat' : 'DNA', - 'fst3' : 6, - 'fst5' : 9, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (9, 6, None, None, 'GACTC'), - 'ovhgseq' : 'NN', + 'compsite': '(?PGACTC)|(?PGAGTC)', + 'results': None, + 'site': 'GACTC', + 'substrat': 'DNA', + 'fst3': 6, + 'fst5': 9, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (9, 6, None, None, 'GACTC'), + 'ovhgseq': 'NN', } rest_dict['BspD6I'] = _temp() def _temp(): return { - 'compsite' : '(?PATCGAT)|(?PATCGAT)', - 'results' : None, - 'site' : 'ATCGAT', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'ATCGAT'), - 'ovhgseq' : 'CG', + 'compsite': '(?PATCGAT)', + 'results': None, + 'site': 'ATCGAT', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (2, -2, None, None, 'ATCGAT'), + 'ovhgseq': 'CG', } rest_dict['BspDI'] = _temp() def _temp(): return { - 'compsite' : '(?PTCCGGA)|(?PTCCGGA)', - 'results' : None, - 'site' : 'TCCGGA', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'TCCGGA'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?PTCCGGA)', + 'results': None, + 'site': 'TCCGGA', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'TCCGGA'), + 'ovhgseq': 'CCGG', } rest_dict['BspEI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGCG)|(?PCGCG)', - 'results' : None, - 'site' : 'CGCG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CGCG'), - 'ovhgseq' : '', + 'compsite': '(?PCGCG)', + 'results': None, + 'site': 'CGCG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (2, -2, None, None, 'CGCG'), + 'ovhgseq': '', } rest_dict['BspFNI'] = _temp() def _temp(): return { - 'compsite' : '(?PCTGGAC)|(?PGTCCAG)', - 'results' : None, - 'site' : 'CTGGAC', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'CTGGAC'), - 'ovhgseq' : None, + 'compsite': '(?PCTGGAC)|(?PGTCCAG)', + 'results': None, + 'site': 'CTGGAC', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'CTGGAC'), + 'ovhgseq': None, } rest_dict['BspGI'] = _temp() def _temp(): return { - 'compsite' : '(?PTCATGA)|(?PTCATGA)', - 'results' : None, - 'site' : 'TCATGA', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'TCATGA'), - 'ovhgseq' : 'CATG', + 'compsite': '(?PTCATGA)', + 'results': None, + 'site': 'TCATGA', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'TCATGA'), + 'ovhgseq': 'CATG', } rest_dict['BspHI'] = _temp() def _temp(): return { - 'compsite' : '(?PGG..CC)|(?PGG..CC)', - 'results' : None, - 'site' : 'GGNNCC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 256, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GGNNCC'), - 'ovhgseq' : '', + 'compsite': '(?PGG..CC)', + 'results': None, + 'site': 'GGNNCC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 256, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (3, -3, None, None, 'GGNNCC'), + 'ovhgseq': '', } rest_dict['BspLI'] = _temp() def _temp(): return { - 'compsite' : '(?PACATGT)|(?PACATGT)', - 'results' : None, - 'site' : 'ACATGT', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'ACATGT'), - 'ovhgseq' : 'CATG', + 'compsite': '(?PACATGT)', + 'results': None, + 'site': 'ACATGT', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (1, -1, None, None, 'ACATGT'), + 'ovhgseq': 'CATG', } rest_dict['BspLU11I'] = _temp() def _temp(): return { - 'compsite' : '(?PACCTGC)|(?PGCAGGT)', - 'results' : None, - 'site' : 'ACCTGC', - 'substrat' : 'DNA', - 'fst3' : 8, - 'fst5' : 10, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (10, 8, None, None, 'ACCTGC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PACCTGC)|(?PGCAGGT)', + 'results': None, + 'site': 'ACCTGC', + 'substrat': 'DNA', + 'fst3': 8, + 'fst5': 10, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (10, 8, None, None, 'ACCTGC'), + 'ovhgseq': 'NNNN', } rest_dict['BspMI'] = _temp() def _temp(): return { - 'compsite' : '(?PTCCGGA)|(?PTCCGGA)', - 'results' : None, - 'site' : 'TCCGGA', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'TCCGGA'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?PTCCGGA)', + 'results': None, + 'site': 'TCCGGA', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (1, -1, None, None, 'TCCGGA'), + 'ovhgseq': 'CCGG', } rest_dict['BspMII'] = _temp() def _temp(): return { - 'compsite' : '(?PCCAGA)|(?PTCTGG)', - 'results' : None, - 'site' : 'CCAGA', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'CCAGA'), - 'ovhgseq' : None, + 'compsite': '(?PCCAGA)|(?PTCTGG)', + 'results': None, + 'site': 'CCAGA', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'CCAGA'), + 'ovhgseq': None, } rest_dict['BspNCI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCTAGC)|(?PGCTAGC)', - 'results' : None, - 'site' : 'GCTAGC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GCTAGC'), - 'ovhgseq' : 'CTAG', + 'compsite': '(?PGCTAGC)', + 'results': None, + 'site': 'GCTAGC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (5, -5, None, None, 'GCTAGC'), + 'ovhgseq': 'CTAG', } rest_dict['BspOI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGATC)|(?PGATCC)', - 'results' : None, - 'site' : 'GGATC', - 'substrat' : 'DNA', - 'fst3' : 5, - 'fst5' : 9, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (9, 5, None, None, 'GGATC'), - 'ovhgseq' : 'N', + 'compsite': '(?PGGATC)|(?PGATCC)', + 'results': None, + 'site': 'GGATC', + 'substrat': 'DNA', + 'fst3': 5, + 'fst5': 9, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (9, 5, None, None, 'GGATC'), + 'ovhgseq': 'N', } rest_dict['BspPI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCTCTTC)|(?PGAAGAGC)', - 'results' : None, - 'site' : 'GCTCTTC', - 'substrat' : 'DNA', - 'fst3' : 4, - 'fst5' : 8, - 'freq' : 16384, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (8, 4, None, None, 'GCTCTTC'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PGCTCTTC)|(?PGAAGAGC)', + 'results': None, + 'site': 'GCTCTTC', + 'substrat': 'DNA', + 'fst3': 4, + 'fst5': 8, + 'freq': 16384, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (8, 4, None, None, 'GCTCTTC'), + 'ovhgseq': 'NNN', } rest_dict['BspQI'] = _temp() def _temp(): return { - 'compsite' : '(?PTTCGAA)|(?PTTCGAA)', - 'results' : None, - 'site' : 'TTCGAA', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('K',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'TTCGAA'), - 'ovhgseq' : 'CG', + 'compsite': '(?PTTCGAA)', + 'results': None, + 'site': 'TTCGAA', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('K',), + 'scd5': None, + 'charac': (2, -2, None, None, 'TTCGAA'), + 'ovhgseq': 'CG', } rest_dict['BspT104I'] = _temp() def _temp(): return { - 'compsite' : '(?PGG[CT][AG]CC)|(?PGG[CT][AG]CC)', - 'results' : None, - 'site' : 'GGYRCC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('K',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGYRCC'), - 'ovhgseq' : 'GYRC', + 'compsite': '(?PGG[CT][AG]CC)', + 'results': None, + 'site': 'GGYRCC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('K',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGYRCC'), + 'ovhgseq': 'GYRC', } rest_dict['BspT107I'] = _temp() def _temp(): return { - 'compsite' : '(?PCTTAAG)|(?PCTTAAG)', - 'results' : None, - 'site' : 'CTTAAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTTAAG'), - 'ovhgseq' : 'TTAA', + 'compsite': '(?PCTTAAG)', + 'results': None, + 'site': 'CTTAAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CTTAAG'), + 'ovhgseq': 'TTAA', } rest_dict['BspTI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGTCTC)|(?PGAGACC)', - 'results' : None, - 'site' : 'GGTCTC', - 'substrat' : 'DNA', - 'fst3' : 5, - 'fst5' : 7, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('Q', 'X'), - 'scd5' : None, - 'charac' : (7, 5, None, None, 'GGTCTC'), - 'ovhgseq' : 'NNNN', - } -rest_dict['BspTNI'] = _temp() - -def _temp(): - return { - 'compsite' : '(?PATCGAT)|(?PATCGAT)', - 'results' : None, - 'site' : 'ATCGAT', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('W',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'ATCGAT'), - 'ovhgseq' : 'CG', - } -rest_dict['BspXI'] = _temp() - -def _temp(): - return { - 'compsite' : '(?PCCGCTC)|(?PGAGCGG)', - 'results' : None, - 'site' : 'CCGCTC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'CCGCTC'), - 'ovhgseq' : '', + 'compsite': '(?PCCGCTC)|(?PGAGCGG)', + 'results': None, + 'site': 'CCGCTC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (3, -3, None, None, 'CCGCTC'), + 'ovhgseq': '', } rest_dict['BsrBI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCAATG)|(?PCATTGC)', - 'results' : None, - 'site' : 'GCAATG', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 8, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (8, 0, None, None, 'GCAATG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PGCAATG)|(?PCATTGC)', + 'results': None, + 'site': 'GCAATG', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 8, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (8, 0, None, None, 'GCAATG'), + 'ovhgseq': 'NN', } rest_dict['BsrDI'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]CCGG[CT])|(?P[AG]CCGG[CT])', - 'results' : None, - 'site' : 'RCCGGY', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'RCCGGY'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?P[AG]CCGG[CT])', + 'results': None, + 'site': 'RCCGGY', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'RCCGGY'), + 'ovhgseq': 'CCGG', } rest_dict['BsrFI'] = _temp() def _temp(): return { - 'compsite' : '(?PTGTACA)|(?PTGTACA)', - 'results' : None, - 'site' : 'TGTACA', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'TGTACA'), - 'ovhgseq' : 'GTAC', + 'compsite': '(?PTGTACA)', + 'results': None, + 'site': 'TGTACA', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'TGTACA'), + 'ovhgseq': 'GTAC', } rest_dict['BsrGI'] = _temp() def _temp(): return { - 'compsite' : '(?PACTGG)|(?PCCAGT)', - 'results' : None, - 'site' : 'ACTGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 6, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (6, -1, None, None, 'ACTGG'), - 'ovhgseq' : 'GN', + 'compsite': '(?PACTGG)|(?PCCAGT)', + 'results': None, + 'site': 'ACTGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 6, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (6, -1, None, None, 'ACTGG'), + 'ovhgseq': 'GN', } rest_dict['BsrI'] = _temp() def _temp(): return { - 'compsite' : '(?PACTGG)|(?PCCAGT)', - 'results' : None, - 'site' : 'ACTGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 6, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('R',), - 'scd5' : None, - 'charac' : (6, -1, None, None, 'ACTGG'), - 'ovhgseq' : 'GN', + 'compsite': '(?PACTGG)|(?PCCAGT)', + 'results': None, + 'site': 'ACTGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 6, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('R',), + 'scd5': None, + 'charac': (6, -1, None, None, 'ACTGG'), + 'ovhgseq': 'GN', } rest_dict['BsrSI'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]CCGG[CT])|(?P[AG]CCGG[CT])', - 'results' : None, - 'site' : 'RCCGGY', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('C',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'RCCGGY'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?P[AG]CCGG[CT])', + 'results': None, + 'site': 'RCCGGY', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('C',), + 'scd5': None, + 'charac': (1, -1, None, None, 'RCCGGY'), + 'ovhgseq': 'CCGG', } rest_dict['BssAI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC..GG)|(?PCC..GG)', - 'results' : None, - 'site' : 'CCNNGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCNNGG'), - 'ovhgseq' : 'CNNG', + 'compsite': '(?PCC..GG)', + 'results': None, + 'site': 'CCNNGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCNNGG'), + 'ovhgseq': 'CNNG', } rest_dict['BssECI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCGCGC)|(?PGCGCGC)', - 'results' : None, - 'site' : 'GCGCGC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'X'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GCGCGC'), - 'ovhgseq' : 'CGCG', + 'compsite': '(?PGCGCGC)', + 'results': None, + 'site': 'GCGCGC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('J', 'K', 'M', 'N', 'Q', 'R', 'S', 'X'), + 'scd5': None, + 'charac': (1, -1, None, None, 'GCGCGC'), + 'ovhgseq': 'CGCG', } rest_dict['BssHII'] = _temp() def _temp(): return { - 'compsite' : '(?PCC.GG)|(?PCC.GG)', - 'results' : None, - 'site' : 'CCNGG', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -5, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'CCNGG'), - 'ovhgseq' : 'CCNGG', + 'compsite': '(?PCC.GG)', + 'results': None, + 'site': 'CCNGG', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (0, 0, None, None, 'CCNGG'), + 'ovhgseq': 'CCNGG', } rest_dict['BssKI'] = _temp() def _temp(): return { - 'compsite' : '(?PGATC)|(?PGATC)', - 'results' : None, - 'site' : 'GATC', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('V',), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'GATC'), - 'ovhgseq' : 'GATC', + 'compsite': '(?PGATC)', + 'results': None, + 'site': 'GATC', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('V',), + 'scd5': None, + 'charac': (0, 0, None, None, 'GATC'), + 'ovhgseq': 'GATC', } rest_dict['BssMI'] = _temp() def _temp(): return { - 'compsite' : '(?PGTATAC)|(?PGTATAC)', - 'results' : None, - 'site' : 'GTATAC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GTATAC'), - 'ovhgseq' : '', + 'compsite': '(?PGTATAC)', + 'results': None, + 'site': 'GTATAC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (3, -3, None, None, 'GTATAC'), + 'ovhgseq': '', } rest_dict['BssNAI'] = _temp() def _temp(): return { - 'compsite' : '(?PG[AG]CG[CT]C)|(?PG[AG]CG[CT]C)', - 'results' : None, - 'site' : 'GRCGYC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('V',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GRCGYC'), - 'ovhgseq' : 'CG', + 'compsite': '(?PG[AG]CG[CT]C)', + 'results': None, + 'site': 'GRCGYC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('V',), + 'scd5': None, + 'charac': (2, -2, None, None, 'GRCGYC'), + 'ovhgseq': 'CG', } rest_dict['BssNI'] = _temp() def _temp(): return { - 'compsite' : '(?PCACGAG)|(?PCTCGTG)', - 'results' : None, - 'site' : 'CACGAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CACGAG'), - 'ovhgseq' : 'ACGA', + 'compsite': '(?PCACGAG)|(?PCTCGTG)', + 'results': None, + 'site': 'CACGAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CACGAG'), + 'ovhgseq': 'ACGA', } rest_dict['BssSI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC[AT][AT]GG)|(?PCC[AT][AT]GG)', - 'results' : None, - 'site' : 'CCWWGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCWWGG'), - 'ovhgseq' : 'CWWG', + 'compsite': '(?PCC[AT][AT]GG)', + 'results': None, + 'site': 'CCWWGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCWWGG'), + 'ovhgseq': 'CWWG', } rest_dict['BssT1I'] = _temp() def _temp(): return { - 'compsite' : '(?PGTATAC)|(?PGTATAC)', - 'results' : None, - 'site' : 'GTATAC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F', 'K', 'M'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GTATAC'), - 'ovhgseq' : '', + 'compsite': '(?PGTATAC)', + 'results': None, + 'site': 'GTATAC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F', 'K'), + 'scd5': None, + 'charac': (3, -3, None, None, 'GTATAC'), + 'ovhgseq': '', } rest_dict['Bst1107I'] = _temp() def _temp(): return { - 'compsite' : '(?PCACGAG)|(?PCTCGTG)', - 'results' : None, - 'site' : 'CACGAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CACGAG'), - 'ovhgseq' : 'ACGA', + 'compsite': '(?PCACGAG)|(?PCTCGTG)', + 'results': None, + 'site': 'CACGAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CACGAG'), + 'ovhgseq': 'ACGA', } rest_dict['Bst2BI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC[AT]GG)|(?PCC[AT]GG)', - 'results' : None, - 'site' : 'CCWGG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CCWGG'), - 'ovhgseq' : 'W', + 'compsite': '(?PCC[AT]GG)', + 'results': None, + 'site': 'CCWGG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (2, -2, None, None, 'CCWGG'), + 'ovhgseq': 'W', } rest_dict['Bst2UI'] = _temp() def _temp(): return { - 'compsite' : '(?PAC.GT)|(?PAC.GT)', - 'results' : None, - 'site' : 'ACNGT', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 1, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'ACNGT'), - 'ovhgseq' : 'N', + 'compsite': '(?PAC.GT)', + 'results': None, + 'site': 'ACNGT', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (3, -3, None, None, 'ACNGT'), + 'ovhgseq': 'N', } rest_dict['Bst4CI'] = _temp() def _temp(): return { - 'compsite' : '(?PCTCTTC)|(?PGAAGAG)', - 'results' : None, - 'site' : 'CTCTTC', - 'substrat' : 'DNA', - 'fst3' : 4, - 'fst5' : 7, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (7, 4, None, None, 'CTCTTC'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PCTCTTC)|(?PGAAGAG)', + 'results': None, + 'site': 'CTCTTC', + 'substrat': 'DNA', + 'fst3': 4, + 'fst5': 7, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (7, 4, None, None, 'CTCTTC'), + 'ovhgseq': 'NNN', } rest_dict['Bst6I'] = _temp() def _temp(): return { - 'compsite' : '(?PCTTAAG)|(?PCTTAAG)', - 'results' : None, - 'site' : 'CTTAAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('R',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTTAAG'), - 'ovhgseq' : 'TTAA', - } -rest_dict['Bst98I'] = _temp() - -def _temp(): - return { - 'compsite' : '(?PG[AG]CG[CT]C)|(?PG[AG]CG[CT]C)', - 'results' : None, - 'site' : 'GRCGYC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GRCGYC'), - 'ovhgseq' : 'CG', + 'compsite': '(?PG[AG]CG[CT]C)', + 'results': None, + 'site': 'GRCGYC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (2, -2, None, None, 'GRCGYC'), + 'ovhgseq': 'CG', } rest_dict['BstACI'] = _temp() def _temp(): return { - 'compsite' : '(?PCTTAAG)|(?PCTTAAG)', - 'results' : None, - 'site' : 'CTTAAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTTAAG'), - 'ovhgseq' : 'TTAA', + 'compsite': '(?PCTTAAG)', + 'results': None, + 'site': 'CTTAAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CTTAAG'), + 'ovhgseq': 'TTAA', } rest_dict['BstAFI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCA.....TGC)|(?PGCA.....TGC)', - 'results' : None, - 'site' : 'GCANNNNNTGC', - 'substrat' : 'DNA', - 'fst3' : -7, - 'fst5' : 7, - 'freq' : 4096, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : None, - 'suppl' : ('I', 'N'), - 'scd5' : None, - 'charac' : (7, -7, None, None, 'GCANNNNNTGC'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PGCA.....TGC)', + 'results': None, + 'site': 'GCANNNNNTGC', + 'substrat': 'DNA', + 'fst3': -7, + 'fst5': 7, + 'freq': 4096, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': ('I', 'N'), + 'scd5': None, + 'charac': (7, -7, None, None, 'GCANNNNNTGC'), + 'ovhgseq': 'NNN', } rest_dict['BstAPI'] = _temp() def _temp(): return { - 'compsite' : '(?PTGTACA)|(?PTGTACA)', - 'results' : None, - 'site' : 'TGTACA', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'TGTACA'), - 'ovhgseq' : 'GTAC', + 'compsite': '(?PTGTACA)', + 'results': None, + 'site': 'TGTACA', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'TGTACA'), + 'ovhgseq': 'GTAC', } rest_dict['BstAUI'] = _temp() def _temp(): return { - 'compsite' : '(?P[CT]ACGT[AG])|(?P[CT]ACGT[AG])', - 'results' : None, - 'site' : 'YACGTR', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'YACGTR'), - 'ovhgseq' : '', + 'compsite': '(?P[CT]ACGT[AG])', + 'results': None, + 'site': 'YACGTR', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (3, -3, None, None, 'YACGTR'), + 'ovhgseq': '', } rest_dict['BstBAI'] = _temp() def _temp(): return { - 'compsite' : '(?PTTCGAA)|(?PTTCGAA)', - 'results' : None, - 'site' : 'TTCGAA', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'TTCGAA'), - 'ovhgseq' : 'CG', + 'compsite': '(?PTTCGAA)', + 'results': None, + 'site': 'TTCGAA', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (2, -2, None, None, 'TTCGAA'), + 'ovhgseq': 'CG', } rest_dict['BstBI'] = _temp() def _temp(): return { - 'compsite' : '(?PGC..GC)|(?PGC..GC)', - 'results' : None, - 'site' : 'GCNNGC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 256, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GCNNGC'), - 'ovhgseq' : '', + 'compsite': '(?PGC..GC)', + 'results': None, + 'site': 'GCNNGC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 256, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (3, -3, None, None, 'GCNNGC'), + 'ovhgseq': '', } rest_dict['BstC8I'] = _temp() def _temp(): return { - 'compsite' : '(?PCT.AG)|(?PCT.AG)', - 'results' : None, - 'site' : 'CTNAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTNAG'), - 'ovhgseq' : 'TNA', + 'compsite': '(?PCT.AG)', + 'results': None, + 'site': 'CTNAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CTNAG'), + 'ovhgseq': 'TNA', } rest_dict['BstDEI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC[AG][CT]GG)|(?PCC[AG][CT]GG)', - 'results' : None, - 'site' : 'CCRYGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCRYGG'), - 'ovhgseq' : 'CRYG', + 'compsite': '(?PCC[AG][CT]GG)', + 'results': None, + 'site': 'CCRYGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCRYGG'), + 'ovhgseq': 'CRYG', } rest_dict['BstDSI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGT.ACC)|(?PGGT.ACC)', - 'results' : None, - 'site' : 'GGTNACC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -5, - 'scd3' : None, - 'suppl' : ('C', 'H', 'J', 'M', 'N', 'O', 'R', 'S', 'U', 'W'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGTNACC'), - 'ovhgseq' : 'GTNAC', + 'compsite': '(?PGGT.ACC)', + 'results': None, + 'site': 'GGTNACC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': None, + 'suppl': ('C', 'J', 'N', 'R', 'S', 'U'), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGTNACC'), + 'ovhgseq': 'GTNAC', } rest_dict['BstEII'] = _temp() def _temp(): return { - 'compsite' : '(?PCCT.....AGG)|(?PCCT.....AGG)', - 'results' : None, - 'site' : 'CCTNNNNNAGG', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'CCTNNNNNAGG'), - 'ovhgseq' : 'N', + 'compsite': '(?PCCT.....AGG)', + 'results': None, + 'site': 'CCTNNNNNAGG', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (5, -5, None, None, 'CCTNNNNNAGG'), + 'ovhgseq': 'N', } rest_dict['BstENI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGATG)|(?PCATCC)', - 'results' : None, - 'site' : 'GGATG', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 7, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (7, 0, None, None, 'GGATG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PGGATG)|(?PCATCC)', + 'results': None, + 'site': 'GGATG', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 7, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (7, 0, None, None, 'GGATG'), + 'ovhgseq': 'NN', } rest_dict['BstF5I'] = _temp() def _temp(): return { - 'compsite' : '(?PCGCG)|(?PCGCG)', - 'results' : None, - 'site' : 'CGCG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CGCG'), - 'ovhgseq' : '', + 'compsite': '(?PCGCG)', + 'results': None, + 'site': 'CGCG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (2, -2, None, None, 'CGCG'), + 'ovhgseq': '', } rest_dict['BstFNI'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]GCGC[CT])|(?P[AG]GCGC[CT])', - 'results' : None, - 'site' : 'RGCGCY', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'RGCGCY'), - 'ovhgseq' : 'GCGC', + 'compsite': '(?P[AG]GCGC[CT])', + 'results': None, + 'site': 'RGCGCY', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (5, -5, None, None, 'RGCGCY'), + 'ovhgseq': 'GCGC', } rest_dict['BstH2I'] = _temp() def _temp(): return { - 'compsite' : '(?PGCGC)|(?PGCGC)', - 'results' : None, - 'site' : 'GCGC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GCGC'), - 'ovhgseq' : 'CG', + 'compsite': '(?PGCGC)', + 'results': None, + 'site': 'GCGC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (3, -3, None, None, 'GCGC'), + 'ovhgseq': 'CG', } rest_dict['BstHHI'] = _temp() def _temp(): return { - 'compsite' : '(?PGATC)|(?PGATC)', - 'results' : None, - 'site' : 'GATC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GATC'), - 'ovhgseq' : 'AT', + 'compsite': '(?PGATC)', + 'results': None, + 'site': 'GATC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (3, -3, None, None, 'GATC'), + 'ovhgseq': 'AT', } rest_dict['BstKTI'] = _temp() def _temp(): return { - 'compsite' : '(?PGTCTC)|(?PGAGAC)', - 'results' : None, - 'site' : 'GTCTC', - 'substrat' : 'DNA', - 'fst3' : 5, - 'fst5' : 6, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (6, 5, None, None, 'GTCTC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PGTCTC)|(?PGAGAC)', + 'results': None, + 'site': 'GTCTC', + 'substrat': 'DNA', + 'fst3': 5, + 'fst5': 6, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (6, 5, None, None, 'GTCTC'), + 'ovhgseq': 'NNNN', } rest_dict['BstMAI'] = _temp() def _temp(): return { - 'compsite' : '(?PGATC)|(?PGATC)', - 'results' : None, - 'site' : 'GATC', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'GATC'), - 'ovhgseq' : 'GATC', + 'compsite': '(?PGATC)', + 'results': None, + 'site': 'GATC', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (0, 0, None, None, 'GATC'), + 'ovhgseq': 'GATC', } rest_dict['BstMBI'] = _temp() def _temp(): return { - 'compsite' : '(?PCG[AG][CT]CG)|(?PCG[AG][CT]CG)', - 'results' : None, - 'site' : 'CGRYCG', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'CGRYCG'), - 'ovhgseq' : 'RY', + 'compsite': '(?PCG[AG][CT]CG)', + 'results': None, + 'site': 'CGRYCG', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (4, -4, None, None, 'CGRYCG'), + 'ovhgseq': 'RY', } rest_dict['BstMCI'] = _temp() def _temp(): return { - 'compsite' : '(?PGC.......GC)|(?PGC.......GC)', - 'results' : None, - 'site' : 'GCNNNNNNNGC', - 'substrat' : 'DNA', - 'fst3' : -7, - 'fst5' : 7, - 'freq' : 256, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (7, -7, None, None, 'GCNNNNNNNGC'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PGC.......GC)', + 'results': None, + 'site': 'GCNNNNNNNGC', + 'substrat': 'DNA', + 'fst3': -7, + 'fst5': 7, + 'freq': 256, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (7, -7, None, None, 'GCNNNNNNNGC'), + 'ovhgseq': 'NNN', } rest_dict['BstMWI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC[AT]GG)|(?PCC[AT]GG)', - 'results' : None, - 'site' : 'CCWGG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CCWGG'), - 'ovhgseq' : 'W', + 'compsite': '(?PCC[AT]GG)', + 'results': None, + 'site': 'CCWGG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (2, -2, None, None, 'CCWGG'), + 'ovhgseq': 'W', } rest_dict['BstNI'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]CATG[CT])|(?P[AG]CATG[CT])', - 'results' : None, - 'site' : 'RCATGY', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'RCATGY'), - 'ovhgseq' : 'CATG', + 'compsite': '(?P[AG]CATG[CT])', + 'results': None, + 'site': 'RCATGY', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (5, -5, None, None, 'RCATGY'), + 'ovhgseq': 'CATG', } rest_dict['BstNSI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC[AT]GG)|(?PCC[AT]GG)', - 'results' : None, - 'site' : 'CCWGG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('R',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CCWGG'), - 'ovhgseq' : 'W', + 'compsite': '(?PCC[AT]GG)', + 'results': None, + 'site': 'CCWGG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('R',), + 'scd5': None, + 'charac': (2, -2, None, None, 'CCWGG'), + 'ovhgseq': 'W', } rest_dict['BstOI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAC....GTC)|(?PGAC....GTC)', - 'results' : None, - 'site' : 'GACNNNNGTC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 10, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GACNNNNGTC'), - 'ovhgseq' : '', + 'compsite': '(?PGAC....GTC)', + 'results': None, + 'site': 'GACNNNNGTC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 10, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (5, -5, None, None, 'GACNNNNGTC'), + 'ovhgseq': '', } rest_dict['BstPAI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGT.ACC)|(?PGGT.ACC)', - 'results' : None, - 'site' : 'GGTNACC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -5, - 'scd3' : None, - 'suppl' : ('K',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGTNACC'), - 'ovhgseq' : 'GTNAC', + 'compsite': '(?PGGT.ACC)', + 'results': None, + 'site': 'GGTNACC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': None, + 'suppl': ('K',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGTNACC'), + 'ovhgseq': 'GTNAC', } rest_dict['BstPI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC.GG)|(?PCC.GG)', - 'results' : None, - 'site' : 'CCNGG', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -5, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'CCNGG'), - 'ovhgseq' : 'CCNGG', + 'compsite': '(?PCC.GG)', + 'results': None, + 'site': 'CCNGG', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (0, 0, None, None, 'CCNGG'), + 'ovhgseq': 'CCNGG', } rest_dict['BstSCI'] = _temp() def _temp(): return { - 'compsite' : '(?PCT[AG][CT]AG)|(?PCT[AG][CT]AG)', - 'results' : None, - 'site' : 'CTRYAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTRYAG'), - 'ovhgseq' : 'TRYA', + 'compsite': '(?PCT[AG][CT]AG)', + 'results': None, + 'site': 'CTRYAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CTRYAG'), + 'ovhgseq': 'TRYA', } rest_dict['BstSFI'] = _temp() def _temp(): return { - 'compsite' : '(?PG[GT]GC[AC]C)|(?PG[GT]GC[AC]C)', - 'results' : None, - 'site' : 'GKGCMC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GKGCMC'), - 'ovhgseq' : 'KGCM', + 'compsite': '(?PG[GT]GC[AC]C)', + 'results': None, + 'site': 'GKGCMC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (5, -5, None, None, 'GKGCMC'), + 'ovhgseq': 'KGCM', } rest_dict['BstSLI'] = _temp() def _temp(): return { - 'compsite' : '(?PTACGTA)|(?PTACGTA)', - 'results' : None, - 'site' : 'TACGTA', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'TACGTA'), - 'ovhgseq' : '', + 'compsite': '(?PTACGTA)', + 'results': None, + 'site': 'TACGTA', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (3, -3, None, None, 'TACGTA'), + 'ovhgseq': '', } rest_dict['BstSNI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGCG)|(?PCGCG)', - 'results' : None, - 'site' : 'CGCG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CGCG'), - 'ovhgseq' : '', + 'compsite': '(?PCGCG)', + 'results': None, + 'site': 'CGCG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (2, -2, None, None, 'CGCG'), + 'ovhgseq': '', } rest_dict['BstUI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCAGC)|(?PGCTGC)', - 'results' : None, - 'site' : 'GCAGC', - 'substrat' : 'DNA', - 'fst3' : 12, - 'fst5' : 13, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (13, 12, None, None, 'GCAGC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PGCAGC)|(?PGCTGC)', + 'results': None, + 'site': 'GCAGC', + 'substrat': 'DNA', + 'fst3': 12, + 'fst5': 13, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (13, 12, None, None, 'GCAGC'), + 'ovhgseq': 'NNNN', } rest_dict['BstV1I'] = _temp() def _temp(): return { - 'compsite' : '(?PGAAGAC)|(?PGTCTTC)', - 'results' : None, - 'site' : 'GAAGAC', - 'substrat' : 'DNA', - 'fst3' : 6, - 'fst5' : 8, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (8, 6, None, None, 'GAAGAC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PGAAGAC)|(?PGTCTTC)', + 'results': None, + 'site': 'GAAGAC', + 'substrat': 'DNA', + 'fst3': 6, + 'fst5': 8, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (8, 6, None, None, 'GAAGAC'), + 'ovhgseq': 'NNNN', } rest_dict['BstV2I'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]GATC[CT])|(?P[AG]GATC[CT])', - 'results' : None, - 'site' : 'RGATCY', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'RGATCY'), - 'ovhgseq' : 'GATC', + 'compsite': '(?P[AG]GATC[CT])', + 'results': None, + 'site': 'RGATCY', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'RGATCY'), + 'ovhgseq': 'GATC', } rest_dict['BstX2I'] = _temp() def _temp(): return { - 'compsite' : '(?PCCA......TGG)|(?PCCA......TGG)', - 'results' : None, - 'site' : 'CCANNNNNNTGG', - 'substrat' : 'DNA', - 'fst3' : -8, - 'fst5' : 8, - 'freq' : 4096, - 'size' : 12, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('F', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'V', 'W', 'X'), - 'scd5' : None, - 'charac' : (8, -8, None, None, 'CCANNNNNNTGG'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PCCA......TGG)', + 'results': None, + 'site': 'CCANNNNNNTGG', + 'substrat': 'DNA', + 'fst3': -8, + 'fst5': 8, + 'freq': 4096, + 'size': 12, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('F', 'I', 'J', 'K', 'M', 'N', 'Q', 'R', 'V', 'X'), + 'scd5': None, + 'charac': (8, -8, None, None, 'CCANNNNNNTGG'), + 'ovhgseq': 'NNNN', } rest_dict['BstXI'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]GATC[CT])|(?P[AG]GATC[CT])', - 'results' : None, - 'site' : 'RGATCY', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'RGATCY'), - 'ovhgseq' : 'GATC', + 'compsite': '(?P[AG]GATC[CT])', + 'results': None, + 'site': 'RGATCY', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'RGATCY'), + 'ovhgseq': 'GATC', } rest_dict['BstYI'] = _temp() def _temp(): return { - 'compsite' : '(?PGTATAC)|(?PGTATAC)', - 'results' : None, - 'site' : 'GTATAC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GTATAC'), - 'ovhgseq' : '', + 'compsite': '(?PGTATAC)', + 'results': None, + 'site': 'GTATAC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (3, -3, None, None, 'GTATAC'), + 'ovhgseq': '', } rest_dict['BstZ17I'] = _temp() def _temp(): return { - 'compsite' : '(?PCGGCCG)|(?PCGGCCG)', - 'results' : None, - 'site' : 'CGGCCG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('R',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CGGCCG'), - 'ovhgseq' : 'GGCC', + 'compsite': '(?PCGGCCG)', + 'results': None, + 'site': 'CGGCCG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('R',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CGGCCG'), + 'ovhgseq': 'GGCC', } rest_dict['BstZI'] = _temp() def _temp(): return { - 'compsite' : '(?PATCGAT)|(?PATCGAT)', - 'results' : None, - 'site' : 'ATCGAT', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'ATCGAT'), - 'ovhgseq' : 'CG', + 'compsite': '(?PATCGAT)', + 'results': None, + 'site': 'ATCGAT', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (2, -2, None, None, 'ATCGAT'), + 'ovhgseq': 'CG', } rest_dict['Bsu15I'] = _temp() def _temp(): return { - 'compsite' : '(?PCCT.AGG)|(?PCCT.AGG)', - 'results' : None, - 'site' : 'CCTNAGG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('N', 'R'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CCTNAGG'), - 'ovhgseq' : 'TNA', + 'compsite': '(?PCCT.AGG)', + 'results': None, + 'site': 'CCTNAGG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('N', 'R'), + 'scd5': None, + 'charac': (2, -2, None, None, 'CCTNAGG'), + 'ovhgseq': 'TNA', } rest_dict['Bsu36I'] = _temp() def _temp(): return { - 'compsite' : '(?PGGCC)|(?PGGCC)', - 'results' : None, - 'site' : 'GGCC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F', 'I'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GGCC'), - 'ovhgseq' : '', - } -rest_dict['BsuRI'] = _temp() + 'compsite': '(?PGTATCC)|(?PGGATAC)', + 'results': None, + 'site': 'GTATCC', + 'substrat': 'DNA', + 'fst3': 5, + 'fst5': 12, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (12, 5, None, None, 'GTATCC'), + 'ovhgseq': 'N', + } +rest_dict['BsuI'] = _temp() def _temp(): return { - 'compsite' : '(?PATCGAT)|(?PATCGAT)', - 'results' : None, - 'site' : 'ATCGAT', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('X',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'ATCGAT'), - 'ovhgseq' : 'CG', - } -rest_dict['BsuTUI'] = _temp() + 'compsite': '(?PGGCC)', + 'results': None, + 'site': 'GGCC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F', 'I'), + 'scd5': None, + 'charac': (2, -2, None, None, 'GGCC'), + 'ovhgseq': '', + } +rest_dict['BsuRI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC[AG][CT]GG)|(?PCC[AG][CT]GG)', - 'results' : None, - 'site' : 'CCRYGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCRYGG'), - 'ovhgseq' : 'CRYG', + 'compsite': '(?PCC[AG][CT]GG)', + 'results': None, + 'site': 'CCRYGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCRYGG'), + 'ovhgseq': 'CRYG', } rest_dict['BtgI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCGATG)|(?PCATCGC)', - 'results' : None, - 'site' : 'GCGATG', - 'substrat' : 'DNA', - 'fst3' : 14, - 'fst5' : 16, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (16, 14, None, None, 'GCGATG'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PGCGATG)|(?PCATCGC)', + 'results': None, + 'site': 'GCGATG', + 'substrat': 'DNA', + 'fst3': 14, + 'fst5': 16, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (16, 14, None, None, 'GCGATG'), + 'ovhgseq': 'NNNN', } rest_dict['BtgZI'] = _temp() def _temp(): return { - 'compsite' : '(?PGC.GC)|(?PGC.GC)', - 'results' : None, - 'site' : 'GCNGC', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'GCNGC'), - 'ovhgseq' : 'CNG', + 'compsite': '(?PGC.GC)', + 'results': None, + 'site': 'GCNGC', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (4, -4, None, None, 'GCNGC'), + 'ovhgseq': 'CNG', } rest_dict['BthCI'] = _temp() def _temp(): return { - 'compsite' : '(?PCACGTC)|(?PGACGTG)', - 'results' : None, - 'site' : 'CACGTC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'CACGTC'), - 'ovhgseq' : '', + 'compsite': '(?PCACGTC)|(?PGACGTG)', + 'results': None, + 'site': 'CACGTC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (3, -3, None, None, 'CACGTC'), + 'ovhgseq': '', } rest_dict['BtrI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGATG)|(?PCATCC)', - 'results' : None, - 'site' : 'GGATG', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 7, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (7, 0, None, None, 'GGATG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PGGATG)|(?PCATCC)', + 'results': None, + 'site': 'GGATG', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 7, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (7, 0, None, None, 'GGATG'), + 'ovhgseq': 'NN', } rest_dict['BtsCI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCAGTG)|(?PCACTGC)', - 'results' : None, - 'site' : 'GCAGTG', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 8, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (8, 0, None, None, 'GCAGTG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PGCAGTG)|(?PCACTGC)', + 'results': None, + 'site': 'GCAGTG', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 8, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (8, 0, None, None, 'GCAGTG'), + 'ovhgseq': 'NN', } rest_dict['BtsI'] = _temp() def _temp(): return { - 'compsite' : '(?PTCGCGA)|(?PTCGCGA)', - 'results' : None, - 'site' : 'TCGCGA', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('V',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'TCGCGA'), - 'ovhgseq' : '', + 'compsite': '(?PCAGTG)|(?PCACTG)', + 'results': None, + 'site': 'CAGTG', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 7, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (7, 0, None, None, 'CAGTG'), + 'ovhgseq': 'NN', + } +rest_dict['BtsIMutI'] = _temp() + +def _temp(): + return { + 'compsite': '(?PTCGCGA)', + 'results': None, + 'site': 'TCGCGA', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('V',), + 'scd5': None, + 'charac': (3, -3, None, None, 'TCGCGA'), + 'ovhgseq': '', } rest_dict['BtuMI'] = _temp() def _temp(): return { - 'compsite' : '(?PACCTGC)|(?PGCAGGT)', - 'results' : None, - 'site' : 'ACCTGC', - 'substrat' : 'DNA', - 'fst3' : 8, - 'fst5' : 10, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (10, 8, None, None, 'ACCTGC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PACCTGC)|(?PGCAGGT)', + 'results': None, + 'site': 'ACCTGC', + 'substrat': 'DNA', + 'fst3': 8, + 'fst5': 10, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (10, 8, None, None, 'ACCTGC'), + 'ovhgseq': 'NNNN', } rest_dict['BveI'] = _temp() def _temp(): return { - 'compsite' : '(?PGC..GC)|(?PGC..GC)', - 'results' : None, - 'site' : 'GCNNGC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 256, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GCNNGC'), - 'ovhgseq' : '', + 'compsite': '(?PGC..GC)', + 'results': None, + 'site': 'GCNNGC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 256, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (3, -3, None, None, 'GCNNGC'), + 'ovhgseq': '', } rest_dict['Cac8I'] = _temp() def _temp(): return { - 'compsite' : '(?PCAG...CTG)|(?PCAG...CTG)', - 'results' : None, - 'site' : 'CAGNNNCTG', - 'substrat' : 'DNA', - 'fst3' : -6, - 'fst5' : 6, - 'freq' : 4096, - 'size' : 9, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (6, -6, None, None, 'CAGNNNCTG'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PCAG...CTG)', + 'results': None, + 'site': 'CAGNNNCTG', + 'substrat': 'DNA', + 'fst3': -6, + 'fst5': 6, + 'freq': 4096, + 'size': 9, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (6, -6, None, None, 'CAGNNNCTG'), + 'ovhgseq': 'NNN', } rest_dict['CaiI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC[CG]GG)|(?PCC[CG]GG)', - 'results' : None, - 'site' : 'CCSGG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CCSGG'), - 'ovhgseq' : 'S', + 'compsite': '(?PCC[CG]GG)', + 'results': None, + 'site': 'CCSGG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (2, -2, None, None, 'CCSGG'), + 'ovhgseq': 'S', } rest_dict['CauII'] = _temp() def _temp(): return { - 'compsite' : '(?PTCATGA)|(?PTCATGA)', - 'results' : None, - 'site' : 'TCATGA', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'TCATGA'), - 'ovhgseq' : 'CATG', + 'compsite': '(?PGGA[AG]GA)|(?PTC[CT]TCC)', + 'results': None, + 'site': 'GGARGA', + 'substrat': 'DNA', + 'fst3': 9, + 'fst5': 17, + 'freq': 2048, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (17, 9, None, None, 'GGARGA'), + 'ovhgseq': 'NN', + } +rest_dict['CchII'] = _temp() + +def _temp(): + return { + 'compsite': '(?PCCCAAG)|(?PCTTGGG)', + 'results': None, + 'site': 'CCCAAG', + 'substrat': 'DNA', + 'fst3': 18, + 'fst5': 26, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (26, 18, None, None, 'CCCAAG'), + 'ovhgseq': 'NN', + } +rest_dict['CchIII'] = _temp() + +def _temp(): + return { + 'compsite': '(?PTCATGA)', + 'results': None, + 'site': 'TCATGA', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (1, -1, None, None, 'TCATGA'), + 'ovhgseq': 'CATG', } rest_dict['CciI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCGGCCGC)|(?PGCGGCCGC)', - 'results' : None, - 'site' : 'GCGGCCGC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 65536, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GCGGCCGC'), - 'ovhgseq' : 'GGCC', + 'compsite': '(?PGCGGCCGC)', + 'results': None, + 'site': 'GCGGCCGC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (2, -2, None, None, 'GCGGCCGC'), + 'ovhgseq': 'GGCC', } rest_dict['CciNI'] = _temp() def _temp(): return { - 'compsite' : '(?PCATCG)|(?PCGATG)', - 'results' : None, - 'site' : 'CATCG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 4, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (4, -1, None, None, 'CATCG'), - 'ovhgseq' : '', - } -rest_dict['CdiI'] = _temp() + 'compsite': '(?PCAAAAA)|(?PTTTTTG)', + 'results': None, + 'site': 'CAAAAA', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'CAAAAA'), + 'ovhgseq': None, + } +rest_dict['Cdi630V'] = _temp() def _temp(): return { - 'compsite' : '(?PGCGGAG)|(?PCTCCGC)', - 'results' : None, - 'site' : 'GCGGAG', - 'substrat' : 'DNA', - 'fst3' : 18, - 'fst5' : 26, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (26, 18, None, None, 'GCGGAG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PCATCG)|(?PCGATG)', + 'results': None, + 'site': 'CATCG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 4, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (4, -1, None, None, 'CATCG'), + 'ovhgseq': '', } -rest_dict['CdpI'] = _temp() +rest_dict['CdiI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCT.AGC)|(?PGCT.AGC)', - 'results' : None, - 'site' : 'GCTNAGC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('M',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GCTNAGC'), - 'ovhgseq' : 'TNA', - } -rest_dict['CelII'] = _temp() + 'compsite': '(?PGCGGAG)|(?PCTCCGC)', + 'results': None, + 'site': 'GCGGAG', + 'substrat': 'DNA', + 'fst3': 18, + 'fst5': 26, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (26, 18, None, None, 'GCGGAG'), + 'ovhgseq': 'NN', + } +rest_dict['CdpI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCGC)|(?PGCGC)', - 'results' : None, - 'site' : 'GCGC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('M', 'R', 'S'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GCGC'), - 'ovhgseq' : 'CG', + 'compsite': '(?PGCGC)', + 'results': None, + 'site': 'GCGC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('M', 'R', 'S'), + 'scd5': None, + 'charac': (3, -3, None, None, 'GCGC'), + 'ovhgseq': 'CG', } rest_dict['CfoI'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]CCGG[CT])|(?P[AG]CCGG[CT])', - 'results' : None, - 'site' : 'RCCGGY', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F', 'K', 'O'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'RCCGGY'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?P[AG]CCGG[CT])', + 'results': None, + 'site': 'RCCGGY', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F', 'K'), + 'scd5': None, + 'charac': (1, -1, None, None, 'RCCGGY'), + 'ovhgseq': 'CCGG', } rest_dict['Cfr10I'] = _temp() def _temp(): return { - 'compsite' : '(?PGG.CC)|(?PGG.CC)', - 'results' : None, - 'site' : 'GGNCC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('F', 'O'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGNCC'), - 'ovhgseq' : 'GNC', + 'compsite': '(?PGG.CC)', + 'results': None, + 'site': 'GGNCC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGNCC'), + 'ovhgseq': 'GNC', } rest_dict['Cfr13I'] = _temp() def _temp(): return { - 'compsite' : '(?PCCGCGG)|(?PCCGCGG)', - 'results' : None, - 'site' : 'CCGCGG', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'CCGCGG'), - 'ovhgseq' : 'GC', + 'compsite': '(?PCCGCGG)', + 'results': None, + 'site': 'CCGCGG', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (4, -4, None, None, 'CCGCGG'), + 'ovhgseq': 'GC', } rest_dict['Cfr42I'] = _temp() def _temp(): return { - 'compsite' : '(?PCCCGGG)|(?PCCCGGG)', - 'results' : None, - 'site' : 'CCCGGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F', 'O'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCCGGG'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?PCCCGGG)', + 'results': None, + 'site': 'CCCGGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCCGGG'), + 'ovhgseq': 'CCGG', } rest_dict['Cfr9I'] = _temp() def _temp(): return { - 'compsite' : '(?P[CT]GGCC[AG])|(?P[CT]GGCC[AG])', - 'results' : None, - 'site' : 'YGGCCR', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'YGGCCR'), - 'ovhgseq' : 'GGCC', + 'compsite': '(?P[CT]GGCC[AG])', + 'results': None, + 'site': 'YGGCCR', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (1, -1, None, None, 'YGGCCR'), + 'ovhgseq': 'GGCC', } rest_dict['CfrI'] = _temp() def _temp(): return { - 'compsite' : '(?PGATC)|(?PGATC)', - 'results' : None, - 'site' : 'GATC', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'GATC'), - 'ovhgseq' : 'GATC', + 'compsite': '(?PGGCGCA)|(?PTGCGCC)', + 'results': None, + 'site': 'GGCGCA', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'GGCGCA'), + 'ovhgseq': None, + } +rest_dict['Cgl13032I'] = _temp() + +def _temp(): + return { + 'compsite': '(?PACGA[CGT]GG)|(?PCC[ACG]TCGT)', + 'results': None, + 'site': 'ACGABGG', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 4096, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'ACGABGG'), + 'ovhgseq': None, + } +rest_dict['Cgl13032II'] = _temp() + +def _temp(): + return { + 'compsite': '(?PGATC)', + 'results': None, + 'site': 'GATC', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (4, -4, None, None, 'GATC'), + 'ovhgseq': 'GATC', } rest_dict['ChaI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCA......GT)|(?PAC......TGG)', - 'results' : None, - 'site' : 'CCANNNNNNGT', - 'substrat' : 'DNA', - 'fst3' : -25, - 'fst5' : -8, - 'freq' : 1024, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 6, - 'scd3' : 9, - 'suppl' : (), - 'scd5' : 26, - 'charac' : (-8, -25, 26, 9, 'CCANNNNNNGT'), - 'ovhgseq' : 'NNNNNN', + 'compsite': '(?PGCAAGG)|(?PCCTTGC)', + 'results': None, + 'site': 'GCAAGG', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'GCAAGG'), + 'ovhgseq': None, + } +rest_dict['CjeFIII'] = _temp() + +def _temp(): + return { + 'compsite': '(?PGG[AG]CA)|(?PTG[CT]CC)', + 'results': None, + 'site': 'GGRCA', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'GGRCA'), + 'ovhgseq': None, + } +rest_dict['CjeFV'] = _temp() + +def _temp(): + return { + 'compsite': '(?PCCA......GT)|(?PAC......TGG)', + 'results': None, + 'site': 'CCANNNNNNGT', + 'substrat': 'DNA', + 'fst3': -25, + 'fst5': -8, + 'freq': 1024, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 6, + 'scd3': 9, + 'suppl': (), + 'scd5': 26, + 'charac': (-8, -25, 26, 9, 'CCANNNNNNGT'), + 'ovhgseq': 'NNNNNN', } rest_dict['CjeI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAG.....GT)|(?PAC.....CTC)', - 'results' : None, - 'site' : 'GAGNNNNNGT', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 1024, - 'size' : 10, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'GAGNNNNNGT'), - 'ovhgseq' : None, + 'compsite': '(?PGAG.....GT)|(?PAC.....CTC)', + 'results': None, + 'site': 'GAGNNNNNGT', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 1024, + 'size': 10, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'GAGNNNNNGT'), + 'ovhgseq': None, } rest_dict['CjeNII'] = _temp() def _temp(): return { - 'compsite' : '(?PCCA.......TC)|(?PGA.......TGG)', - 'results' : None, - 'site' : 'CCANNNNNNNTC', - 'substrat' : 'DNA', - 'fst3' : -25, - 'fst5' : -7, - 'freq' : 1024, - 'size' : 12, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 6, - 'scd3' : 8, - 'suppl' : (), - 'scd5' : 26, - 'charac' : (-7, -25, 26, 8, 'CCANNNNNNNTC'), - 'ovhgseq' : 'NNNNNN', + 'compsite': '(?PG[GT]AA[CT]G)|(?PC[AG]TT[AC]C)', + 'results': None, + 'site': 'GKAAYG', + 'substrat': 'DNA', + 'fst3': 17, + 'fst5': 25, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (25, 17, None, None, 'GKAAYG'), + 'ovhgseq': 'NN', + } +rest_dict['CjeNIII'] = _temp() + +def _temp(): + return { + 'compsite': '(?PCAC.......GAA)|(?PTTC.......GTG)', + 'results': None, + 'site': 'CACNNNNNNNGAA', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 4096, + 'size': 13, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'CACNNNNNNNGAA'), + 'ovhgseq': None, + } +rest_dict['CjeP659IV'] = _temp() + +def _temp(): + return { + 'compsite': '(?PCCA.......TC)|(?PGA.......TGG)', + 'results': None, + 'site': 'CCANNNNNNNTC', + 'substrat': 'DNA', + 'fst3': -25, + 'fst5': -7, + 'freq': 1024, + 'size': 12, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 6, + 'scd3': 8, + 'suppl': (), + 'scd5': 26, + 'charac': (-7, -25, 26, 8, 'CCANNNNNNNTC'), + 'ovhgseq': 'NNNNNN', } rest_dict['CjePI'] = _temp() def _temp(): return { - 'compsite' : '(?PCA[CT].....[AG]TG)|(?PCA[CT].....[AG]TG)', - 'results' : None, - 'site' : 'CAYNNNNNRTG', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 1024, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'CAYNNNNNRTG'), - 'ovhgseq' : None, + 'compsite': '(?PCA[CT].....[AG]TG)', + 'results': None, + 'site': 'CAYNNNNNRTG', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 1024, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'CAYNNNNNRTG'), + 'ovhgseq': None, } rest_dict['CjuI'] = _temp() def _temp(): return { - 'compsite' : '(?PCA[CT].....CTC)|(?PGAG.....[AG]TG)', - 'results' : None, - 'site' : 'CAYNNNNNCTC', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 2048, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'CAYNNNNNCTC'), - 'ovhgseq' : None, + 'compsite': '(?PCA[CT].....CTC)|(?PGAG.....[AG]TG)', + 'results': None, + 'site': 'CAYNNNNNCTC', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 2048, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'CAYNNNNNCTC'), + 'ovhgseq': None, } rest_dict['CjuII'] = _temp() def _temp(): return { - 'compsite' : '(?PATCGAT)|(?PATCGAT)', - 'results' : None, - 'site' : 'ATCGAT', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('B', 'H', 'K', 'M', 'N', 'R', 'S', 'U'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'ATCGAT'), - 'ovhgseq' : 'CG', + 'compsite': '(?PATCGAT)', + 'results': None, + 'site': 'ATCGAT', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('B', 'K', 'M', 'N', 'Q', 'R', 'S', 'U', 'X'), + 'scd5': None, + 'charac': (2, -2, None, None, 'ATCGAT'), + 'ovhgseq': 'CG', } rest_dict['ClaI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGG[AT]CCG)|(?PCGG[AT]CCG)', - 'results' : None, - 'site' : 'CGGWCCG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 8192, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('F', 'K'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CGGWCCG'), - 'ovhgseq' : 'GWC', + 'compsite': '(?PCGG[AT]CCG)', + 'results': None, + 'site': 'CGGWCCG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 8192, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('F', 'K'), + 'scd5': None, + 'charac': (2, -2, None, None, 'CGGWCCG'), + 'ovhgseq': 'GWC', } rest_dict['CpoI'] = _temp() def _temp(): return { - 'compsite' : '(?PGACGC)|(?PGCGTC)', - 'results' : None, - 'site' : 'GACGC', - 'substrat' : 'DNA', - 'fst3' : 10, - 'fst5' : 10, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -5, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (10, 10, None, None, 'GACGC'), - 'ovhgseq' : 'NNNNN', + 'compsite': '(?PGACGC)|(?PGCGTC)', + 'results': None, + 'site': 'GACGC', + 'substrat': 'DNA', + 'fst3': 10, + 'fst5': 10, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (10, 10, None, None, 'GACGC'), + 'ovhgseq': 'NNNNN', } rest_dict['CseI'] = _temp() def _temp(): return { - 'compsite' : '(?PACC[AT]GGT)|(?PACC[AT]GGT)', - 'results' : None, - 'site' : 'ACCWGGT', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 8192, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -5, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'ACCWGGT'), - 'ovhgseq' : 'CCWGG', + 'compsite': '(?PACC[AT]GGT)', + 'results': None, + 'site': 'ACCWGGT', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 8192, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'ACCWGGT'), + 'ovhgseq': 'CCWGG', } rest_dict['CsiI'] = _temp() def _temp(): return { - 'compsite' : '(?PTTCGAA)|(?PTTCGAA)', - 'results' : None, - 'site' : 'TTCGAA', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('O', 'R'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'TTCGAA'), - 'ovhgseq' : 'CG', - } -rest_dict['Csp45I'] = _temp() - -def _temp(): - return { - 'compsite' : '(?PGTAC)|(?PGTAC)', - 'results' : None, - 'site' : 'GTAC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GTAC'), - 'ovhgseq' : 'TA', + 'compsite': '(?PGTAC)', + 'results': None, + 'site': 'GTAC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GTAC'), + 'ovhgseq': 'TA', } rest_dict['Csp6I'] = _temp() def _temp(): return { - 'compsite' : '(?PACCGGT)|(?PACCGGT)', - 'results' : None, - 'site' : 'ACCGGT', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('C',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'ACCGGT'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?PACCGGT)', + 'results': None, + 'site': 'ACCGGT', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('C',), + 'scd5': None, + 'charac': (1, -1, None, None, 'ACCGGT'), + 'ovhgseq': 'CCGG', } rest_dict['CspAI'] = _temp() def _temp(): return { - 'compsite' : '(?PCAA.....GTGG)|(?PCCAC.....TTG)', - 'results' : None, - 'site' : 'CAANNNNNGTGG', - 'substrat' : 'DNA', - 'fst3' : -25, - 'fst5' : -11, - 'freq' : 16384, - 'size' : 12, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : 10, - 'suppl' : ('N',), - 'scd5' : 24, - 'charac' : (-11, -25, 24, 10, 'CAANNNNNGTGG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PCAA.....GTGG)|(?PCCAC.....TTG)', + 'results': None, + 'site': 'CAANNNNNGTGG', + 'substrat': 'DNA', + 'fst3': -25, + 'fst5': -11, + 'freq': 16384, + 'size': 12, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': 10, + 'suppl': ('N',), + 'scd5': 24, + 'charac': (-11, -25, 24, 10, 'CAANNNNNGTGG'), + 'ovhgseq': 'NN', } rest_dict['CspCI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGG[AT]CCG)|(?PCGG[AT]CCG)', - 'results' : None, - 'site' : 'CGGWCCG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 8192, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('O', 'R'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CGGWCCG'), - 'ovhgseq' : 'GWC', + 'compsite': '(?PCGG[AT]CCG)', + 'results': None, + 'site': 'CGGWCCG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 8192, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('R',), + 'scd5': None, + 'charac': (2, -2, None, None, 'CGGWCCG'), + 'ovhgseq': 'GWC', } rest_dict['CspI'] = _temp() def _temp(): return { - 'compsite' : '(?PAAGGAG)|(?PCTCCTT)', - 'results' : None, - 'site' : 'AAGGAG', - 'substrat' : 'DNA', - 'fst3' : 18, - 'fst5' : 26, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (26, 18, None, None, 'AAGGAG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PAAGGAG)|(?PCTCCTT)', + 'results': None, + 'site': 'AAGGAG', + 'substrat': 'DNA', + 'fst3': 18, + 'fst5': 26, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (26, 18, None, None, 'AAGGAG'), + 'ovhgseq': 'NN', } rest_dict['CstMI'] = _temp() def _temp(): return { - 'compsite' : '(?PCATG)|(?PCATG)', - 'results' : None, - 'site' : 'CATG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CATG'), - 'ovhgseq' : 'AT', + 'compsite': '(?PCATG)', + 'results': None, + 'site': 'CATG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CATG'), + 'ovhgseq': 'AT', } rest_dict['CviAII'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]GC[CT])|(?P[AG]GC[CT])', - 'results' : None, - 'site' : 'RGCY', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 64, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('Q', 'X'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'RGCY'), - 'ovhgseq' : '', + 'compsite': '(?P[AG]GC[CT])', + 'results': None, + 'site': 'RGCY', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 64, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('Q', 'X'), + 'scd5': None, + 'charac': (2, -2, None, None, 'RGCY'), + 'ovhgseq': '', } rest_dict['CviJI'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]GC[CT])|(?P[AG]GC[CT])', - 'results' : None, - 'site' : 'RGCY', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 64, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'RGCY'), - 'ovhgseq' : '', + 'compsite': '(?P[AG]GC[CT])', + 'results': None, + 'site': 'RGCY', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 64, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (2, -2, None, None, 'RGCY'), + 'ovhgseq': '', } rest_dict['CviKI_1'] = _temp() def _temp(): return { - 'compsite' : '(?PGTAC)|(?PGTAC)', - 'results' : None, - 'site' : 'GTAC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GTAC'), - 'ovhgseq' : 'TA', + 'compsite': '(?PGTAC)', + 'results': None, + 'site': 'GTAC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GTAC'), + 'ovhgseq': 'TA', } rest_dict['CviQI'] = _temp() def _temp(): return { - 'compsite' : '(?PTGCA)|(?PTGCA)', - 'results' : None, - 'site' : 'TGCA', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'TGCA'), - 'ovhgseq' : '', + 'compsite': '(?PTGCA)', + 'results': None, + 'site': 'TGCA', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (2, -2, None, None, 'TGCA'), + 'ovhgseq': '', } rest_dict['CviRI'] = _temp() def _temp(): return { - 'compsite' : '(?PCT.AG)|(?PCT.AG)', - 'results' : None, - 'site' : 'CTNAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('B', 'M', 'N', 'O', 'R', 'S', 'W'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTNAG'), - 'ovhgseq' : 'TNA', + 'compsite': '(?PCT.AG)', + 'results': None, + 'site': 'CTNAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('K', 'M', 'N', 'O', 'Q', 'R', 'S', 'X'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CTNAG'), + 'ovhgseq': 'TNA', } rest_dict['DdeI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGCGCC)|(?PGGCGCC)', - 'results' : None, - 'site' : 'GGCGCC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('V',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GGCGCC'), - 'ovhgseq' : '', + 'compsite': '(?PGGCGCC)', + 'results': None, + 'site': 'GGCGCC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('V',), + 'scd5': None, + 'charac': (3, -3, None, None, 'GGCGCC'), + 'ovhgseq': '', } rest_dict['DinI'] = _temp() def _temp(): return { - 'compsite' : '(?PGATC)|(?PGATC)', - 'results' : None, - 'site' : 'GATC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('B', 'E', 'F', 'M', 'N', 'O', 'R', 'S', 'W', 'X'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GATC'), - 'ovhgseq' : '', + 'compsite': '(?PGATC)', + 'results': None, + 'site': 'GATC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('B', 'E', 'F', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'X'), + 'scd5': None, + 'charac': (2, -2, None, None, 'GATC'), + 'ovhgseq': '', } rest_dict['DpnI'] = _temp() def _temp(): return { - 'compsite' : '(?PGATC)|(?PGATC)', - 'results' : None, - 'site' : 'GATC', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'GATC'), - 'ovhgseq' : 'GATC', + 'compsite': '(?PGATC)', + 'results': None, + 'site': 'GATC', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (0, 0, None, None, 'GATC'), + 'ovhgseq': 'GATC', } rest_dict['DpnII'] = _temp() def _temp(): return { - 'compsite' : '(?PTTTAAA)|(?PTTTAAA)', - 'results' : None, - 'site' : 'TTTAAA', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('B', 'F', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'TTTAAA'), - 'ovhgseq' : '', + 'compsite': '(?PTTTAAA)', + 'results': None, + 'site': 'TTTAAA', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('B', 'F', 'I', 'J', 'K', 'M', 'N', 'Q', 'R', 'S', 'U', 'V', 'X', 'Y'), + 'scd5': None, + 'charac': (3, -3, None, None, 'TTTAAA'), + 'ovhgseq': '', } rest_dict['DraI'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]GG.CC[CT])|(?P[AG]GG.CC[CT])', - 'results' : None, - 'site' : 'RGGNCCY', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 1024, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('M', 'W'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'RGGNCCY'), - 'ovhgseq' : 'GNC', + 'compsite': '(?P[AG]GG.CC[CT])', + 'results': None, + 'site': 'RGGNCCY', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 1024, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (2, -2, None, None, 'RGGNCCY'), + 'ovhgseq': 'GNC', } rest_dict['DraII'] = _temp() def _temp(): return { - 'compsite' : '(?PCAC...GTG)|(?PCAC...GTG)', - 'results' : None, - 'site' : 'CACNNNGTG', - 'substrat' : 'DNA', - 'fst3' : -6, - 'fst5' : 6, - 'freq' : 4096, - 'size' : 9, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : None, - 'suppl' : ('I', 'M', 'N', 'V', 'W'), - 'scd5' : None, - 'charac' : (6, -6, None, None, 'CACNNNGTG'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PCAC...GTG)', + 'results': None, + 'site': 'CACNNNGTG', + 'substrat': 'DNA', + 'fst3': -6, + 'fst5': 6, + 'freq': 4096, + 'size': 9, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': ('I', 'M', 'N', 'V'), + 'scd5': None, + 'charac': (6, -6, None, None, 'CACNNNGTG'), + 'ovhgseq': 'NNN', } rest_dict['DraIII'] = _temp() def _temp(): return { - 'compsite' : '(?PCAAG.AC)|(?PGT.CTTG)', - 'results' : None, - 'site' : 'CAAGNAC', - 'substrat' : 'DNA', - 'fst3' : 18, - 'fst5' : 27, - 'freq' : 4096, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (27, 18, None, None, 'CAAGNAC'), - 'ovhgseq' : 'NN', + 'compsite': '(?PCAAG.AC)|(?PGT.CTTG)', + 'results': None, + 'site': 'CAAGNAC', + 'substrat': 'DNA', + 'fst3': 18, + 'fst5': 27, + 'freq': 4096, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (27, 18, None, None, 'CAAGNAC'), + 'ovhgseq': 'NN', } rest_dict['DraRI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAC......GTC)|(?PGAC......GTC)', - 'results' : None, - 'site' : 'GACNNNNNNGTC', - 'substrat' : 'DNA', - 'fst3' : -7, - 'fst5' : 7, - 'freq' : 4096, - 'size' : 12, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (7, -7, None, None, 'GACNNNNNNGTC'), - 'ovhgseq' : 'NN', + 'compsite': '(?PGAC......GTC)', + 'results': None, + 'site': 'GACNNNNNNGTC', + 'substrat': 'DNA', + 'fst3': -7, + 'fst5': 7, + 'freq': 4096, + 'size': 12, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (7, -7, None, None, 'GACNNNNNNGTC'), + 'ovhgseq': 'NN', } rest_dict['DrdI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAACCA)|(?PTGGTTC)', - 'results' : None, - 'site' : 'GAACCA', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'GAACCA'), - 'ovhgseq' : None, + 'compsite': '(?PGAACCA)|(?PTGGTTC)', + 'results': None, + 'site': 'GAACCA', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'GAACCA'), + 'ovhgseq': None, } rest_dict['DrdII'] = _temp() def _temp(): return { - 'compsite' : '(?PTACGAC)|(?PGTCGTA)', - 'results' : None, - 'site' : 'TACGAC', - 'substrat' : 'DNA', - 'fst3' : 18, - 'fst5' : 26, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (26, 18, None, None, 'TACGAC'), - 'ovhgseq' : 'NN', - } -rest_dict['DrdIV'] = _temp() - -def _temp(): - return { - 'compsite' : '(?PGAC.....GTC)|(?PGAC.....GTC)', - 'results' : None, - 'site' : 'GACNNNNNGTC', - 'substrat' : 'DNA', - 'fst3' : -6, - 'fst5' : 6, - 'freq' : 4096, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 1, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (6, -6, None, None, 'GACNNNNNGTC'), - 'ovhgseq' : 'N', + 'compsite': '(?PGAC.....GTC)', + 'results': None, + 'site': 'GACNNNNNGTC', + 'substrat': 'DNA', + 'fst3': -6, + 'fst5': 6, + 'freq': 4096, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (6, -6, None, None, 'GACNNNNNGTC'), + 'ovhgseq': 'N', } rest_dict['DriI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC[AG][CT]GG)|(?PCC[AG][CT]GG)', - 'results' : None, - 'site' : 'CCRYGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCRYGG'), - 'ovhgseq' : 'CRYG', + 'compsite': '(?PCC[AG][CT]GG)', + 'results': None, + 'site': 'CCRYGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCRYGG'), + 'ovhgseq': 'CRYG', } rest_dict['DsaI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAC......GTC)|(?PGAC......GTC)', - 'results' : None, - 'site' : 'GACNNNNNNGTC', - 'substrat' : 'DNA', - 'fst3' : -7, - 'fst5' : 7, - 'freq' : 4096, - 'size' : 12, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (7, -7, None, None, 'GACNNNNNNGTC'), - 'ovhgseq' : 'NN', + 'compsite': '(?PGAC......GTC)', + 'results': None, + 'site': 'GACNNNNNNGTC', + 'substrat': 'DNA', + 'fst3': -7, + 'fst5': 7, + 'freq': 4096, + 'size': 12, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (7, -7, None, None, 'GACNNNNNNGTC'), + 'ovhgseq': 'NN', } rest_dict['DseDI'] = _temp() def _temp(): return { - 'compsite' : '(?P[CT]GGCC[AG])|(?P[CT]GGCC[AG])', - 'results' : None, - 'site' : 'YGGCCR', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('K', 'N'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'YGGCCR'), - 'ovhgseq' : 'GGCC', + 'compsite': '(?P[CT]GGCC[AG])', + 'results': None, + 'site': 'YGGCCR', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('K', 'N'), + 'scd5': None, + 'charac': (1, -1, None, None, 'YGGCCR'), + 'ovhgseq': 'GGCC', } rest_dict['EaeI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGGCCG)|(?PCGGCCG)', - 'results' : None, - 'site' : 'CGGCCG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N', 'W'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CGGCCG'), - 'ovhgseq' : 'GGCC', + 'compsite': '(?PCGGCCG)', + 'results': None, + 'site': 'CGGCCG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CGGCCG'), + 'ovhgseq': 'GGCC', } rest_dict['EagI'] = _temp() def _temp(): return { - 'compsite' : '(?PCTCTTC)|(?PGAAGAG)', - 'results' : None, - 'site' : 'CTCTTC', - 'substrat' : 'DNA', - 'fst3' : 4, - 'fst5' : 7, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (7, 4, None, None, 'CTCTTC'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PCTCTTC)|(?PGAAGAG)', + 'results': None, + 'site': 'CTCTTC', + 'substrat': 'DNA', + 'fst3': 4, + 'fst5': 7, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (7, 4, None, None, 'CTCTTC'), + 'ovhgseq': 'NNN', } rest_dict['Eam1104I'] = _temp() def _temp(): return { - 'compsite' : '(?PGAC.....GTC)|(?PGAC.....GTC)', - 'results' : None, - 'site' : 'GACNNNNNGTC', - 'substrat' : 'DNA', - 'fst3' : -6, - 'fst5' : 6, - 'freq' : 4096, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 1, - 'scd3' : None, - 'suppl' : ('F', 'K'), - 'scd5' : None, - 'charac' : (6, -6, None, None, 'GACNNNNNGTC'), - 'ovhgseq' : 'N', + 'compsite': '(?PGAC.....GTC)', + 'results': None, + 'site': 'GACNNNNNGTC', + 'substrat': 'DNA', + 'fst3': -6, + 'fst5': 6, + 'freq': 4096, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': ('F', 'K'), + 'scd5': None, + 'charac': (6, -6, None, None, 'GACNNNNNGTC'), + 'ovhgseq': 'N', } rest_dict['Eam1105I'] = _temp() def _temp(): return { - 'compsite' : '(?PCTCTTC)|(?PGAAGAG)', - 'results' : None, - 'site' : 'CTCTTC', - 'substrat' : 'DNA', - 'fst3' : 4, - 'fst5' : 7, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (7, 4, None, None, 'CTCTTC'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PCTCTTC)|(?PGAAGAG)', + 'results': None, + 'site': 'CTCTTC', + 'substrat': 'DNA', + 'fst3': 4, + 'fst5': 7, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (7, 4, None, None, 'CTCTTC'), + 'ovhgseq': 'NNN', } rest_dict['EarI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGCGGA)|(?PTCCGCC)', - 'results' : None, - 'site' : 'GGCGGA', - 'substrat' : 'DNA', - 'fst3' : 9, - 'fst5' : 17, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (17, 9, None, None, 'GGCGGA'), - 'ovhgseq' : 'NN', + 'compsite': '(?PGGCGGA)|(?PTCCGCC)', + 'results': None, + 'site': 'GGCGGA', + 'substrat': 'DNA', + 'fst3': 9, + 'fst5': 17, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (17, 9, None, None, 'GGCGGA'), + 'ovhgseq': 'NN', } rest_dict['EciI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAGCTC)|(?PGAGCTC)', - 'results' : None, - 'site' : 'GAGCTC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GAGCTC'), - 'ovhgseq' : '', + 'compsite': '(?PGAGCTC)', + 'results': None, + 'site': 'GAGCTC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (3, -3, None, None, 'GAGCTC'), + 'ovhgseq': '', } rest_dict['Ecl136II'] = _temp() def _temp(): return { - 'compsite' : '(?PCGGCCG)|(?PCGGCCG)', - 'results' : None, - 'site' : 'CGGCCG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('M', 'S'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CGGCCG'), - 'ovhgseq' : 'GGCC', + 'compsite': '(?PCGGCCG)', + 'results': None, + 'site': 'CGGCCG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('M', 'S'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CGGCCG'), + 'ovhgseq': 'GGCC', } rest_dict['EclXI'] = _temp() def _temp(): return { - 'compsite' : '(?PTACGTA)|(?PTACGTA)', - 'results' : None, - 'site' : 'TACGTA', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F', 'O'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'TACGTA'), - 'ovhgseq' : '', + 'compsite': '(?PTACGTA)', + 'results': None, + 'site': 'TACGTA', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (3, -3, None, None, 'TACGTA'), + 'ovhgseq': '', } rest_dict['Eco105I'] = _temp() def _temp(): return { - 'compsite' : '(?PCC[AT][AT]GG)|(?PCC[AT][AT]GG)', - 'results' : None, - 'site' : 'CCWWGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCWWGG'), - 'ovhgseq' : 'CWWG', + 'compsite': '(?PCC[AT][AT]GG)', + 'results': None, + 'site': 'CCWWGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCWWGG'), + 'ovhgseq': 'CWWG', } rest_dict['Eco130I'] = _temp() def _temp(): return { - 'compsite' : '(?PAGGCCT)|(?PAGGCCT)', - 'results' : None, - 'site' : 'AGGCCT', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'AGGCCT'), - 'ovhgseq' : '', + 'compsite': '(?PAGGCCT)', + 'results': None, + 'site': 'AGGCCT', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (3, -3, None, None, 'AGGCCT'), + 'ovhgseq': '', } rest_dict['Eco147I'] = _temp() def _temp(): return { - 'compsite' : '(?PG[AG]GC[CT]C)|(?PG[AG]GC[CT]C)', - 'results' : None, - 'site' : 'GRGCYC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GRGCYC'), - 'ovhgseq' : 'RGCY', + 'compsite': '(?PG[AG]GC[CT]C)', + 'results': None, + 'site': 'GRGCYC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (5, -5, None, None, 'GRGCYC'), + 'ovhgseq': 'RGCY', } rest_dict['Eco24I'] = _temp() def _temp(): return { - 'compsite' : '(?PGGTCTC)|(?PGAGACC)', - 'results' : None, - 'site' : 'GGTCTC', - 'substrat' : 'DNA', - 'fst3' : 5, - 'fst5' : 7, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (7, 5, None, None, 'GGTCTC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PGGTCTC)|(?PGAGACC)', + 'results': None, + 'site': 'GGTCTC', + 'substrat': 'DNA', + 'fst3': 5, + 'fst5': 7, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (7, 5, None, None, 'GGTCTC'), + 'ovhgseq': 'NNNN', } rest_dict['Eco31I'] = _temp() def _temp(): return { - 'compsite' : '(?PGATATC)|(?PGATATC)', - 'results' : None, - 'site' : 'GATATC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GATATC'), - 'ovhgseq' : '', + 'compsite': '(?PGATATC)', + 'results': None, + 'site': 'GATATC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (3, -3, None, None, 'GATATC'), + 'ovhgseq': '', } rest_dict['Eco32I'] = _temp() def _temp(): return { - 'compsite' : '(?PGG[AT]CC)|(?PGG[AT]CC)', - 'results' : None, - 'site' : 'GGWCC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('F', 'O'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGWCC'), - 'ovhgseq' : 'GWC', + 'compsite': '(?PGG[AT]CC)', + 'results': None, + 'site': 'GGWCC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGWCC'), + 'ovhgseq': 'GWC', } rest_dict['Eco47I'] = _temp() def _temp(): return { - 'compsite' : '(?PAGCGCT)|(?PAGCGCT)', - 'results' : None, - 'site' : 'AGCGCT', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F', 'M', 'O', 'R', 'W'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'AGCGCT'), - 'ovhgseq' : '', + 'compsite': '(?PAGCGCT)', + 'results': None, + 'site': 'AGCGCT', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F', 'M', 'R'), + 'scd5': None, + 'charac': (3, -3, None, None, 'AGCGCT'), + 'ovhgseq': '', } rest_dict['Eco47III'] = _temp() def _temp(): return { - 'compsite' : '(?PCGGCCG)|(?PCGGCCG)', - 'results' : None, - 'site' : 'CGGCCG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F', 'K', 'O'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CGGCCG'), - 'ovhgseq' : 'GGCC', + 'compsite': '(?PCGGCCG)', + 'results': None, + 'site': 'CGGCCG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F', 'K'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CGGCCG'), + 'ovhgseq': 'GGCC', } rest_dict['Eco52I'] = _temp() def _temp(): return { - 'compsite' : '(?PGAGCTC)|(?PGAGCTC)', - 'results' : None, - 'site' : 'GAGCTC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GAGCTC'), - 'ovhgseq' : '', + 'compsite': '(?PGAGCTC)', + 'results': None, + 'site': 'GAGCTC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (3, -3, None, None, 'GAGCTC'), + 'ovhgseq': '', } rest_dict['Eco53kI'] = _temp() def _temp(): return { - 'compsite' : '(?PCTGAAG)|(?PCTTCAG)', - 'results' : None, - 'site' : 'CTGAAG', - 'substrat' : 'DNA', - 'fst3' : 14, - 'fst5' : 22, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (22, 14, None, None, 'CTGAAG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PCTGAAG)|(?PCTTCAG)', + 'results': None, + 'site': 'CTGAAG', + 'substrat': 'DNA', + 'fst3': 14, + 'fst5': 22, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (22, 14, None, None, 'CTGAAG'), + 'ovhgseq': 'NN', } rest_dict['Eco57I'] = _temp() def _temp(): return { - 'compsite' : '(?PCTG[AG]AG)|(?PCT[CT]CAG)', - 'results' : None, - 'site' : 'CTGRAG', - 'substrat' : 'DNA', - 'fst3' : 14, - 'fst5' : 22, - 'freq' : 2048, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (22, 14, None, None, 'CTGRAG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PCTG[AG]AG)|(?PCT[CT]CAG)', + 'results': None, + 'site': 'CTGRAG', + 'substrat': 'DNA', + 'fst3': 14, + 'fst5': 22, + 'freq': 2048, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (22, 14, None, None, 'CTGRAG'), + 'ovhgseq': 'NN', } rest_dict['Eco57MI'] = _temp() def _temp(): return { - 'compsite' : '(?PCACGTG)|(?PCACGTG)', - 'results' : None, - 'site' : 'CACGTG', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'CACGTG'), - 'ovhgseq' : '', + 'compsite': '(?PCACGTG)', + 'results': None, + 'site': 'CACGTG', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (3, -3, None, None, 'CACGTG'), + 'ovhgseq': '', } rest_dict['Eco72I'] = _temp() def _temp(): return { - 'compsite' : '(?PCCT.AGG)|(?PCCT.AGG)', - 'results' : None, - 'site' : 'CCTNAGG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('F', 'K', 'O'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CCTNAGG'), - 'ovhgseq' : 'TNA', + 'compsite': '(?PCCT.AGG)', + 'results': None, + 'site': 'CCTNAGG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('F', 'K'), + 'scd5': None, + 'charac': (2, -2, None, None, 'CCTNAGG'), + 'ovhgseq': 'TNA', } rest_dict['Eco81I'] = _temp() def _temp(): return { - 'compsite' : '(?PC[CT]CG[AG]G)|(?PC[CT]CG[AG]G)', - 'results' : None, - 'site' : 'CYCGRG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CYCGRG'), - 'ovhgseq' : 'YCGR', + 'compsite': '(?PC[CT]CG[AG]G)', + 'results': None, + 'site': 'CYCGRG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CYCGRG'), + 'ovhgseq': 'YCGR', } rest_dict['Eco88I'] = _temp() def _temp(): return { - 'compsite' : '(?PGGT.ACC)|(?PGGT.ACC)', - 'results' : None, - 'site' : 'GGTNACC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -5, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGTNACC'), - 'ovhgseq' : 'GTNAC', + 'compsite': '(?PGGT.ACC)', + 'results': None, + 'site': 'GGTNACC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGTNACC'), + 'ovhgseq': 'GTNAC', } rest_dict['Eco91I'] = _temp() def _temp(): return { - 'compsite' : '(?PCC[CG]GG)|(?PCC[CG]GG)', - 'results' : None, - 'site' : 'CCSGG', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -5, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'CCSGG'), - 'ovhgseq' : 'CCSGG', + 'compsite': '(?PCC[CG]GG)', + 'results': None, + 'site': 'CCSGG', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (0, 0, None, None, 'CCSGG'), + 'ovhgseq': 'CCSGG', } rest_dict['EcoHI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAGCTC)|(?PGAGCTC)', - 'results' : None, - 'site' : 'GAGCTC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I', 'R', 'V'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GAGCTC'), - 'ovhgseq' : '', + 'compsite': '(?PGAGCTC)', + 'results': None, + 'site': 'GAGCTC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I', 'R', 'V'), + 'scd5': None, + 'charac': (3, -3, None, None, 'GAGCTC'), + 'ovhgseq': '', } rest_dict['EcoICRI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCT.....AGG)|(?PCCT.....AGG)', - 'results' : None, - 'site' : 'CCTNNNNNAGG', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'CCTNNNNNAGG'), - 'ovhgseq' : 'N', + 'compsite': '(?PCCT.....AGG)', + 'results': None, + 'site': 'CCTNNNNNAGG', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (5, -5, None, None, 'CCTNNNNNAGG'), + 'ovhgseq': 'N', } rest_dict['EcoNI'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]GG.CC[CT])|(?P[AG]GG.CC[CT])', - 'results' : None, - 'site' : 'RGGNCCY', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 1024, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('F', 'J', 'K', 'N'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'RGGNCCY'), - 'ovhgseq' : 'GNC', + 'compsite': '(?P[AG]GG.CC[CT])', + 'results': None, + 'site': 'RGGNCCY', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 1024, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('F', 'J', 'K', 'N'), + 'scd5': None, + 'charac': (2, -2, None, None, 'RGGNCCY'), + 'ovhgseq': 'GNC', } rest_dict['EcoO109I'] = _temp() def _temp(): return { - 'compsite' : '(?PGGT.ACC)|(?PGGT.ACC)', - 'results' : None, - 'site' : 'GGTNACC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -5, - 'scd3' : None, - 'suppl' : ('K',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGTNACC'), - 'ovhgseq' : 'GTNAC', + 'compsite': '(?PGGT.ACC)', + 'results': None, + 'site': 'GGTNACC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': None, + 'suppl': ('K',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGTNACC'), + 'ovhgseq': 'GTNAC', } rest_dict['EcoO65I'] = _temp() def _temp(): return { - 'compsite' : '(?PGAATTC)|(?PGAATTC)', - 'results' : None, - 'site' : 'GAATTC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('B', 'C', 'F', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GAATTC'), - 'ovhgseq' : 'AATT', + 'compsite': '(?PGAATTC)', + 'results': None, + 'site': 'GAATTC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('B', 'C', 'F', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'X', 'Y'), + 'scd5': None, + 'charac': (1, -1, None, None, 'GAATTC'), + 'ovhgseq': 'AATT', } rest_dict['EcoRI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC[AT]GG)|(?PCC[AT]GG)', - 'results' : None, - 'site' : 'CCWGG', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -5, - 'scd3' : None, - 'suppl' : ('F', 'J', 'M', 'O', 'S'), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'CCWGG'), - 'ovhgseq' : 'CCWGG', + 'compsite': '(?PCC[AT]GG)', + 'results': None, + 'site': 'CCWGG', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': None, + 'suppl': ('F', 'J'), + 'scd5': None, + 'charac': (0, 0, None, None, 'CCWGG'), + 'ovhgseq': 'CCWGG', } rest_dict['EcoRII'] = _temp() def _temp(): return { - 'compsite' : '(?PGATATC)|(?PGATATC)', - 'results' : None, - 'site' : 'GATATC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('B', 'C', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GATATC'), - 'ovhgseq' : '', + 'compsite': '(?PGATATC)', + 'results': None, + 'site': 'GATATC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('B', 'C', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'X', 'Y'), + 'scd5': None, + 'charac': (3, -3, None, None, 'GATATC'), + 'ovhgseq': '', } rest_dict['EcoRV'] = _temp() def _temp(): return { - 'compsite' : '(?PCC[AT][AT]GG)|(?PCC[AT][AT]GG)', - 'results' : None, - 'site' : 'CCWWGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('K',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCWWGG'), - 'ovhgseq' : 'CWWG', + 'compsite': '(?PCC[AT][AT]GG)', + 'results': None, + 'site': 'CCWWGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('K',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCWWGG'), + 'ovhgseq': 'CWWG', } rest_dict['EcoT14I'] = _temp() def _temp(): return { - 'compsite' : '(?PATGCAT)|(?PATGCAT)', - 'results' : None, - 'site' : 'ATGCAT', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('K', 'O'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'ATGCAT'), - 'ovhgseq' : 'TGCA', + 'compsite': '(?PATGCAT)', + 'results': None, + 'site': 'ATGCAT', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('B', 'K'), + 'scd5': None, + 'charac': (5, -5, None, None, 'ATGCAT'), + 'ovhgseq': 'TGCA', } rest_dict['EcoT22I'] = _temp() def _temp(): return { - 'compsite' : '(?PG[AG]GC[CT]C)|(?PG[AG]GC[CT]C)', - 'results' : None, - 'site' : 'GRGCYC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('J',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GRGCYC'), - 'ovhgseq' : 'RGCY', + 'compsite': '(?PG[AG]GC[CT]C)', + 'results': None, + 'site': 'GRGCYC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('J',), + 'scd5': None, + 'charac': (5, -5, None, None, 'GRGCYC'), + 'ovhgseq': 'RGCY', } rest_dict['EcoT38I'] = _temp() def _temp(): return { - 'compsite' : '(?PGGCGCC)|(?PGGCGCC)', - 'results' : None, - 'site' : 'GGCGCC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GGCGCC'), - 'ovhgseq' : '', + 'compsite': '(?PGGCGCC)', + 'results': None, + 'site': 'GGCGCC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (3, -3, None, None, 'GGCGCC'), + 'ovhgseq': '', } rest_dict['EgeI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGCGCC)|(?PGGCGCC)', - 'results' : None, - 'site' : 'GGCGCC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F', 'O'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GGCGCC'), - 'ovhgseq' : '', + 'compsite': '(?PGGCGCC)', + 'results': None, + 'site': 'GGCGCC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (3, -3, None, None, 'GGCGCC'), + 'ovhgseq': '', } rest_dict['EheI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC[AT][AT]GG)|(?PCC[AT][AT]GG)', - 'results' : None, - 'site' : 'CCWWGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCWWGG'), - 'ovhgseq' : 'CWWG', + 'compsite': '(?PCC[AT][AT]GG)', + 'results': None, + 'site': 'CCWWGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCWWGG'), + 'ovhgseq': 'CWWG', } rest_dict['ErhI'] = _temp() def _temp(): return { - 'compsite' : '(?PTCGA)|(?PTCGA)', - 'results' : None, - 'site' : 'TCGA', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'TCGA'), - 'ovhgseq' : '', + 'compsite': '(?PTCGA)', + 'results': None, + 'site': 'TCGA', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (2, -2, None, None, 'TCGA'), + 'ovhgseq': '', } rest_dict['EsaBC3I'] = _temp() def _temp(): return { - 'compsite' : '(?PGACCAC)|(?PGTGGTC)', - 'results' : None, - 'site' : 'GACCAC', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'GACCAC'), - 'ovhgseq' : None, + 'compsite': '(?PGACCAC)|(?PGTGGTC)', + 'results': None, + 'site': 'GACCAC', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'GACCAC'), + 'ovhgseq': None, } rest_dict['EsaSSI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGTCTC)|(?PGAGACG)', - 'results' : None, - 'site' : 'CGTCTC', - 'substrat' : 'DNA', - 'fst3' : 5, - 'fst5' : 7, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (7, 5, None, None, 'CGTCTC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PCGTCTC)|(?PGAGACG)', + 'results': None, + 'site': 'CGTCTC', + 'substrat': 'DNA', + 'fst3': 5, + 'fst5': 7, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (7, 5, None, None, 'CGTCTC'), + 'ovhgseq': 'NNNN', } rest_dict['Esp3I'] = _temp() def _temp(): return { - 'compsite' : '(?PGCT.AGC)|(?PGCT.AGC)', - 'results' : None, - 'site' : 'GCTNAGC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GCTNAGC'), - 'ovhgseq' : 'TNA', + 'compsite': '(?PGCT.AGC)', + 'results': None, + 'site': 'GCTNAGC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (2, -2, None, None, 'GCTNAGC'), + 'ovhgseq': 'TNA', } rest_dict['EspI'] = _temp() def _temp(): return { - 'compsite' : '(?PCATG)|(?PCATG)', - 'results' : None, - 'site' : 'CATG', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'CATG'), - 'ovhgseq' : 'CATG', + 'compsite': '(?PCATG)', + 'results': None, + 'site': 'CATG', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (4, -4, None, None, 'CATG'), + 'ovhgseq': 'CATG', } rest_dict['FaeI'] = _temp() def _temp(): return { - 'compsite' : '(?P[CT]AT[AG])|(?P[CT]AT[AG])', - 'results' : None, - 'site' : 'YATR', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 64, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'YATR'), - 'ovhgseq' : '', + 'compsite': '(?P[CT]AT[AG])', + 'results': None, + 'site': 'YATR', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 64, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (2, -2, None, None, 'YATR'), + 'ovhgseq': '', } rest_dict['FaiI'] = _temp() def _temp(): return { - 'compsite' : '(?PAAG.....CTT)|(?PAAG.....CTT)', - 'results' : None, - 'site' : 'AAGNNNNNCTT', - 'substrat' : 'DNA', - 'fst3' : -24, - 'fst5' : -8, - 'freq' : 4096, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 5, - 'scd3' : 8, - 'suppl' : ('I',), - 'scd5' : 24, - 'charac' : (-8, -24, 24, 8, 'AAGNNNNNCTT'), - 'ovhgseq' : 'NNNNN', + 'compsite': '(?PAAG.....CTT)', + 'results': None, + 'site': 'AAGNNNNNCTT', + 'substrat': 'DNA', + 'fst3': -24, + 'fst5': -8, + 'freq': 4096, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 5, + 'scd3': 8, + 'suppl': ('I',), + 'scd5': 24, + 'charac': (-8, -24, 24, 8, 'AAGNNNNNCTT'), + 'ovhgseq': 'NNNNN', } rest_dict['FalI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGGAC)|(?PGTCCC)', - 'results' : None, - 'site' : 'GGGAC', - 'substrat' : 'DNA', - 'fst3' : 14, - 'fst5' : 15, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (15, 14, None, None, 'GGGAC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PGGGAC)|(?PGTCCC)', + 'results': None, + 'site': 'GGGAC', + 'substrat': 'DNA', + 'fst3': 14, + 'fst5': 15, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (15, 14, None, None, 'GGGAC'), + 'ovhgseq': 'NNNN', } rest_dict['FaqI'] = _temp() def _temp(): return { - 'compsite' : '(?PCATG)|(?PCATG)', - 'results' : None, - 'site' : 'CATG', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'N'), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'CATG'), - 'ovhgseq' : 'CATG', + 'compsite': '(?PCATG)', + 'results': None, + 'site': 'CATG', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'N'), + 'scd5': None, + 'charac': (0, 0, None, None, 'CATG'), + 'ovhgseq': 'CATG', } rest_dict['FatI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCCGC)|(?PGCGGG)', - 'results' : None, - 'site' : 'CCCGC', - 'substrat' : 'DNA', - 'fst3' : 6, - 'fst5' : 9, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('I', 'N'), - 'scd5' : None, - 'charac' : (9, 6, None, None, 'CCCGC'), - 'ovhgseq' : 'NN', + 'compsite': '(?PCCCGC)|(?PGCGGG)', + 'results': None, + 'site': 'CCCGC', + 'substrat': 'DNA', + 'fst3': 6, + 'fst5': 9, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('I', 'N'), + 'scd5': None, + 'charac': (9, 6, None, None, 'CCCGC'), + 'ovhgseq': 'NN', } rest_dict['FauI'] = _temp() def _temp(): return { - 'compsite' : '(?PCATATG)|(?PCATATG)', - 'results' : None, - 'site' : 'CATATG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CATATG'), - 'ovhgseq' : 'TA', + 'compsite': '(?PCATATG)', + 'results': None, + 'site': 'CATATG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (2, -2, None, None, 'CATATG'), + 'ovhgseq': 'TA', } rest_dict['FauNDI'] = _temp() def _temp(): return { - 'compsite' : '(?PTGATCA)|(?PTGATCA)', - 'results' : None, - 'site' : 'TGATCA', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('K',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'TGATCA'), - 'ovhgseq' : 'GATC', + 'compsite': '(?PTGATCA)', + 'results': None, + 'site': 'TGATCA', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('K',), + 'scd5': None, + 'charac': (1, -1, None, None, 'TGATCA'), + 'ovhgseq': 'GATC', } rest_dict['FbaI'] = _temp() def _temp(): return { - 'compsite' : '(?PGT[AC][GT]AC)|(?PGT[AC][GT]AC)', - 'results' : None, - 'site' : 'GTMKAC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GTMKAC'), - 'ovhgseq' : 'MK', + 'compsite': '(?PGT[AC][GT]AC)', + 'results': None, + 'site': 'GTMKAC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (2, -2, None, None, 'GTMKAC'), + 'ovhgseq': 'MK', } rest_dict['FblI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGGAC)|(?PGTCCC)', - 'results' : None, - 'site' : 'GGGAC', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'GGGAC'), - 'ovhgseq' : None, + 'compsite': '(?PGGGAC)|(?PGTCCC)', + 'results': None, + 'site': 'GGGAC', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'GGGAC'), + 'ovhgseq': None, } rest_dict['FinI'] = _temp() def _temp(): return { - 'compsite' : '(?PGG.CC)|(?PGG.CC)', - 'results' : None, - 'site' : 'GGNCC', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'GGNCC'), - 'ovhgseq' : 'GNC', + 'compsite': '(?PGG.CC)', + 'results': None, + 'site': 'GGNCC', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (4, -4, None, None, 'GGNCC'), + 'ovhgseq': 'GNC', } rest_dict['FmuI'] = _temp() def _temp(): return { - 'compsite' : '(?PGC.GC)|(?PGC.GC)', - 'results' : None, - 'site' : 'GCNGC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GCNGC'), - 'ovhgseq' : 'N', + 'compsite': '(?PGC.GC)', + 'results': None, + 'site': 'GCNGC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (2, -2, None, None, 'GCNGC'), + 'ovhgseq': 'N', } rest_dict['Fnu4HI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGCG)|(?PCGCG)', - 'results' : None, - 'site' : 'CGCG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CGCG'), - 'ovhgseq' : '', + 'compsite': '(?PCGCG)', + 'results': None, + 'site': 'CGCG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (2, -2, None, None, 'CGCG'), + 'ovhgseq': '', } rest_dict['FnuDII'] = _temp() def _temp(): return { - 'compsite' : '(?PGGATG)|(?PCATCC)', - 'results' : None, - 'site' : 'GGATG', - 'substrat' : 'DNA', - 'fst3' : 13, - 'fst5' : 14, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'J', 'K', 'M', 'N', 'Q', 'R', 'V', 'W', 'X'), - 'scd5' : None, - 'charac' : (14, 13, None, None, 'GGATG'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PGGATG)|(?PCATCC)', + 'results': None, + 'site': 'GGATG', + 'substrat': 'DNA', + 'fst3': 13, + 'fst5': 14, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'J', 'K', 'M', 'N', 'V', 'X'), + 'scd5': None, + 'charac': (14, 13, None, None, 'GGATG'), + 'ovhgseq': 'NNNN', } rest_dict['FokI'] = _temp() def _temp(): return { - 'compsite' : '(?PG[AG]GC[CT]C)|(?PG[AG]GC[CT]C)', - 'results' : None, - 'site' : 'GRGCYC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GRGCYC'), - 'ovhgseq' : 'RGCY', + 'compsite': '(?PG[AG]GC[CT]C)', + 'results': None, + 'site': 'GRGCYC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (5, -5, None, None, 'GRGCYC'), + 'ovhgseq': 'RGCY', } rest_dict['FriOI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGCCGGCC)|(?PGGCCGGCC)', - 'results' : None, - 'site' : 'GGCCGGCC', - 'substrat' : 'DNA', - 'fst3' : -6, - 'fst5' : 6, - 'freq' : 65536, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (6, -6, None, None, 'GGCCGGCC'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?PGGCCGGCC)', + 'results': None, + 'site': 'GGCCGGCC', + 'substrat': 'DNA', + 'fst3': -6, + 'fst5': 6, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (6, -6, None, None, 'GGCCGGCC'), + 'ovhgseq': 'CCGG', } rest_dict['FseI'] = _temp() def _temp(): return { - 'compsite' : '(?PGC.GC)|(?PGC.GC)', - 'results' : None, - 'site' : 'GCNGC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GCNGC'), - 'ovhgseq' : 'N', + 'compsite': '(?PGC.GC)', + 'results': None, + 'site': 'GCNGC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (2, -2, None, None, 'GCNGC'), + 'ovhgseq': 'N', } rest_dict['Fsp4HI'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]TGCGCA[CT])|(?P[AG]TGCGCA[CT])', - 'results' : None, - 'site' : 'RTGCGCAY', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 16384, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'RTGCGCAY'), - 'ovhgseq' : '', + 'compsite': '(?P[AG]TGCGCA[CT])', + 'results': None, + 'site': 'RTGCGCAY', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 16384, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (4, -4, None, None, 'RTGCGCAY'), + 'ovhgseq': '', } rest_dict['FspAI'] = _temp() def _temp(): return { - 'compsite' : '(?PCTAG)|(?PCTAG)', - 'results' : None, - 'site' : 'CTAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTAG'), - 'ovhgseq' : 'TA', + 'compsite': '(?PCTAG)', + 'results': None, + 'site': 'CTAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CTAG'), + 'ovhgseq': 'TA', } rest_dict['FspBI'] = _temp() def _temp(): return { - 'compsite' : '(?PTGCGCA)|(?PTGCGCA)', - 'results' : None, - 'site' : 'TGCGCA', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('J', 'N', 'O'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'TGCGCA'), - 'ovhgseq' : '', + 'compsite': '(?PCC)|(?PGG)', + 'results': None, + 'site': 'CC', + 'substrat': 'DNA', + 'fst3': 16, + 'fst5': 14, + 'freq': 16, + 'size': 2, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (14, 16, None, None, 'CC'), + 'ovhgseq': 'NNNN', + } +rest_dict['FspEI'] = _temp() + +def _temp(): + return { + 'compsite': '(?PTGCGCA)', + 'results': None, + 'site': 'TGCGCA', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('J', 'N'), + 'scd5': None, + 'charac': (3, -3, None, None, 'TGCGCA'), + 'ovhgseq': '', } rest_dict['FspI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGGCC[AG])|(?P[CT]GGCCG)', - 'results' : None, - 'site' : 'CGGCCR', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 2048, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CGGCCR'), - 'ovhgseq' : 'GGCC', + 'compsite': '(?PCGCGCAGG)|(?PCCTGCGCG)', + 'results': None, + 'site': 'CGCGCAGG', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'CGCGCAGG'), + 'ovhgseq': None, + } +rest_dict['GauT27I'] = _temp() + +def _temp(): + return { + 'compsite': '(?PCGGCC[AG])|(?P[CT]GGCCG)', + 'results': None, + 'site': 'CGGCCR', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 2048, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (1, -1, None, None, 'CGGCCR'), + 'ovhgseq': 'GGCC', } rest_dict['GdiII'] = _temp() def _temp(): return { - 'compsite' : '(?PGCGC)|(?PGCGC)', - 'results' : None, - 'site' : 'GCGC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GCGC'), - 'ovhgseq' : '', + 'compsite': '(?PGCGC)', + 'results': None, + 'site': 'GCGC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (2, -2, None, None, 'GCGC'), + 'ovhgseq': '', } rest_dict['GlaI'] = _temp() def _temp(): return { - 'compsite' : '(?PGC.GC)|(?PGC.GC)', - 'results' : None, - 'site' : 'GCNGC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GCNGC'), - 'ovhgseq' : 'N', + 'compsite': '(?PGC.GC)', + 'results': None, + 'site': 'GCNGC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (2, -2, None, None, 'GCNGC'), + 'ovhgseq': 'N', } rest_dict['GluI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCCAGC)|(?PGCTGGG)', - 'results' : None, - 'site' : 'CCCAGC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'CCCAGC'), - 'ovhgseq' : 'CCAG', + 'compsite': '(?PCCCAGC)|(?PGCTGGG)', + 'results': None, + 'site': 'CCCAGC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (5, -5, None, None, 'CCCAGC'), + 'ovhgseq': 'CCAG', } rest_dict['GsaI'] = _temp() def _temp(): return { - 'compsite' : '(?PCTGGAG)|(?PCTCCAG)', - 'results' : None, - 'site' : 'CTGGAG', - 'substrat' : 'DNA', - 'fst3' : 14, - 'fst5' : 22, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (22, 14, None, None, 'CTGGAG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PCTGGAG)|(?PCTCCAG)', + 'results': None, + 'site': 'CTGGAG', + 'substrat': 'DNA', + 'fst3': 14, + 'fst5': 22, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (22, 14, None, None, 'CTGGAG'), + 'ovhgseq': 'NN', } rest_dict['GsuI'] = _temp() def _temp(): return { - 'compsite' : '(?P[AT]GGCC[AT])|(?P[AT]GGCC[AT])', - 'results' : None, - 'site' : 'WGGCCW', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'WGGCCW'), - 'ovhgseq' : '', + 'compsite': '(?P[AT]GGCC[AT])', + 'results': None, + 'site': 'WGGCCW', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (3, -3, None, None, 'WGGCCW'), + 'ovhgseq': '', } rest_dict['HaeI'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]GCGC[CT])|(?P[AG]GCGC[CT])', - 'results' : None, - 'site' : 'RGCGCY', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('J', 'K', 'N', 'O', 'R', 'W'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'RGCGCY'), - 'ovhgseq' : 'GCGC', + 'compsite': '(?P[AG]GCGC[CT])', + 'results': None, + 'site': 'RGCGCY', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('J', 'K', 'N', 'R'), + 'scd5': None, + 'charac': (5, -5, None, None, 'RGCGCY'), + 'ovhgseq': 'GCGC', } rest_dict['HaeII'] = _temp() def _temp(): return { - 'compsite' : '(?PGGCC)|(?PGGCC)', - 'results' : None, - 'site' : 'GGCC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('B', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GGCC'), - 'ovhgseq' : '', + 'compsite': '(?PGGCC)', + 'results': None, + 'site': 'GGCC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('B', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'X', 'Y'), + 'scd5': None, + 'charac': (2, -2, None, None, 'GGCC'), + 'ovhgseq': '', } rest_dict['HaeIII'] = _temp() def _temp(): return { - 'compsite' : '(?PCCGG)|(?PCCGG)', - 'results' : None, - 'site' : 'CCGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('K',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCGG'), - 'ovhgseq' : 'CG', + 'compsite': '(?PCCGG)', + 'results': None, + 'site': 'CCGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('B', 'K'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCGG'), + 'ovhgseq': 'CG', } rest_dict['HapII'] = _temp() def _temp(): return { - 'compsite' : '(?PGACGC)|(?PGCGTC)', - 'results' : None, - 'site' : 'GACGC', - 'substrat' : 'DNA', - 'fst3' : 10, - 'fst5' : 10, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -5, - 'scd3' : None, - 'suppl' : ('I', 'N'), - 'scd5' : None, - 'charac' : (10, 10, None, None, 'GACGC'), - 'ovhgseq' : 'NNNNN', + 'compsite': '(?PTGGCCA)', + 'results': None, + 'site': 'TGGCCA', + 'substrat': 'DNA', + 'fst3': 9, + 'fst5': 17, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (17, 9, None, None, 'TGGCCA'), + 'ovhgseq': 'NN', + } +rest_dict['HauII'] = _temp() + +def _temp(): + return { + 'compsite': '(?PGACGC)|(?PGCGTC)', + 'results': None, + 'site': 'GACGC', + 'substrat': 'DNA', + 'fst3': 10, + 'fst5': 10, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': None, + 'suppl': ('I', 'N'), + 'scd5': None, + 'charac': (10, 10, None, None, 'GACGC'), + 'ovhgseq': 'NNNNN', } rest_dict['HgaI'] = _temp() def _temp(): return { - 'compsite' : '(?PG[AT]GC[AT]C)|(?PG[AT]GC[AT]C)', - 'results' : None, - 'site' : 'GWGCWC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GWGCWC'), - 'ovhgseq' : 'WGCW', + 'compsite': '(?PG[AT]GC[AT]C)', + 'results': None, + 'site': 'GWGCWC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (5, -5, None, None, 'GWGCWC'), + 'ovhgseq': 'WGCW', } rest_dict['HgiAI'] = _temp() def _temp(): return { - 'compsite' : '(?PGG[CT][AG]CC)|(?PGG[CT][AG]CC)', - 'results' : None, - 'site' : 'GGYRCC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGYRCC'), - 'ovhgseq' : 'GYRC', + 'compsite': '(?PGG[CT][AG]CC)', + 'results': None, + 'site': 'GGYRCC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGYRCC'), + 'ovhgseq': 'GYRC', } rest_dict['HgiCI'] = _temp() def _temp(): return { - 'compsite' : '(?PACC......GGT)|(?PACC......GGT)', - 'results' : None, - 'site' : 'ACCNNNNNNGGT', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 4096, - 'size' : 12, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'ACCNNNNNNGGT'), - 'ovhgseq' : None, + 'compsite': '(?PACC......GGT)', + 'results': None, + 'site': 'ACCNNNNNNGGT', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 4096, + 'size': 12, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'ACCNNNNNNGGT'), + 'ovhgseq': None, } rest_dict['HgiEII'] = _temp() def _temp(): return { - 'compsite' : '(?PG[AG]GC[CT]C)|(?PG[AG]GC[CT]C)', - 'results' : None, - 'site' : 'GRGCYC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GRGCYC'), - 'ovhgseq' : 'RGCY', + 'compsite': '(?PG[AG]GC[CT]C)', + 'results': None, + 'site': 'GRGCYC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (5, -5, None, None, 'GRGCYC'), + 'ovhgseq': 'RGCY', } rest_dict['HgiJII'] = _temp() def _temp(): return { - 'compsite' : '(?PGCGC)|(?PGCGC)', - 'results' : None, - 'site' : 'GCGC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('B', 'F', 'J', 'K', 'N', 'O', 'R', 'U', 'W', 'Y'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GCGC'), - 'ovhgseq' : 'CG', + 'compsite': '(?PGCGC)', + 'results': None, + 'site': 'GCGC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('B', 'F', 'J', 'K', 'N', 'Q', 'R', 'U', 'X', 'Y'), + 'scd5': None, + 'charac': (3, -3, None, None, 'GCGC'), + 'ovhgseq': 'CG', } rest_dict['HhaI'] = _temp() def _temp(): return { - 'compsite' : '(?PG[AG]CG[CT]C)|(?PG[AG]CG[CT]C)', - 'results' : None, - 'site' : 'GRCGYC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('F', 'K', 'O'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GRCGYC'), - 'ovhgseq' : 'CG', + 'compsite': '(?PG[AG]CG[CT]C)', + 'results': None, + 'site': 'GRCGYC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('F', 'K'), + 'scd5': None, + 'charac': (2, -2, None, None, 'GRCGYC'), + 'ovhgseq': 'CG', } rest_dict['Hin1I'] = _temp() def _temp(): return { - 'compsite' : '(?PCATG)|(?PCATG)', - 'results' : None, - 'site' : 'CATG', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'CATG'), - 'ovhgseq' : 'CATG', + 'compsite': '(?PCATG)', + 'results': None, + 'site': 'CATG', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (4, -4, None, None, 'CATG'), + 'ovhgseq': 'CATG', } rest_dict['Hin1II'] = _temp() def _temp(): return { - 'compsite' : '(?PGA[CT].....[ACG]TC)|(?PGA[CGT].....[AG]TC)', - 'results' : None, - 'site' : 'GAYNNNNNVTC', - 'substrat' : 'DNA', - 'fst3' : -24, - 'fst5' : -8, - 'freq' : 512, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 5, - 'scd3' : 8, - 'suppl' : ('F',), - 'scd5' : 24, - 'charac' : (-8, -24, 24, 8, 'GAYNNNNNVTC'), - 'ovhgseq' : 'NNNNN', + 'compsite': '(?PGA[CT].....[ACG]TC)|(?PGA[CGT].....[AG]TC)', + 'results': None, + 'site': 'GAYNNNNNVTC', + 'substrat': 'DNA', + 'fst3': -24, + 'fst5': -8, + 'freq': 512, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 5, + 'scd3': 8, + 'suppl': (), + 'scd5': 24, + 'charac': (-8, -24, 24, 8, 'GAYNNNNNVTC'), + 'ovhgseq': 'NNNNN', } rest_dict['Hin4I'] = _temp() def _temp(): return { - 'compsite' : '(?PCCTTC)|(?PGAAGG)', - 'results' : None, - 'site' : 'CCTTC', - 'substrat' : 'DNA', - 'fst3' : 5, - 'fst5' : 11, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 1, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (11, 5, None, None, 'CCTTC'), - 'ovhgseq' : 'N', + 'compsite': '(?PCCTTC)|(?PGAAGG)', + 'results': None, + 'site': 'CCTTC', + 'substrat': 'DNA', + 'fst3': 5, + 'fst5': 11, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (11, 5, None, None, 'CCTTC'), + 'ovhgseq': 'N', } rest_dict['Hin4II'] = _temp() def _temp(): return { - 'compsite' : '(?PGCGC)|(?PGCGC)', - 'results' : None, - 'site' : 'GCGC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GCGC'), - 'ovhgseq' : 'CG', + 'compsite': '(?PGCGC)', + 'results': None, + 'site': 'GCGC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GCGC'), + 'ovhgseq': 'CG', } rest_dict['Hin6I'] = _temp() def _temp(): return { - 'compsite' : '(?PGCGC)|(?PGCGC)', - 'results' : None, - 'site' : 'GCGC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GCGC'), - 'ovhgseq' : 'CG', + 'compsite': '(?PGCGC)', + 'results': None, + 'site': 'GCGC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GCGC'), + 'ovhgseq': 'CG', } rest_dict['HinP1I'] = _temp() def _temp(): return { - 'compsite' : '(?PGT[CT][AG]AC)|(?PGT[CT][AG]AC)', - 'results' : None, - 'site' : 'GTYRAC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('B', 'F', 'H', 'J', 'K', 'N', 'O', 'Q', 'R', 'U', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GTYRAC'), - 'ovhgseq' : '', + 'compsite': '(?PGT[CT][AG]AC)', + 'results': None, + 'site': 'GTYRAC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('B', 'F', 'J', 'K', 'N', 'O', 'Q', 'R', 'U', 'X', 'Y'), + 'scd5': None, + 'charac': (3, -3, None, None, 'GTYRAC'), + 'ovhgseq': '', } rest_dict['HincII'] = _temp() def _temp(): return { - 'compsite' : '(?PGT[CT][AG]AC)|(?PGT[CT][AG]AC)', - 'results' : None, - 'site' : 'GTYRAC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I', 'M', 'S', 'V'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GTYRAC'), - 'ovhgseq' : '', + 'compsite': '(?PGT[CT][AG]AC)', + 'results': None, + 'site': 'GTYRAC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I', 'M', 'V'), + 'scd5': None, + 'charac': (3, -3, None, None, 'GTYRAC'), + 'ovhgseq': '', } rest_dict['HindII'] = _temp() def _temp(): return { - 'compsite' : '(?PAAGCTT)|(?PAAGCTT)', - 'results' : None, - 'site' : 'AAGCTT', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('B', 'C', 'F', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'AAGCTT'), - 'ovhgseq' : 'AGCT', + 'compsite': '(?PAAGCTT)', + 'results': None, + 'site': 'AAGCTT', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('B', 'C', 'F', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'X', 'Y'), + 'scd5': None, + 'charac': (1, -1, None, None, 'AAGCTT'), + 'ovhgseq': 'AGCT', } rest_dict['HindIII'] = _temp() def _temp(): return { - 'compsite' : '(?PGA.TC)|(?PGA.TC)', - 'results' : None, - 'site' : 'GANTC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('B', 'C', 'F', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'U', 'V', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GANTC'), - 'ovhgseq' : 'ANT', + 'compsite': '(?PGA.TC)', + 'results': None, + 'site': 'GANTC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('B', 'C', 'F', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'U', 'V', 'X', 'Y'), + 'scd5': None, + 'charac': (1, -1, None, None, 'GANTC'), + 'ovhgseq': 'ANT', } rest_dict['HinfI'] = _temp() def _temp(): return { - 'compsite' : '(?PGTTAAC)|(?PGTTAAC)', - 'results' : None, - 'site' : 'GTTAAC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('B', 'C', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'W', 'X'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GTTAAC'), - 'ovhgseq' : '', + 'compsite': '(?PGTTAAC)', + 'results': None, + 'site': 'GTTAAC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('B', 'C', 'I', 'J', 'K', 'M', 'N', 'Q', 'R', 'S', 'U', 'V', 'X'), + 'scd5': None, + 'charac': (3, -3, None, None, 'GTTAAC'), + 'ovhgseq': '', } rest_dict['HpaI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCGG)|(?PCCGG)', - 'results' : None, - 'site' : 'CCGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('B', 'F', 'I', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'W', 'X'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCGG'), - 'ovhgseq' : 'CG', + 'compsite': '(?PCCGG)', + 'results': None, + 'site': 'CCGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('F', 'I', 'N', 'Q', 'R', 'S', 'U', 'V', 'X'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCGG'), + 'ovhgseq': 'CG', } rest_dict['HpaII'] = _temp() def _temp(): return { - 'compsite' : '(?PGGTGA)|(?PTCACC)', - 'results' : None, - 'site' : 'GGTGA', - 'substrat' : 'DNA', - 'fst3' : 7, - 'fst5' : 13, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 1, - 'scd3' : None, - 'suppl' : ('F', 'N'), - 'scd5' : None, - 'charac' : (13, 7, None, None, 'GGTGA'), - 'ovhgseq' : 'N', + 'compsite': '(?PGGTGA)|(?PTCACC)', + 'results': None, + 'site': 'GGTGA', + 'substrat': 'DNA', + 'fst3': 7, + 'fst5': 13, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': ('F', 'N'), + 'scd5': None, + 'charac': (13, 7, None, None, 'GGTGA'), + 'ovhgseq': 'N', } rest_dict['HphI'] = _temp() def _temp(): return { - 'compsite' : '(?PGT..AC)|(?PGT..AC)', - 'results' : None, - 'site' : 'GTNNAC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 256, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GTNNAC'), - 'ovhgseq' : '', + 'compsite': '(?PGT..AC)', + 'results': None, + 'site': 'GTNNAC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 256, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (3, -3, None, None, 'GTNNAC'), + 'ovhgseq': '', } rest_dict['Hpy166II'] = _temp() def _temp(): return { - 'compsite' : '(?PTC..GA)|(?PTC..GA)', - 'results' : None, - 'site' : 'TCNNGA', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'TCNNGA'), - 'ovhgseq' : 'NN', + 'compsite': '(?PTC..GA)', + 'results': None, + 'site': 'TCNNGA', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (2, -2, None, None, 'TCNNGA'), + 'ovhgseq': 'NN', } rest_dict['Hpy178III'] = _temp() def _temp(): return { - 'compsite' : '(?PTC.GA)|(?PTC.GA)', - 'results' : None, - 'site' : 'TCNGA', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 1, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'TCNGA'), - 'ovhgseq' : 'N', + 'compsite': '(?PTC.GA)', + 'results': None, + 'site': 'TCNGA', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (3, -3, None, None, 'TCNGA'), + 'ovhgseq': 'N', } rest_dict['Hpy188I'] = _temp() def _temp(): return { - 'compsite' : '(?PTC..GA)|(?PTC..GA)', - 'results' : None, - 'site' : 'TCNNGA', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'TCNNGA'), - 'ovhgseq' : 'NN', + 'compsite': '(?PTC..GA)', + 'results': None, + 'site': 'TCNNGA', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (2, -2, None, None, 'TCNNGA'), + 'ovhgseq': 'NN', } rest_dict['Hpy188III'] = _temp() def _temp(): return { - 'compsite' : '(?PGT..AC)|(?PGT..AC)', - 'results' : None, - 'site' : 'GTNNAC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 256, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GTNNAC'), - 'ovhgseq' : '', + 'compsite': '(?PGT..AC)', + 'results': None, + 'site': 'GTNNAC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 256, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (3, -3, None, None, 'GTNNAC'), + 'ovhgseq': '', } rest_dict['Hpy8I'] = _temp() def _temp(): return { - 'compsite' : '(?PCG[AT]CG)|(?PCG[AT]CG)', - 'results' : None, - 'site' : 'CGWCG', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 5, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'CGWCG'), - 'ovhgseq' : 'CGWCG', + 'compsite': '(?PCG[AT]CG)', + 'results': None, + 'site': 'CGWCG', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 5, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (5, -5, None, None, 'CGWCG'), + 'ovhgseq': 'CGWCG', } rest_dict['Hpy99I'] = _temp() def _temp(): return { - 'compsite' : '(?PCCTTC)|(?PGAAGG)', - 'results' : None, - 'site' : 'CCTTC', - 'substrat' : 'DNA', - 'fst3' : 5, - 'fst5' : 11, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 1, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (11, 5, None, None, 'CCTTC'), - 'ovhgseq' : 'N', + 'compsite': '(?PGCCTA)|(?PTAGGC)', + 'results': None, + 'site': 'GCCTA', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'GCCTA'), + 'ovhgseq': None, + } +rest_dict['Hpy99XIII'] = _temp() + +def _temp(): + return { + 'compsite': '(?PGG[AT]TAA)|(?PTTA[AT]CC)', + 'results': None, + 'site': 'GGWTAA', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 2048, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'GGWTAA'), + 'ovhgseq': None, + } +rest_dict['Hpy99XIV'] = _temp() + +def _temp(): + return { + 'compsite': '(?PCCTTC)|(?PGAAGG)', + 'results': None, + 'site': 'CCTTC', + 'substrat': 'DNA', + 'fst3': 5, + 'fst5': 11, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (11, 5, None, None, 'CCTTC'), + 'ovhgseq': 'N', } rest_dict['HpyAV'] = _temp() def _temp(): return { - 'compsite' : '(?PAC.GT)|(?PAC.GT)', - 'results' : None, - 'site' : 'ACNGT', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 1, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'ACNGT'), - 'ovhgseq' : 'N', + 'compsite': '(?PAC.GT)', + 'results': None, + 'site': 'ACNGT', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (3, -3, None, None, 'ACNGT'), + 'ovhgseq': 'N', } rest_dict['HpyCH4III'] = _temp() def _temp(): return { - 'compsite' : '(?PACGT)|(?PACGT)', - 'results' : None, - 'site' : 'ACGT', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'ACGT'), - 'ovhgseq' : 'CG', + 'compsite': '(?PACGT)', + 'results': None, + 'site': 'ACGT', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'ACGT'), + 'ovhgseq': 'CG', } rest_dict['HpyCH4IV'] = _temp() def _temp(): return { - 'compsite' : '(?PTGCA)|(?PTGCA)', - 'results' : None, - 'site' : 'TGCA', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'TGCA'), - 'ovhgseq' : '', + 'compsite': '(?PTGCA)', + 'results': None, + 'site': 'TGCA', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (2, -2, None, None, 'TGCA'), + 'ovhgseq': '', } rest_dict['HpyCH4V'] = _temp() def _temp(): return { - 'compsite' : '(?PGC.......GC)|(?PGC.......GC)', - 'results' : None, - 'site' : 'GCNNNNNNNGC', - 'substrat' : 'DNA', - 'fst3' : -7, - 'fst5' : 7, - 'freq' : 256, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (7, -7, None, None, 'GCNNNNNNNGC'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PGC.......GC)', + 'results': None, + 'site': 'GCNNNNNNNGC', + 'substrat': 'DNA', + 'fst3': -7, + 'fst5': 7, + 'freq': 256, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (7, -7, None, None, 'GCNNNNNNNGC'), + 'ovhgseq': 'NNN', } rest_dict['HpyF10VI'] = _temp() def _temp(): return { - 'compsite' : '(?PCT.AG)|(?PCT.AG)', - 'results' : None, - 'site' : 'CTNAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTNAG'), - 'ovhgseq' : 'TNA', + 'compsite': '(?PCT.AG)', + 'results': None, + 'site': 'CTNAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CTNAG'), + 'ovhgseq': 'TNA', } rest_dict['HpyF3I'] = _temp() def _temp(): return { - 'compsite' : '(?PG[AG]CG[CT]C)|(?PG[AG]CG[CT]C)', - 'results' : None, - 'site' : 'GRCGYC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('R',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GRCGYC'), - 'ovhgseq' : 'CG', + 'compsite': '(?PACGT)', + 'results': None, + 'site': 'ACGT', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (1, -1, None, None, 'ACGT'), + 'ovhgseq': 'CG', + } +rest_dict['HpySE526I'] = _temp() + +def _temp(): + return { + 'compsite': '(?PG[AG]CG[CT]C)', + 'results': None, + 'site': 'GRCGYC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('R',), + 'scd5': None, + 'charac': (2, -2, None, None, 'GRCGYC'), + 'ovhgseq': 'CG', } rest_dict['Hsp92I'] = _temp() def _temp(): return { - 'compsite' : '(?PCATG)|(?PCATG)', - 'results' : None, - 'site' : 'CATG', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('R',), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'CATG'), - 'ovhgseq' : 'CATG', + 'compsite': '(?PCATG)', + 'results': None, + 'site': 'CATG', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('R',), + 'scd5': None, + 'charac': (4, -4, None, None, 'CATG'), + 'ovhgseq': 'CATG', } rest_dict['Hsp92II'] = _temp() def _temp(): return { - 'compsite' : '(?PGCGC)|(?PGCGC)', - 'results' : None, - 'site' : 'GCGC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GCGC'), - 'ovhgseq' : 'CG', + 'compsite': '(?PGCGC)', + 'results': None, + 'site': 'GCGC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'GCGC'), + 'ovhgseq': 'CG', } rest_dict['HspAI'] = _temp() def _temp(): return { - 'compsite' : '(?PGC.GC)|(?PGC.GC)', - 'results' : None, - 'site' : 'GCNGC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('M',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GCNGC'), - 'ovhgseq' : 'N', - } -rest_dict['ItaI'] = _temp() + 'compsite': '(?PGTAT.AC)|(?PGT.ATAC)', + 'results': None, + 'site': 'GTATNAC', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 4096, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'GTATNAC'), + 'ovhgseq': None, + } +rest_dict['Jma19592I'] = _temp() def _temp(): return { - 'compsite' : '(?PGGCGCC)|(?PGGCGCC)', - 'results' : None, - 'site' : 'GGCGCC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGCGCC'), - 'ovhgseq' : 'GCGC', + 'compsite': '(?PGGCGCC)', + 'results': None, + 'site': 'GGCGCC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGCGCC'), + 'ovhgseq': 'GCGC', } rest_dict['KasI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGG[AT]CCC)|(?PGGG[AT]CCC)', - 'results' : None, - 'site' : 'GGGWCCC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 8192, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GGGWCCC'), - 'ovhgseq' : 'GWC', + 'compsite': '(?PGGG[AT]CCC)', + 'results': None, + 'site': 'GGGWCCC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 8192, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (2, -2, None, None, 'GGGWCCC'), + 'ovhgseq': 'GWC', } rest_dict['KflI'] = _temp() def _temp(): return { - 'compsite' : '(?PTCCGGA)|(?PTCCGGA)', - 'results' : None, - 'site' : 'TCCGGA', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'TCCGGA'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?PTCCGGA)', + 'results': None, + 'site': 'TCCGGA', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'TCCGGA'), + 'ovhgseq': 'CCGG', } rest_dict['Kpn2I'] = _temp() def _temp(): return { - 'compsite' : '(?PGGTACC)|(?PGGTACC)', - 'results' : None, - 'site' : 'GGTACC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('B', 'C', 'F', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GGTACC'), - 'ovhgseq' : 'GTAC', + 'compsite': '(?PGGTACC)', + 'results': None, + 'site': 'GGTACC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('B', 'C', 'F', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'X', 'Y'), + 'scd5': None, + 'charac': (5, -5, None, None, 'GGTACC'), + 'ovhgseq': 'GTAC', } rest_dict['KpnI'] = _temp() def _temp(): return { - 'compsite' : '(?PTGATCA)|(?PTGATCA)', - 'results' : None, - 'site' : 'TGATCA', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'TGATCA'), - 'ovhgseq' : 'GATC', + 'compsite': '(?PGCCGGC)', + 'results': None, + 'site': 'GCCGGC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GCCGGC'), + 'ovhgseq': 'CCGG', + } +rest_dict['KroI'] = _temp() + +def _temp(): + return { + 'compsite': '(?PTGATCA)', + 'results': None, + 'site': 'TGATCA', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'TGATCA'), + 'ovhgseq': 'GATC', } rest_dict['Ksp22I'] = _temp() def _temp(): return { - 'compsite' : '(?PCTCTTC)|(?PGAAGAG)', - 'results' : None, - 'site' : 'CTCTTC', - 'substrat' : 'DNA', - 'fst3' : 4, - 'fst5' : 7, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (7, 4, None, None, 'CTCTTC'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PCTCTTC)|(?PGAAGAG)', + 'results': None, + 'site': 'CTCTTC', + 'substrat': 'DNA', + 'fst3': 4, + 'fst5': 7, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (7, 4, None, None, 'CTCTTC'), + 'ovhgseq': 'NNN', } rest_dict['Ksp632I'] = _temp() def _temp(): return { - 'compsite' : '(?PGTTAAC)|(?PGTTAAC)', - 'results' : None, - 'site' : 'GTTAAC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GTTAAC'), - 'ovhgseq' : '', + 'compsite': '(?PGTTAAC)', + 'results': None, + 'site': 'GTTAAC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (3, -3, None, None, 'GTTAAC'), + 'ovhgseq': '', } rest_dict['KspAI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCGCGG)|(?PCCGCGG)', - 'results' : None, - 'site' : 'CCGCGG', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('M', 'S'), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'CCGCGG'), - 'ovhgseq' : 'GC', + 'compsite': '(?PCCGCGG)', + 'results': None, + 'site': 'CCGCGG', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('M', 'S'), + 'scd5': None, + 'charac': (4, -4, None, None, 'CCGCGG'), + 'ovhgseq': 'GC', } rest_dict['KspI'] = _temp() def _temp(): return { - 'compsite' : '(?PGATC)|(?PGATC)', - 'results' : None, - 'site' : 'GATC', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'GATC'), - 'ovhgseq' : 'GATC', + 'compsite': '(?PGATC)', + 'results': None, + 'site': 'GATC', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (0, 0, None, None, 'GATC'), + 'ovhgseq': 'GATC', } rest_dict['Kzo9I'] = _temp() def _temp(): return { - 'compsite' : '(?PGCTCTTC)|(?PGAAGAGC)', - 'results' : None, - 'site' : 'GCTCTTC', - 'substrat' : 'DNA', - 'fst3' : 4, - 'fst5' : 8, - 'freq' : 16384, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (8, 4, None, None, 'GCTCTTC'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PGCTCTTC)|(?PGAAGAGC)', + 'results': None, + 'site': 'GCTCTTC', + 'substrat': 'DNA', + 'fst3': 4, + 'fst5': 8, + 'freq': 16384, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (8, 4, None, None, 'GCTCTTC'), + 'ovhgseq': 'NNN', } rest_dict['LguI'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]GCGC[CT])|(?P[AG]GCGC[CT])', - 'results' : None, - 'site' : 'RGCGCY', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'RGCGCY'), - 'ovhgseq' : '', + 'compsite': '(?P[AG]GCGC[CT])', + 'results': None, + 'site': 'RGCGCY', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (3, -3, None, None, 'RGCGCY'), + 'ovhgseq': '', } rest_dict['LpnI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCAGC)|(?PGCTGC)', - 'results' : None, - 'site' : 'GCAGC', - 'substrat' : 'DNA', - 'fst3' : 12, - 'fst5' : 13, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (13, 12, None, None, 'GCAGC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PCC[AGT]G)|(?PC[ACT]GG)', + 'results': None, + 'site': 'CCDG', + 'substrat': 'DNA', + 'fst3': 14, + 'fst5': 14, + 'freq': 64, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (14, 14, None, None, 'CCDG'), + 'ovhgseq': 'NNNN', + } +rest_dict['LpnPI'] = _temp() + +def _temp(): + return { + 'compsite': '(?PGCAGC)|(?PGCTGC)', + 'results': None, + 'site': 'GCAGC', + 'substrat': 'DNA', + 'fst3': 12, + 'fst5': 13, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (13, 12, None, None, 'GCAGC'), + 'ovhgseq': 'NNNN', } rest_dict['Lsp1109I'] = _temp() def _temp(): return { - 'compsite' : '(?PGCATC)|(?PGATGC)', - 'results' : None, - 'site' : 'GCATC', - 'substrat' : 'DNA', - 'fst3' : 9, - 'fst5' : 10, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (10, 9, None, None, 'GCATC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PGCATC)|(?PGATGC)', + 'results': None, + 'site': 'GCATC', + 'substrat': 'DNA', + 'fst3': 9, + 'fst5': 10, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (10, 9, None, None, 'GCATC'), + 'ovhgseq': 'NNNN', } rest_dict['LweI'] = _temp() def _temp(): return { - 'compsite' : '(?PACC[AT]GGT)|(?PACC[AT]GGT)', - 'results' : None, - 'site' : 'ACCWGGT', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 8192, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -5, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'ACCWGGT'), - 'ovhgseq' : 'CCWGG', + 'compsite': '(?PACC[AT]GGT)', + 'results': None, + 'site': 'ACCWGGT', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 8192, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (1, -1, None, None, 'ACCWGGT'), + 'ovhgseq': 'CCWGG', } rest_dict['MabI'] = _temp() def _temp(): return { - 'compsite' : '(?PCTAG)|(?PCTAG)', - 'results' : None, - 'site' : 'CTAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('M',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTAG'), - 'ovhgseq' : 'TA', + 'compsite': '(?PCTAG)', + 'results': None, + 'site': 'CTAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('M',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CTAG'), + 'ovhgseq': 'TA', } rest_dict['MaeI'] = _temp() def _temp(): return { - 'compsite' : '(?PACGT)|(?PACGT)', - 'results' : None, - 'site' : 'ACGT', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('M',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'ACGT'), - 'ovhgseq' : 'CG', + 'compsite': '(?PACGT)', + 'results': None, + 'site': 'ACGT', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('M',), + 'scd5': None, + 'charac': (1, -1, None, None, 'ACGT'), + 'ovhgseq': 'CG', } rest_dict['MaeII'] = _temp() def _temp(): return { - 'compsite' : '(?PGT.AC)|(?PGT.AC)', - 'results' : None, - 'site' : 'GTNAC', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -5, - 'scd3' : None, - 'suppl' : ('M',), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'GTNAC'), - 'ovhgseq' : 'GTNAC', + 'compsite': '(?PGT.AC)', + 'results': None, + 'site': 'GTNAC', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': None, + 'suppl': ('M',), + 'scd5': None, + 'charac': (0, 0, None, None, 'GTNAC'), + 'ovhgseq': 'GTNAC', } rest_dict['MaeIII'] = _temp() def _temp(): return { - 'compsite' : '(?PGATC)|(?PGATC)', - 'results' : None, - 'site' : 'GATC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GATC'), - 'ovhgseq' : '', + 'compsite': '(?PGATC)', + 'results': None, + 'site': 'GATC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (2, -2, None, None, 'GATC'), + 'ovhgseq': '', } rest_dict['MalI'] = _temp() def _temp(): return { - 'compsite' : '(?PC[AG]TTGAC)|(?PGTCAA[CT]G)', - 'results' : None, - 'site' : 'CRTTGAC', - 'substrat' : 'DNA', - 'fst3' : 19, - 'fst5' : 28, - 'freq' : 8192, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (28, 19, None, None, 'CRTTGAC'), - 'ovhgseq' : 'NN', + 'compsite': '(?PC[AG]TTGAC)|(?PGTCAA[CT]G)', + 'results': None, + 'site': 'CRTTGAC', + 'substrat': 'DNA', + 'fst3': 19, + 'fst5': 28, + 'freq': 8192, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (28, 19, None, None, 'CRTTGAC'), + 'ovhgseq': 'NN', } rest_dict['MaqI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGCGCGCG)|(?PCGCGCGCG)', - 'results' : None, - 'site' : 'CGCGCGCG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 65536, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CGCGCGCG'), - 'ovhgseq' : 'CGCG', + 'compsite': '(?PCGCGCGCG)', + 'results': None, + 'site': 'CGCGCGCG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (2, -2, None, None, 'CGCGCGCG'), + 'ovhgseq': 'CGCG', } rest_dict['MauBI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCGCTC)|(?PGAGCGG)', - 'results' : None, - 'site' : 'CCGCTC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'CCGCTC'), - 'ovhgseq' : '', + 'compsite': '(?PCCGCTC)|(?PGAGCGG)', + 'results': None, + 'site': 'CCGCTC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (3, -3, None, None, 'CCGCTC'), + 'ovhgseq': '', } rest_dict['MbiI'] = _temp() def _temp(): return { - 'compsite' : '(?PGATC)|(?PGATC)', - 'results' : None, - 'site' : 'GATC', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('B', 'C', 'F', 'K', 'N', 'Q', 'R', 'U', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'GATC'), - 'ovhgseq' : 'GATC', + 'compsite': '(?PGATC)', + 'results': None, + 'site': 'GATC', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('B', 'C', 'F', 'K', 'N', 'Q', 'R', 'U', 'X', 'Y'), + 'scd5': None, + 'charac': (0, 0, None, None, 'GATC'), + 'ovhgseq': 'GATC', } rest_dict['MboI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAAGA)|(?PTCTTC)', - 'results' : None, - 'site' : 'GAAGA', - 'substrat' : 'DNA', - 'fst3' : 7, - 'fst5' : 13, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 1, - 'scd3' : None, - 'suppl' : ('F', 'I', 'J', 'K', 'N', 'O', 'Q', 'R', 'V', 'W', 'X'), - 'scd5' : None, - 'charac' : (13, 7, None, None, 'GAAGA'), - 'ovhgseq' : 'N', + 'compsite': '(?PGAAGA)|(?PTCTTC)', + 'results': None, + 'site': 'GAAGA', + 'substrat': 'DNA', + 'fst3': 7, + 'fst5': 13, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': ('F', 'I', 'J', 'K', 'N', 'Q', 'R', 'V', 'X'), + 'scd5': None, + 'charac': (13, 7, None, None, 'GAAGA'), + 'ovhgseq': 'N', } rest_dict['MboII'] = _temp() def _temp(): return { - 'compsite' : '(?PGCGCGC)|(?PGCGCGC)', - 'results' : None, - 'site' : 'GCGCGC', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'GCGCGC'), - 'ovhgseq' : 'GC', + 'compsite': '(?PGCGCGC)', + 'results': None, + 'site': 'GCGCGC', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (4, -4, None, None, 'GCGCGC'), + 'ovhgseq': 'GC', } rest_dict['McaTI'] = _temp() def _temp(): return { - 'compsite' : '(?PCG[AG][CT]CG)|(?PCG[AG][CT]CG)', - 'results' : None, - 'site' : 'CGRYCG', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'CGRYCG'), - 'ovhgseq' : 'RY', + 'compsite': '(?PCG[AG][CT]CG)', + 'results': None, + 'site': 'CGRYCG', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (4, -4, None, None, 'CGRYCG'), + 'ovhgseq': 'RY', } rest_dict['McrI'] = _temp() def _temp(): return { - 'compsite' : '(?PCAATTG)|(?PCAATTG)', - 'results' : None, - 'site' : 'CAATTG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CAATTG'), - 'ovhgseq' : 'AATT', + 'compsite': '(?PCAATTG)', + 'results': None, + 'site': 'CAATTG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'N'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CAATTG'), + 'ovhgseq': 'AATT', } rest_dict['MfeI'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]GATC[CT])|(?P[AG]GATC[CT])', - 'results' : None, - 'site' : 'RGATCY', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('K',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'RGATCY'), - 'ovhgseq' : 'GATC', + 'compsite': '(?P[AG]GATC[CT])', + 'results': None, + 'site': 'RGATCY', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('K',), + 'scd5': None, + 'charac': (1, -1, None, None, 'RGATCY'), + 'ovhgseq': 'GATC', } rest_dict['MflI'] = _temp() def _temp(): return { - 'compsite' : '(?PG[AGT]GC[ACT]C)|(?PG[AGT]GC[ACT]C)', - 'results' : None, - 'site' : 'GDGCHC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 256, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GDGCHC'), - 'ovhgseq' : 'DGCH', + 'compsite': '(?PG[AGT]GC[ACT]C)', + 'results': None, + 'site': 'GDGCHC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 256, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (5, -5, None, None, 'GDGCHC'), + 'ovhgseq': 'DGCH', } rest_dict['MhlI'] = _temp() def _temp(): return { - 'compsite' : '(?PGT..AC)|(?PGT..AC)', - 'results' : None, - 'site' : 'GTNNAC', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 256, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'GTNNAC'), - 'ovhgseq' : None, + 'compsite': '(?PGT..AC)', + 'results': None, + 'site': 'GTNNAC', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 256, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'GTNNAC'), + 'ovhgseq': None, } rest_dict['MjaIV'] = _temp() def _temp(): return { - 'compsite' : '(?PTGGCCA)|(?PTGGCCA)', - 'results' : None, - 'site' : 'TGGCCA', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'TGGCCA'), - 'ovhgseq' : '', + 'compsite': '(?PGAGA[CT]GT)|(?PAC[AG]TCTC)', + 'results': None, + 'site': 'GAGAYGT', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 8192, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'GAGAYGT'), + 'ovhgseq': None, + } +rest_dict['MkaDII'] = _temp() + +def _temp(): + return { + 'compsite': '(?PTGGCCA)', + 'results': None, + 'site': 'TGGCCA', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (3, -3, None, None, 'TGGCCA'), + 'ovhgseq': '', } rest_dict['MlsI'] = _temp() def _temp(): return { - 'compsite' : '(?PACGCGT)|(?PACGCGT)', - 'results' : None, - 'site' : 'ACGCGT', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('B', 'F', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'W', 'X'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'ACGCGT'), - 'ovhgseq' : 'CGCG', + 'compsite': '(?PAATT)', + 'results': None, + 'site': 'AATT', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (0, 0, None, None, 'AATT'), + 'ovhgseq': 'AATT', + } +rest_dict['MluCI'] = _temp() + +def _temp(): + return { + 'compsite': '(?PACGCGT)', + 'results': None, + 'site': 'ACGCGT', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('B', 'F', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'U', 'V', 'X'), + 'scd5': None, + 'charac': (1, -1, None, None, 'ACGCGT'), + 'ovhgseq': 'CGCG', } rest_dict['MluI'] = _temp() def _temp(): return { - 'compsite' : '(?PTGGCCA)|(?PTGGCCA)', - 'results' : None, - 'site' : 'TGGCCA', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('M', 'S'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'TGGCCA'), - 'ovhgseq' : '', + 'compsite': '(?PTGGCCA)', + 'results': None, + 'site': 'TGGCCA', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('M',), + 'scd5': None, + 'charac': (3, -3, None, None, 'TGGCCA'), + 'ovhgseq': '', } rest_dict['MluNI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGCGCC)|(?PGGCGCC)', - 'results' : None, - 'site' : 'GGCGCC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GGCGCC'), - 'ovhgseq' : 'CG', + 'compsite': '(?PGGCGCC)', + 'results': None, + 'site': 'GGCGCC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (2, -2, None, None, 'GGCGCC'), + 'ovhgseq': 'CG', } rest_dict['Mly113I'] = _temp() def _temp(): return { - 'compsite' : '(?PGAGTC)|(?PGACTC)', - 'results' : None, - 'site' : 'GAGTC', - 'substrat' : 'DNA', - 'fst3' : 5, - 'fst5' : 10, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (10, 5, None, None, 'GAGTC'), - 'ovhgseq' : '', + 'compsite': '(?PGAGTC)|(?PGACTC)', + 'results': None, + 'site': 'GAGTC', + 'substrat': 'DNA', + 'fst3': 5, + 'fst5': 10, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (10, 5, None, None, 'GAGTC'), + 'ovhgseq': '', } rest_dict['MlyI'] = _temp() def _temp(): return { - 'compsite' : '(?PTCC[AG]AC)|(?PGT[CT]GGA)', - 'results' : None, - 'site' : 'TCCRAC', - 'substrat' : 'DNA', - 'fst3' : 18, - 'fst5' : 26, - 'freq' : 2048, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('N', 'X'), - 'scd5' : None, - 'charac' : (26, 18, None, None, 'TCCRAC'), - 'ovhgseq' : 'NN', + 'compsite': '(?PTCC[AG]AC)|(?PGT[CT]GGA)', + 'results': None, + 'site': 'TCCRAC', + 'substrat': 'DNA', + 'fst3': 18, + 'fst5': 26, + 'freq': 2048, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (26, 18, None, None, 'TCCRAC'), + 'ovhgseq': 'NN', } rest_dict['MmeI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCTC)|(?PGAGG)', - 'results' : None, - 'site' : 'CCTC', - 'substrat' : 'DNA', - 'fst3' : 6, - 'fst5' : 11, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 1, - 'scd3' : None, - 'suppl' : ('F', 'I', 'N', 'Q', 'V', 'W', 'X'), - 'scd5' : None, - 'charac' : (11, 6, None, None, 'CCTC'), - 'ovhgseq' : 'N', + 'compsite': '(?PCCTC)|(?PGAGG)', + 'results': None, + 'site': 'CCTC', + 'substrat': 'DNA', + 'fst3': 6, + 'fst5': 11, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': ('F', 'I', 'N', 'Q', 'V', 'X'), + 'scd5': None, + 'charac': (11, 6, None, None, 'CCTC'), + 'ovhgseq': 'N', } rest_dict['MnlI'] = _temp() def _temp(): return { - 'compsite' : '(?PATGCAT)|(?PATGCAT)', - 'results' : None, - 'site' : 'ATGCAT', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'ATGCAT'), - 'ovhgseq' : 'TGCA', + 'compsite': '(?PATGCAT)', + 'results': None, + 'site': 'ATGCAT', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (5, -5, None, None, 'ATGCAT'), + 'ovhgseq': 'TGCA', } rest_dict['Mph1103I'] = _temp() def _temp(): return { - 'compsite' : '(?PCGCCGGCG)|(?PCGCCGGCG)', - 'results' : None, - 'site' : 'CGCCGGCG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 65536, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CGCCGGCG'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?PCGCCGGCG)', + 'results': None, + 'site': 'CGCCGGCG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (2, -2, None, None, 'CGCCGGCG'), + 'ovhgseq': 'CCGG', } rest_dict['MreI'] = _temp() def _temp(): return { - 'compsite' : '(?PTCCGGA)|(?PTCCGGA)', - 'results' : None, - 'site' : 'TCCGGA', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('M', 'O'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'TCCGGA'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?PTCCGGA)', + 'results': None, + 'site': 'TCCGGA', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('M', 'O'), + 'scd5': None, + 'charac': (1, -1, None, None, 'TCCGGA'), + 'ovhgseq': 'CCGG', } rest_dict['MroI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCCGGC)|(?PGCCGGC)', - 'results' : None, - 'site' : 'GCCGGC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GCCGGC'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?PGCCGGC)', + 'results': None, + 'site': 'GCCGGC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'GCCGGC'), + 'ovhgseq': 'CCGG', } rest_dict['MroNI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAA....TTC)|(?PGAA....TTC)', - 'results' : None, - 'site' : 'GAANNNNTTC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 10, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GAANNNNTTC'), - 'ovhgseq' : '', + 'compsite': '(?PGAA....TTC)', + 'results': None, + 'site': 'GAANNNNTTC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 10, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (5, -5, None, None, 'GAANNNNTTC'), + 'ovhgseq': '', } rest_dict['MroXI'] = _temp() def _temp(): return { - 'compsite' : '(?PTGGCCA)|(?PTGGCCA)', - 'results' : None, - 'site' : 'TGGCCA', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('B', 'N', 'O'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'TGGCCA'), - 'ovhgseq' : '', + 'compsite': '(?PTGGCCA)', + 'results': None, + 'site': 'TGGCCA', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('N', 'O'), + 'scd5': None, + 'charac': (3, -3, None, None, 'TGGCCA'), + 'ovhgseq': '', } rest_dict['MscI'] = _temp() def _temp(): return { - 'compsite' : '(?PTTAA)|(?PTTAA)', - 'results' : None, - 'site' : 'TTAA', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('B', 'N'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'TTAA'), - 'ovhgseq' : 'TA', + 'compsite': '(?PTTAA)', + 'results': None, + 'site': 'TTAA', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('B', 'N'), + 'scd5': None, + 'charac': (1, -1, None, None, 'TTAA'), + 'ovhgseq': 'TA', } rest_dict['MseI'] = _temp() def _temp(): return { - 'compsite' : '(?PCA[CT]....[AG]TG)|(?PCA[CT]....[AG]TG)', - 'results' : None, - 'site' : 'CAYNNNNRTG', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 1024, - 'size' : 10, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'CAYNNNNRTG'), - 'ovhgseq' : '', + 'compsite': '(?PCA[CT]....[AG]TG)', + 'results': None, + 'site': 'CAYNNNNRTG', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 1024, + 'size': 10, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (5, -5, None, None, 'CAYNNNNRTG'), + 'ovhgseq': '', } rest_dict['MslI'] = _temp() def _temp(): return { - 'compsite' : '(?PTGGCCA)|(?PTGGCCA)', - 'results' : None, - 'site' : 'TGGCCA', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'TGGCCA'), - 'ovhgseq' : '', + 'compsite': '(?PTGGCCA)', + 'results': None, + 'site': 'TGGCCA', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (3, -3, None, None, 'TGGCCA'), + 'ovhgseq': '', } rest_dict['Msp20I'] = _temp() def _temp(): return { - 'compsite' : '(?PC[AC]GC[GT]G)|(?PC[AC]GC[GT]G)', - 'results' : None, - 'site' : 'CMGCKG', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I', 'N', 'R', 'V'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'CMGCKG'), - 'ovhgseq' : '', + 'compsite': '(?PC[AC]GC[GT]G)', + 'results': None, + 'site': 'CMGCKG', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I', 'N', 'R', 'V'), + 'scd5': None, + 'charac': (3, -3, None, None, 'CMGCKG'), + 'ovhgseq': '', } rest_dict['MspA1I'] = _temp() def _temp(): return { - 'compsite' : '(?PCTTAAG)|(?PCTTAAG)', - 'results' : None, - 'site' : 'CTTAAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('C',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTTAAG'), - 'ovhgseq' : 'TTAA', + 'compsite': '(?PCTTAAG)', + 'results': None, + 'site': 'CTTAAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('C',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CTTAAG'), + 'ovhgseq': 'TTAA', } rest_dict['MspCI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCGG)|(?PCCGG)', - 'results' : None, - 'site' : 'CCGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('F', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCGG'), - 'ovhgseq' : 'CG', + 'compsite': '(?PCCGG)', + 'results': None, + 'site': 'CCGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('F', 'I', 'J', 'K', 'N', 'Q', 'R', 'S', 'U', 'V', 'X', 'Y'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCGG'), + 'ovhgseq': 'CG', } rest_dict['MspI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC.GG)|(?PCC.GG)', - 'results' : None, - 'site' : 'CCNGG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CCNGG'), - 'ovhgseq' : 'N', + 'compsite': '(?PC..[AG])|(?P[CT]..G)', + 'results': None, + 'site': 'CNNR', + 'substrat': 'DNA', + 'fst3': 13, + 'fst5': 13, + 'freq': 8, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (13, 13, None, None, 'CNNR'), + 'ovhgseq': 'NNNN', + } +rest_dict['MspJI'] = _temp() + +def _temp(): + return { + 'compsite': '(?PCC.GG)', + 'results': None, + 'site': 'CCNGG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (2, -2, None, None, 'CCNGG'), + 'ovhgseq': 'N', } rest_dict['MspR9I'] = _temp() def _temp(): return { - 'compsite' : '(?PGTTTAAAC)|(?PGTTTAAAC)', - 'results' : None, - 'site' : 'GTTTAAAC', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 65536, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'GTTTAAAC'), - 'ovhgseq' : '', + 'compsite': '(?PGTTTAAAC)', + 'results': None, + 'site': 'GTTTAAAC', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (4, -4, None, None, 'GTTTAAAC'), + 'ovhgseq': '', } rest_dict['MssI'] = _temp() def _temp(): return { - 'compsite' : '(?PTGCGCA)|(?PTGCGCA)', - 'results' : None, - 'site' : 'TGCGCA', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'TGCGCA'), - 'ovhgseq' : '', + 'compsite': '(?PTGCGCA)', + 'results': None, + 'site': 'TGCGCA', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (3, -3, None, None, 'TGCGCA'), + 'ovhgseq': '', } rest_dict['MstI'] = _temp() def _temp(): return { - 'compsite' : '(?PCAATTG)|(?PCAATTG)', - 'results' : None, - 'site' : 'CAATTG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F', 'K', 'M'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CAATTG'), - 'ovhgseq' : 'AATT', + 'compsite': '(?PCAATTG)', + 'results': None, + 'site': 'CAATTG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F', 'K', 'M'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CAATTG'), + 'ovhgseq': 'AATT', } rest_dict['MunI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAATGC)|(?PGCATTC)', - 'results' : None, - 'site' : 'GAATGC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 7, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (7, -1, None, None, 'GAATGC'), - 'ovhgseq' : 'CN', + 'compsite': '(?PGAATGC)|(?PGCATTC)', + 'results': None, + 'site': 'GAATGC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 7, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (7, -1, None, None, 'GAATGC'), + 'ovhgseq': 'CN', } rest_dict['Mva1269I'] = _temp() def _temp(): return { - 'compsite' : '(?PCC[AT]GG)|(?PCC[AT]GG)', - 'results' : None, - 'site' : 'CCWGG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('F', 'K', 'M', 'O', 'S', 'W'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CCWGG'), - 'ovhgseq' : 'W', + 'compsite': '(?PCC[AT]GG)', + 'results': None, + 'site': 'CCWGG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('F', 'M', 'S'), + 'scd5': None, + 'charac': (2, -2, None, None, 'CCWGG'), + 'ovhgseq': 'W', } rest_dict['MvaI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGCG)|(?PCGCG)', - 'results' : None, - 'site' : 'CGCG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('M',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CGCG'), - 'ovhgseq' : '', + 'compsite': '(?PCGCG)', + 'results': None, + 'site': 'CGCG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('M',), + 'scd5': None, + 'charac': (2, -2, None, None, 'CGCG'), + 'ovhgseq': '', } rest_dict['MvnI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGATCG)|(?PCGATCG)', - 'results' : None, - 'site' : 'CGATCG', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('U',), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'CGATCG'), - 'ovhgseq' : 'AT', + 'compsite': '(?PCGATCG)', + 'results': None, + 'site': 'CGATCG', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('U',), + 'scd5': None, + 'charac': (4, -4, None, None, 'CGATCG'), + 'ovhgseq': 'AT', } rest_dict['MvrI'] = _temp() def _temp(): return { - 'compsite' : '(?PGC.......GC)|(?PGC.......GC)', - 'results' : None, - 'site' : 'GCNNNNNNNGC', - 'substrat' : 'DNA', - 'fst3' : -7, - 'fst5' : 7, - 'freq' : 256, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (7, -7, None, None, 'GCNNNNNNNGC'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PGC.......GC)', + 'results': None, + 'site': 'GCNNNNNNNGC', + 'substrat': 'DNA', + 'fst3': -7, + 'fst5': 7, + 'freq': 256, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (7, -7, None, None, 'GCNNNNNNNGC'), + 'ovhgseq': 'NNN', } rest_dict['MwoI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCCGGC)|(?PGCCGGC)', - 'results' : None, - 'site' : 'GCCGGC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('C', 'K', 'M', 'N', 'O', 'R', 'U'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GCCGGC'), - 'ovhgseq' : '', + 'compsite': '(?PGCCGGC)', + 'results': None, + 'site': 'GCCGGC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('C', 'K', 'N', 'U'), + 'scd5': None, + 'charac': (3, -3, None, None, 'GCCGGC'), + 'ovhgseq': '', } rest_dict['NaeI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGCGCC)|(?PGGCGCC)', - 'results' : None, - 'site' : 'GGCGCC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('J', 'M', 'N', 'O', 'Q', 'R', 'U', 'W', 'X'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GGCGCC'), - 'ovhgseq' : 'CG', + 'compsite': '(?PGGCGCC)', + 'results': None, + 'site': 'GGCGCC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('J', 'M', 'N', 'Q', 'R', 'U', 'X'), + 'scd5': None, + 'charac': (2, -2, None, None, 'GGCGCC'), + 'ovhgseq': 'CG', } rest_dict['NarI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC[CG]GG)|(?PCC[CG]GG)', - 'results' : None, - 'site' : 'CCSGG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('J', 'N', 'O', 'R', 'W'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CCSGG'), - 'ovhgseq' : 'S', + 'compsite': '(?PCC[CG]GG)', + 'results': None, + 'site': 'CCSGG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('J', 'N', 'R'), + 'scd5': None, + 'charac': (2, -2, None, None, 'CCSGG'), + 'ovhgseq': 'S', } rest_dict['NciI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCATGG)|(?PCCATGG)', - 'results' : None, - 'site' : 'CCATGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('B', 'C', 'F', 'H', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCATGG'), - 'ovhgseq' : 'CATG', + 'compsite': '(?PCCATGG)', + 'results': None, + 'site': 'CCATGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('B', 'C', 'F', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'X', 'Y'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCATGG'), + 'ovhgseq': 'CATG', } rest_dict['NcoI'] = _temp() def _temp(): return { - 'compsite' : '(?PCATATG)|(?PCATATG)', - 'results' : None, - 'site' : 'CATATG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('B', 'F', 'J', 'K', 'M', 'N', 'Q', 'R', 'S', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CATATG'), - 'ovhgseq' : 'TA', + 'compsite': '(?PCATATG)', + 'results': None, + 'site': 'CATATG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('B', 'F', 'J', 'K', 'M', 'N', 'Q', 'R', 'S', 'U', 'X', 'Y'), + 'scd5': None, + 'charac': (2, -2, None, None, 'CATATG'), + 'ovhgseq': 'TA', } rest_dict['NdeI'] = _temp() def _temp(): return { - 'compsite' : '(?PGATC)|(?PGATC)', - 'results' : None, - 'site' : 'GATC', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('J', 'M', 'R', 'W'), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'GATC'), - 'ovhgseq' : 'GATC', + 'compsite': '(?PGATC)', + 'results': None, + 'site': 'GATC', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('J', 'M'), + 'scd5': None, + 'charac': (0, 0, None, None, 'GATC'), + 'ovhgseq': 'GATC', } rest_dict['NdeII'] = _temp() def _temp(): return { - 'compsite' : '(?PGAC.....TGA)|(?PTCA.....GTC)', - 'results' : None, - 'site' : 'GACNNNNNTGA', - 'substrat' : 'DNA', - 'fst3' : -25, - 'fst5' : -12, - 'freq' : 4096, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : 11, - 'suppl' : (), - 'scd5' : 24, - 'charac' : (-12, -25, 24, 11, 'GACNNNNNTGA'), - 'ovhgseq' : 'NN', + 'compsite': '(?PGAC.....TGA)|(?PTCA.....GTC)', + 'results': None, + 'site': 'GACNNNNNTGA', + 'substrat': 'DNA', + 'fst3': -25, + 'fst5': -12, + 'freq': 4096, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': 11, + 'suppl': (), + 'scd5': 24, + 'charac': (-12, -25, 24, 11, 'GACNNNNNTGA'), + 'ovhgseq': 'NN', } rest_dict['NgoAVIII'] = _temp() def _temp(): return { - 'compsite' : '(?PGCCGGC)|(?PGCCGGC)', - 'results' : None, - 'site' : 'GCCGGC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N', 'R'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GCCGGC'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?PGCCGGC)', + 'results': None, + 'site': 'GCCGGC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GCCGGC'), + 'ovhgseq': 'CCGG', } rest_dict['NgoMIV'] = _temp() def _temp(): return { - 'compsite' : '(?PCAAG[AG]AG)|(?PCT[CT]CTTG)', - 'results' : None, - 'site' : 'CAAGRAG', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 8192, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'CAAGRAG'), - 'ovhgseq' : None, + 'compsite': '(?PCAAG[AG]AG)|(?PCT[CT]CTTG)', + 'results': None, + 'site': 'CAAGRAG', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 8192, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'CAAGRAG'), + 'ovhgseq': None, } rest_dict['NhaXI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCTAGC)|(?PGCTAGC)', - 'results' : None, - 'site' : 'GCTAGC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('B', 'C', 'F', 'J', 'K', 'M', 'N', 'O', 'R', 'S', 'U', 'W'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GCTAGC'), - 'ovhgseq' : 'CTAG', + 'compsite': '(?PGCTAGC)', + 'results': None, + 'site': 'GCTAGC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('B', 'C', 'F', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'X'), + 'scd5': None, + 'charac': (1, -1, None, None, 'GCTAGC'), + 'ovhgseq': 'CTAG', } rest_dict['NheI'] = _temp() def _temp(): return { - 'compsite' : '(?PCATCAC)|(?PGTGATG)', - 'results' : None, - 'site' : 'CATCAC', - 'substrat' : 'DNA', - 'fst3' : 17, - 'fst5' : 25, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (25, 17, None, None, 'CATCAC'), - 'ovhgseq' : 'NN', + 'compsite': '(?PCATCAC)|(?PGTGATG)', + 'results': None, + 'site': 'CATCAC', + 'substrat': 'DNA', + 'fst3': 17, + 'fst5': 25, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (25, 17, None, None, 'CATCAC'), + 'ovhgseq': 'NN', } rest_dict['NlaCI'] = _temp() def _temp(): return { - 'compsite' : '(?PCATG)|(?PCATG)', - 'results' : None, - 'site' : 'CATG', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('N', 'W'), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'CATG'), - 'ovhgseq' : 'CATG', + 'compsite': '(?PCATG)', + 'results': None, + 'site': 'CATG', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (4, -4, None, None, 'CATG'), + 'ovhgseq': 'CATG', } rest_dict['NlaIII'] = _temp() def _temp(): return { - 'compsite' : '(?PGG..CC)|(?PGG..CC)', - 'results' : None, - 'site' : 'GGNNCC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 256, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('N', 'W'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GGNNCC'), - 'ovhgseq' : '', + 'compsite': '(?PGG..CC)', + 'results': None, + 'site': 'GGNNCC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 256, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (3, -3, None, None, 'GGNNCC'), + 'ovhgseq': '', } rest_dict['NlaIV'] = _temp() def _temp(): return { - 'compsite' : '(?PC[CT]CG[AG]G)|(?PC[CT]CG[AG]G)', - 'results' : None, - 'site' : 'CYCGRG', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'CYCGRG'), - 'ovhgseq' : 'YCGR', + 'compsite': '(?PC[CT]CG[AG]G)', + 'results': None, + 'site': 'CYCGRG', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (5, -5, None, None, 'CYCGRG'), + 'ovhgseq': 'YCGR', } rest_dict['Nli3877I'] = _temp() def _temp(): return { - 'compsite' : '(?PGCCGAG)|(?PCTCGGC)', - 'results' : None, - 'site' : 'GCCGAG', - 'substrat' : 'DNA', - 'fst3' : 19, - 'fst5' : 27, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (27, 19, None, None, 'GCCGAG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PGCCGAG)|(?PCTCGGC)', + 'results': None, + 'site': 'GCCGAG', + 'substrat': 'DNA', + 'fst3': 19, + 'fst5': 27, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (27, 19, None, None, 'GCCGAG'), + 'ovhgseq': 'NN', } rest_dict['NmeAIII'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]CCGG[CT])|(?P[AG]CCGG[CT])', - 'results' : None, - 'site' : 'RCCGGY', - 'substrat' : 'DNA', - 'fst3' : -13, - 'fst5' : -12, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -5, - 'scd3' : 12, - 'suppl' : (), - 'scd5' : 13, - 'charac' : (-12, -13, 13, 12, 'RCCGGY'), - 'ovhgseq' : 'NNNNN', + 'compsite': '(?P[AG]CCGG[CT])', + 'results': None, + 'site': 'RCCGGY', + 'substrat': 'DNA', + 'fst3': -13, + 'fst5': -12, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': 12, + 'suppl': (), + 'scd5': 13, + 'charac': (-12, -13, 13, 12, 'RCCGGY'), + 'ovhgseq': 'NNNNN', } rest_dict['NmeDI'] = _temp() def _temp(): return { - 'compsite' : '(?PGT[CG]AC)|(?PGT[CG]AC)', - 'results' : None, - 'site' : 'GTSAC', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -5, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'GTSAC'), - 'ovhgseq' : 'GTSAC', + 'compsite': '(?PGT[CG]AC)', + 'results': None, + 'site': 'GTSAC', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (0, 0, None, None, 'GTSAC'), + 'ovhgseq': 'GTSAC', } rest_dict['NmuCI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCGGCCGC)|(?PGCGGCCGC)', - 'results' : None, - 'site' : 'GCGGCCGC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 65536, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('B', 'C', 'F', 'H', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GCGGCCGC'), - 'ovhgseq' : 'GGCC', + 'compsite': '(?PGCGGCCGC)', + 'results': None, + 'site': 'GCGGCCGC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('B', 'C', 'F', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'X', 'Y'), + 'scd5': None, + 'charac': (2, -2, None, None, 'GCGGCCGC'), + 'ovhgseq': 'GGCC', } rest_dict['NotI'] = _temp() def _temp(): return { - 'compsite' : '(?PTCGCGA)|(?PTCGCGA)', - 'results' : None, - 'site' : 'TCGCGA', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('B', 'C', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'U', 'W', 'X'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'TCGCGA'), - 'ovhgseq' : '', + 'compsite': '(?PTCGCGA)', + 'results': None, + 'site': 'TCGCGA', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('B', 'C', 'I', 'J', 'K', 'M', 'N', 'Q', 'R', 'U', 'X'), + 'scd5': None, + 'charac': (3, -3, None, None, 'TCGCGA'), + 'ovhgseq': '', } rest_dict['NruI'] = _temp() def _temp(): return { - 'compsite' : '(?PTGCGCA)|(?PTGCGCA)', - 'results' : None, - 'site' : 'TGCGCA', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F', 'K'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'TGCGCA'), - 'ovhgseq' : '', + 'compsite': '(?PTGCGCA)', + 'results': None, + 'site': 'TGCGCA', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F', 'K'), + 'scd5': None, + 'charac': (3, -3, None, None, 'TGCGCA'), + 'ovhgseq': '', } rest_dict['NsbI'] = _temp() def _temp(): return { - 'compsite' : '(?PATGCAT)|(?PATGCAT)', - 'results' : None, - 'site' : 'ATGCAT', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('B', 'H', 'J', 'M', 'N', 'R', 'S', 'U', 'W'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'ATGCAT'), - 'ovhgseq' : 'TGCA', + 'compsite': '(?PATGCAT)', + 'results': None, + 'site': 'ATGCAT', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('J', 'M', 'N', 'Q', 'R', 'S', 'U', 'X'), + 'scd5': None, + 'charac': (5, -5, None, None, 'ATGCAT'), + 'ovhgseq': 'TGCA', } rest_dict['NsiI'] = _temp() def _temp(): return { - 'compsite' : '(?PC[AC]GC[GT]G)|(?PC[AC]GC[GT]G)', - 'results' : None, - 'site' : 'CMGCKG', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'CMGCKG'), - 'ovhgseq' : '', + 'compsite': '(?PC[AC]GC[GT]G)', + 'results': None, + 'site': 'CMGCKG', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (3, -3, None, None, 'CMGCKG'), + 'ovhgseq': '', } rest_dict['NspBII'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]CATG[CT])|(?P[AG]CATG[CT])', - 'results' : None, - 'site' : 'RCATGY', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('M', 'N'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'RCATGY'), - 'ovhgseq' : 'CATG', + 'compsite': '(?P[AG]CATG[CT])', + 'results': None, + 'site': 'RCATGY', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (5, -5, None, None, 'RCATGY'), + 'ovhgseq': 'CATG', } rest_dict['NspI'] = _temp() def _temp(): return { - 'compsite' : '(?PTTCGAA)|(?PTTCGAA)', - 'results' : None, - 'site' : 'TTCGAA', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('J', 'O'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'TTCGAA'), - 'ovhgseq' : 'CG', + 'compsite': '(?PTTCGAA)', + 'results': None, + 'site': 'TTCGAA', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('J',), + 'scd5': None, + 'charac': (2, -2, None, None, 'TTCGAA'), + 'ovhgseq': 'CG', } rest_dict['NspV'] = _temp() def _temp(): return { - 'compsite' : '(?PCAC....GTG)|(?PCAC....GTG)', - 'results' : None, - 'site' : 'CACNNNNGTG', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 10, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'CACNNNNGTG'), - 'ovhgseq' : '', + 'compsite': '(?PCAC....GTG)', + 'results': None, + 'site': 'CACNNNNGTG', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 10, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (5, -5, None, None, 'CACNNNNGTG'), + 'ovhgseq': '', } rest_dict['OliI'] = _temp() def _temp(): return { - 'compsite' : '(?PGTAC)|(?PGTAC)', - 'results' : None, - 'site' : 'GTAC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GTAC'), - 'ovhgseq' : 'TA', + 'compsite': '(?PGTAC)', + 'results': None, + 'site': 'GTAC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (3, -3, None, None, 'GTAC'), + 'ovhgseq': 'TA', } rest_dict['PabI'] = _temp() def _temp(): return { - 'compsite' : '(?PTTAATTAA)|(?PTTAATTAA)', - 'results' : None, - 'site' : 'TTAATTAA', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 65536, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('F', 'N', 'O', 'W'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'TTAATTAA'), - 'ovhgseq' : 'AT', + 'compsite': '(?PTTAATTAA)', + 'results': None, + 'site': 'TTAATTAA', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('F', 'N', 'O'), + 'scd5': None, + 'charac': (5, -5, None, None, 'TTAATTAA'), + 'ovhgseq': 'AT', } rest_dict['PacI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCATGC)|(?PGCATGC)', - 'results' : None, - 'site' : 'GCATGC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GCATGC'), - 'ovhgseq' : 'CATG', + 'compsite': '(?PGCATGC)', + 'results': None, + 'site': 'GCATGC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (5, -5, None, None, 'GCATGC'), + 'ovhgseq': 'CATG', } rest_dict['PaeI'] = _temp() def _temp(): return { - 'compsite' : '(?PCTCGAG)|(?PCTCGAG)', - 'results' : None, - 'site' : 'CTCGAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTCGAG'), - 'ovhgseq' : 'TCGA', + 'compsite': '(?PCTCGAG)', + 'results': None, + 'site': 'CTCGAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CTCGAG'), + 'ovhgseq': 'TCGA', } rest_dict['PaeR7I'] = _temp() def _temp(): return { - 'compsite' : '(?PTCATGA)|(?PTCATGA)', - 'results' : None, - 'site' : 'TCATGA', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'TCATGA'), - 'ovhgseq' : 'CATG', + 'compsite': '(?PTCATGA)', + 'results': None, + 'site': 'TCATGA', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'TCATGA'), + 'ovhgseq': 'CATG', } rest_dict['PagI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGCGCGCC)|(?PGGCGCGCC)', - 'results' : None, - 'site' : 'GGCGCGCC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 65536, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GGCGCGCC'), - 'ovhgseq' : 'CGCG', + 'compsite': '(?PGGCGCGCC)', + 'results': None, + 'site': 'GGCGCGCC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (2, -2, None, None, 'GGCGCGCC'), + 'ovhgseq': 'CGCG', } rest_dict['PalAI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCC[AT]GGG)|(?PCCC[AT]GGG)', - 'results' : None, - 'site' : 'CCCWGGG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 8192, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CCCWGGG'), - 'ovhgseq' : 'CWG', + 'compsite': '(?PCCC[AT]GGG)', + 'results': None, + 'site': 'CCCWGGG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 8192, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (2, -2, None, None, 'CCCWGGG'), + 'ovhgseq': 'CWG', } rest_dict['PasI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCGCGC)|(?PGCGCGC)', - 'results' : None, - 'site' : 'GCGCGC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GCGCGC'), - 'ovhgseq' : 'CGCG', + 'compsite': '(?PGCGCGC)', + 'results': None, + 'site': 'GCGCGC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GCGCGC'), + 'ovhgseq': 'CGCG', } rest_dict['PauI'] = _temp() def _temp(): return { - 'compsite' : '(?PAGGCCT)|(?PAGGCCT)', - 'results' : None, - 'site' : 'AGGCCT', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'AGGCCT'), - 'ovhgseq' : '', + 'compsite': '(?PAGGCCT)', + 'results': None, + 'site': 'AGGCCT', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (3, -3, None, None, 'AGGCCT'), + 'ovhgseq': '', } rest_dict['PceI'] = _temp() def _temp(): return { - 'compsite' : '(?PACATGT)|(?PACATGT)', - 'results' : None, - 'site' : 'ACATGT', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'N'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'ACATGT'), - 'ovhgseq' : 'CATG', + 'compsite': '(?PACATGT)', + 'results': None, + 'site': 'ACATGT', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'N'), + 'scd5': None, + 'charac': (1, -1, None, None, 'ACATGT'), + 'ovhgseq': 'CATG', } rest_dict['PciI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCTCTTC)|(?PGAAGAGC)', - 'results' : None, - 'site' : 'GCTCTTC', - 'substrat' : 'DNA', - 'fst3' : 4, - 'fst5' : 8, - 'freq' : 16384, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (8, 4, None, None, 'GCTCTTC'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PGCTCTTC)|(?PGAAGAGC)', + 'results': None, + 'site': 'GCTCTTC', + 'substrat': 'DNA', + 'fst3': 4, + 'fst5': 8, + 'freq': 16384, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (8, 4, None, None, 'GCTCTTC'), + 'ovhgseq': 'NNN', } rest_dict['PciSI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAATGC)|(?PGCATTC)', - 'results' : None, - 'site' : 'GAATGC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 7, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (7, -1, None, None, 'GAATGC'), - 'ovhgseq' : 'CN', + 'compsite': '(?P[AT]CG.......CG[AT])', + 'results': None, + 'site': 'WCGNNNNNNNCGW', + 'substrat': 'DNA', + 'fst3': -7, + 'fst5': 7, + 'freq': 1024, + 'size': 13, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (7, -7, None, None, 'WCGNNNNNNNCGW'), + 'ovhgseq': 'N', + } +rest_dict['PcsI'] = _temp() + +def _temp(): + return { + 'compsite': '(?PGAATGC)|(?PGCATTC)', + 'results': None, + 'site': 'GAATGC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 7, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (7, -1, None, None, 'GAATGC'), + 'ovhgseq': 'CN', } rest_dict['PctI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCCGGC)|(?PGCCGGC)', - 'results' : None, - 'site' : 'GCCGGC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GCCGGC'), - 'ovhgseq' : '', + 'compsite': '(?PGCCGGC)', + 'results': None, + 'site': 'GCCGGC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (3, -3, None, None, 'GCCGGC'), + 'ovhgseq': '', } rest_dict['PdiI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAA....TTC)|(?PGAA....TTC)', - 'results' : None, - 'site' : 'GAANNNNTTC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 10, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GAANNNNTTC'), - 'ovhgseq' : '', + 'compsite': '(?PGAA....TTC)', + 'results': None, + 'site': 'GAANNNNTTC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 10, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (5, -5, None, None, 'GAANNNNTTC'), + 'ovhgseq': '', } rest_dict['PdmI'] = _temp() def _temp(): return { - 'compsite' : '(?PGA[AT]TC)|(?PGA[AT]TC)', - 'results' : None, - 'site' : 'GAWTC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GAWTC'), - 'ovhgseq' : 'AWT', + 'compsite': '(?PGCAGT)|(?PACTGC)', + 'results': None, + 'site': 'GCAGT', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'GCAGT'), + 'ovhgseq': None, + } +rest_dict['PenI'] = _temp() + +def _temp(): + return { + 'compsite': '(?PGA[AT]TC)', + 'results': None, + 'site': 'GAWTC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GAWTC'), + 'ovhgseq': 'AWT', } rest_dict['PfeI'] = _temp() def _temp(): return { - 'compsite' : '(?PTCGTAG)|(?PCTACGA)', - 'results' : None, - 'site' : 'TCGTAG', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'TCGTAG'), - 'ovhgseq' : None, + 'compsite': '(?PTCGTAG)|(?PCTACGA)', + 'results': None, + 'site': 'TCGTAG', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'TCGTAG'), + 'ovhgseq': None, } rest_dict['Pfl1108I'] = _temp() def _temp(): return { - 'compsite' : '(?PCGTACG)|(?PCGTACG)', - 'results' : None, - 'site' : 'CGTACG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CGTACG'), - 'ovhgseq' : 'GTAC', + 'compsite': '(?PCGTACG)', + 'results': None, + 'site': 'CGTACG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CGTACG'), + 'ovhgseq': 'GTAC', } rest_dict['Pfl23II'] = _temp() def _temp(): return { - 'compsite' : '(?PGAC...GTC)|(?PGAC...GTC)', - 'results' : None, - 'site' : 'GACNNNGTC', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 4096, - 'size' : 9, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'GACNNNGTC'), - 'ovhgseq' : 'N', + 'compsite': '(?PGAC...GTC)', + 'results': None, + 'site': 'GACNNNGTC', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 4096, + 'size': 9, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (4, -4, None, None, 'GACNNNGTC'), + 'ovhgseq': 'N', } rest_dict['PflFI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCA.....TGG)|(?PCCA.....TGG)', - 'results' : None, - 'site' : 'CCANNNNNTGG', - 'substrat' : 'DNA', - 'fst3' : -7, - 'fst5' : 7, - 'freq' : 4096, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (7, -7, None, None, 'CCANNNNNTGG'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PCCA.....TGG)', + 'results': None, + 'site': 'CCANNNNNTGG', + 'substrat': 'DNA', + 'fst3': -7, + 'fst5': 7, + 'freq': 4096, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (7, -7, None, None, 'CCANNNNNTGG'), + 'ovhgseq': 'NNN', } rest_dict['PflMI'] = _temp() def _temp(): return { - 'compsite' : '(?PTCC.GGA)|(?PTCC.GGA)', - 'results' : None, - 'site' : 'TCCNGGA', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -5, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'TCCNGGA'), - 'ovhgseq' : 'CCNGG', + 'compsite': '(?PTCC.GGA)', + 'results': None, + 'site': 'TCCNGGA', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'TCCNGGA'), + 'ovhgseq': 'CCNGG', } rest_dict['PfoI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGCC)|(?PGGCC)', - 'results' : None, - 'site' : 'GGCC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GGCC'), - 'ovhgseq' : '', - } -rest_dict['PhoI'] = _temp() - -def _temp(): - return { - 'compsite' : '(?PACCGGT)|(?PACCGGT)', - 'results' : None, - 'site' : 'ACCGGT', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('B', 'M', 'Q', 'X'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'ACCGGT'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?PACCGGT)', + 'results': None, + 'site': 'ACCGGT', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('M', 'Q', 'X'), + 'scd5': None, + 'charac': (1, -1, None, None, 'ACCGGT'), + 'ovhgseq': 'CCGG', } rest_dict['PinAI'] = _temp() def _temp(): return { - 'compsite' : '(?PCATCAG)|(?PCTGATG)', - 'results' : None, - 'site' : 'CATCAG', - 'substrat' : 'DNA', - 'fst3' : 19, - 'fst5' : 27, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (27, 19, None, None, 'CATCAG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PCATCAG)|(?PCTGATG)', + 'results': None, + 'site': 'CATCAG', + 'substrat': 'DNA', + 'fst3': 19, + 'fst5': 27, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (27, 19, None, None, 'CATCAG'), + 'ovhgseq': 'NN', } rest_dict['PlaDI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGATCG)|(?PCGATCG)', - 'results' : None, - 'site' : 'CGATCG', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'CGATCG'), - 'ovhgseq' : 'AT', + 'compsite': '(?PCGATCG)', + 'results': None, + 'site': 'CGATCG', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (4, -4, None, None, 'CGATCG'), + 'ovhgseq': 'AT', } rest_dict['Ple19I'] = _temp() def _temp(): return { - 'compsite' : '(?PGAGTC)|(?PGACTC)', - 'results' : None, - 'site' : 'GAGTC', - 'substrat' : 'DNA', - 'fst3' : 5, - 'fst5' : 9, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (9, 5, None, None, 'GAGTC'), - 'ovhgseq' : 'N', + 'compsite': '(?PGAGTC)|(?PGACTC)', + 'results': None, + 'site': 'GAGTC', + 'substrat': 'DNA', + 'fst3': 5, + 'fst5': 9, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (9, 5, None, None, 'GAGTC'), + 'ovhgseq': 'N', } rest_dict['PleI'] = _temp() def _temp(): return { - 'compsite' : '(?PCACGTG)|(?PCACGTG)', - 'results' : None, - 'site' : 'CACGTG', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('K',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'CACGTG'), - 'ovhgseq' : '', + 'compsite': '(?PGGCGCC)', + 'results': None, + 'site': 'GGCGCC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (5, -5, None, None, 'GGCGCC'), + 'ovhgseq': 'GCGC', + } +rest_dict['PluTI'] = _temp() + +def _temp(): + return { + 'compsite': '(?PCACGTG)', + 'results': None, + 'site': 'CACGTG', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('K',), + 'scd5': None, + 'charac': (3, -3, None, None, 'CACGTG'), + 'ovhgseq': '', } rest_dict['PmaCI'] = _temp() def _temp(): return { - 'compsite' : '(?PGTTTAAAC)|(?PGTTTAAAC)', - 'results' : None, - 'site' : 'GTTTAAAC', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 65536, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('N', 'W'), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'GTTTAAAC'), - 'ovhgseq' : '', + 'compsite': '(?PGTTTAAAC)', + 'results': None, + 'site': 'GTTTAAAC', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (4, -4, None, None, 'GTTTAAAC'), + 'ovhgseq': '', } rest_dict['PmeI'] = _temp() def _temp(): return { - 'compsite' : '(?PCACGTG)|(?PCACGTG)', - 'results' : None, - 'site' : 'CACGTG', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'CACGTG'), - 'ovhgseq' : '', + 'compsite': '(?PCACGTG)', + 'results': None, + 'site': 'CACGTG', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (3, -3, None, None, 'CACGTG'), + 'ovhgseq': '', } rest_dict['PmlI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAAC.....CTC)|(?PGAG.....GTTC)', - 'results' : None, - 'site' : 'GAACNNNNNCTC', - 'substrat' : 'DNA', - 'fst3' : -24, - 'fst5' : -7, - 'freq' : 16384, - 'size' : 12, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 5, - 'scd3' : 8, - 'suppl' : ('F',), - 'scd5' : 25, - 'charac' : (-7, -24, 25, 8, 'GAACNNNNNCTC'), - 'ovhgseq' : 'NNNNN', + 'compsite': '(?PGAAC.....CTC)|(?PGAG.....GTTC)', + 'results': None, + 'site': 'GAACNNNNNCTC', + 'substrat': 'DNA', + 'fst3': -24, + 'fst5': -7, + 'freq': 16384, + 'size': 12, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 5, + 'scd3': 8, + 'suppl': (), + 'scd5': 25, + 'charac': (-7, -24, 25, 8, 'GAACNNNNNCTC'), + 'ovhgseq': 'NNNNN', } rest_dict['PpiI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAGTC)|(?PGACTC)', - 'results' : None, - 'site' : 'GAGTC', - 'substrat' : 'DNA', - 'fst3' : 5, - 'fst5' : 9, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (9, 5, None, None, 'GAGTC'), - 'ovhgseq' : 'N', + 'compsite': '(?PGAGTC)|(?PGACTC)', + 'results': None, + 'site': 'GAGTC', + 'substrat': 'DNA', + 'fst3': 5, + 'fst5': 9, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (9, 5, None, None, 'GAGTC'), + 'ovhgseq': 'N', } rest_dict['PpsI'] = _temp() def _temp(): return { - 'compsite' : '(?PATGCAT)|(?PATGCAT)', - 'results' : None, - 'site' : 'ATGCAT', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'ATGCAT'), - 'ovhgseq' : 'TGCA', + 'compsite': '(?PATGCAT)', + 'results': None, + 'site': 'ATGCAT', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (1, -1, None, None, 'ATGCAT'), + 'ovhgseq': 'TGCA', } rest_dict['Ppu10I'] = _temp() def _temp(): return { - 'compsite' : '(?P[CT]ACGT[AG])|(?P[CT]ACGT[AG])', - 'results' : None, - 'site' : 'YACGTR', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'YACGTR'), - 'ovhgseq' : '', + 'compsite': '(?P[CT]ACGT[AG])', + 'results': None, + 'site': 'YACGTR', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (3, -3, None, None, 'YACGTR'), + 'ovhgseq': '', } rest_dict['Ppu21I'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]GG[AT]CC[CT])|(?P[AG]GG[AT]CC[CT])', - 'results' : None, - 'site' : 'RGGWCCY', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 2048, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('N', 'O'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'RGGWCCY'), - 'ovhgseq' : 'GWC', + 'compsite': '(?P[AG]GG[AT]CC[CT])', + 'results': None, + 'site': 'RGGWCCY', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 2048, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (2, -2, None, None, 'RGGWCCY'), + 'ovhgseq': 'GWC', } rest_dict['PpuMI'] = _temp() def _temp(): return { - 'compsite' : '(?PACATGT)|(?PACATGT)', - 'results' : None, - 'site' : 'ACATGT', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'ACATGT'), - 'ovhgseq' : 'CATG', + 'compsite': '(?PACATGT)', + 'results': None, + 'site': 'ACATGT', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'ACATGT'), + 'ovhgseq': 'CATG', } rest_dict['PscI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAC....GTC)|(?PGAC....GTC)', - 'results' : None, - 'site' : 'GACNNNNGTC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 10, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('K', 'N'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GACNNNNGTC'), - 'ovhgseq' : '', + 'compsite': '(?PGAC....GTC)', + 'results': None, + 'site': 'GACNNNNGTC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 10, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('K', 'N'), + 'scd5': None, + 'charac': (5, -5, None, None, 'GACNNNNGTC'), + 'ovhgseq': '', } rest_dict['PshAI'] = _temp() def _temp(): return { - 'compsite' : '(?PATTAAT)|(?PATTAAT)', - 'results' : None, - 'site' : 'ATTAAT', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('K',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'ATTAAT'), - 'ovhgseq' : 'TA', + 'compsite': '(?PATTAAT)', + 'results': None, + 'site': 'ATTAAT', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('K',), + 'scd5': None, + 'charac': (2, -2, None, None, 'ATTAAT'), + 'ovhgseq': 'TA', } rest_dict['PshBI'] = _temp() def _temp(): return { - 'compsite' : '(?PTTATAA)|(?PTTATAA)', - 'results' : None, - 'site' : 'TTATAA', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I', 'N', 'O'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'TTATAA'), - 'ovhgseq' : '', + 'compsite': '(?PTTATAA)', + 'results': None, + 'site': 'TTATAA', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I', 'N'), + 'scd5': None, + 'charac': (3, -3, None, None, 'TTATAA'), + 'ovhgseq': '', } rest_dict['PsiI'] = _temp() def _temp(): return { - 'compsite' : '(?PGG[AT]CC)|(?PGG[AT]CC)', - 'results' : None, - 'site' : 'GGWCC', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'GGWCC'), - 'ovhgseq' : 'GWC', + 'compsite': '(?PGG[AT]CC)', + 'results': None, + 'site': 'GGWCC', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (4, -4, None, None, 'GGWCC'), + 'ovhgseq': 'GWC', } rest_dict['Psp03I'] = _temp() def _temp(): return { - 'compsite' : '(?PGAGCTC)|(?PGAGCTC)', - 'results' : None, - 'site' : 'GAGCTC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GAGCTC'), - 'ovhgseq' : 'AGCT', + 'compsite': '(?PGAGCTC)', + 'results': None, + 'site': 'GAGCTC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (5, -5, None, None, 'GAGCTC'), + 'ovhgseq': 'AGCT', } rest_dict['Psp124BI'] = _temp() def _temp(): return { - 'compsite' : '(?PAACGTT)|(?PAACGTT)', - 'results' : None, - 'site' : 'AACGTT', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('F', 'K'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'AACGTT'), - 'ovhgseq' : 'CG', + 'compsite': '(?PAACGTT)', + 'results': None, + 'site': 'AACGTT', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('F', 'K'), + 'scd5': None, + 'charac': (2, -2, None, None, 'AACGTT'), + 'ovhgseq': 'CG', } rest_dict['Psp1406I'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]GG[AT]CC[CT])|(?P[AG]GG[AT]CC[CT])', - 'results' : None, - 'site' : 'RGGWCCY', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 2048, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'RGGWCCY'), - 'ovhgseq' : 'GWC', + 'compsite': '(?P[AG]GG[AT]CC[CT])', + 'results': None, + 'site': 'RGGWCCY', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 2048, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (2, -2, None, None, 'RGGWCCY'), + 'ovhgseq': 'GWC', } rest_dict['Psp5II'] = _temp() def _temp(): return { - 'compsite' : '(?PCC[AT]GG)|(?PCC[AT]GG)', - 'results' : None, - 'site' : 'CCWGG', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -5, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'CCWGG'), - 'ovhgseq' : 'CCWGG', + 'compsite': '(?PCC[AT]GG)', + 'results': None, + 'site': 'CCWGG', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (0, 0, None, None, 'CCWGG'), + 'ovhgseq': 'CCWGG', } rest_dict['Psp6I'] = _temp() def _temp(): return { - 'compsite' : '(?PCACGTG)|(?PCACGTG)', - 'results' : None, - 'site' : 'CACGTG', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'CACGTG'), - 'ovhgseq' : '', + 'compsite': '(?PCACGTG)', + 'results': None, + 'site': 'CACGTG', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (3, -3, None, None, 'CACGTG'), + 'ovhgseq': '', } rest_dict['PspCI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGT.ACC)|(?PGGT.ACC)', - 'results' : None, - 'site' : 'GGTNACC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -5, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGTNACC'), - 'ovhgseq' : 'GTNAC', + 'compsite': '(?PGGT.ACC)', + 'results': None, + 'site': 'GGTNACC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGTNACC'), + 'ovhgseq': 'GTNAC', } rest_dict['PspEI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC[AT]GG)|(?PCC[AT]GG)', - 'results' : None, - 'site' : 'CCWGG', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -5, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'CCWGG'), - 'ovhgseq' : 'CCWGG', + 'compsite': '(?PCC[AT]GG)', + 'results': None, + 'site': 'CCWGG', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (0, 0, None, None, 'CCWGG'), + 'ovhgseq': 'CCWGG', } rest_dict['PspGI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGTACG)|(?PCGTACG)', - 'results' : None, - 'site' : 'CGTACG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CGTACG'), - 'ovhgseq' : 'GTAC', + 'compsite': '(?PCGTACG)', + 'results': None, + 'site': 'CGTACG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CGTACG'), + 'ovhgseq': 'GTAC', } rest_dict['PspLI'] = _temp() def _temp(): return { - 'compsite' : '(?PGG..CC)|(?PGG..CC)', - 'results' : None, - 'site' : 'GGNNCC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 256, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GGNNCC'), - 'ovhgseq' : '', + 'compsite': '(?PGG..CC)', + 'results': None, + 'site': 'GGNNCC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 256, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (3, -3, None, None, 'GGNNCC'), + 'ovhgseq': '', } rest_dict['PspN4I'] = _temp() def _temp(): return { - 'compsite' : '(?PGGGCCC)|(?PGGGCCC)', - 'results' : None, - 'site' : 'GGGCCC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'N', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGGCCC'), - 'ovhgseq' : 'GGCC', + 'compsite': '(?PGGGCCC)', + 'results': None, + 'site': 'GGGCCC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'N', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGGCCC'), + 'ovhgseq': 'GGCC', } rest_dict['PspOMI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGCCCA[AG])|(?P[CT]TGGGCG)', - 'results' : None, - 'site' : 'CGCCCAR', - 'substrat' : 'DNA', - 'fst3' : 18, - 'fst5' : 27, - 'freq' : 8192, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (27, 18, None, None, 'CGCCCAR'), - 'ovhgseq' : 'NN', + 'compsite': '(?PCGCCCA[AG])|(?P[CT]TGGGCG)', + 'results': None, + 'site': 'CGCCCAR', + 'substrat': 'DNA', + 'fst3': 18, + 'fst5': 27, + 'freq': 8192, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (27, 18, None, None, 'CGCCCAR'), + 'ovhgseq': 'NN', } rest_dict['PspOMII'] = _temp() def _temp(): return { - 'compsite' : '(?PGG.CC)|(?PGG.CC)', - 'results' : None, - 'site' : 'GGNCC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('C',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGNCC'), - 'ovhgseq' : 'GNC', + 'compsite': '(?PGG.CC)', + 'results': None, + 'site': 'GGNCC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('C',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGNCC'), + 'ovhgseq': 'GNC', } rest_dict['PspPI'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]GG[AT]CC[CT])|(?P[AG]GG[AT]CC[CT])', - 'results' : None, - 'site' : 'RGGWCCY', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 2048, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'RGGWCCY'), - 'ovhgseq' : 'GWC', + 'compsite': '(?P[AG]GG[AT]CC[CT])', + 'results': None, + 'site': 'RGGWCCY', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 2048, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (2, -2, None, None, 'RGGWCCY'), + 'ovhgseq': 'GWC', } rest_dict['PspPPI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC[CT]CAG)|(?PCTG[AG]GG)', - 'results' : None, - 'site' : 'CCYCAG', - 'substrat' : 'DNA', - 'fst3' : 13, - 'fst5' : 21, - 'freq' : 2048, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (21, 13, None, None, 'CCYCAG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PCC[CT]CAG)|(?PCTG[AG]GG)', + 'results': None, + 'site': 'CCYCAG', + 'substrat': 'DNA', + 'fst3': 13, + 'fst5': 21, + 'freq': 2048, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (21, 13, None, None, 'CCYCAG'), + 'ovhgseq': 'NN', } rest_dict['PspPRI'] = _temp() def _temp(): return { - 'compsite' : '(?P[ACG]CTCGAG[CGT])|(?P[ACG]CTCGAG[CGT])', - 'results' : None, - 'site' : 'VCTCGAGB', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'N'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'VCTCGAGB'), - 'ovhgseq' : 'TCGA', + 'compsite': '(?P[ACG]CTCGAG[CGT])', + 'results': None, + 'site': 'VCTCGAGB', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'N'), + 'scd5': None, + 'charac': (2, -2, None, None, 'VCTCGAGB'), + 'ovhgseq': 'TCGA', } rest_dict['PspXI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAAC......TAC)|(?PGTA......GTTC)', - 'results' : None, - 'site' : 'GAACNNNNNNTAC', - 'substrat' : 'DNA', - 'fst3' : -25, - 'fst5' : -7, - 'freq' : 16384, - 'size' : 13, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 5, - 'scd3' : 7, - 'suppl' : ('I',), - 'scd5' : 25, - 'charac' : (-7, -25, 25, 7, 'GAACNNNNNNTAC'), - 'ovhgseq' : 'NNNNN', + 'compsite': '(?PGAAC......TAC)|(?PGTA......GTTC)', + 'results': None, + 'site': 'GAACNNNNNNTAC', + 'substrat': 'DNA', + 'fst3': -25, + 'fst5': -7, + 'freq': 16384, + 'size': 13, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 5, + 'scd3': 7, + 'suppl': ('I',), + 'scd5': 25, + 'charac': (-7, -25, 25, 7, 'GAACNNNNNNTAC'), + 'ovhgseq': 'NNNNN', } rest_dict['PsrI'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]GG.CC[CT])|(?P[AG]GG.CC[CT])', - 'results' : None, - 'site' : 'RGGNCCY', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 1024, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'RGGNCCY'), - 'ovhgseq' : 'GNC', + 'compsite': '(?P[AG]GG.CC[CT])', + 'results': None, + 'site': 'RGGNCCY', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 1024, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (5, -5, None, None, 'RGGNCCY'), + 'ovhgseq': 'GNC', } rest_dict['PssI'] = _temp() def _temp(): return { - 'compsite' : '(?PCTGCAG)|(?PCTGCAG)', - 'results' : None, - 'site' : 'CTGCAG', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('B', 'C', 'F', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'CTGCAG'), - 'ovhgseq' : 'TGCA', + 'compsite': '(?PCTGCAG)', + 'results': None, + 'site': 'CTGCAG', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('B', 'C', 'F', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'X', 'Y'), + 'scd5': None, + 'charac': (5, -5, None, None, 'CTGCAG'), + 'ovhgseq': 'TGCA', } rest_dict['PstI'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]GATC[CT])|(?P[AG]GATC[CT])', - 'results' : None, - 'site' : 'RGATCY', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'RGATCY'), - 'ovhgseq' : 'GATC', + 'compsite': '(?PCAG...CTG)', + 'results': None, + 'site': 'CAGNNNCTG', + 'substrat': 'DNA', + 'fst3': -6, + 'fst5': 6, + 'freq': 4096, + 'size': 9, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (6, -6, None, None, 'CAGNNNCTG'), + 'ovhgseq': 'NNN', + } +rest_dict['PstNI'] = _temp() + +def _temp(): + return { + 'compsite': '(?P[AG]GATC[CT])', + 'results': None, + 'site': 'RGATCY', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'RGATCY'), + 'ovhgseq': 'GATC', } rest_dict['PsuI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAC...GTC)|(?PGAC...GTC)', - 'results' : None, - 'site' : 'GACNNNGTC', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 4096, - 'size' : 9, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'GACNNNGTC'), - 'ovhgseq' : 'N', + 'compsite': '(?PGAC...GTC)', + 'results': None, + 'site': 'GACNNNGTC', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 4096, + 'size': 9, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (4, -4, None, None, 'GACNNNGTC'), + 'ovhgseq': 'N', } rest_dict['PsyI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCGCGC)|(?PGCGCGC)', - 'results' : None, - 'site' : 'GCGCGC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GCGCGC'), - 'ovhgseq' : 'CGCG', + 'compsite': '(?PGCGCGC)', + 'results': None, + 'site': 'GCGCGC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GCGCGC'), + 'ovhgseq': 'CGCG', } rest_dict['PteI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGATCG)|(?PCGATCG)', - 'results' : None, - 'site' : 'CGATCG', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('B', 'F', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'CGATCG'), - 'ovhgseq' : 'AT', + 'compsite': '(?PCGATCG)', + 'results': None, + 'site': 'CGATCG', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('B', 'F', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'X', 'Y'), + 'scd5': None, + 'charac': (4, -4, None, None, 'CGATCG'), + 'ovhgseq': 'AT', } rest_dict['PvuI'] = _temp() def _temp(): return { - 'compsite' : '(?PCAGCTG)|(?PCAGCTG)', - 'results' : None, - 'site' : 'CAGCTG', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('B', 'C', 'F', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'R', 'S', 'U', 'V', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'CAGCTG'), - 'ovhgseq' : '', + 'compsite': '(?PCAGCTG)', + 'results': None, + 'site': 'CAGCTG', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('B', 'C', 'F', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'X', 'Y'), + 'scd5': None, + 'charac': (3, -3, None, None, 'CAGCTG'), + 'ovhgseq': '', } rest_dict['PvuII'] = _temp() def _temp(): return { - 'compsite' : '(?PTCATGA)|(?PTCATGA)', - 'results' : None, - 'site' : 'TCATGA', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('M',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'TCATGA'), - 'ovhgseq' : 'CATG', - } -rest_dict['RcaI'] = _temp() + 'compsite': '(?PGCAGC)|(?PGCTGC)', + 'results': None, + 'site': 'GCAGC', + 'substrat': 'DNA', + 'fst3': -10, + 'fst5': -7, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': 11, + 'suppl': (), + 'scd5': 14, + 'charac': (-7, -10, 14, 11, 'GCAGC'), + 'ovhgseq': 'NN', + } +rest_dict['R2_BceSIV'] = _temp() def _temp(): return { - 'compsite' : '(?PCATCGAC)|(?PGTCGATG)', - 'results' : None, - 'site' : 'CATCGAC', - 'substrat' : 'DNA', - 'fst3' : 18, - 'fst5' : 27, - 'freq' : 16384, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (27, 18, None, None, 'CATCGAC'), - 'ovhgseq' : 'NN', + 'compsite': '(?PCATCGAC)|(?PGTCGATG)', + 'results': None, + 'site': 'CATCGAC', + 'substrat': 'DNA', + 'fst3': 18, + 'fst5': 27, + 'freq': 16384, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (27, 18, None, None, 'CATCGAC'), + 'ovhgseq': 'NN', } rest_dict['RceI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCGATCGC)|(?PGCGATCGC)', - 'results' : None, - 'site' : 'GCGATCGC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 65536, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GCGATCGC'), - 'ovhgseq' : 'AT', + 'compsite': '(?PCCGCAG)|(?PCTGCGG)', + 'results': None, + 'site': 'CCGCAG', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'CCGCAG'), + 'ovhgseq': None, + } +rest_dict['RdeGBI'] = _temp() + +def _temp(): + return { + 'compsite': '(?PACCCAG)|(?PCTGGGT)', + 'results': None, + 'site': 'ACCCAG', + 'substrat': 'DNA', + 'fst3': 18, + 'fst5': 26, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (26, 18, None, None, 'ACCCAG'), + 'ovhgseq': 'NN', + } +rest_dict['RdeGBII'] = _temp() + +def _temp(): + return { + 'compsite': '(?PTG[AG][CT]CA)', + 'results': None, + 'site': 'TGRYCA', + 'substrat': 'DNA', + 'fst3': -17, + 'fst5': -9, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': 9, + 'suppl': (), + 'scd5': 17, + 'charac': (-9, -17, 17, 9, 'TGRYCA'), + 'ovhgseq': 'NN', + } +rest_dict['RdeGBIII'] = _temp() + +def _temp(): + return { + 'compsite': '(?PCGCCAG)|(?PCTGGCG)', + 'results': None, + 'site': 'CGCCAG', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'CGCCAG'), + 'ovhgseq': None, + } +rest_dict['RflFIII'] = _temp() + +def _temp(): + return { + 'compsite': '(?PGCGATCGC)', + 'results': None, + 'site': 'GCGATCGC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (5, -5, None, None, 'GCGATCGC'), + 'ovhgseq': 'AT', } rest_dict['RgaI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGCCGGCC)|(?PGGCCGGCC)', - 'results' : None, - 'site' : 'GGCCGGCC', - 'substrat' : 'DNA', - 'fst3' : -6, - 'fst5' : 6, - 'freq' : 65536, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (6, -6, None, None, 'GGCCGGCC'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?PGGCCGGCC)', + 'results': None, + 'site': 'GGCCGGCC', + 'substrat': 'DNA', + 'fst3': -6, + 'fst5': 6, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (6, -6, None, None, 'GGCCGGCC'), + 'ovhgseq': 'CCGG', } rest_dict['RigI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCCACA)|(?PTGTGGG)', - 'results' : None, - 'site' : 'CCCACA', - 'substrat' : 'DNA', - 'fst3' : 9, - 'fst5' : 18, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (18, 9, None, None, 'CCCACA'), - 'ovhgseq' : 'NNN', + 'compsite': '(?P[ACG]C[AT])|(?P[AT]G[CGT])', + 'results': None, + 'site': 'VCW', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 8, + 'size': 3, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'VCW'), + 'ovhgseq': None, + } +rest_dict['RlaI'] = _temp() + +def _temp(): + return { + 'compsite': '(?PCCCACA)|(?PTGTGGG)', + 'results': None, + 'site': 'CCCACA', + 'substrat': 'DNA', + 'fst3': 9, + 'fst5': 18, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (18, 9, None, None, 'CCCACA'), + 'ovhgseq': 'NNN', } rest_dict['RleAI'] = _temp() def _temp(): return { - 'compsite' : '(?PCG[AG]GGAC)|(?PGTCC[CT]CG)', - 'results' : None, - 'site' : 'CGRGGAC', - 'substrat' : 'DNA', - 'fst3' : 18, - 'fst5' : 27, - 'freq' : 8192, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (27, 18, None, None, 'CGRGGAC'), - 'ovhgseq' : 'NN', + 'compsite': '(?PCG[AG]GGAC)|(?PGTCC[CT]CG)', + 'results': None, + 'site': 'CGRGGAC', + 'substrat': 'DNA', + 'fst3': 18, + 'fst5': 27, + 'freq': 8192, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (27, 18, None, None, 'CGRGGAC'), + 'ovhgseq': 'NN', } rest_dict['RpaB5I'] = _temp() def _temp(): return { - 'compsite' : '(?PTCGCGA)|(?PTCGCGA)', - 'results' : None, - 'site' : 'TCGCGA', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'TCGCGA'), - 'ovhgseq' : '', + 'compsite': '(?PCCCGCAG)|(?PCTGCGGG)', + 'results': None, + 'site': 'CCCGCAG', + 'substrat': 'DNA', + 'fst3': 18, + 'fst5': 27, + 'freq': 16384, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (27, 18, None, None, 'CCCGCAG'), + 'ovhgseq': 'NN', + } +rest_dict['RpaBI'] = _temp() + +def _temp(): + return { + 'compsite': '(?PGT[CT]GGAG)|(?PCTCC[AG]AC)', + 'results': None, + 'site': 'GTYGGAG', + 'substrat': 'DNA', + 'fst3': 9, + 'fst5': 18, + 'freq': 8192, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (18, 9, None, None, 'GTYGGAG'), + 'ovhgseq': 'NN', + } +rest_dict['RpaI'] = _temp() + +def _temp(): + return { + 'compsite': '(?PG[AG]TGGAG)|(?PCTCCA[CT]C)', + 'results': None, + 'site': 'GRTGGAG', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 8192, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'GRTGGAG'), + 'ovhgseq': None, + } +rest_dict['RpaTI'] = _temp() + +def _temp(): + return { + 'compsite': '(?PTCGCGA)', + 'results': None, + 'site': 'TCGCGA', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (3, -3, None, None, 'TCGCGA'), + 'ovhgseq': '', } rest_dict['RruI'] = _temp() def _temp(): return { - 'compsite' : '(?PGTAC)|(?PGTAC)', - 'results' : None, - 'site' : 'GTAC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('B', 'C', 'F', 'H', 'I', 'J', 'M', 'N', 'O', 'Q', 'R', 'S', 'V', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GTAC'), - 'ovhgseq' : '', + 'compsite': '(?PGTAC)', + 'results': None, + 'site': 'GTAC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('C', 'F', 'I', 'J', 'M', 'N', 'Q', 'R', 'S', 'V', 'X', 'Y'), + 'scd5': None, + 'charac': (2, -2, None, None, 'GTAC'), + 'ovhgseq': '', } rest_dict['RsaI'] = _temp() def _temp(): return { - 'compsite' : '(?PGTAC)|(?PGTAC)', - 'results' : None, - 'site' : 'GTAC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GTAC'), - 'ovhgseq' : 'TA', + 'compsite': '(?PGTAC)', + 'results': None, + 'site': 'GTAC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GTAC'), + 'ovhgseq': 'TA', } rest_dict['RsaNI'] = _temp() def _temp(): return { - 'compsite' : '(?PCA[CT]....[AG]TG)|(?PCA[CT]....[AG]TG)', - 'results' : None, - 'site' : 'CAYNNNNRTG', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 1024, - 'size' : 10, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'CAYNNNNRTG'), - 'ovhgseq' : '', + 'compsite': '(?PCA[CT]....[AG]TG)', + 'results': None, + 'site': 'CAYNNNNRTG', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 1024, + 'size': 10, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (5, -5, None, None, 'CAYNNNNRTG'), + 'ovhgseq': '', } rest_dict['RseI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGG[AT]CCG)|(?PCGG[AT]CCG)', - 'results' : None, - 'site' : 'CGGWCCG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 8192, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CGGWCCG'), - 'ovhgseq' : 'GWC', + 'compsite': '(?PCGG[AT]CCG)', + 'results': None, + 'site': 'CGGWCCG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 8192, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (2, -2, None, None, 'CGGWCCG'), + 'ovhgseq': 'GWC', } rest_dict['Rsr2I'] = _temp() def _temp(): return { - 'compsite' : '(?PCGG[AT]CCG)|(?PCGG[AT]CCG)', - 'results' : None, - 'site' : 'CGGWCCG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 8192, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('M', 'N', 'Q', 'X'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CGGWCCG'), - 'ovhgseq' : 'GWC', + 'compsite': '(?PCGG[AT]CCG)', + 'results': None, + 'site': 'CGGWCCG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 8192, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('N', 'Q', 'X'), + 'scd5': None, + 'charac': (2, -2, None, None, 'CGGWCCG'), + 'ovhgseq': 'GWC', } rest_dict['RsrII'] = _temp() def _temp(): return { - 'compsite' : '(?PGAGCTC)|(?PGAGCTC)', - 'results' : None, - 'site' : 'GAGCTC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('F', 'H', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'W', 'X'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GAGCTC'), - 'ovhgseq' : 'AGCT', + 'compsite': '(?PGAGCTC)', + 'results': None, + 'site': 'GAGCTC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('B', 'F', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'X'), + 'scd5': None, + 'charac': (5, -5, None, None, 'GAGCTC'), + 'ovhgseq': 'AGCT', } rest_dict['SacI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCGCGG)|(?PCCGCGG)', - 'results' : None, - 'site' : 'CCGCGG', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('H', 'J', 'K', 'N', 'O', 'Q', 'R', 'W', 'X'), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'CCGCGG'), - 'ovhgseq' : 'GC', + 'compsite': '(?PCCGCGG)', + 'results': None, + 'site': 'CCGCGG', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('B', 'J', 'K', 'N', 'O', 'Q', 'R', 'X'), + 'scd5': None, + 'charac': (4, -4, None, None, 'CCGCGG'), + 'ovhgseq': 'GC', } rest_dict['SacII'] = _temp() def _temp(): return { - 'compsite' : '(?PGTCGAC)|(?PGTCGAC)', - 'results' : None, - 'site' : 'GTCGAC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('B', 'C', 'F', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GTCGAC'), - 'ovhgseq' : 'TCGA', + 'compsite': '(?PGTCGAC)', + 'results': None, + 'site': 'GTCGAC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('B', 'C', 'F', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'X', 'Y'), + 'scd5': None, + 'charac': (1, -1, None, None, 'GTCGAC'), + 'ovhgseq': 'TCGA', } rest_dict['SalI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGG[AT]CCC)|(?PGGG[AT]CCC)', - 'results' : None, - 'site' : 'GGGWCCC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 8192, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('E',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GGGWCCC'), - 'ovhgseq' : 'GWC', + 'compsite': '(?PGGG[AT]CCC)', + 'results': None, + 'site': 'GGGWCCC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 8192, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (2, -2, None, None, 'GGGWCCC'), + 'ovhgseq': 'GWC', } rest_dict['SanDI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCTCTTC)|(?PGAAGAGC)', - 'results' : None, - 'site' : 'GCTCTTC', - 'substrat' : 'DNA', - 'fst3' : 4, - 'fst5' : 8, - 'freq' : 16384, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (8, 4, None, None, 'GCTCTTC'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PGCTCTTC)|(?PGAAGAGC)', + 'results': None, + 'site': 'GCTCTTC', + 'substrat': 'DNA', + 'fst3': 4, + 'fst5': 8, + 'freq': 16384, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (8, 4, None, None, 'GCTCTTC'), + 'ovhgseq': 'NNN', } rest_dict['SapI'] = _temp() def _temp(): return { - 'compsite' : '(?PTTAA)|(?PTTAA)', - 'results' : None, - 'site' : 'TTAA', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'TTAA'), - 'ovhgseq' : 'TA', + 'compsite': '(?PTTAA)', + 'results': None, + 'site': 'TTAA', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'TTAA'), + 'ovhgseq': 'TA', } rest_dict['SaqAI'] = _temp() def _temp(): return { - 'compsite' : '(?PGC.GC)|(?PGC.GC)', - 'results' : None, - 'site' : 'GCNGC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GCNGC'), - 'ovhgseq' : 'N', + 'compsite': '(?PGC.GC)', + 'results': None, + 'site': 'GCNGC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (2, -2, None, None, 'GCNGC'), + 'ovhgseq': 'N', } rest_dict['SatI'] = _temp() def _temp(): return { - 'compsite' : '(?PGATC)|(?PGATC)', - 'results' : None, - 'site' : 'GATC', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('C', 'H', 'J', 'K', 'M', 'N', 'O', 'R', 'S', 'U', 'W', 'X'), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'GATC'), - 'ovhgseq' : 'GATC', + 'compsite': '(?PGATC)', + 'results': None, + 'site': 'GATC', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('C', 'J', 'K', 'M', 'N', 'R', 'S', 'U'), + 'scd5': None, + 'charac': (0, 0, None, None, 'GATC'), + 'ovhgseq': 'GATC', } rest_dict['Sau3AI'] = _temp() def _temp(): return { - 'compsite' : '(?PGG.CC)|(?PGG.CC)', - 'results' : None, - 'site' : 'GGNCC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('J', 'N', 'O', 'U', 'W'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGNCC'), - 'ovhgseq' : 'GNC', + 'compsite': '(?PGG.CC)', + 'results': None, + 'site': 'GGNCC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('J', 'N', 'U'), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGNCC'), + 'ovhgseq': 'GNC', } rest_dict['Sau96I'] = _temp() def _temp(): return { - 'compsite' : '(?PCCT.AGG)|(?PCCT.AGG)', - 'results' : None, - 'site' : 'CCTNAGG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CCTNAGG'), - 'ovhgseq' : 'TNA', + 'compsite': '(?PCCT.AGG)', + 'results': None, + 'site': 'CCTNAGG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (2, -2, None, None, 'CCTNAGG'), + 'ovhgseq': 'TNA', } rest_dict['SauI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCTGCAGG)|(?PCCTGCAGG)', - 'results' : None, - 'site' : 'CCTGCAGG', - 'substrat' : 'DNA', - 'fst3' : -6, - 'fst5' : 6, - 'freq' : 65536, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('I', 'N', 'O', 'V'), - 'scd5' : None, - 'charac' : (6, -6, None, None, 'CCTGCAGG'), - 'ovhgseq' : 'TGCA', + 'compsite': '(?PCCTGCAGG)', + 'results': None, + 'site': 'CCTGCAGG', + 'substrat': 'DNA', + 'fst3': -6, + 'fst5': 6, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('I', 'N', 'V'), + 'scd5': None, + 'charac': (6, -6, None, None, 'CCTGCAGG'), + 'ovhgseq': 'TGCA', } rest_dict['SbfI'] = _temp() def _temp(): return { - 'compsite' : '(?PAGTACT)|(?PAGTACT)', - 'results' : None, - 'site' : 'AGTACT', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('B', 'C', 'F', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'W', 'X'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'AGTACT'), - 'ovhgseq' : '', + 'compsite': '(?PAGTACT)', + 'results': None, + 'site': 'AGTACT', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('B', 'C', 'F', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'X'), + 'scd5': None, + 'charac': (3, -3, None, None, 'AGTACT'), + 'ovhgseq': '', } rest_dict['ScaI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAGTC)|(?PGACTC)', - 'results' : None, - 'site' : 'GAGTC', - 'substrat' : 'DNA', - 'fst3' : 5, - 'fst5' : 10, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (10, 5, None, None, 'GAGTC'), - 'ovhgseq' : '', + 'compsite': '(?PGAGTC)|(?PGACTC)', + 'results': None, + 'site': 'GAGTC', + 'substrat': 'DNA', + 'fst3': 5, + 'fst5': 10, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (10, 5, None, None, 'GAGTC'), + 'ovhgseq': '', } rest_dict['SchI'] = _temp() def _temp(): return { - 'compsite' : '(?PCTCGAG)|(?PCTCGAG)', - 'results' : None, - 'site' : 'CTCGAG', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'CTCGAG'), - 'ovhgseq' : '', + 'compsite': '(?PCTCGAG)', + 'results': None, + 'site': 'CTCGAG', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (3, -3, None, None, 'CTCGAG'), + 'ovhgseq': '', } rest_dict['SciI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC.GG)|(?PCC.GG)', - 'results' : None, - 'site' : 'CCNGG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('J', 'N', 'O', 'S'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CCNGG'), - 'ovhgseq' : 'N', + 'compsite': '(?PCC.GG)', + 'results': None, + 'site': 'CCNGG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('J', 'N'), + 'scd5': None, + 'charac': (2, -2, None, None, 'CCNGG'), + 'ovhgseq': 'N', } rest_dict['ScrFI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCTGCAGG)|(?PCCTGCAGG)', - 'results' : None, - 'site' : 'CCTGCAGG', - 'substrat' : 'DNA', - 'fst3' : -6, - 'fst5' : 6, - 'freq' : 65536, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (6, -6, None, None, 'CCTGCAGG'), - 'ovhgseq' : 'TGCA', + 'compsite': '(?PCCTGCAGG)', + 'results': None, + 'site': 'CCTGCAGG', + 'substrat': 'DNA', + 'fst3': -6, + 'fst5': 6, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (6, -6, None, None, 'CCTGCAGG'), + 'ovhgseq': 'TGCA', } rest_dict['SdaI'] = _temp() def _temp(): return { - 'compsite' : '(?PCAG[AG]AG)|(?PCT[CT]CTG)', - 'results' : None, - 'site' : 'CAGRAG', - 'substrat' : 'DNA', - 'fst3' : 19, - 'fst5' : 27, - 'freq' : 2048, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (27, 19, None, None, 'CAGRAG'), - 'ovhgseq' : 'NN', + 'compsite': '(?PCAG[AG]AG)|(?PCT[CT]CTG)', + 'results': None, + 'site': 'CAGRAG', + 'substrat': 'DNA', + 'fst3': 19, + 'fst5': 27, + 'freq': 2048, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (27, 19, None, None, 'CAGRAG'), + 'ovhgseq': 'NN', } rest_dict['SdeAI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAC....[AG]TGA)|(?PTCA[CT]....GTC)', - 'results' : None, - 'site' : 'GACNNNNRTGA', - 'substrat' : 'DNA', - 'fst3' : -24, - 'fst5' : -11, - 'freq' : 8192, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : 10, - 'suppl' : (), - 'scd5' : 23, - 'charac' : (-11, -24, 23, 10, 'GACNNNNRTGA'), - 'ovhgseq' : 'NN', + 'compsite': '(?PGAC....[AG]TGA)|(?PTCA[CT]....GTC)', + 'results': None, + 'site': 'GACNNNNRTGA', + 'substrat': 'DNA', + 'fst3': -24, + 'fst5': -11, + 'freq': 8192, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': 10, + 'suppl': (), + 'scd5': 23, + 'charac': (-11, -24, 23, 10, 'GACNNNNRTGA'), + 'ovhgseq': 'NN', } rest_dict['SdeOSI'] = _temp() def _temp(): return { - 'compsite' : '(?PG[AGT]GC[ACT]C)|(?PG[AGT]GC[ACT]C)', - 'results' : None, - 'site' : 'GDGCHC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 256, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GDGCHC'), - 'ovhgseq' : 'DGCH', + 'compsite': '(?PG[AGT]GC[ACT]C)', + 'results': None, + 'site': 'GDGCHC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 256, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (5, -5, None, None, 'GDGCHC'), + 'ovhgseq': 'DGCH', } rest_dict['SduI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC..GG)|(?PCC..GG)', - 'results' : None, - 'site' : 'CCNNGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCNNGG'), - 'ovhgseq' : 'CNNG', + 'compsite': '(?PCC..GG)', + 'results': None, + 'site': 'CCNNGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCNNGG'), + 'ovhgseq': 'CNNG', } rest_dict['SecI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGCG)|(?PCGCG)', - 'results' : None, - 'site' : 'CGCG', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'CGCG'), - 'ovhgseq' : 'CGCG', + 'compsite': '(?PCGCG)', + 'results': None, + 'site': 'CGCG', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (0, 0, None, None, 'CGCG'), + 'ovhgseq': 'CGCG', } rest_dict['SelI'] = _temp() def _temp(): return { - 'compsite' : '(?PA[CG][CG]T)|(?PA[CG][CG]T)', - 'results' : None, - 'site' : 'ASST', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 64, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'ASST'), - 'ovhgseq' : 'ASST', + 'compsite': '(?PA[CG][CG]T)', + 'results': None, + 'site': 'ASST', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 64, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (4, -4, None, None, 'ASST'), + 'ovhgseq': 'ASST', } rest_dict['SetI'] = _temp() def _temp(): return { - 'compsite' : '(?PACC[AT]GGT)|(?PACC[AT]GGT)', - 'results' : None, - 'site' : 'ACCWGGT', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 8192, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -5, - 'scd3' : None, - 'suppl' : ('M', 'N'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'ACCWGGT'), - 'ovhgseq' : 'CCWGG', + 'compsite': '(?PACC[AT]GGT)', + 'results': None, + 'site': 'ACCWGGT', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 8192, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': None, + 'suppl': ('M', 'N'), + 'scd5': None, + 'charac': (1, -1, None, None, 'ACCWGGT'), + 'ovhgseq': 'CCWGG', } rest_dict['SexAI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCGATCGC)|(?PGCGATCGC)', - 'results' : None, - 'site' : 'GCGATCGC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 65536, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GCGATCGC'), - 'ovhgseq' : 'AT', + 'compsite': '(?PGCGATCGC)', + 'results': None, + 'site': 'GCGATCGC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (5, -5, None, None, 'GCGATCGC'), + 'ovhgseq': 'AT', } rest_dict['SfaAI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCATC)|(?PGATGC)', - 'results' : None, - 'site' : 'GCATC', - 'substrat' : 'DNA', - 'fst3' : 9, - 'fst5' : 10, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'N', 'V'), - 'scd5' : None, - 'charac' : (10, 9, None, None, 'GCATC'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PGCATC)|(?PGATGC)', + 'results': None, + 'site': 'GCATC', + 'substrat': 'DNA', + 'fst3': 9, + 'fst5': 10, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'N', 'V'), + 'scd5': None, + 'charac': (10, 9, None, None, 'GCATC'), + 'ovhgseq': 'NNNN', } rest_dict['SfaNI'] = _temp() def _temp(): return { - 'compsite' : '(?PCT[AG][CT]AG)|(?PCT[AG][CT]AG)', - 'results' : None, - 'site' : 'CTRYAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTRYAG'), - 'ovhgseq' : 'TRYA', + 'compsite': '(?PCT[AG][CT]AG)', + 'results': None, + 'site': 'CTRYAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CTRYAG'), + 'ovhgseq': 'TRYA', } rest_dict['SfcI'] = _temp() def _temp(): return { - 'compsite' : '(?PCT[AG][CT]AG)|(?PCT[AG][CT]AG)', - 'results' : None, - 'site' : 'CTRYAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTRYAG'), - 'ovhgseq' : 'TRYA', + 'compsite': '(?PCT[AG][CT]AG)', + 'results': None, + 'site': 'CTRYAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (1, -1, None, None, 'CTRYAG'), + 'ovhgseq': 'TRYA', } rest_dict['SfeI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGCC.....GGCC)|(?PGGCC.....GGCC)', - 'results' : None, - 'site' : 'GGCCNNNNNGGCC', - 'substrat' : 'DNA', - 'fst3' : -8, - 'fst5' : 8, - 'freq' : 65536, - 'size' : 13, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : None, - 'suppl' : ('C', 'F', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'W', 'X'), - 'scd5' : None, - 'charac' : (8, -8, None, None, 'GGCCNNNNNGGCC'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PGGCC.....GGCC)', + 'results': None, + 'site': 'GGCCNNNNNGGCC', + 'substrat': 'DNA', + 'fst3': -8, + 'fst5': 8, + 'freq': 65536, + 'size': 13, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': ('C', 'F', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'X'), + 'scd5': None, + 'charac': (8, -8, None, None, 'GGCCNNNNNGGCC'), + 'ovhgseq': 'NNN', } rest_dict['SfiI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGCGCC)|(?PGGCGCC)', - 'results' : None, - 'site' : 'GGCGCC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GGCGCC'), - 'ovhgseq' : '', + 'compsite': '(?PGGCGCC)', + 'results': None, + 'site': 'GGCGCC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (3, -3, None, None, 'GGCGCC'), + 'ovhgseq': '', } rest_dict['SfoI'] = _temp() def _temp(): return { - 'compsite' : '(?PCTCGAG)|(?PCTCGAG)', - 'results' : None, - 'site' : 'CTCGAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTCGAG'), - 'ovhgseq' : 'TCGA', + 'compsite': '(?PCTCGAG)', + 'results': None, + 'site': 'CTCGAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CTCGAG'), + 'ovhgseq': 'TCGA', } rest_dict['Sfr274I'] = _temp() def _temp(): return { - 'compsite' : '(?PCCGCGG)|(?PCCGCGG)', - 'results' : None, - 'site' : 'CCGCGG', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'CCGCGG'), - 'ovhgseq' : 'GC', + 'compsite': '(?PCCGCGG)', + 'results': None, + 'site': 'CCGCGG', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (4, -4, None, None, 'CCGCGG'), + 'ovhgseq': 'GC', } rest_dict['Sfr303I'] = _temp() def _temp(): return { - 'compsite' : '(?PTTCGAA)|(?PTTCGAA)', - 'results' : None, - 'site' : 'TTCGAA', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('M',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'TTCGAA'), - 'ovhgseq' : 'CG', + 'compsite': '(?PTTCGAA)', + 'results': None, + 'site': 'TTCGAA', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('M',), + 'scd5': None, + 'charac': (2, -2, None, None, 'TTCGAA'), + 'ovhgseq': 'CG', } rest_dict['SfuI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCGATCGC)|(?PGCGATCGC)', - 'results' : None, - 'site' : 'GCGATCGC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 65536, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('R',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GCGATCGC'), - 'ovhgseq' : 'AT', + 'compsite': '(?PC..G)', + 'results': None, + 'site': 'CNNG', + 'substrat': 'DNA', + 'fst3': 13, + 'fst5': 13, + 'freq': 16, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (13, 13, None, None, 'CNNG'), + 'ovhgseq': 'NNNN', + } +rest_dict['SgeI'] = _temp() + +def _temp(): + return { + 'compsite': '(?PGCGATCGC)', + 'results': None, + 'site': 'GCGATCGC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('R',), + 'scd5': None, + 'charac': (5, -5, None, None, 'GCGATCGC'), + 'ovhgseq': 'AT', } rest_dict['SgfI'] = _temp() def _temp(): return { - 'compsite' : '(?PC[AG]CCGG[CT]G)|(?PC[AG]CCGG[CT]G)', - 'results' : None, - 'site' : 'CRCCGGYG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 16384, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('M', 'N'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CRCCGGYG'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?PC[AG]CCGG[CT]G)', + 'results': None, + 'site': 'CRCCGGYG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 16384, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (2, -2, None, None, 'CRCCGGYG'), + 'ovhgseq': 'CCGG', } rest_dict['SgrAI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCGCGG)|(?PCCGCGG)', - 'results' : None, - 'site' : 'CCGCGG', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('C',), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'CCGCGG'), - 'ovhgseq' : 'GC', + 'compsite': '(?PCCGCGG)', + 'results': None, + 'site': 'CCGCGG', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('C',), + 'scd5': None, + 'charac': (4, -4, None, None, 'CCGCGG'), + 'ovhgseq': 'GC', } rest_dict['SgrBI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGTCGACG)|(?PCGTCGACG)', - 'results' : None, - 'site' : 'CGTCGACG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 65536, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CGTCGACG'), - 'ovhgseq' : 'TCGA', + 'compsite': '(?PCGTCGACG)', + 'results': None, + 'site': 'CGTCGACG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (2, -2, None, None, 'CGTCGACG'), + 'ovhgseq': 'TCGA', } rest_dict['SgrDI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGCGCGCC)|(?PGGCGCGCC)', - 'results' : None, - 'site' : 'GGCGCGCC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 65536, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GGCGCGCC'), - 'ovhgseq' : 'CGCG', - } -rest_dict['SgsI'] = _temp() + 'compsite': '(?PCC[AGT][CG])|(?P[CG][ACT]GG)', + 'results': None, + 'site': 'CCDS', + 'substrat': 'DNA', + 'fst3': 14, + 'fst5': 14, + 'freq': 32, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (14, 14, None, None, 'CCDS'), + 'ovhgseq': 'NNNN', + } +rest_dict['SgrTI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGGTC)|(?PGACCC)', - 'results' : None, - 'site' : 'GGGTC', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 2, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (2, 0, None, None, 'GGGTC'), - 'ovhgseq' : 'GTC', + 'compsite': '(?PGGCGCGCC)', + 'results': None, + 'site': 'GGCGCGCC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (2, -2, None, None, 'GGCGCGCC'), + 'ovhgseq': 'CGCG', } -rest_dict['SimI'] = _temp() +rest_dict['SgsI'] = _temp() def _temp(): return { - 'compsite' : '(?PGG[AT]CC)|(?PGG[AT]CC)', - 'results' : None, - 'site' : 'GGWCC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('Q', 'R', 'W', 'X'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGWCC'), - 'ovhgseq' : 'GWC', - } -rest_dict['SinI'] = _temp() + 'compsite': '(?PGGGTC)|(?PGACCC)', + 'results': None, + 'site': 'GGGTC', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 2, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (2, 0, None, None, 'GGGTC'), + 'ovhgseq': 'GTC', + } +rest_dict['SimI'] = _temp() def _temp(): return { - 'compsite' : '(?PCTCGAG)|(?PCTCGAG)', - 'results' : None, - 'site' : 'CTCGAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('C',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTCGAG'), - 'ovhgseq' : 'TCGA', + 'compsite': '(?PCTCGAG)', + 'results': None, + 'site': 'CTCGAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('C',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CTCGAG'), + 'ovhgseq': 'TCGA', } rest_dict['SlaI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCCGGG)|(?PCCCGGG)', - 'results' : None, - 'site' : 'CCCGGG', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('B', 'C', 'F', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'CCCGGG'), - 'ovhgseq' : '', + 'compsite': '(?PCCCGGG)', + 'results': None, + 'site': 'CCCGGG', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('B', 'C', 'F', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'X', 'Y'), + 'scd5': None, + 'charac': (3, -3, None, None, 'CCCGGG'), + 'ovhgseq': '', } rest_dict['SmaI'] = _temp() def _temp(): return { - 'compsite' : '(?PATTTAAAT)|(?PATTTAAAT)', - 'results' : None, - 'site' : 'ATTTAAAT', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 65536, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('F', 'I', 'K', 'V'), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'ATTTAAAT'), - 'ovhgseq' : '', + 'compsite': '(?PATTTAAAT)', + 'results': None, + 'site': 'ATTTAAAT', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('F', 'I', 'K', 'V'), + 'scd5': None, + 'charac': (4, -4, None, None, 'ATTTAAAT'), + 'ovhgseq': '', } rest_dict['SmiI'] = _temp() def _temp(): return { - 'compsite' : '(?PCA[CT]....[AG]TG)|(?PCA[CT]....[AG]TG)', - 'results' : None, - 'site' : 'CAYNNNNRTG', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 1024, - 'size' : 10, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'CAYNNNNRTG'), - 'ovhgseq' : '', + 'compsite': '(?PCA[CT]....[AG]TG)', + 'results': None, + 'site': 'CAYNNNNRTG', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 1024, + 'size': 10, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (5, -5, None, None, 'CAYNNNNRTG'), + 'ovhgseq': '', } rest_dict['SmiMI'] = _temp() def _temp(): return { - 'compsite' : '(?PCT[CT][AG]AG)|(?PCT[CT][AG]AG)', - 'results' : None, - 'site' : 'CTYRAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTYRAG'), - 'ovhgseq' : 'TYRA', + 'compsite': '(?PCT[CT][AG]AG)', + 'results': None, + 'site': 'CTYRAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CTYRAG'), + 'ovhgseq': 'TYRA', } rest_dict['SmlI'] = _temp() def _temp(): return { - 'compsite' : '(?PCT[CT][AG]AG)|(?PCT[CT][AG]AG)', - 'results' : None, - 'site' : 'CTYRAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTYRAG'), - 'ovhgseq' : 'TYRA', + 'compsite': '(?PCT[CT][AG]AG)', + 'results': None, + 'site': 'CTYRAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CTYRAG'), + 'ovhgseq': 'TYRA', } rest_dict['SmoI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCCGC)|(?PGCGGG)', - 'results' : None, - 'site' : 'CCCGC', - 'substrat' : 'DNA', - 'fst3' : 6, - 'fst5' : 9, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (9, 6, None, None, 'CCCGC'), - 'ovhgseq' : 'NN', - } -rest_dict['SmuI'] = _temp() - -def _temp(): - return { - 'compsite' : '(?PTACGTA)|(?PTACGTA)', - 'results' : None, - 'site' : 'TACGTA', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('C', 'K', 'M', 'N', 'R'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'TACGTA'), - 'ovhgseq' : '', + 'compsite': '(?PTACGTA)', + 'results': None, + 'site': 'TACGTA', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('C', 'K', 'M', 'N', 'R', 'U'), + 'scd5': None, + 'charac': (3, -3, None, None, 'TACGTA'), + 'ovhgseq': '', } rest_dict['SnaBI'] = _temp() def _temp(): return { - 'compsite' : '(?PGTATAC)|(?PGTATAC)', - 'results' : None, - 'site' : 'GTATAC', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'GTATAC'), - 'ovhgseq' : None, + 'compsite': '(?PGTATAC)', + 'results': None, + 'site': 'GTATAC', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'GTATAC'), + 'ovhgseq': None, } rest_dict['SnaI'] = _temp() def _temp(): return { - 'compsite' : '(?PACTAGT)|(?PACTAGT)', - 'results' : None, - 'site' : 'ACTAGT', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('B', 'H', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'W', 'X'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'ACTAGT'), - 'ovhgseq' : 'CTAG', + 'compsite': '(?PGGCCGAG)|(?PCTCGGCC)', + 'results': None, + 'site': 'GGCCGAG', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 16384, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'GGCCGAG'), + 'ovhgseq': None, + } +rest_dict['Sno506I'] = _temp() + +def _temp(): + return { + 'compsite': '(?PACTAGT)', + 'results': None, + 'site': 'ACTAGT', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('B', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'X'), + 'scd5': None, + 'charac': (1, -1, None, None, 'ACTAGT'), + 'ovhgseq': 'CTAG', } rest_dict['SpeI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCATGC)|(?PGCATGC)', - 'results' : None, - 'site' : 'GCATGC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('B', 'C', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'V', 'W', 'X'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GCATGC'), - 'ovhgseq' : 'CATG', + 'compsite': '(?PGCATGC)', + 'results': None, + 'site': 'GCATGC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('B', 'C', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'V', 'X'), + 'scd5': None, + 'charac': (5, -5, None, None, 'GCATGC'), + 'ovhgseq': 'CATG', } rest_dict['SphI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGTACG)|(?PCGTACG)', - 'results' : None, - 'site' : 'CGTACG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CGTACG'), - 'ovhgseq' : 'GTAC', + 'compsite': '(?PCGTACG)', + 'results': None, + 'site': 'CGTACG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (1, -1, None, None, 'CGTACG'), + 'ovhgseq': 'GTAC', } rest_dict['SplI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCGG[AG]AG)|(?PCT[CT]CCGC)', - 'results' : None, - 'site' : 'GCGGRAG', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 8192, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'GCGGRAG'), - 'ovhgseq' : None, + 'compsite': '(?PGCGG[AG]AG)|(?PCT[CT]CCGC)', + 'results': None, + 'site': 'GCGGRAG', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 8192, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'GCGGRAG'), + 'ovhgseq': None, } rest_dict['SpoDI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCCCGGGC)|(?PGCCCGGGC)', - 'results' : None, - 'site' : 'GCCCGGGC', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 65536, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('E', 'O'), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'GCCCGGGC'), - 'ovhgseq' : '', + 'compsite': '(?PGCCCGGGC)', + 'results': None, + 'site': 'GCCCGGGC', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (4, -4, None, None, 'GCCCGGGC'), + 'ovhgseq': '', } rest_dict['SrfI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGCCGGCG)|(?PCGCCGGCG)', - 'results' : None, - 'site' : 'CGCCGGCG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 65536, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CGCCGGCG'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?PCGCCGGCG)', + 'results': None, + 'site': 'CGCCGGCG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (2, -2, None, None, 'CGCCGGCG'), + 'ovhgseq': 'CCGG', } rest_dict['Sse232I'] = _temp() def _temp(): return { - 'compsite' : '(?PCCTGCAGG)|(?PCCTGCAGG)', - 'results' : None, - 'site' : 'CCTGCAGG', - 'substrat' : 'DNA', - 'fst3' : -6, - 'fst5' : 6, - 'freq' : 65536, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('K',), - 'scd5' : None, - 'charac' : (6, -6, None, None, 'CCTGCAGG'), - 'ovhgseq' : 'TGCA', + 'compsite': '(?PCCTGCAGG)', + 'results': None, + 'site': 'CCTGCAGG', + 'substrat': 'DNA', + 'fst3': -6, + 'fst5': 6, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('K',), + 'scd5': None, + 'charac': (6, -6, None, None, 'CCTGCAGG'), + 'ovhgseq': 'TGCA', } rest_dict['Sse8387I'] = _temp() def _temp(): return { - 'compsite' : '(?PAGG[AT]CCT)|(?PAGG[AT]CCT)', - 'results' : None, - 'site' : 'AGGWCCT', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 8192, - 'size' : 7, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'AGGWCCT'), - 'ovhgseq' : 'GWC', + 'compsite': '(?PAGG[AT]CCT)', + 'results': None, + 'site': 'AGGWCCT', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 8192, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (2, -2, None, None, 'AGGWCCT'), + 'ovhgseq': 'GWC', } rest_dict['Sse8647I'] = _temp() def _temp(): return { - 'compsite' : '(?PAATT)|(?PAATT)', - 'results' : None, - 'site' : 'AATT', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'AATT'), - 'ovhgseq' : 'AATT', + 'compsite': '(?PAATT)', + 'results': None, + 'site': 'AATT', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (0, 0, None, None, 'AATT'), + 'ovhgseq': 'AATT', } rest_dict['Sse9I'] = _temp() def _temp(): return { - 'compsite' : '(?PAGGCCT)|(?PAGGCCT)', - 'results' : None, - 'site' : 'AGGCCT', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('C',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'AGGCCT'), - 'ovhgseq' : '', + 'compsite': '(?PAGGCCT)', + 'results': None, + 'site': 'AGGCCT', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('C',), + 'scd5': None, + 'charac': (3, -3, None, None, 'AGGCCT'), + 'ovhgseq': '', } rest_dict['SseBI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCGC)|(?PGCGG)', - 'results' : None, - 'site' : 'CCGC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCGC'), - 'ovhgseq' : 'CG', + 'compsite': '(?PCCGC)|(?PGCGG)', + 'results': None, + 'site': 'CCGC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCGC'), + 'ovhgseq': 'CG', } rest_dict['SsiI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGTGA)|(?PTCACC)', - 'results' : None, - 'site' : 'GGTGA', - 'substrat' : 'DNA', - 'fst3' : 8, - 'fst5' : 13, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (13, 8, None, None, 'GGTGA'), - 'ovhgseq' : '', + 'compsite': '(?PGGTGA)|(?PTCACC)', + 'results': None, + 'site': 'GGTGA', + 'substrat': 'DNA', + 'fst3': 8, + 'fst5': 13, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (13, 8, None, None, 'GGTGA'), + 'ovhgseq': '', } rest_dict['SspD5I'] = _temp() def _temp(): return { - 'compsite' : '(?PGGCGCC)|(?PGGCGCC)', - 'results' : None, - 'site' : 'GGCGCC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGCGCC'), - 'ovhgseq' : 'GCGC', + 'compsite': '(?PGGCGCC)', + 'results': None, + 'site': 'GGCGCC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGCGCC'), + 'ovhgseq': 'GCGC', } rest_dict['SspDI'] = _temp() def _temp(): return { - 'compsite' : '(?PAATATT)|(?PAATATT)', - 'results' : None, - 'site' : 'AATATT', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('B', 'C', 'F', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'W', 'X'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'AATATT'), - 'ovhgseq' : '', + 'compsite': '(?PAATATT)', + 'results': None, + 'site': 'AATATT', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('B', 'C', 'F', 'I', 'J', 'K', 'M', 'N', 'Q', 'R', 'S', 'U', 'V', 'X'), + 'scd5': None, + 'charac': (3, -3, None, None, 'AATATT'), + 'ovhgseq': '', } rest_dict['SspI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAGCTC)|(?PGAGCTC)', - 'results' : None, - 'site' : 'GAGCTC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('B', 'C'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GAGCTC'), - 'ovhgseq' : 'AGCT', - } -rest_dict['SstI'] = _temp() + 'compsite': '(?PCGAAGAC)|(?PGTCTTCG)', + 'results': None, + 'site': 'CGAAGAC', + 'substrat': 'DNA', + 'fst3': 18, + 'fst5': 27, + 'freq': 16384, + 'size': 7, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (27, 18, None, None, 'CGAAGAC'), + 'ovhgseq': 'NN', + } +rest_dict['SstE37I'] = _temp() def _temp(): return { - 'compsite' : '(?PCCGCGG)|(?PCCGCGG)', - 'results' : None, - 'site' : 'CCGCGG', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('B',), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'CCGCGG'), - 'ovhgseq' : 'GC', - } -rest_dict['SstII'] = _temp() + 'compsite': '(?PGAGCTC)', + 'results': None, + 'site': 'GAGCTC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('C',), + 'scd5': None, + 'charac': (5, -5, None, None, 'GAGCTC'), + 'ovhgseq': 'AGCT', + } +rest_dict['SstI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCCG)|(?PCGGG)', - 'results' : None, - 'site' : 'CCCG', - 'substrat' : 'DNA', - 'fst3' : 8, - 'fst5' : 8, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (8, 8, None, None, 'CCCG'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PCCCG)|(?PCGGG)', + 'results': None, + 'site': 'CCCG', + 'substrat': 'DNA', + 'fst3': 8, + 'fst5': 8, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (8, 8, None, None, 'CCCG'), + 'ovhgseq': 'NNNN', } rest_dict['Sth132I'] = _temp() def _temp(): return { - 'compsite' : '(?PCCGG)|(?PCCGG)', - 'results' : None, - 'site' : 'CCGG', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'CCGG'), - 'ovhgseq' : '', + 'compsite': '(?PCCGG)', + 'results': None, + 'site': 'CCGG', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (2, -2, None, None, 'CCGG'), + 'ovhgseq': '', } rest_dict['Sth302II'] = _temp() def _temp(): return { - 'compsite' : '(?PCTCGAG)|(?PCTCGAG)', - 'results' : None, - 'site' : 'CTCGAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('U',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTCGAG'), - 'ovhgseq' : 'TCGA', + 'compsite': '(?PCTCGAG)', + 'results': None, + 'site': 'CTCGAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('U',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CTCGAG'), + 'ovhgseq': 'TCGA', } rest_dict['StrI'] = _temp() def _temp(): return { - 'compsite' : '(?PGGATG)|(?PCATCC)', - 'results' : None, - 'site' : 'GGATG', - 'substrat' : 'DNA', - 'fst3' : 14, - 'fst5' : 15, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (15, 14, None, None, 'GGATG'), - 'ovhgseq' : 'NNNN', + 'compsite': '(?PGGATG)|(?PCATCC)', + 'results': None, + 'site': 'GGATG', + 'substrat': 'DNA', + 'fst3': 14, + 'fst5': 15, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (15, 14, None, None, 'GGATG'), + 'ovhgseq': 'NNNN', } rest_dict['StsI'] = _temp() def _temp(): return { - 'compsite' : '(?PAGGCCT)|(?PAGGCCT)', - 'results' : None, - 'site' : 'AGGCCT', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('B', 'J', 'K', 'M', 'N', 'Q', 'R', 'S', 'U', 'X'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'AGGCCT'), - 'ovhgseq' : '', + 'compsite': '(?PAGGCCT)', + 'results': None, + 'site': 'AGGCCT', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('B', 'J', 'K', 'M', 'N', 'Q', 'R', 'U', 'X'), + 'scd5': None, + 'charac': (3, -3, None, None, 'AGGCCT'), + 'ovhgseq': '', } rest_dict['StuI'] = _temp() def _temp(): return { - 'compsite' : '(?PCC.GG)|(?PCC.GG)', - 'results' : None, - 'site' : 'CCNGG', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -5, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'CCNGG'), - 'ovhgseq' : 'CCNGG', + 'compsite': '(?PCC.GG)', + 'results': None, + 'site': 'CCNGG', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (0, 0, None, None, 'CCNGG'), + 'ovhgseq': 'CCNGG', } rest_dict['StyD4I'] = _temp() def _temp(): return { - 'compsite' : '(?PCC[AT][AT]GG)|(?PCC[AT][AT]GG)', - 'results' : None, - 'site' : 'CCWWGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('C', 'J', 'M', 'N', 'R', 'S'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCWWGG'), - 'ovhgseq' : 'CWWG', + 'compsite': '(?PCC[AT][AT]GG)', + 'results': None, + 'site': 'CCWWGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('C', 'J', 'N'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCWWGG'), + 'ovhgseq': 'CWWG', } rest_dict['StyI'] = _temp() def _temp(): return { - 'compsite' : '(?PATTTAAAT)|(?PATTTAAAT)', - 'results' : None, - 'site' : 'ATTTAAAT', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 65536, - 'size' : 8, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('J', 'M', 'N', 'S', 'W'), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'ATTTAAAT'), - 'ovhgseq' : '', + 'compsite': '(?PATTTAAAT)', + 'results': None, + 'site': 'ATTTAAAT', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 65536, + 'size': 8, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('J', 'M', 'N'), + 'scd5': None, + 'charac': (4, -4, None, None, 'ATTTAAAT'), + 'ovhgseq': '', } rest_dict['SwaI'] = _temp() def _temp(): return { - 'compsite' : '(?PAC.GT)|(?PAC.GT)', - 'results' : None, - 'site' : 'ACNGT', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 1, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'ACNGT'), - 'ovhgseq' : 'N', + 'compsite': '(?PAC.GT)', + 'results': None, + 'site': 'ACNGT', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (3, -3, None, None, 'ACNGT'), + 'ovhgseq': 'N', } rest_dict['TaaI'] = _temp() def _temp(): return { - 'compsite' : '(?PACGT)|(?PACGT)', - 'results' : None, - 'site' : 'ACGT', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'ACGT'), - 'ovhgseq' : 'ACGT', + 'compsite': '(?PACGT)', + 'results': None, + 'site': 'ACGT', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (4, -4, None, None, 'ACGT'), + 'ovhgseq': 'ACGT', } rest_dict['TaiI'] = _temp() def _temp(): return { - 'compsite' : '(?PTCGA)|(?PTCGA)', - 'results' : None, - 'site' : 'TCGA', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('B', 'C', 'F', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'TCGA'), - 'ovhgseq' : 'CG', + 'compsite': '(?PTCGA)', + 'results': None, + 'site': 'TCGA', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('B', 'C', 'F', 'I', 'J', 'K', 'M', 'N', 'Q', 'R', 'S', 'U', 'V', 'X', 'Y'), + 'scd5': None, + 'charac': (1, -1, None, None, 'TCGA'), + 'ovhgseq': 'CG', } rest_dict['TaqI'] = _temp() def _temp(): return { - 'compsite' : '(?PCACCCA)|(?PTGGGTG)', - 'results' : None, - 'site' : 'CACCCA|GACCGA', - 'substrat' : 'DNA', - 'fst3' : 9, - 'fst5' : 17, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('Q', 'X'), - 'scd5' : None, - 'charac' : (17, 9, None, None, 'CACCCA|GACCGA'), - 'ovhgseq' : '(?PCACCCA|GACCGA)|(?PTGGGTG|TCGGTC)', + 'compsite': '(?PGACCGA)|(?PTCGGTC)', + 'results': None, + 'site': 'GACCGA', + 'substrat': 'DNA', + 'fst3': 9, + 'fst5': 17, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('Q', 'X'), + 'scd5': None, + 'charac': (17, 9, None, None, 'GACCGA'), + 'ovhgseq': 'NN', } rest_dict['TaqII'] = _temp() def _temp(): return { - 'compsite' : '(?P[AT]GTAC[AT])|(?P[AT]GTAC[AT])', - 'results' : None, - 'site' : 'WGTACW', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'WGTACW'), - 'ovhgseq' : 'GTAC', + 'compsite': '(?PAATT)', + 'results': None, + 'site': 'AATT', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (0, 0, None, None, 'AATT'), + 'ovhgseq': 'AATT', + } +rest_dict['TasI'] = _temp() + +def _temp(): + return { + 'compsite': '(?P[AT]GTAC[AT])', + 'results': None, + 'site': 'WGTACW', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'WGTACW'), + 'ovhgseq': 'GTAC', } rest_dict['TatI'] = _temp() def _temp(): return { - 'compsite' : '(?PGC[CG]GC)|(?PGC[CG]GC)', - 'results' : None, - 'site' : 'GCSGC', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'GCSGC'), - 'ovhgseq' : 'CSG', + 'compsite': '(?PGC[CG]GC)', + 'results': None, + 'site': 'GCSGC', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (4, -4, None, None, 'GCSGC'), + 'ovhgseq': 'CSG', } rest_dict['TauI'] = _temp() def _temp(): return { - 'compsite' : '(?PGA[AT]TC)|(?PGA[AT]TC)', - 'results' : None, - 'site' : 'GAWTC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GAWTC'), - 'ovhgseq' : 'AWT', + 'compsite': '(?PGA[AT]TC)', + 'results': None, + 'site': 'GAWTC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GAWTC'), + 'ovhgseq': 'AWT', } rest_dict['TfiI'] = _temp() def _temp(): return { - 'compsite' : '(?PCTCGAG)|(?PCTCGAG)', - 'results' : None, - 'site' : 'CTCGAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTCGAG'), - 'ovhgseq' : 'TCGA', - } -rest_dict['TliI'] = _temp() - -def _temp(): - return { - 'compsite' : '(?PTTAA)|(?PTTAA)', - 'results' : None, - 'site' : 'TTAA', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'TTAA'), - 'ovhgseq' : 'TA', + 'compsite': '(?PTTAA)', + 'results': None, + 'site': 'TTAA', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'TTAA'), + 'ovhgseq': 'TA', } rest_dict['Tru1I'] = _temp() def _temp(): return { - 'compsite' : '(?PTTAA)|(?PTTAA)', - 'results' : None, - 'site' : 'TTAA', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('I', 'M', 'R', 'V', 'W'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'TTAA'), - 'ovhgseq' : 'TA', + 'compsite': '(?PTTAA)', + 'results': None, + 'site': 'TTAA', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('I', 'M', 'R', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'TTAA'), + 'ovhgseq': 'TA', } rest_dict['Tru9I'] = _temp() def _temp(): return { - 'compsite' : '(?PCA[CG]TG)|(?PCA[CG]TG)', - 'results' : None, - 'site' : 'CASTG', - 'substrat' : 'DNA', - 'fst3' : -7, - 'fst5' : 7, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 10, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (7, -7, None, None, 'CASTG'), - 'ovhgseq' : 'NNCASTGNN', + 'compsite': '(?PCA[CG]TG)', + 'results': None, + 'site': 'CASTG', + 'substrat': 'DNA', + 'fst3': -7, + 'fst5': 7, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 10, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (7, -7, None, None, 'CASTG'), + 'ovhgseq': 'NNCASTGNN', } rest_dict['TscAI'] = _temp() def _temp(): return { - 'compsite' : '(?PGC[AT]GC)|(?PGC[AT]GC)', - 'results' : None, - 'site' : 'GCWGC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GCWGC'), - 'ovhgseq' : 'CWG', + 'compsite': '(?PGT[CG]AC)', + 'results': None, + 'site': 'GTSAC', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (0, 0, None, None, 'GTSAC'), + 'ovhgseq': 'GTSAC', + } +rest_dict['TseFI'] = _temp() + +def _temp(): + return { + 'compsite': '(?PGC[AT]GC)', + 'results': None, + 'site': 'GCWGC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GCWGC'), + 'ovhgseq': 'CWG', } rest_dict['TseI'] = _temp() def _temp(): return { - 'compsite' : '(?PTA[AG]CCA)|(?PTGG[CT]TA)', - 'results' : None, - 'site' : 'TARCCA', - 'substrat' : 'DNA', - 'fst3' : 9, - 'fst5' : 17, - 'freq' : 2048, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (17, 9, None, None, 'TARCCA'), - 'ovhgseq' : 'NN', + 'compsite': '(?PTA[AG]CCA)|(?PTGG[CT]TA)', + 'results': None, + 'site': 'TARCCA', + 'substrat': 'DNA', + 'fst3': 9, + 'fst5': 17, + 'freq': 2048, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (17, 9, None, None, 'TARCCA'), + 'ovhgseq': 'NN', } rest_dict['TsoI'] = _temp() def _temp(): return { - 'compsite' : '(?PGT[CG]AC)|(?PGT[CG]AC)', - 'results' : None, - 'site' : 'GTSAC', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -5, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'GTSAC'), - 'ovhgseq' : 'GTSAC', + 'compsite': '(?PGT[CG]AC)', + 'results': None, + 'site': 'GTSAC', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (0, 0, None, None, 'GTSAC'), + 'ovhgseq': 'GTSAC', } rest_dict['Tsp45I'] = _temp() def _temp(): return { - 'compsite' : '(?PAC.GT)|(?PAC.GT)', - 'results' : None, - 'site' : 'ACNGT', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 1, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'ACNGT'), - 'ovhgseq' : 'N', + 'compsite': '(?PAC.GT)', + 'results': None, + 'site': 'ACNGT', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (3, -3, None, None, 'ACNGT'), + 'ovhgseq': 'N', } rest_dict['Tsp4CI'] = _temp() def _temp(): return { - 'compsite' : '(?PAATT)|(?PAATT)', - 'results' : None, - 'site' : 'AATT', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'AATT'), - 'ovhgseq' : 'AATT', - } -rest_dict['Tsp509I'] = _temp() - -def _temp(): - return { - 'compsite' : '(?PATGAA)|(?PTTCAT)', - 'results' : None, - 'site' : 'ATGAA', - 'substrat' : 'DNA', - 'fst3' : 9, - 'fst5' : 16, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('X',), - 'scd5' : None, - 'charac' : (16, 9, None, None, 'ATGAA'), - 'ovhgseq' : 'NN', + 'compsite': '(?PATGAA)|(?PTTCAT)', + 'results': None, + 'site': 'ATGAA', + 'substrat': 'DNA', + 'fst3': 9, + 'fst5': 16, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('Q', 'X'), + 'scd5': None, + 'charac': (16, 9, None, None, 'ATGAA'), + 'ovhgseq': 'NN', } rest_dict['TspDTI'] = _temp() def _temp(): return { - 'compsite' : '(?PAATT)|(?PAATT)', - 'results' : None, - 'site' : 'AATT', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('O',), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'AATT'), - 'ovhgseq' : 'AATT', + 'compsite': '(?PAATT)', + 'results': None, + 'site': 'AATT', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (0, 0, None, None, 'AATT'), + 'ovhgseq': 'AATT', } rest_dict['TspEI'] = _temp() def _temp(): return { - 'compsite' : '(?PACGGA)|(?PTCCGT)', - 'results' : None, - 'site' : 'ACGGA', - 'substrat' : 'DNA', - 'fst3' : 9, - 'fst5' : 16, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : ('X',), - 'scd5' : None, - 'charac' : (16, 9, None, None, 'ACGGA'), - 'ovhgseq' : 'NN', + 'compsite': '(?PACGGA)|(?PTCCGT)', + 'results': None, + 'site': 'ACGGA', + 'substrat': 'DNA', + 'fst3': 9, + 'fst5': 16, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': ('Q', 'X'), + 'scd5': None, + 'charac': (16, 9, None, None, 'ACGGA'), + 'ovhgseq': 'NN', } rest_dict['TspGWI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCCGGG)|(?PCCCGGG)', - 'results' : None, - 'site' : 'CCCGGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCCGGG'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?PCCCGGG)', + 'results': None, + 'site': 'CCCGGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCCGGG'), + 'ovhgseq': 'CCGG', } rest_dict['TspMI'] = _temp() def _temp(): return { - 'compsite' : '(?PCA[CG]TG)|(?PCA[CG]TG)', - 'results' : None, - 'site' : 'CASTG', - 'substrat' : 'DNA', - 'fst3' : -7, - 'fst5' : 7, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 10, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (7, -7, None, None, 'CASTG'), - 'ovhgseq' : 'NNCASTGNN', + 'compsite': '(?PCA[CG]TG)', + 'results': None, + 'site': 'CASTG', + 'substrat': 'DNA', + 'fst3': -7, + 'fst5': 7, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 10, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (7, -7, None, None, 'CASTG'), + 'ovhgseq': 'NNCASTGNN', } rest_dict['TspRI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAG...CTC)|(?PGAG...CTC)', - 'results' : None, - 'site' : 'GAGNNNCTC', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 4096, - 'size' : 9, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'GAGNNNCTC'), - 'ovhgseq' : None, + 'compsite': '(?PGAG...CTC)', + 'results': None, + 'site': 'GAGNNNCTC', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 4096, + 'size': 9, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'GAGNNNCTC'), + 'ovhgseq': None, } rest_dict['TssI'] = _temp() def _temp(): return { - 'compsite' : '(?PCAC......TCC)|(?PGGA......GTG)', - 'results' : None, - 'site' : 'CACNNNNNNTCC', - 'substrat' : 'DNA', - 'fst3' : -25, - 'fst5' : -8, - 'freq' : 4096, - 'size' : 12, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 5, - 'scd3' : 7, - 'suppl' : ('F',), - 'scd5' : 24, - 'charac' : (-8, -25, 24, 7, 'CACNNNNNNTCC'), - 'ovhgseq' : 'NNNNN', + 'compsite': '(?PCAC......TCC)|(?PGGA......GTG)', + 'results': None, + 'site': 'CACNNNNNNTCC', + 'substrat': 'DNA', + 'fst3': -25, + 'fst5': -8, + 'freq': 4096, + 'size': 12, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 5, + 'scd3': 7, + 'suppl': (), + 'scd5': 24, + 'charac': (-8, -25, 24, 7, 'CACNNNNNNTCC'), + 'ovhgseq': 'NNNNN', } rest_dict['TstI'] = _temp() def _temp(): return { - 'compsite' : '(?PGCGAC)|(?PGTCGC)', - 'results' : None, - 'site' : 'GCGAC', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'GCGAC'), - 'ovhgseq' : None, + 'compsite': '(?PGCGAC)|(?PGTCGC)', + 'results': None, + 'site': 'GCGAC', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'GCGAC'), + 'ovhgseq': None, } rest_dict['TsuI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAC...GTC)|(?PGAC...GTC)', - 'results' : None, - 'site' : 'GACNNNGTC', - 'substrat' : 'DNA', - 'fst3' : -4, - 'fst5' : 4, - 'freq' : 4096, - 'size' : 9, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('I', 'K', 'N', 'Q', 'R', 'V', 'W', 'X'), - 'scd5' : None, - 'charac' : (4, -4, None, None, 'GACNNNGTC'), - 'ovhgseq' : 'N', + 'compsite': '(?PGAC...GTC)', + 'results': None, + 'site': 'GACNNNGTC', + 'substrat': 'DNA', + 'fst3': -4, + 'fst5': 4, + 'freq': 4096, + 'size': 9, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('I', 'K', 'N', 'Q', 'V', 'X'), + 'scd5': None, + 'charac': (4, -4, None, None, 'GACNNNGTC'), + 'ovhgseq': 'N', } rest_dict['Tth111I'] = _temp() def _temp(): return { - 'compsite' : '(?PCAA[AG]CA)|(?PTG[CT]TTG)', - 'results' : None, - 'site' : 'CAARCA', - 'substrat' : 'DNA', - 'fst3' : 9, - 'fst5' : 17, - 'freq' : 2048, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 2, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (17, 9, None, None, 'CAARCA'), - 'ovhgseq' : 'NN', + 'compsite': '(?PCAA[AG]CA)|(?PTG[CT]TTG)', + 'results': None, + 'site': 'CAARCA', + 'substrat': 'DNA', + 'fst3': 9, + 'fst5': 17, + 'freq': 2048, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (17, 9, None, None, 'CAARCA'), + 'ovhgseq': 'NN', } rest_dict['Tth111II'] = _temp() def _temp(): return { - 'compsite' : '(?PTCGTA)|(?PTACGA)', - 'results' : None, - 'site' : 'TCGTA', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 1024, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'TCGTA'), - 'ovhgseq' : None, + 'compsite': '(?PTCGTA)|(?PTACGA)', + 'results': None, + 'site': 'TCGTA', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 1024, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'TCGTA'), + 'ovhgseq': None, } rest_dict['UbaF11I'] = _temp() def _temp(): return { - 'compsite' : '(?PCTAC...GTC)|(?PGAC...GTAG)', - 'results' : None, - 'site' : 'CTACNNNGTC', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 16384, - 'size' : 10, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'CTACNNNGTC'), - 'ovhgseq' : None, + 'compsite': '(?PCTAC...GTC)|(?PGAC...GTAG)', + 'results': None, + 'site': 'CTACNNNGTC', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 16384, + 'size': 10, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'CTACNNNGTC'), + 'ovhgseq': None, } rest_dict['UbaF12I'] = _temp() def _temp(): return { - 'compsite' : '(?PGAG......CTGG)|(?PCCAG......CTC)', - 'results' : None, - 'site' : 'GAGNNNNNNCTGG', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 16384, - 'size' : 13, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'GAGNNNNNNCTGG'), - 'ovhgseq' : None, + 'compsite': '(?PGAG......CTGG)|(?PCCAG......CTC)', + 'results': None, + 'site': 'GAGNNNNNNCTGG', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 16384, + 'size': 13, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'GAGNNNNNNCTGG'), + 'ovhgseq': None, } rest_dict['UbaF13I'] = _temp() def _temp(): return { - 'compsite' : '(?PCCA.....TCG)|(?PCGA.....TGG)', - 'results' : None, - 'site' : 'CCANNNNNTCG', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 4096, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'CCANNNNNTCG'), - 'ovhgseq' : None, + 'compsite': '(?PCCA.....TCG)|(?PCGA.....TGG)', + 'results': None, + 'site': 'CCANNNNNTCG', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 4096, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'CCANNNNNTCG'), + 'ovhgseq': None, } rest_dict['UbaF14I'] = _temp() def _temp(): return { - 'compsite' : '(?PTAC.....[AG]TGT)|(?PACA[CT].....GTA)', - 'results' : None, - 'site' : 'TACNNNNNRTGT', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 8192, - 'size' : 12, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'TACNNNNNRTGT'), - 'ovhgseq' : None, + 'compsite': '(?PTAC.....[AG]TGT)|(?PACA[CT].....GTA)', + 'results': None, + 'site': 'TACNNNNNRTGT', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 8192, + 'size': 12, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'TACNNNNNRTGT'), + 'ovhgseq': None, } rest_dict['UbaF9I'] = _temp() def _temp(): return { - 'compsite' : '(?PCGAACG)|(?PCGTTCG)', - 'results' : None, - 'site' : 'CGAACG', - 'substrat' : 'DNA', - 'fst3' : None, - 'fst5' : None, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : None, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (None, None, None, None, 'CGAACG'), - 'ovhgseq' : None, + 'compsite': '(?PCGAACG)|(?PCGTTCG)', + 'results': None, + 'site': 'CGAACG', + 'substrat': 'DNA', + 'fst3': None, + 'fst5': None, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': None, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (None, None, None, None, 'CGAACG'), + 'ovhgseq': None, } rest_dict['UbaPI'] = _temp() def _temp(): return { - 'compsite' : '(?PGG.CC)|(?PGG.CC)', - 'results' : None, - 'site' : 'GGNCC', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 256, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -5, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'GGNCC'), - 'ovhgseq' : 'GGNCC', + 'compsite': '(?PGAGCTC)', + 'results': None, + 'site': 'GAGCTC', + 'substrat': 'DNA', + 'fst3': -11, + 'fst5': -7, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': 7, + 'suppl': (), + 'scd5': 11, + 'charac': (-7, -11, 11, 7, 'GAGCTC'), + 'ovhgseq': 'NN', + } +rest_dict['UcoMSI'] = _temp() + +def _temp(): + return { + 'compsite': '(?PGG.CC)', + 'results': None, + 'site': 'GGNCC', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 256, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (0, 0, None, None, 'GGNCC'), + 'ovhgseq': 'GGNCC', } rest_dict['UnbI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCA.....TGG)|(?PCCA.....TGG)', - 'results' : None, - 'site' : 'CCANNNNNTGG', - 'substrat' : 'DNA', - 'fst3' : -7, - 'fst5' : 7, - 'freq' : 4096, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 3, - 'scd3' : None, - 'suppl' : ('F', 'K', 'M'), - 'scd5' : None, - 'charac' : (7, -7, None, None, 'CCANNNNNTGG'), - 'ovhgseq' : 'NNN', + 'compsite': '(?PCCA.....TGG)', + 'results': None, + 'site': 'CCANNNNNTGG', + 'substrat': 'DNA', + 'fst3': -7, + 'fst5': 7, + 'freq': 4096, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 3, + 'scd3': None, + 'suppl': ('F', 'K'), + 'scd5': None, + 'charac': (7, -7, None, None, 'CCANNNNNTGG'), + 'ovhgseq': 'NNN', } rest_dict['Van91I'] = _temp() def _temp(): return { - 'compsite' : '(?PCTTAAG)|(?PCTTAAG)', - 'results' : None, - 'site' : 'CTTAAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('V',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTTAAG'), - 'ovhgseq' : 'TTAA', + 'compsite': '(?PCTTAAG)', + 'results': None, + 'site': 'CTTAAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('V',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CTTAAG'), + 'ovhgseq': 'TTAA', } rest_dict['Vha464I'] = _temp() def _temp(): return { - 'compsite' : '(?PGTGCAC)|(?PGTGCAC)', - 'results' : None, - 'site' : 'GTGCAC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GTGCAC'), - 'ovhgseq' : 'TGCA', + 'compsite': '(?PGTGCAC)', + 'results': None, + 'site': 'GTGCAC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'GTGCAC'), + 'ovhgseq': 'TGCA', } rest_dict['VneI'] = _temp() def _temp(): return { - 'compsite' : '(?PGG[AT]CC)|(?PGG[AT]CC)', - 'results' : None, - 'site' : 'GGWCC', - 'substrat' : 'DNA', - 'fst3' : 0, - 'fst5' : 0, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -5, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (0, 0, None, None, 'GGWCC'), - 'ovhgseq' : 'GGWCC', + 'compsite': '(?PGG[AT]CC)', + 'results': None, + 'site': 'GGWCC', + 'substrat': 'DNA', + 'fst3': 0, + 'fst5': 0, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -5, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (0, 0, None, None, 'GGWCC'), + 'ovhgseq': 'GGWCC', } rest_dict['VpaK11AI'] = _temp() def _temp(): return { - 'compsite' : '(?PGG[AT]CC)|(?PGG[AT]CC)', - 'results' : None, - 'site' : 'GGWCC', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 512, - 'size' : 5, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -3, - 'scd3' : None, - 'suppl' : ('K',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'GGWCC'), - 'ovhgseq' : 'GWC', + 'compsite': '(?PGG[AT]CC)', + 'results': None, + 'site': 'GGWCC', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 512, + 'size': 5, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -3, + 'scd3': None, + 'suppl': ('K',), + 'scd5': None, + 'charac': (1, -1, None, None, 'GGWCC'), + 'ovhgseq': 'GWC', } rest_dict['VpaK11BI'] = _temp() def _temp(): return { - 'compsite' : '(?PATTAAT)|(?PATTAAT)', - 'results' : None, - 'site' : 'ATTAAT', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('F', 'I', 'R', 'V'), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'ATTAAT'), - 'ovhgseq' : 'TA', + 'compsite': '(?PATTAAT)', + 'results': None, + 'site': 'ATTAAT', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('F', 'I', 'R', 'V'), + 'scd5': None, + 'charac': (2, -2, None, None, 'ATTAAT'), + 'ovhgseq': 'TA', } rest_dict['VspI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCT.....AGG)|(?PCCT.....AGG)', - 'results' : None, - 'site' : 'CCTNNNNNAGG', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 11, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -1, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'CCTNNNNNAGG'), - 'ovhgseq' : 'N', + 'compsite': '(?PCAC[AG]AG)|(?PCT[CT]GTG)', + 'results': None, + 'site': 'CACRAG', + 'substrat': 'DNA', + 'fst3': 19, + 'fst5': 27, + 'freq': 2048, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 2, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (27, 19, None, None, 'CACRAG'), + 'ovhgseq': 'NN', + } +rest_dict['WviI'] = _temp() + +def _temp(): + return { + 'compsite': '(?PCCT.....AGG)', + 'results': None, + 'site': 'CCTNNNNNAGG', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 11, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -1, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (5, -5, None, None, 'CCTNNNNNAGG'), + 'ovhgseq': 'N', } rest_dict['XagI'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]AATT[CT])|(?P[AG]AATT[CT])', - 'results' : None, - 'site' : 'RAATTY', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'RAATTY'), - 'ovhgseq' : 'AATT', + 'compsite': '(?P[AG]AATT[CT])', + 'results': None, + 'site': 'RAATTY', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'RAATTY'), + 'ovhgseq': 'AATT', } rest_dict['XapI'] = _temp() def _temp(): return { - 'compsite' : '(?PTCTAGA)|(?PTCTAGA)', - 'results' : None, - 'site' : 'TCTAGA', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('B', 'C', 'F', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'TCTAGA'), - 'ovhgseq' : 'CTAG', + 'compsite': '(?PTCTAGA)', + 'results': None, + 'site': 'TCTAGA', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('B', 'C', 'F', 'I', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'V', 'X', 'Y'), + 'scd5': None, + 'charac': (1, -1, None, None, 'TCTAGA'), + 'ovhgseq': 'CTAG', } rest_dict['XbaI'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]CATG[CT])|(?P[AG]CATG[CT])', - 'results' : None, - 'site' : 'RCATGY', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'RCATGY'), - 'ovhgseq' : 'CATG', + 'compsite': '(?P[AG]CATG[CT])', + 'results': None, + 'site': 'RCATGY', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (5, -5, None, None, 'RCATGY'), + 'ovhgseq': 'CATG', } rest_dict['XceI'] = _temp() def _temp(): return { - 'compsite' : '(?PCCA.........TGG)|(?PCCA.........TGG)', - 'results' : None, - 'site' : 'CCANNNNNNNNNTGG', - 'substrat' : 'DNA', - 'fst3' : -8, - 'fst5' : 8, - 'freq' : 4096, - 'size' : 15, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 1, - 'scd3' : None, - 'suppl' : ('N',), - 'scd5' : None, - 'charac' : (8, -8, None, None, 'CCANNNNNNNNNTGG'), - 'ovhgseq' : 'N', + 'compsite': '(?PCCA.........TGG)', + 'results': None, + 'site': 'CCANNNNNNNNNTGG', + 'substrat': 'DNA', + 'fst3': -8, + 'fst5': 8, + 'freq': 4096, + 'size': 15, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': ('N',), + 'scd5': None, + 'charac': (8, -8, None, None, 'CCANNNNNNNNNTGG'), + 'ovhgseq': 'N', } rest_dict['XcmI'] = _temp() def _temp(): return { - 'compsite' : '(?PCTCGAG)|(?PCTCGAG)', - 'results' : None, - 'site' : 'CTCGAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('B', 'F', 'H', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'W', 'X', 'Y'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTCGAG'), - 'ovhgseq' : 'TCGA', + 'compsite': '(?PCTCGAG)', + 'results': None, + 'site': 'CTCGAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('B', 'F', 'J', 'K', 'M', 'N', 'O', 'Q', 'R', 'S', 'U', 'X', 'Y'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CTCGAG'), + 'ovhgseq': 'TCGA', } rest_dict['XhoI'] = _temp() def _temp(): return { - 'compsite' : '(?P[AG]GATC[CT])|(?P[AG]GATC[CT])', - 'results' : None, - 'site' : 'RGATCY', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('R', 'W'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'RGATCY'), - 'ovhgseq' : 'GATC', + 'compsite': '(?P[AG]GATC[CT])', + 'results': None, + 'site': 'RGATCY', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('R',), + 'scd5': None, + 'charac': (1, -1, None, None, 'RGATCY'), + 'ovhgseq': 'GATC', } rest_dict['XhoII'] = _temp() def _temp(): return { - 'compsite' : '(?PCCCGGG)|(?PCCCGGG)', - 'results' : None, - 'site' : 'CCCGGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('M',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCCGGG'), - 'ovhgseq' : 'CCGG', - } -rest_dict['XmaCI'] = _temp() - -def _temp(): - return { - 'compsite' : '(?PCCCGGG)|(?PCCCGGG)', - 'results' : None, - 'site' : 'CCCGGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('I', 'N', 'R', 'U', 'V'), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCCGGG'), - 'ovhgseq' : 'CCGG', + 'compsite': '(?PCCCGGG)', + 'results': None, + 'site': 'CCCGGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('I', 'N', 'R', 'U', 'V'), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCCGGG'), + 'ovhgseq': 'CCGG', } rest_dict['XmaI'] = _temp() def _temp(): return { - 'compsite' : '(?PCGGCCG)|(?PCGGCCG)', - 'results' : None, - 'site' : 'CGGCCG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : (), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CGGCCG'), - 'ovhgseq' : 'GGCC', + 'compsite': '(?PCGGCCG)', + 'results': None, + 'site': 'CGGCCG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (1, -1, None, None, 'CGGCCG'), + 'ovhgseq': 'GGCC', } rest_dict['XmaIII'] = _temp() def _temp(): return { - 'compsite' : '(?PCCTAGG)|(?PCCTAGG)', - 'results' : None, - 'site' : 'CCTAGG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -4, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CCTAGG'), - 'ovhgseq' : 'CTAG', + 'compsite': '(?PCCTAGG)', + 'results': None, + 'site': 'CCTAGG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -4, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CCTAGG'), + 'ovhgseq': 'CTAG', } rest_dict['XmaJI'] = _temp() def _temp(): return { - 'compsite' : '(?PGT[AC][GT]AC)|(?PGT[AC][GT]AC)', - 'results' : None, - 'site' : 'GTMKAC', - 'substrat' : 'DNA', - 'fst3' : -2, - 'fst5' : 2, - 'freq' : 1024, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('F',), - 'scd5' : None, - 'charac' : (2, -2, None, None, 'GTMKAC'), - 'ovhgseq' : 'MK', + 'compsite': '(?PGT[AC][GT]AC)', + 'results': None, + 'site': 'GTMKAC', + 'substrat': 'DNA', + 'fst3': -2, + 'fst5': 2, + 'freq': 1024, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('F',), + 'scd5': None, + 'charac': (2, -2, None, None, 'GTMKAC'), + 'ovhgseq': 'MK', } rest_dict['XmiI'] = _temp() def _temp(): return { - 'compsite' : '(?PGAA....TTC)|(?PGAA....TTC)', - 'results' : None, - 'site' : 'GAANNNNTTC', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 10, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('N', 'R', 'U', 'W'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'GAANNNNTTC'), - 'ovhgseq' : '', + 'compsite': '(?PGAA....TTC)', + 'results': None, + 'site': 'GAANNNNTTC', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 10, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('N', 'R', 'U'), + 'scd5': None, + 'charac': (5, -5, None, None, 'GAANNNNTTC'), + 'ovhgseq': '', } rest_dict['XmnI'] = _temp() def _temp(): return { - 'compsite' : '(?PCTAG)|(?PCTAG)', - 'results' : None, - 'site' : 'CTAG', - 'substrat' : 'DNA', - 'fst3' : -1, - 'fst5' : 1, - 'freq' : 256, - 'size' : 4, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : -2, - 'scd3' : None, - 'suppl' : ('K',), - 'scd5' : None, - 'charac' : (1, -1, None, None, 'CTAG'), - 'ovhgseq' : 'TA', + 'compsite': '(?PCTAG)', + 'results': None, + 'site': 'CTAG', + 'substrat': 'DNA', + 'fst3': -1, + 'fst5': 1, + 'freq': 256, + 'size': 4, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': -2, + 'scd3': None, + 'suppl': ('K',), + 'scd5': None, + 'charac': (1, -1, None, None, 'CTAG'), + 'ovhgseq': 'TA', } rest_dict['XspI'] = _temp() def _temp(): return { - 'compsite' : '(?PGACGTC)|(?PGACGTC)', - 'results' : None, - 'site' : 'GACGTC', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I', 'N', 'V'), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'GACGTC'), - 'ovhgseq' : '', + 'compsite': '(?PC)|(?PG)', + 'results': None, + 'site': 'C', + 'substrat': 'DNA', + 'fst3': 9, + 'fst5': 11, + 'freq': 4, + 'size': 1, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 1, + 'scd3': None, + 'suppl': (), + 'scd5': None, + 'charac': (11, 9, None, None, 'C'), + 'ovhgseq': 'N', + } +rest_dict['YkrI'] = _temp() + +def _temp(): + return { + 'compsite': '(?PGACGTC)', + 'results': None, + 'site': 'GACGTC', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I', 'N', 'V'), + 'scd5': None, + 'charac': (3, -3, None, None, 'GACGTC'), + 'ovhgseq': '', } rest_dict['ZraI'] = _temp() def _temp(): return { - 'compsite' : '(?PAGTACT)|(?PAGTACT)', - 'results' : None, - 'site' : 'AGTACT', - 'substrat' : 'DNA', - 'fst3' : -3, - 'fst5' : 3, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 0, - 'scd3' : None, - 'suppl' : ('I',), - 'scd5' : None, - 'charac' : (3, -3, None, None, 'AGTACT'), - 'ovhgseq' : '', + 'compsite': '(?PAGTACT)', + 'results': None, + 'site': 'AGTACT', + 'substrat': 'DNA', + 'fst3': -3, + 'fst5': 3, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 0, + 'scd3': None, + 'suppl': ('I',), + 'scd5': None, + 'charac': (3, -3, None, None, 'AGTACT'), + 'ovhgseq': '', } rest_dict['ZrmI'] = _temp() def _temp(): return { - 'compsite' : '(?PATGCAT)|(?PATGCAT)', - 'results' : None, - 'site' : 'ATGCAT', - 'substrat' : 'DNA', - 'fst3' : -5, - 'fst5' : 5, - 'freq' : 4096, - 'size' : 6, - 'opt_temp' : 37, - 'dna' : None, - 'inact_temp' : 65, - 'ovhg' : 4, - 'scd3' : None, - 'suppl' : ('I', 'V'), - 'scd5' : None, - 'charac' : (5, -5, None, None, 'ATGCAT'), - 'ovhgseq' : 'TGCA', + 'compsite': '(?PATGCAT)', + 'results': None, + 'site': 'ATGCAT', + 'substrat': 'DNA', + 'fst3': -5, + 'fst5': 5, + 'freq': 4096, + 'size': 6, + 'opt_temp': 37, + 'dna': None, + 'inact_temp': 65, + 'ovhg': 4, + 'scd3': None, + 'suppl': ('I', 'V'), + 'scd5': None, + 'charac': (5, -5, None, None, 'ATGCAT'), + 'ovhgseq': 'TGCA', } rest_dict['Zsp2I'] = _temp() suppliers = {} def _temp(): return ( - 'Invitrogen Corporation', - ['MluI', 'HpaII', 'SalI', 'NcoI', 'ClaI', 'DraI', 'SstII', 'AvaI', 'PvuI', 'DpnI', 'TaqI', 'KpnI', 'NdeI', 'PinAI', 'BglII', 'NruI', 'RsaI', 'HincII', 'XbaI', 'MboI', 'AluI', 'MscI', 'SmaI', 'NheI', 'StuI', 'SphI', 'PvuII', 'SstI', 'SpeI', 'HinfI', 'EcoRV', 'EcoRI', 'XhoI', 'PstI', 'MseI', 'HaeIII', 'AccI', 'SspI', 'NsiI', 'ApaI', 'ScaI', 'DdeI', 'NotI', 'HindIII', 'BamHI', 'HpaI', 'HhaI'], + 'Life Technologies', + ['MluI', 'SacI', 'SalI', 'BshTI', 'NcoI', 'ClaI', 'DraI', 'PvuI', 'DpnI', 'TaqI', 'KpnI', 'NdeI', 'HapII', 'BglII', 'SacII', 'BmeT110I', 'MseI', 'NruI', 'HincII', 'XbaI', 'MboI', 'AluI', 'SmaI', 'NheI', 'StuI', 'SphI', 'PvuII', 'SpeI', 'HinfI', 'EcoRV', 'EcoRI', 'XhoI', 'PstI', 'HaeIII', 'AccI', 'SspI', 'ApaI', 'EcoT22I', 'ScaI', 'BalI', 'AfaI', 'NotI', 'HindIII', 'BamHI', 'HpaI', 'HhaI'], ) suppliers['B'] = _temp() def _temp(): return ( 'Minotech Biotechnology', - ['SgrBI', 'BclI', 'BglI', 'SalI', 'PspPI', 'SnaBI', 'BstEII', 'NcoI', 'BshFI', 'AsuII', 'BssAI', 'BseAI', 'TaqI', 'KpnI', 'BglII', 'NaeI', 'BseBI', 'NruI', 'SlaI', 'RsaI', 'BsiSI', 'XbaI', 'Sau3AI', 'MboI', 'AluI', 'SseBI', 'SmaI', 'NheI', 'SphI', 'PvuII', 'ApaLI', 'SstI', 'HinfI', 'MspCI', 'EcoRV', 'EcoRI', 'BseCI', 'PstI', 'SfiI', 'SspI', 'CspAI', 'ScaI', 'NotI', 'HindIII', 'BamHI', 'HpaI', 'StyI'], + ['SgrBI', 'BclI', 'BglI', 'SalI', 'PspPI', 'SnaBI', 'BstEII', 'NcoI', 'BshFI', 'AsuII', 'BssAI', 'BseAI', 'TaqI', 'KpnI', 'BglII', 'NaeI', 'BseBI', 'NruI', 'SlaI', 'RsaI', 'BsiSI', 'XbaI', 'Sau3AI', 'MboI', 'AluI', 'SseBI', 'SmaI', 'NheI', 'SstI', 'SphI', 'PvuII', 'ApaLI', 'HinfI', 'MspCI', 'EcoRV', 'EcoRI', 'BseCI', 'PstI', 'SfiI', 'SspI', 'CspAI', 'ScaI', 'NotI', 'HindIII', 'BamHI', 'HpaI', 'StyI'], ) suppliers['C'] = _temp() def _temp(): return ( - 'Stratagene', - ['SanDI', 'DpnI', 'SrfI'], + 'Agilent Technologies', + ['DpnI'], ) suppliers['E'] = _temp() def _temp(): return ( - 'Fermentas International Inc.', - ['MluI', 'CseI', 'PscI', 'HpaII', 'MreI', 'BclI', 'SacI', 'PauI', 'BglI', 'SalI', 'MspI', 'Bsu15I', 'Mva1269I', 'Bsp68I', 'LweI', 'SmiI', 'PteI', 'BshTI', 'TstI', 'TscAI', 'NcoI', 'PsyI', 'BseJI', 'MauBI', 'Eco24I', 'Eco47III', 'Eco91I', 'DraI', 'BseXI', 'BstXI', 'RruI', 'Esp3I', 'BseSI', 'Cfr9I', 'AarI', 'RseI', 'PvuI', 'BspOI', 'DpnI', 'Hin6I', 'Van91I', 'Bst1107I', 'Bme1390I', 'BveI', 'Psp5II', 'TaqI', 'Eco52I', 'BfiI', 'KpnI', 'Kpn2I', 'SspDI', 'SsiI', 'MlsI', 'NdeI', 'PpiI', 'Cfr13I', 'MboII', 'SdaI', 'BmsI', 'BglII', 'AjuI', 'AloI', 'FspBI', 'SchI', 'PfoI', 'Bpu10I', 'BshNI', 'Acc65I', 'XapI', 'TaaI', 'Bsp1407I', 'MvaI', 'PasI', 'Hin1II', 'Bsh1236I', 'MssI', 'CpoI', 'Eco130I', 'BdaI', 'TaiI', 'FspAI', 'BfmI', 'Eco47I', 'BoxI', 'RsaI', 'HincII', 'HpyF10VI', 'XbaI', 'Lsp1109I', 'Cfr10I', 'AjiI', 'Bsp119I', 'MboI', 'AluI', 'SduI', 'SgsI', 'BseGI', 'Eco72I', 'BcnI', 'Mph1103I', 'EcoRII', 'Alw21I', 'XagI', 'Hpy8I', 'PsuI', 'PaeI', 'SmaI', 'NheI', 'BplI', 'Ppu21I', 'SmoI', 'FaqI', 'AdeI', 'BcuI', 'BspTI', 'GsuI', 'BseLI', 'AasI', 'PvuII', 'EheI', 'Hin1I', 'Alw26I', 'SgrDI', 'Eco31I', 'HinfI', 'Eam1105I', 'BsuRI', 'TsoI', 'XmiI', 'Eam1104I', 'Ecl136II', 'XmaJI', 'SfaAI', 'HphI', 'Psp1406I', 'Csp6I', 'EcoO109I', 'BseMII', 'AatII', 'BfuI', 'EcoRI', 'TauI', 'XhoI', 'Bsp143I', 'BspPI', 'CfrI', 'MnlI', 'PfeI', 'CaiI', 'Bpu1102I', 'MunI', 'Tru1I', 'BspLI', 'SmuI', 'Eco105I', 'NsbI', 'PstI', 'LguI', 'VspI', 'Alw44I', 'SfiI', 'BpiI', 'XceI', 'BseMI', 'Eco57MI', 'Cfr42I', 'SatI', 'Hin4I', 'SspI', 'Eco32I', 'KflI', 'BseDI', 'KspAI', 'Eco81I', 'BauI', 'AanI', 'ApaI', 'SaqAI', 'Eco88I', 'ScaI', 'AlfI', 'Eco57I', 'Eco147I', 'OliI', 'PacI', 'PdmI', 'CsiI', 'Bsp120I', 'NotI', 'MbiI', 'HindIII', 'BamHI', 'BfoI', 'TatI', 'HpyF3I', 'Pfl23II', 'Bsh1285I', 'HhaI', 'NmuCI', 'BseNI', 'PagI', 'PdiI'], + 'Thermo Scientific Fermentas', + ['MluI', 'CseI', 'HpaII', 'Cfr9I', 'MreI', 'BclI', 'SacI', 'PauI', 'BglI', 'SalI', 'MspI', 'Bsu15I', 'Mva1269I', 'Bsp68I', 'LweI', 'SmiI', 'PteI', 'BshTI', 'TscAI', 'NcoI', 'PsyI', 'BseJI', 'MauBI', 'Eco24I', 'Eco47III', 'Eco91I', 'DraI', 'BseXI', 'BstXI', 'RruI', 'Esp3I', 'BseSI', 'AdeI', 'AarI', 'RseI', 'PvuI', 'BspOI', 'DpnI', 'Hin6I', 'Van91I', 'Bst1107I', 'Bme1390I', 'BveI', 'Psp5II', 'TaqI', 'Eco52I', 'KpnI', 'SspDI', 'SsiI', 'MlsI', 'NdeI', 'Cfr13I', 'MboII', 'SdaI', 'BmsI', 'BglII', 'TasI', 'AjuI', 'AloI', 'FspBI', 'SchI', 'PfoI', 'Bpu10I', 'BshNI', 'Acc65I', 'XapI', 'TaaI', 'PscI', 'Bsp1407I', 'MvaI', 'PasI', 'Hin1II', 'Bsh1236I', 'MssI', 'CpoI', 'Eco130I', 'TaiI', 'FspAI', 'BfmI', 'Eco47I', 'BoxI', 'RsaI', 'HincII', 'HpyF10VI', 'XbaI', 'Lsp1109I', 'Cfr10I', 'AjiI', 'Bsp119I', 'MboI', 'AluI', 'SduI', 'SgsI', 'BseGI', 'Eco72I', 'BcnI', 'SgeI', 'Mph1103I', 'EcoRII', 'Alw21I', 'Hpy8I', 'PsuI', 'PaeI', 'SmaI', 'NheI', 'BplI', 'Ppu21I', 'SmoI', 'FaqI', 'BcuI', 'BspTI', 'GsuI', 'BseLI', 'AasI', 'PvuII', 'EheI', 'XagI', 'Hin1I', 'Alw26I', 'SgrDI', 'Eco31I', 'HinfI', 'Eam1105I', 'BsuRI', 'XmiI', 'Eam1104I', 'Ecl136II', 'XmaJI', 'SfaAI', 'HphI', 'Psp1406I', 'Csp6I', 'EcoO109I', 'BseMII', 'AatII', 'BfuI', 'EcoRI', 'TauI', 'XhoI', 'Bsp143I', 'BspPI', 'MnlI', 'PfeI', 'CaiI', 'Bpu1102I', 'MunI', 'Tru1I', 'BspLI', 'Eco105I', 'NsbI', 'PstI', 'LguI', 'VspI', 'Alw44I', 'SfiI', 'BpiI', 'XceI', 'BseMI', 'Kpn2I', 'Cfr42I', 'SatI', 'SspI', 'Eco32I', 'KflI', 'BseDI', 'KspAI', 'Eco81I', 'BauI', 'AanI', 'ApaI', 'SaqAI', 'Eco88I', 'ScaI', 'AlfI', 'Eco57I', 'Eco147I', 'OliI', 'PacI', 'PdmI', 'CsiI', 'Bsp120I', 'NotI', 'MbiI', 'HindIII', 'BamHI', 'BfoI', 'TatI', 'HpyF3I', 'Pfl23II', 'Bsh1285I', 'HhaI', 'NmuCI', 'BseNI', 'PagI', 'PdiI'], ) suppliers['F'] = _temp() def _temp(): return ( - 'American Allied Biochemical, Inc.', - ['MluI', 'SacI', 'BglI', 'SalI', 'MspI', 'BstEII', 'NcoI', 'ClaI', 'BstXI', 'KpnI', 'BglII', 'SacII', 'RsaI', 'HincII', 'XbaI', 'Sau3AI', 'AluI', 'SmaI', 'SphI', 'PvuII', 'SpeI', 'HinfI', 'EcoRV', 'EcoRI', 'XhoI', 'PstI', 'HaeIII', 'NsiI', 'NotI', 'HindIII', 'BamHI', 'HpaI'], - ) -suppliers['H'] = _temp() - -def _temp(): - return ( 'SibEnzyme Ltd.', - ['AsuNHI', 'AgsI', 'BstSFI', 'MluI', 'CciI', 'BstHHI', 'HpaII', 'AhlI', 'PspN4I', 'BglI', 'SalI', 'MspI', 'VneI', 'BstH2I', 'BisI', 'BmtI', 'PspXI', 'AsiGI', 'CciNI', 'Sfr274I', 'SmiI', 'Ksp22I', 'BssT1I', 'MspA1I', 'Bsp19I', 'Bse1I', 'AspS9I', 'AbsI', 'FauNDI', 'BstMWI', 'AclWI', 'DraI', 'Bst2UI', 'AluBI', 'PsrI', 'BstACI', 'BstXI', 'BstDEI', 'GluI', 'BspACI', 'AcoI', 'XmaI', 'BstF5I', 'BstMBI', 'BstENI', 'BssECI', 'FalI', 'EgeI', 'Ama87I', 'BstDSI', 'BstV2I', 'AjnI', 'AspLEI', 'PalAI', 'Zsp2I', 'DseDI', 'BstAUI', 'Bpu14I', 'FaeI', 'TaqI', 'KpnI', 'BstSNI', 'AclI', 'MboII', 'BglII', 'PspPPI', 'SetI', 'AcsI', 'BstNSI', 'BseX3I', 'RsaNI', 'Bpu10I', 'Rsr2I', 'Acc65I', 'PspEI', 'Bst2BI', 'NruI', 'Ple19I', 'SmiMI', 'PciI', 'MalI', 'Bse118I', 'BsePI', 'BstMCI', 'Bme18I', 'RsaI', 'BssNAI', 'BstV1I', 'Bsp13I', 'Bst4CI', 'MabI', 'AsuHPI', 'BtrI', 'XbaI', 'ArsI', 'BstC8I', 'Psp124BI', 'GlaI', 'HgaI', 'BstX2I', 'AluI', 'ZraI', 'Bse21I', 'Sfr303I', 'BstSCI', 'Bse3DI', 'Bso31I', 'AccB7I', 'BstKTI', 'AccBSI', 'SmaI', 'AspA2I', 'Bsp1720I', 'Bsc4I', 'SphI', 'Mly113I', 'FriOI', 'PvuII', 'ErhI', 'FokI', 'AsuC2I', 'GsaI', 'HinfI', 'BsuRI', 'PpsI', 'BstPAI', 'HspAI', 'RgaI', 'Fsp4HI', 'Kzo9I', 'Acc36I', 'DraIII', 'Acc16I', 'MspR9I', 'EcoRV', 'PsiI', 'AatII', 'MroXI', 'EcoRI', 'ZrmI', 'BstFNI', 'PspOMI', 'BslFI', 'Bsa29I', 'MnlI', 'SbfI', 'PstI', 'Bse8I', 'FauI', 'VspI', 'PciSI', 'SfiI', 'Bst6I', 'PspLI', 'BspFNI', 'Msp20I', 'Bbv12I', 'HaeIII', 'BstAPI', 'SspI', 'AfeI', 'Tth111I', 'BstMAI', 'BstSLI', 'ApaI', 'BlsI', 'FblI', 'BmuI', 'BarI', 'PctI', 'FaiI', 'BpmI', 'AcuI', 'AccB1I', 'PceI', 'Sse9I', 'Tru9I', 'MhlI', 'BstBAI', 'DriI', 'MroNI', 'HindIII', 'EcoICRI', 'FatI', 'BamHI', 'Psp6I', 'BstAFI', 'SfaNI', 'RigI', 'HpaI', 'PspCI', 'HindII'], + ['AsuNHI', 'AgsI', 'BstSFI', 'MluI', 'CciI', 'BstHHI', 'HpaII', 'AhlI', 'KroI', 'PspN4I', 'BglI', 'SalI', 'PspEI', 'MspI', 'VneI', 'BstH2I', 'BisI', 'BmtI', 'PspXI', 'AsiGI', 'CciNI', 'Sfr274I', 'SmiI', 'Ksp22I', 'BssT1I', 'MspA1I', 'Bsp19I', 'Bse1I', 'AspS9I', 'AbsI', 'FauNDI', 'BstMWI', 'AclWI', 'DraI', 'Bst2UI', 'AluBI', 'PsrI', 'BstACI', 'BstXI', 'BstDEI', 'GluI', 'AcoI', 'XmaI', 'BstF5I', 'BstENI', 'BssECI', 'FalI', 'EgeI', 'Ama87I', 'BstDSI', 'BstV2I', 'AjnI', 'AspLEI', 'PalAI', 'Zsp2I', 'DseDI', 'BstAUI', 'Bpu14I', 'FaeI', 'TaqI', 'KpnI', 'BstSNI', 'AclI', 'MboII', 'BglII', 'PspPPI', 'SetI', 'AcsI', 'BstNSI', 'BseX3I', 'RsaNI', 'Bpu10I', 'Rsr2I', 'Acc65I', 'Bst2BI', 'NruI', 'Ple19I', 'TseFI', 'SmiMI', 'PciI', 'MalI', 'Bse118I', 'BsuI', 'BsePI', 'BstMCI', 'Bme18I', 'RsaI', 'BssNAI', 'BstV1I', 'Bsp13I', 'Bst4CI', 'MabI', 'AsuHPI', 'BtrI', 'XbaI', 'ArsI', 'BstC8I', 'Psp124BI', 'GlaI', 'HgaI', 'BstX2I', 'AluI', 'ZraI', 'Bse21I', 'Sfr303I', 'BstSCI', 'Bse3DI', 'Bso31I', 'AccB7I', 'BstKTI', 'AccBSI', 'SmaI', 'BspACI', 'AspA2I', 'Bsp1720I', 'Bsc4I', 'SphI', 'Mly113I', 'FriOI', 'PvuII', 'MfeI', 'ErhI', 'FokI', 'AsuC2I', 'GsaI', 'HinfI', 'BsuRI', 'PpsI', 'BstPAI', 'HspAI', 'RgaI', 'Fsp4HI', 'Kzo9I', 'Acc36I', 'DraIII', 'Acc16I', 'MspR9I', 'EcoRV', 'PsiI', 'AatII', 'MroXI', 'EcoRI', 'ZrmI', 'BstFNI', 'BslFI', 'Bsa29I', 'MnlI', 'SbfI', 'PstI', 'Bse8I', 'FauI', 'VspI', 'PciSI', 'SfiI', 'Bst6I', 'PspLI', 'BspFNI', 'Msp20I', 'Bbv12I', 'HaeIII', 'BstAPI', 'SspI', 'AfeI', 'Tth111I', 'BstMBI', 'PspOMI', 'BstMAI', 'BstSLI', 'ApaI', 'BlsI', 'FblI', 'BmuI', 'PcsI', 'BarI', 'PctI', 'FaiI', 'BpmI', 'PstNI', 'AcuI', 'AccB1I', 'PceI', 'HpySE526I', 'Sse9I', 'Tru9I', 'MhlI', 'BstBAI', 'DriI', 'MroNI', 'HindIII', 'EcoICRI', 'FatI', 'BamHI', 'Psp6I', 'BstAFI', 'SfaNI', 'RigI', 'HpaI', 'PspCI', 'HindII', 'AsiSI'], ) suppliers['I'] = _temp() @@ -16637,83 +17180,76 @@ def _temp(): return ( 'Takara Bio Inc.', - ['BssHII', 'MluI', 'BspT107I', 'SacI', 'XspI', 'BglI', 'SalI', 'MspI', 'BstPI', 'BanII', 'PmaCI', 'SnaBI', 'SmiI', 'BmgT120I', 'NcoI', 'ClaI', 'DraI', 'BstXI', 'PshAI', 'PvuI', 'Van91I', 'Bst1107I', 'TaqI', 'EaeI', 'Eco52I', 'BspT104I', 'KpnI', 'HaeII', 'EcoO65I', 'NdeI', 'HapII', 'MboII', 'AflII', 'EcoT14I', 'BglII', 'NaeI', 'AccII', 'SacII', 'BmeT110I', 'Aor51HI', 'Bsp1407I', 'NruI', 'MvaI', 'Sse8387I', 'CpoI', 'HincII', 'XbaI', 'Sau3AI', 'Cfr10I', 'MboI', 'AluI', 'BcnI', 'SmaI', 'NheI', 'StuI', 'SphI', 'PvuII', 'MflI', 'FokI', 'Hin1I', 'ApaLI', 'SpeI', 'HinfI', 'Eam1105I', 'Psp1406I', 'EcoO109I', 'BbeI', 'EcoRV', 'AatII', 'EcoRI', 'XhoI', 'VpaK11BI', 'Bsp1286I', 'AccIII', 'Bpu1102I', 'MunI', 'Aor13HI', 'NsbI', 'PstI', 'SfiI', 'BlnI', 'HaeIII', 'AccI', 'SspI', 'Tth111I', 'FbaI', 'Eco81I', 'ApaI', 'PshBI', 'EcoT22I', 'ScaI', 'BalI', 'AfaI', 'NotI', 'HindIII', 'BamHI', 'AvaII', 'HpaI', 'HhaI'], + ['BssHII', 'MluI', 'BspT107I', 'SacI', 'XspI', 'BglI', 'SalI', 'MspI', 'BstPI', 'BanII', 'PmaCI', 'SnaBI', 'SmiI', 'BmgT120I', 'NcoI', 'ClaI', 'DraI', 'BstXI', 'PshAI', 'PvuI', 'DpnI', 'Van91I', 'Bst1107I', 'TaqI', 'EaeI', 'Eco52I', 'BspT104I', 'KpnI', 'HaeII', 'EcoO65I', 'NdeI', 'HapII', 'MboII', 'AflII', 'EcoT14I', 'BglII', 'NaeI', 'AccII', 'SacII', 'BmeT110I', 'Aor51HI', 'Bsp1407I', 'NruI', 'Sse8387I', 'CpoI', 'HincII', 'XbaI', 'Sau3AI', 'Cfr10I', 'MboI', 'AluI', 'BcnI', 'SmaI', 'NheI', 'StuI', 'SphI', 'PvuII', 'MflI', 'FokI', 'Hin1I', 'ApaLI', 'SpeI', 'HinfI', 'Eam1105I', 'Psp1406I', 'EcoO109I', 'EcoRV', 'AatII', 'EcoRI', 'XhoI', 'VpaK11BI', 'Bsp1286I', 'AccIII', 'Bpu1102I', 'MunI', 'Aor13HI', 'NsbI', 'PstI', 'SfiI', 'BlnI', 'HaeIII', 'BciT130I', 'AccI', 'SspI', 'Tth111I', 'FbaI', 'Eco81I', 'ApaI', 'PshBI', 'EcoT22I', 'ScaI', 'BalI', 'DdeI', 'AfaI', 'NotI', 'HindIII', 'BamHI', 'HpaI', 'HhaI'], ) suppliers['K'] = _temp() def _temp(): return ( 'Roche Applied Science', - ['BssHII', 'MluI', 'HpaII', 'BclI', 'SacI', 'BglI', 'SalI', 'Asp718I', 'MspI', 'SnaBI', 'XmaCI', 'BstEII', 'NcoI', 'ClaI', 'DraII', 'Eco47III', 'DraI', 'BstXI', 'SwaI', 'AvaI', 'PvuI', 'BseAI', 'DpnI', 'Van91I', 'Bst1107I', 'BsiWI', 'TaqI', 'SexAI', 'KpnI', 'NdeI', 'PinAI', 'BglII', 'NaeI', 'MaeI', 'AspI', 'NruI', 'MvaI', 'BpuAI', 'NarI', 'RsaI', 'MaeII', 'AflIII', 'AspEI', 'XbaI', 'Sau3AI', 'MvnI', 'AluI', 'RsrII', 'EcoRII', 'CfoI', 'SmaI', 'NheI', 'StuI', 'BbrPI', 'SphI', 'MaeIII', 'PvuII', 'FokI', 'SpeI', 'HinfI', 'DraIII', 'MluNI', 'EcoRV', 'AatII', 'EcoRI', 'XhoI', 'MunI', 'EclXI', 'PstI', 'BsmI', 'SfiI', 'BlnI', 'HaeIII', 'NdeII', 'AccI', 'SspI', 'SgrAI', 'NsiI', 'ItaI', 'ApaI', 'SfuI', 'ScaI', 'BfrI', 'NspI', 'KspI', 'Tru9I', 'DdeI', 'NotI', 'MroI', 'Asp700I', 'HindIII', 'AcyI', 'RcaI', 'BamHI', 'AviII', 'AvaII', 'CelII', 'HpaI', 'StyI', 'HindII'], + ['BssHII', 'MluI', 'BclI', 'SacI', 'SalI', 'Asp718I', 'SnaBI', 'NcoI', 'ClaI', 'Eco47III', 'DraI', 'BstXI', 'SwaI', 'PvuI', 'BseAI', 'DpnI', 'TaqI', 'SexAI', 'KpnI', 'NdeI', 'PinAI', 'BglII', 'MaeI', 'NruI', 'MvaI', 'NarI', 'RsaI', 'MaeII', 'AflIII', 'XbaI', 'Sau3AI', 'MvnI', 'AluI', 'CfoI', 'SmaI', 'NheI', 'StuI', 'BbrPI', 'SphI', 'MaeIII', 'PvuII', 'FokI', 'SpeI', 'HinfI', 'DraIII', 'MluNI', 'EcoRV', 'AatII', 'EcoRI', 'XhoI', 'MunI', 'EclXI', 'PstI', 'BsmI', 'SfiI', 'BlnI', 'HaeIII', 'NdeII', 'AccI', 'SspI', 'NsiI', 'ApaI', 'SfuI', 'ScaI', 'BfrI', 'KspI', 'Tru9I', 'DdeI', 'NotI', 'MroI', 'Asp700I', 'HindIII', 'BamHI', 'HpaI', 'HindII'], ) suppliers['M'] = _temp() def _temp(): return ( 'New England Biolabs', - ['BssHII', 'EciI', 'BsrFI', 'DpnII', 'AlwI', 'MluI', 'NgoMIV', 'HpaII', 'TspMI', 'BclI', 'MlyI', 'BsaWI', 'SacI', 'MwoI', 'BfaI', 'DrdI', 'BmgBI', 'BglI', 'SalI', 'MspI', 'BanII', 'MslI', 'BmtI', 'PspXI', 'BsaBI', 'SnaBI', 'BstEII', 'TspRI', 'NcoI', 'MspA1I', 'BtgI', 'ClaI', 'BsaI', 'BsrBI', 'AlwNI', 'XmnI', 'DraI', 'Hpy166II', 'Hpy99I', 'StyD4I', 'BstXI', 'PspGI', 'BsiHKAI', 'BlpI', 'PshAI', 'XmaI', 'SwaI', 'AvaI', 'PvuI', 'DpnI', 'CspCI', 'PflFI', 'BpuEI', 'BsiWI', 'TaqI', 'EaeI', 'SexAI', 'BsrI', 'AseI', 'KpnI', 'Sau96I', 'BstNI', 'HaeII', 'AclI', 'ApoI', 'HpyCH4IV', 'NdeI', 'MboII', 'AflII', 'TseI', 'BglII', 'SmlI', 'NaeI', 'Bpu10I', 'SacII', 'Acc65I', 'BspQI', 'AvrII', 'NruI', 'BaeI', 'BtsCI', 'BssKI', 'PciI', 'PhoI', 'BcgI', 'BsaHI', 'SfoI', 'TliI', 'NarI', 'Bsu36I', 'RsaI', 'HincII', 'AflIII', 'BsgI', 'XbaI', 'Sau3AI', 'BfuAI', 'TfiI', 'PmlI', 'BbvI', 'MboI', 'HgaI', 'BanI', 'AluI', 'BaeGI', 'ZraI', 'Hpy188III', 'RsrII', 'BspMI', 'AciI', 'ScrFI', 'MscI', 'BseYI', 'CviQI', 'BmrI', 'Hpy188I', 'SmaI', 'PleI', 'EcoNI', 'NheI', 'BccI', 'BsiEI', 'StuI', 'BspCNI', 'SphI', 'HpyAV', 'NciI', 'FspI', 'CviAII', 'PvuII', 'Eco53kI', 'MfeI', 'BsrDI', 'BssSI', 'FokI', 'ApaLI', 'ApeKI', 'SpeI', 'HinfI', 'BciVI', 'HinP1I', 'BceAI', 'HphI', 'BsmAI', 'DraIII', 'EcoO109I', 'BtsI', 'SapI', 'PpuMI', 'EcoRV', 'PsiI', 'AatII', 'EcoRI', 'BsmFI', 'XhoI', 'Bsp1286I', 'PspOMI', 'MnlI', 'EagI', 'AscI', 'AhdI', 'NlaIII', 'SbfI', 'BsoBI', 'PstI', 'Tsp509I', 'MseI', 'FauI', 'SfcI', 'BspEI', 'BsmI', 'SfiI', 'BstUI', 'BstZ17I', 'KasI', 'HaeIII', 'BsmBI', 'XcmI', 'BstAPI', 'AccI', 'SspI', 'HpyCH4III', 'BsrGI', 'AfeI', 'Tth111I', 'SgrAI', 'NsiI', 'BspHI', 'BstYI', 'PmeI', 'FseI', 'ApaI', 'BseRI', 'MmeI', 'ScaI', 'AgeI', 'BtgZI', 'BpmI', 'EarI', 'CviKI_1', 'AcuI', 'BfuCI', 'NspI', 'PacI', 'BstBI', 'HpyCH4V', 'NlaIV', 'BbsI', 'DdeI', 'NotI', 'BsaXI', 'HindIII', 'FatI', 'BamHI', 'BslI', 'AvaII', 'BspDI', 'PaeR7I', 'SfaNI', 'HpaI', 'BsaJI', 'BbvCI', 'Fnu4HI', 'Cac8I', 'Tsp45I', 'StyI', 'PflMI', 'HhaI', 'AsiSI', 'AleI', 'NmeAIII', 'BsaAI'], + ['BssHII', 'EciI', 'BsrFI', 'DpnII', 'AlwI', 'MluI', 'NgoMIV', 'HpaII', 'TspMI', 'BclI', 'MlyI', 'BsaWI', 'SacI', 'MwoI', 'BfaI', 'DrdI', 'BmgBI', 'BglI', 'SalI', 'MspI', 'BanII', 'MslI', 'BmtI', 'PspXI', 'BsaBI', 'SnaBI', 'BstEII', 'TspRI', 'NcoI', 'MspA1I', 'BtgI', 'ClaI', 'BsaI', 'BsrBI', 'AlwNI', 'XmnI', 'DraI', 'Hpy166II', 'Hpy99I', 'StyD4I', 'BstXI', 'PspGI', 'BsiHKAI', 'BsoBI', 'BlpI', 'PshAI', 'XmaI', 'BtsIMutI', 'SwaI', 'AvaI', 'PvuI', 'DpnI', 'CspCI', 'PflFI', 'BpuEI', 'TaqI', 'EaeI', 'SexAI', 'BsrI', 'AseI', 'KpnI', 'Sau96I', 'BstNI', 'HaeII', 'AclI', 'ApoI', 'HpyCH4IV', 'NdeI', 'MboII', 'AflII', 'TseI', 'BglII', 'SmlI', 'NaeI', 'Bpu10I', 'SacII', 'Acc65I', 'BspQI', 'MseI', 'AvrII', 'NruI', 'BaeI', 'BtsCI', 'BssKI', 'PciI', 'BcgI', 'BsaHI', 'SfoI', 'MspJI', 'NarI', 'Bsu36I', 'RsaI', 'HincII', 'AflIII', 'BspCNI', 'BsgI', 'XbaI', 'Sau3AI', 'BfuAI', 'TfiI', 'PmlI', 'BbvI', 'MboI', 'HgaI', 'BanI', 'AluI', 'BaeGI', 'ZraI', 'Hpy188III', 'RsrII', 'BspMI', 'MluCI', 'AciI', 'ScrFI', 'MscI', 'BseYI', 'CviQI', 'BmrI', 'Hpy188I', 'SmaI', 'PleI', 'EcoNI', 'NheI', 'BccI', 'FspEI', 'BsiEI', 'StuI', 'BcoDI', 'BsiWI', 'SphI', 'HpyAV', 'NciI', 'FspI', 'CviAII', 'PvuII', 'Eco53kI', 'MfeI', 'BsrDI', 'BssSI', 'FokI', 'ApaLI', 'ApeKI', 'AbaSI', 'SpeI', 'HinfI', 'BciVI', 'HinP1I', 'BceAI', 'HphI', 'BsmAI', 'DraIII', 'EcoO109I', 'BtsI', 'SapI', 'PpuMI', 'EcoRV', 'PsiI', 'AatII', 'EcoRI', 'BsmFI', 'XhoI', 'Bsp1286I', 'PluTI', 'MnlI', 'EagI', 'AscI', 'AhdI', 'NlaIII', 'SbfI', 'PstI', 'FauI', 'SfcI', 'BspEI', 'BsmI', 'SfiI', 'BstUI', 'BstZ17I', 'KasI', 'HaeIII', 'BsmBI', 'XcmI', 'LpnPI', 'BstAPI', 'AccI', 'SspI', 'HpyCH4III', 'BsrGI', 'AfeI', 'Tth111I', 'SgrAI', 'NsiI', 'BspHI', 'BstYI', 'PspOMI', 'PmeI', 'FseI', 'ApaI', 'BseRI', 'MmeI', 'ScaI', 'AgeI', 'BtgZI', 'BpmI', 'EarI', 'CviKI_1', 'AcuI', 'BfuCI', 'NspI', 'PacI', 'BstBI', 'HpyCH4V', 'NlaIV', 'BbsI', 'DdeI', 'NotI', 'BsaXI', 'HindIII', 'FatI', 'BamHI', 'BslI', 'AvaII', 'BspDI', 'PaeR7I', 'SfaNI', 'HpaI', 'BsaJI', 'BbvCI', 'Fnu4HI', 'Cac8I', 'Tsp45I', 'StyI', 'PflMI', 'HhaI', 'AsiSI', 'AleI', 'NmeAIII', 'BsaAI'], ) suppliers['N'] = _temp() def _temp(): return ( 'Toyobo Biochemicals', - ['BssHII', 'MluI', 'HpaII', 'BclI', 'SacI', 'BglI', 'SalI', 'MspI', 'BanII', 'BstEII', 'NcoI', 'Eco47III', 'DraI', 'BstXI', 'Cfr9I', 'AvaI', 'PvuI', 'DpnI', 'BsiWI', 'TaqI', 'Eco52I', 'AseI', 'KpnI', 'Sau96I', 'HaeII', 'Cfr13I', 'MboII', 'TspEI', 'BglII', 'NaeI', 'SacII', 'NruI', 'MvaI', 'CspI', 'NarI', 'Eco47I', 'RsaI', 'HincII', 'XbaI', 'Sau3AI', 'Cfr10I', 'BanIII', 'BanI', 'AluI', 'ScrFI', 'EcoRII', 'MscI', 'Csp45I', 'SmaI', 'NheI', 'BbrPI', 'SphI', 'NciI', 'FspI', 'PvuII', 'EheI', 'Hin1I', 'SpeI', 'HinfI', 'PpuMI', 'EcoRV', 'PsiI', 'AatII', 'EcoRI', 'AatI', 'XhoI', 'SbfI', 'Eco105I', 'PstI', 'BsmI', 'Alw44I', 'SfiI', 'HaeIII', 'AccI', 'SspI', 'SrfI', 'Eco81I', 'ApaI', 'EcoT22I', 'ScaI', 'NspV', 'BfrI', 'PacI', 'DdeI', 'NotI', 'MroI', 'HindIII', 'BamHI', 'HpaI', 'HhaI'], + ['MluI', 'BclI', 'SacI', 'BglI', 'SalI', 'NcoI', 'PvuI', 'DpnI', 'AseI', 'KpnI', 'BglII', 'SacII', 'HincII', 'XbaI', 'AluI', 'MscI', 'SmaI', 'NheI', 'SphI', 'PvuII', 'SpeI', 'HinfI', 'EcoRV', 'EcoRI', 'XhoI', 'PstI', 'SfiI', 'HaeIII', 'ScaI', 'PacI', 'DdeI', 'NotI', 'MroI', 'HindIII', 'BamHI'], ) suppliers['O'] = _temp() def _temp(): return ( 'Molecular Biology Resources - CHIMERx', - ['BssHII', 'MluI', 'HpaII', 'BspTNI', 'SacI', 'BglI', 'SalI', 'MspI', 'BanII', 'NcoI', 'CviJI', 'DraI', 'BstXI', 'AcvI', 'PvuI', 'TaqI', 'SinI', 'KpnI', 'NdeI', 'PinAI', 'MboII', 'BglII', 'SacII', 'NruI', 'NarI', 'TaqII', 'RsaI', 'HincII', 'XbaI', 'MboI', 'AluI', 'RsrII', 'SmaI', 'StuI', 'SphI', 'FokI', 'SpeI', 'HinfI', 'BsiHKCI', 'EcoRV', 'EcoRI', 'XhoI', 'MnlI', 'PstI', 'SfiI', 'HaeIII', 'SspI', 'Tth111I', 'ApaI', 'ScaI', 'NotI', 'HindIII', 'BamHI', 'HpaI'], + ['BssHII', 'MluI', 'HpaII', 'SacI', 'BglI', 'SalI', 'MspI', 'NcoI', 'ClaI', 'CviJI', 'DraI', 'BstXI', 'AcvI', 'AvaI', 'PvuI', 'DpnI', 'TaqI', 'KpnI', 'NdeI', 'PinAI', 'MboII', 'BglII', 'SacII', 'NruI', 'NarI', 'TaqII', 'RsaI', 'HincII', 'XbaI', 'TspGWI', 'MboI', 'AluI', 'RsrII', 'SmaI', 'NheI', 'StuI', 'SphI', 'PvuII', 'SpeI', 'HinfI', 'BsiHKCI', 'EcoRV', 'EcoRI', 'XhoI', 'MnlI', 'PstI', 'SfiI', 'HaeIII', 'AccI', 'SspI', 'Tth111I', 'NsiI', 'ApaI', 'ScaI', 'TspDTI', 'BalI', 'DdeI', 'NotI', 'HindIII', 'BamHI', 'HpaI', 'HhaI'], ) suppliers['Q'] = _temp() def _temp(): return ( 'Promega Corporation', - ['BssHII', 'MluI', 'NgoMIV', 'HpaII', 'BclI', 'SacI', 'BglI', 'SalI', 'BstOI', 'MspI', 'BanII', 'SnaBI', 'BstEII', 'NcoI', 'MspA1I', 'ClaI', 'XmnI', 'Eco47III', 'DraI', 'BstXI', 'XmaI', 'AvaI', 'PvuI', 'DpnI', 'BbuI', 'TaqI', 'SinI', 'KpnI', 'HaeII', 'NdeI', 'MboII', 'BglII', 'NaeI', 'SacII', 'Acc65I', 'NruI', 'CspI', 'NarI', 'Bsu36I', 'Bst98I', 'RsaI', 'HincII', 'XbaI', 'BsrSI', 'Sau3AI', 'MboI', 'BanI', 'AluI', 'CfoI', 'Csp45I', 'AccB7I', 'SmaI', 'NheI', 'XhoII', 'StuI', 'SphI', 'NciI', 'PvuII', 'FokI', 'SpeI', 'HinfI', 'SgfI', 'EcoRV', 'AatII', 'EcoRI', 'XhoI', 'Bsp1286I', 'AccIII', 'PstI', 'VspI', 'BstZI', 'Alw44I', 'SfiI', 'Hsp92I', 'HaeIII', 'NdeII', 'AccI', 'SspI', 'Tth111I', 'NsiI', 'ApaI', 'ScaI', 'AgeI', 'BsaMI', 'BalI', 'Tru9I', 'Hsp92II', 'DdeI', 'NotI', 'HindIII', 'EcoICRI', 'BamHI', 'AvaII', 'HpaI', 'StyI', 'HhaI'], + ['BssHII', 'MluI', 'HpaII', 'BclI', 'SacI', 'BglI', 'SalI', 'BstOI', 'MspI', 'SnaBI', 'BstEII', 'NcoI', 'MspA1I', 'ClaI', 'XmnI', 'Eco47III', 'DraI', 'BstXI', 'XmaI', 'AvaI', 'PvuI', 'DpnI', 'TaqI', 'KpnI', 'HaeII', 'NdeI', 'MboII', 'BglII', 'SacII', 'Acc65I', 'NruI', 'CspI', 'NarI', 'Bsu36I', 'RsaI', 'HincII', 'XbaI', 'BsrSI', 'Sau3AI', 'MboI', 'BanI', 'AluI', 'CfoI', 'SmaI', 'NheI', 'StuI', 'SphI', 'NciI', 'PvuII', 'SpeI', 'HinfI', 'SgfI', 'EcoRV', 'AatII', 'EcoRI', 'XhoI', 'AccIII', 'PstI', 'VspI', 'BstZI', 'SfiI', 'Hsp92I', 'HaeIII', 'AccI', 'SspI', 'NsiI', 'ApaI', 'ScaI', 'AgeI', 'BalI', 'XhoII', 'Tru9I', 'Hsp92II', 'DdeI', 'NotI', 'HindIII', 'EcoICRI', 'BamHI', 'AvaII', 'HpaI', 'HhaI'], ) suppliers['R'] = _temp() def _temp(): return ( 'Sigma Chemical Corporation', - ['BssHII', 'MluI', 'HpaII', 'BclI', 'SacI', 'BglI', 'SalI', 'MspI', 'BstEII', 'NcoI', 'ClaI', 'DraI', 'SwaI', 'AvaI', 'PvuI', 'DpnI', 'TaqI', 'KpnI', 'NdeI', 'BglII', 'MvaI', 'RsaI', 'XbaI', 'Sau3AI', 'AluI', 'ScrFI', 'EcoRII', 'CfoI', 'SmaI', 'NheI', 'StuI', 'SphI', 'PvuII', 'SpeI', 'MluNI', 'EcoRV', 'EcoRI', 'XhoI', 'EclXI', 'PstI', 'BsmI', 'SfiI', 'BlnI', 'HaeIII', 'AccI', 'SspI', 'NsiI', 'ApaI', 'ScaI', 'KspI', 'DdeI', 'NotI', 'HindIII', 'BamHI', 'AvaII', 'HpaI', 'StyI', 'HindII'], + ['BssHII', 'HpaII', 'BclI', 'SacI', 'SalI', 'MspI', 'BstEII', 'NcoI', 'ClaI', 'DraI', 'PvuI', 'DpnI', 'TaqI', 'KpnI', 'NdeI', 'BglII', 'MvaI', 'RsaI', 'XbaI', 'Sau3AI', 'AluI', 'CfoI', 'SmaI', 'NheI', 'SphI', 'PvuII', 'SpeI', 'EcoRV', 'EcoRI', 'XhoI', 'EclXI', 'PstI', 'BsmI', 'SfiI', 'BlnI', 'HaeIII', 'AccI', 'SspI', 'NsiI', 'ApaI', 'ScaI', 'KspI', 'DdeI', 'NotI', 'HindIII', 'BamHI', 'HpaI'], ) suppliers['S'] = _temp() def _temp(): return ( 'Bangalore Genei', - ['MluI', 'HpaII', 'BclI', 'SacI', 'BglI', 'SalI', 'MspI', 'BstEII', 'NcoI', 'ClaI', 'XmnI', 'DraI', 'XmaI', 'AvaI', 'PvuI', 'AssI', 'TaqI', 'KpnI', 'Sau96I', 'BglII', 'NaeI', 'NruI', 'NarI', 'HincII', 'XbaI', 'Sau3AI', 'StrI', 'MboI', 'BanI', 'AluI', 'SmaI', 'BasI', 'NheI', 'StuI', 'PvuII', 'ApaLI', 'SpeI', 'HinfI', 'MvrI', 'EcoRV', 'EcoRI', 'XhoI', 'PstI', 'SfiI', 'HaeIII', 'AccI', 'SspI', 'NsiI', 'ApaI', 'NotI', 'HindIII', 'BamHI', 'HpaI', 'HhaI'], + ['MluI', 'HpaII', 'BclI', 'SacI', 'BglI', 'SalI', 'MspI', 'SnaBI', 'BstEII', 'NcoI', 'ClaI', 'XmnI', 'DraI', 'XmaI', 'AvaI', 'PvuI', 'AssI', 'TaqI', 'KpnI', 'Sau96I', 'NdeI', 'BglII', 'NaeI', 'NruI', 'NarI', 'HincII', 'XbaI', 'Sau3AI', 'StrI', 'MboI', 'BanI', 'AluI', 'SmaI', 'BasI', 'NheI', 'StuI', 'PvuII', 'ApaLI', 'SpeI', 'HinfI', 'MvrI', 'EcoRV', 'EcoRI', 'XhoI', 'PstI', 'SfiI', 'HaeIII', 'AccI', 'SspI', 'NsiI', 'ApaI', 'NotI', 'HindIII', 'BamHI', 'HpaI', 'HhaI'], ) suppliers['U'] = _temp() def _temp(): return ( 'Vivantis Technologies', - ['BssMI', 'AsuNHI', 'MluI', 'BstHHI', 'HpaII', 'AhlI', 'BglI', 'SalI', 'MspI', 'VneI', 'BstH2I', 'BmtI', 'AsiGI', 'CciNI', 'Sfr274I', 'SmiI', 'Ksp22I', 'BssT1I', 'MspA1I', 'Bsp19I', 'Bse1I', 'AspS9I', 'BmcAI', 'FauNDI', 'DraI', 'Bst2UI', 'Vha464I', 'BstXI', 'BstDEI', 'XmaI', 'BstF5I', 'BpvUI', 'BstMBI', 'BstENI', 'Ama87I', 'BstDSI', 'BstV2I', 'AspLEI', 'Zsp2I', 'DseDI', 'BstAUI', 'Bpu14I', 'TaqI', 'KpnI', 'BstSNI', 'AclI', 'MboII', 'BmrFI', 'BglII', 'AcsI', 'BstNSI', 'BmeRI', 'BseX3I', 'Bpu10I', 'Rsr2I', 'Acc65I', 'BtuMI', 'PspEI', 'Bst2BI', 'SmiMI', 'Bse118I', 'BsnI', 'BmiI', 'BsePI', 'BstMCI', 'Bme18I', 'RsaI', 'BssNAI', 'Bsp13I', 'Bst4CI', 'AsuHPI', 'BtrI', 'XbaI', 'Psp124BI', 'BstX2I', 'AluI', 'ZraI', 'Bse21I', 'Sfr303I', 'BpuMI', 'Bse3DI', 'Bso31I', 'AccB7I', 'AccBSI', 'SmaI', 'AspA2I', 'Bsp1720I', 'SphI', 'FriOI', 'PvuII', 'ErhI', 'BshVI', 'FokI', 'HinfI', 'BstPAI', 'HspAI', 'DraIII', 'Acc16I', 'EcoRV', 'AatII', 'MroXI', 'EcoRI', 'DinI', 'BstFNI', 'AfiI', 'PspOMI', 'MnlI', 'SbfI', 'PstI', 'Bse8I', 'VspI', 'SfiI', 'Bst6I', 'Msp20I', 'Bbv12I', 'SspI', 'Tth111I', 'BstMAI', 'ApaI', 'FblI', 'PctI', 'AccB1I', 'BssNI', 'PceI', 'Sse9I', 'Tru9I', 'MhlI', 'BstBAI', 'MroNI', 'HindIII', 'EcoICRI', 'BamHI', 'SfaNI', 'HpaI', 'PspCI', 'HindII'], + ['BssMI', 'AsuNHI', 'MluI', 'BstHHI', 'HpaII', 'AhlI', 'BglI', 'SalI', 'PspEI', 'MspI', 'VneI', 'BstH2I', 'BmtI', 'AsiGI', 'CciNI', 'Sfr274I', 'SmiI', 'Ksp22I', 'BssT1I', 'MspA1I', 'Bsp19I', 'Bse1I', 'AspS9I', 'BmcAI', 'FauNDI', 'DraI', 'Bst2UI', 'Vha464I', 'BstXI', 'BstDEI', 'XmaI', 'BstF5I', 'BpvUI', 'BstENI', 'Ama87I', 'BstDSI', 'BstV2I', 'AspLEI', 'Zsp2I', 'DseDI', 'BstAUI', 'Bpu14I', 'TaqI', 'KpnI', 'BstSNI', 'MboII', 'BmrFI', 'BmeRI', 'BseX3I', 'Bpu10I', 'Rsr2I', 'BtuMI', 'Bst2BI', 'SmiMI', 'Bse118I', 'BsnI', 'BmiI', 'BsePI', 'BstMCI', 'Bme18I', 'RsaI', 'BssNAI', 'Bsp13I', 'Bst4CI', 'AsuHPI', 'XbaI', 'Psp124BI', 'BstX2I', 'AluI', 'ZraI', 'Bse21I', 'Sfr303I', 'BpuMI', 'Bse3DI', 'Bso31I', 'SmaI', 'AspA2I', 'Bsp1720I', 'SphI', 'FriOI', 'ErhI', 'BshVI', 'FokI', 'HinfI', 'BstPAI', 'HspAI', 'DraIII', 'EcoRV', 'MroXI', 'EcoRI', 'DinI', 'BstFNI', 'AfiI', 'MnlI', 'SbfI', 'PstI', 'Bse8I', 'VspI', 'SfiI', 'Bst6I', 'Msp20I', 'Bbv12I', 'SspI', 'Tth111I', 'BstMBI', 'PspOMI', 'BstMAI', 'ApaI', 'FblI', 'PctI', 'BssNI', 'PceI', 'Sse9I', 'Tru9I', 'MhlI', 'BstBAI', 'MroNI', 'HindIII', 'EcoICRI', 'BamHI', 'SfaNI', 'HpaI', 'PspCI', 'HindII'], ) suppliers['V'] = _temp() def _temp(): return ( - 'MP Biomedicals', - ['MluI', 'HpaII', 'BclI', 'SacI', 'BglI', 'SalI', 'MspI', 'BanII', 'BstEII', 'NcoI', 'DraII', 'XmnI', 'Eco47III', 'DraI', 'BstXI', 'SwaI', 'AvaI', 'PvuI', 'DpnI', 'TaqI', 'SinI', 'KpnI', 'Sau96I', 'HaeII', 'NdeI', 'MboII', 'BglII', 'SacII', 'Acc65I', 'BspXI', 'NruI', 'MvaI', 'NarI', 'RsaI', 'HincII', 'AflIII', 'XbaI', 'Sau3AI', 'MboI', 'AluI', 'SmaI', 'NheI', 'XhoII', 'SphI', 'NciI', 'PvuII', 'FokI', 'SpeI', 'HinfI', 'DraIII', 'EcoRV', 'EcoRI', 'XhoI', 'MnlI', 'AccIII', 'EagI', 'AscI', 'NlaIII', 'PstI', 'BsmI', 'SfiI', 'HaeIII', 'NdeII', 'AccI', 'SspI', 'Tth111I', 'NsiI', 'PmeI', 'ApaI', 'ScaI', 'PacI', 'NlaIV', 'Tru9I', 'DdeI', 'NotI', 'HindIII', 'BamHI', 'BslI', 'AvaII', 'HpaI', 'HhaI'], - ) -suppliers['W'] = _temp() - -def _temp(): - return ( 'EURx Ltd.', - ['BssHII', 'MluI', 'HpaII', 'BspTNI', 'SacI', 'BglI', 'SalI', 'MspI', 'BanII', 'NcoI', 'CviJI', 'DraI', 'BstXI', 'AcvI', 'AvaI', 'PvuI', 'DpnI', 'TaqI', 'SinI', 'KpnI', 'NdeI', 'PinAI', 'MboII', 'BglII', 'SacII', 'NruI', 'NarI', 'TaqII', 'RsaI', 'HincII', 'XbaI', 'Sau3AI', 'TspGWI', 'MboI', 'AluI', 'RsrII', 'SmaI', 'StuI', 'SphI', 'PvuII', 'FokI', 'SpeI', 'HinfI', 'BsiHKCI', 'EcoRV', 'EcoRI', 'XhoI', 'MnlI', 'PstI', 'SfiI', 'HaeIII', 'AccI', 'SspI', 'Tth111I', 'ApaI', 'MmeI', 'ScaI', 'TspDTI', 'BalI', 'NotI', 'HindIII', 'BamHI', 'BsuTUI', 'HpaI'], + ['BssHII', 'MluI', 'HpaII', 'SacI', 'BglI', 'SalI', 'MspI', 'BanII', 'NcoI', 'ClaI', 'CviJI', 'DraI', 'BstXI', 'AcvI', 'AvaI', 'PvuI', 'DpnI', 'TaqI', 'KpnI', 'NdeI', 'PinAI', 'MboII', 'BglII', 'SacII', 'NruI', 'NarI', 'TaqII', 'RsaI', 'HincII', 'XbaI', 'TspGWI', 'MboI', 'AluI', 'RsrII', 'SmaI', 'NheI', 'StuI', 'SphI', 'PvuII', 'FokI', 'SpeI', 'HinfI', 'BsiHKCI', 'EcoRV', 'EcoRI', 'XhoI', 'MnlI', 'PstI', 'SfiI', 'HaeIII', 'AccI', 'SspI', 'Tth111I', 'NsiI', 'ApaI', 'ScaI', 'TspDTI', 'BalI', 'DdeI', 'NotI', 'HindIII', 'BamHI', 'AvaII', 'HpaI', 'HhaI'], ) suppliers['X'] = _temp() def _temp(): return ( - 'CinnaGen Inc.', + 'SinaClon BioScience Co.', ['BclI', 'BglI', 'SalI', 'MspI', 'NcoI', 'DraI', 'PvuI', 'TaqI', 'KpnI', 'NdeI', 'BglII', 'RsaI', 'HincII', 'XbaI', 'MboI', 'AluI', 'SmaI', 'PvuII', 'HinfI', 'EcoRV', 'EcoRI', 'XhoI', 'PstI', 'HaeIII', 'NotI', 'HindIII', 'BamHI', 'AvaII', 'HhaI'], ) suppliers['Y'] = _temp() @@ -16721,184 +17257,346 @@ typedict = {} def _temp(): return ( + ('Palindromic', 'TwoCuts', 'Ov5', 'Ambiguous', 'Meth_Dep', 'Not_available', 'AbstractCut', 'RestrictionType'), + ['NmeDI'], + ) +typedict['type130'] = _temp() + +def _temp(): + return ( + ('Palindromic', 'TwoCuts', 'Ov5', 'Ambiguous', 'Meth_Undep', 'Not_available', 'AbstractCut', 'RestrictionType'), + ['UcoMSI'], + ) +typedict['type132'] = _temp() + +def _temp(): + return ( + ('Palindromic', 'TwoCuts', 'Ov3', 'Ambiguous', 'Meth_Dep', 'Not_available', 'AbstractCut', 'RestrictionType'), + ['RdeGBIII'], + ) +typedict['type142'] = _temp() + +def _temp(): + return ( + ('Palindromic', 'TwoCuts', 'Ov3', 'Ambiguous', 'Meth_Undep', 'Commercially_available', 'AbstractCut', 'RestrictionType'), + ['FalI', 'BplI', 'AlfI'], + ) +typedict['type143'] = _temp() + +def _temp(): + return ( + ('Palindromic', 'TwoCuts', 'Ov3', 'Ambiguous', 'Meth_Undep', 'Not_available', 'AbstractCut', 'RestrictionType'), + ['BdaI'], + ) +typedict['type144'] = _temp() + +def _temp(): + return ( ('NonPalindromic', 'NoCut', 'Unknown', 'NotDefined', 'Meth_Dep', 'Not_available', 'AbstractCut', 'RestrictionType'), - ['BscGI', 'AspCNI'], + ['SpoDI', 'Cgl13032I', 'Cdi630V', 'EsaSSI', 'RflFIII', 'Cgl13032II', 'CjeFV', 'BscGI', 'Sno506I', 'Hpy99XIV', 'RdeGBI', 'Hpy99XIII', 'CjeFIII', 'GauT27I', 'DrdII', 'NhaXI', 'RpaTI', 'MkaDII', 'Jma19592I', 'CjeNII'], ) typedict['type146'] = _temp() def _temp(): return ( ('NonPalindromic', 'NoCut', 'Unknown', 'NotDefined', 'Meth_Undep', 'Not_available', 'AbstractCut', 'RestrictionType'), - ['SpoDI', 'UbaF14I', 'EsaSSI', 'UbaPI', 'CjuII', 'AlwFI', 'BspGI', 'CjuI', 'MjaIV', 'Pfl1108I', 'AvaIII', 'UbaF13I', 'TssI', 'UbaF12I', 'DrdII', 'NhaXI', 'BspNCI', 'TsuI', 'UbaF9I', 'FinI', 'UbaF11I', 'CjeNII', 'BmgI', 'SnaI', 'HgiEII'], + ['UbaF14I', 'CjeP659IV', 'UbaPI', 'CjuII', 'AlwFI', 'BspGI', 'Pfl1108I', 'UbaF13I', 'RlaI', 'PenI', 'UbaF12I', 'BspNCI', 'TsuI', 'UbaF9I', 'FinI', 'UbaF11I', 'BmgI'], ) typedict['type148'] = _temp() def _temp(): return ( - ('NonPalindromic', 'OneCut', 'Blunt', 'Defined', 'Meth_Dep', 'Commercially_available', 'AbstractCut', 'RestrictionType'), - ['MlyI', 'BmgBI', 'SnaBI', 'MspA1I', 'CviJI', 'BsrBI', 'DraI', 'PshAI', 'SwaI', 'NaeI', 'PhoI', 'SfoI', 'RsaI', 'HincII', 'AluI', 'Hpy8I', 'SmaI', 'FspI', 'PvuII', 'BsuRI', 'EcoRV', 'BstUI', 'HaeIII', 'SspI', 'ScaI', 'BalI', 'NlaIV', 'HpaI', 'Cac8I', 'HindII', 'BsaAI'], + ('Palindromic', 'NoCut', 'Unknown', 'NotDefined', 'Meth_Dep', 'Not_available', 'AbstractCut', 'RestrictionType'), + ['MjaIV'], ) -typedict['type209'] = _temp() +typedict['type2'] = _temp() def _temp(): return ( - ('NonPalindromic', 'OneCut', 'Blunt', 'Defined', 'Meth_Dep', 'Not_available', 'AbstractCut', 'RestrictionType'), - ['FnuDII', 'EsaBC3I', 'CviRI'], + ('NonPalindromic', 'OneCut', 'Blunt', 'Defined', 'Meth_Dep', 'Commercially_available', 'AbstractCut', 'RestrictionType'), + ['MlyI', 'BsrBI'], ) -typedict['type210'] = _temp() +typedict['type209'] = _temp() def _temp(): return ( ('NonPalindromic', 'OneCut', 'Blunt', 'Defined', 'Meth_Undep', 'Commercially_available', 'AbstractCut', 'RestrictionType'), - ['PspN4I', 'MslI', 'Bsp68I', 'PmaCI', 'BsaBI', 'SmiI', 'BseJI', 'BshFI', 'BmcAI', 'XmnI', 'Eco47III', 'Hpy166II', 'AluBI', 'AcvI', 'RruI', 'EgeI', 'RseI', 'DpnI', 'AssI', 'Bst1107I', 'BstSNI', 'MlsI', 'SchI', 'AccII', 'BtuMI', 'Aor51HI', 'NruI', 'SmiMI', 'Bsh1236I', 'MalI', 'MssI', 'BsnI', 'FspAI', 'BmiI', 'BoxI', 'BssNAI', 'BtrI', 'BstC8I', 'AjiI', 'PmlI', 'GlaI', 'MvnI', 'ZraI', 'Eco72I', 'MscI', 'SseBI', 'AccBSI', 'Ppu21I', 'StuI', 'BbrPI', 'Eco53kI', 'EheI', 'BstPAI', 'Ecl136II', 'Acc16I', 'MluNI', 'PsiI', 'MroXI', 'AatI', 'ZrmI', 'DinI', 'BstFNI', 'BspLI', 'Eco105I', 'NsbI', 'Bse8I', 'BspFNI', 'BstZ17I', 'Msp20I', 'AfeI', 'SrfI', 'Eco32I', 'KspAI', 'AanI', 'PmeI', 'FaiI', 'Eco147I', 'CviKI_1', 'OliI', 'PdmI', 'HpyCH4V', 'PceI', 'BstBAI', 'AfaI', 'MbiI', 'Asp700I', 'EcoICRI', 'AviII', 'PspCI', 'PdiI', 'AleI'], + ['BmgBI', 'SchI', 'BtrI', 'AjiI', 'AccBSI', 'MbiI'], ) typedict['type211'] = _temp() def _temp(): return ( ('NonPalindromic', 'OneCut', 'Blunt', 'Defined', 'Meth_Undep', 'Not_available', 'AbstractCut', 'RestrictionType'), - ['CdiI', 'HaeI', 'SciI', 'NspBII', 'SspD5I', 'LpnI', 'AhaIII', 'Sth302II', 'MstI'], + ['CdiI', 'SspD5I'], ) typedict['type212'] = _temp() def _temp(): return ( ('NonPalindromic', 'OneCut', 'Ov5', 'Defined', 'Meth_Dep', 'Commercially_available', 'AbstractCut', 'RestrictionType'), - ['BssHII', 'BsrFI', 'DpnII', 'MluI', 'NgoMIV', 'HpaII', 'TspMI', 'BclI', 'BsaWI', 'SalI', 'MspI', 'Bsu15I', 'NcoI', 'ClaI', 'XmaI', 'Cfr9I', 'TaqI', 'EaeI', 'AseI', 'Kpn2I', 'AclI', 'ApoI', 'HpyCH4IV', 'NdeI', 'HapII', 'BglII', 'BsaHI', 'XbaI', 'Sau3AI', 'Cfr10I', 'MboI', 'AciI', 'CviQI', 'XhoII', 'CviAII', 'MfeI', 'BssSI', 'ApaLI', 'HinP1I', 'HspAI', 'EcoRI', 'XhoI', 'BseCI', 'CfrI', 'MunI', 'EagI', 'AscI', 'Tsp509I', 'MseI', 'VspI', 'KasI', 'SgrAI', 'BspHI', 'BstYI', 'AgeI', 'Sse9I', 'NotI', 'HindIII', 'FatI', 'BamHI', 'PaeR7I', 'BbvCI'], + ['AciI', 'BspACI', 'BssSI', 'BbvCI'], ) typedict['type221'] = _temp() def _temp(): return ( - ('NonPalindromic', 'OneCut', 'Ov5', 'Defined', 'Meth_Dep', 'Not_available', 'AbstractCut', 'RestrictionType'), - ['XmaIII'], - ) -typedict['type222'] = _temp() - -def _temp(): - return ( ('NonPalindromic', 'OneCut', 'Ov5', 'Defined', 'Meth_Undep', 'Commercially_available', 'AbstractCut', 'RestrictionType'), - ['BssMI', 'AsuNHI', 'CciI', 'PscI', 'MreI', 'AhlI', 'XspI', 'BfaI', 'PauI', 'Asp718I', 'VneI', 'PspXI', 'AsiGI', 'CciNI', 'Sfr274I', 'PteI', 'XmaCI', 'Ksp22I', 'BshTI', 'Bsp19I', 'MauBI', 'AbsI', 'AsuII', 'FauNDI', 'Vha464I', 'BstACI', 'BspACI', 'AcoI', 'BstMBI', 'BssAI', 'BseAI', 'Hin6I', 'PalAI', 'BstAUI', 'BsiWI', 'Bpu14I', 'Eco52I', 'BspT104I', 'SspDI', 'SsiI', 'PinAI', 'AflII', 'TspEI', 'AcsI', 'BseX3I', 'FspBI', 'RsaNI', 'Acc65I', 'AvrII', 'MaeI', 'XapI', 'BspXI', 'Bsp1407I', 'Bst2BI', 'PciI', 'Bse118I', 'SlaI', 'TliI', 'NarI', 'BsePI', 'Bst98I', 'MaeII', 'Bsp13I', 'BsiSI', 'StrI', 'Bsp119I', 'BanIII', 'BstX2I', 'SgsI', 'BseYI', 'Csp45I', 'PsuI', 'NheI', 'AspA2I', 'BcuI', 'BspTI', 'Mly113I', 'MflI', 'BshVI', 'Hin1I', 'SpeI', 'SgrDI', 'XmaJI', 'MspCI', 'Psp1406I', 'Kzo9I', 'Csp6I', 'Bsp143I', 'PspOMI', 'Bsa29I', 'AccIII', 'Tru1I', 'Aor13HI', 'EclXI', 'BspEI', 'BstZI', 'Alw44I', 'Hsp92I', 'PspLI', 'BlnI', 'NdeII', 'BsrGI', 'CspAI', 'FbaI', 'BauI', 'SaqAI', 'PshBI', 'SfuI', 'NspV', 'BfuCI', 'BfrI', 'BstBI', 'BssNI', 'Tru9I', 'Bsp120I', 'MroI', 'MroNI', 'AcyI', 'RcaI', 'BsuTUI', 'BspDI', 'BstAFI', 'TatI', 'Pfl23II', 'PagI'], + ['SsiI', 'Bst2BI', 'BseYI', 'BauI'], ) typedict['type223'] = _temp() def _temp(): return ( ('NonPalindromic', 'OneCut', 'Ov5', 'Defined', 'Meth_Undep', 'Not_available', 'AbstractCut', 'RestrictionType'), - ['SelI', 'BspLU11I', 'SimI', 'Asi256I', 'Ppu10I', 'Sse232I', 'BetI', 'SplI', 'GdiII', 'BsiI', 'BspMII'], + ['SimI', 'GdiII', 'BsiI'], ) typedict['type224'] = _temp() def _temp(): return ( ('NonPalindromic', 'OneCut', 'Ov5', 'Ambiguous', 'Meth_Dep', 'Commercially_available', 'AbstractCut', 'RestrictionType'), - ['AlwI', 'PspPI', 'StyD4I', 'PspGI', 'BlpI', 'Esp3I', 'AvaI', 'SexAI', 'SinI', 'Sau96I', 'BstNI', 'Cfr13I', 'TseI', 'Bpu10I', 'MvaI', 'BssKI', 'AflIII', 'Lsp1109I', 'BfuAI', 'TfiI', 'BbvI', 'HgaI', 'BanI', 'RsrII', 'BspMI', 'BcnI', 'ScrFI', 'EcoRII', 'FokI', 'Alw26I', 'ApeKI', 'Eco31I', 'HinfI', 'BceAI', 'Fsp4HI', 'BsmAI', 'EcoO109I', 'PpuMI', 'BsmFI', 'BsoBI', 'BsmBI', 'AccI', 'Tth111I', 'DdeI', 'AvaII', 'BsaJI', 'Fnu4HI', 'Tsp45I'], + ['AlwI', 'Esp3I', 'Bpu10I', 'Lsp1109I', 'BfuAI', 'BbvI', 'HgaI', 'BspMI', 'BccI', 'FokI', 'Alw26I', 'Eco31I', 'BceAI', 'BsmAI', 'BsmFI', 'FauI', 'BsmBI', 'BtgZI'], ) typedict['type225'] = _temp() def _temp(): return ( ('NonPalindromic', 'OneCut', 'Ov5', 'Ambiguous', 'Meth_Dep', 'Not_available', 'AbstractCut', 'RestrictionType'), - ['StsI', 'HgiCI', 'EcoHI'], + ['StsI'], ) typedict['type226'] = _temp() def _temp(): return ( ('NonPalindromic', 'OneCut', 'Ov5', 'Ambiguous', 'Meth_Undep', 'Commercially_available', 'AbstractCut', 'RestrictionType'), - ['AxyI', 'BstSFI', 'CseI', 'SanDI', 'BspTNI', 'BspT107I', 'BstOI', 'BisI', 'BstPI', 'LweI', 'BstEII', 'BmgT120I', 'BssT1I', 'PsyI', 'BtgI', 'AspS9I', 'BsaI', 'DraII', 'AclWI', 'Eco91I', 'Bst2UI', 'BseXI', 'BstDEI', 'GluI', 'BstENI', 'BssECI', 'Ama87I', 'BstDSI', 'BstV2I', 'AarI', 'AjnI', 'PflFI', 'Bme1390I', 'BveI', 'Psp5II', 'EcoO65I', 'BmrFI', 'EcoT14I', 'BmsI', 'PspPPI', 'SmlI', 'BseBI', 'PfoI', 'BshNI', 'Rsr2I', 'BspQI', 'BmeT110I', 'PspEI', 'AspI', 'BpuAI', 'PasI', 'CpoI', 'Eco130I', 'CspI', 'BfmI', 'Eco47I', 'Bsu36I', 'Bme18I', 'BstV1I', 'MabI', 'Hpy188III', 'Bse21I', 'BstSCI', 'BpuMI', 'XagI', 'Bso31I', 'PleI', 'EcoNI', 'BccI', 'SmoI', 'FaqI', 'Bsp1720I', 'NciI', 'MaeIII', 'ErhI', 'AsuC2I', 'PpsI', 'BsiHKCI', 'XmiI', 'Eam1104I', 'Acc36I', 'MspR9I', 'SapI', 'VpaK11BI', 'BspPI', 'BslFI', 'PfeI', 'Bpu1102I', 'SmuI', 'FauI', 'SfcI', 'LguI', 'PciSI', 'Bst6I', 'BpiI', 'SatI', 'KflI', 'BseDI', 'Eco81I', 'ItaI', 'BstMAI', 'Eco88I', 'FblI', 'BtgZI', 'EarI', 'AccB1I', 'CsiI', 'BbsI', 'Psp6I', 'CelII', 'SfaNI', 'HpyF3I', 'StyI', 'NmuCI'], + ['CseI', 'LweI', 'BsaI', 'AclWI', 'BseXI', 'BstV2I', 'AarI', 'BveI', 'BmsI', 'BspQI', 'MspJI', 'BstV1I', 'Bso31I', 'PleI', 'FaqI', 'FspEI', 'BcoDI', 'PpsI', 'Eam1104I', 'Acc36I', 'SapI', 'BspPI', 'BslFI', 'LguI', 'PciSI', 'Bst6I', 'BpiI', 'LpnPI', 'BstMAI', 'EarI', 'BbsI', 'SfaNI'], ) typedict['type227'] = _temp() def _temp(): return ( ('NonPalindromic', 'OneCut', 'Ov5', 'Ambiguous', 'Meth_Undep', 'Not_available', 'AbstractCut', 'RestrictionType'), - ['DsaI', 'SauI', 'Sth132I', 'UnbI', 'BbvII', 'VpaK11AI', 'BinI', 'Bbr7I', 'SfeI', 'CauII', 'BscAI', 'Hpy178III', 'BspD6I', 'BcefI', 'AceIII', 'Ksp632I', 'AsuI', 'SecI', 'EspI', 'Sse8647I'], + ['SgrTI', 'Sth132I', 'BbvII', 'BinI', 'AspBHI', 'Bbr7I', 'BscAI', 'BspD6I', 'BcefI', 'AceIII', 'Ksp632I'], ) typedict['type228'] = _temp() def _temp(): return ( - ('NonPalindromic', 'OneCut', 'Ov3', 'Defined', 'Meth_Dep', 'Commercially_available', 'AbstractCut', 'RestrictionType'), - ['SacI', 'BmtI', 'KpnI', 'HaeII', 'SacII', 'NlaIII', 'PstI', 'Cfr42I', 'FseI', 'ApaI', 'NspI', 'HhaI', 'AsiSI'], - ) -typedict['type233'] = _temp() - -def _temp(): - return ( - ('NonPalindromic', 'OneCut', 'Ov3', 'Defined', 'Meth_Dep', 'Not_available', 'AbstractCut', 'RestrictionType'), - ['PabI', 'McaTI'], - ) -typedict['type234'] = _temp() - -def _temp(): - return ( ('NonPalindromic', 'OneCut', 'Ov3', 'Defined', 'Meth_Undep', 'Commercially_available', 'AbstractCut', 'RestrictionType'), - ['SgrBI', 'BstHHI', 'BstH2I', 'BpvUI', 'SstII', 'PvuI', 'BspOI', 'BbuI', 'AspLEI', 'Zsp2I', 'FaeI', 'SdaI', 'BstNSI', 'Ple19I', 'Hin1II', 'Sse8387I', 'TaiI', 'Psp124BI', 'Sfr303I', 'Mph1103I', 'CfoI', 'PaeI', 'BstKTI', 'SphI', 'SstI', 'GsaI', 'MvrI', 'SfaAI', 'RgaI', 'BbeI', 'SgfI', 'AatII', 'SbfI', 'XceI', 'NsiI', 'EcoT22I', 'PacI', 'KspI', 'Hsp92II', 'BfoI', 'RigI'], + ['GsaI'], ) typedict['type235'] = _temp() def _temp(): return ( - ('NonPalindromic', 'OneCut', 'Ov3', 'Defined', 'Meth_Undep', 'Not_available', 'AbstractCut', 'RestrictionType'), - ['ChaI'], - ) -typedict['type236'] = _temp() - -def _temp(): - return ( ('NonPalindromic', 'OneCut', 'Ov3', 'Ambiguous', 'Meth_Dep', 'Commercially_available', 'AbstractCut', 'RestrictionType'), - ['MwoI', 'EcoT38I', 'BglI', 'BanII', 'TspRI', 'Hpy99I', 'BsiHKAI', 'BstF5I', 'BsrI', 'BfiI', 'MboII', 'BmrI', 'Hpy188I', 'Bsc4I', 'BspCNI', 'HpyAV', 'HphI', 'DraIII', 'Bsp1286I', 'MnlI', 'SfiI', 'XcmI', 'MmeI', 'Eco57I', 'BslI'], + ['BstF5I', 'BpuEI', 'BsrI', 'MboII', 'TaqII', 'BspCNI', 'BsgI', 'TspGWI', 'BmrI', 'HpyAV', 'HphI', 'BseMII', 'MnlI', 'BseRI', 'MmeI', 'Eco57I', 'BpmI', 'AcuI', 'NmeAIII'], ) typedict['type237'] = _temp() def _temp(): return ( ('NonPalindromic', 'OneCut', 'Ov3', 'Ambiguous', 'Meth_Dep', 'Not_available', 'AbstractCut', 'RestrictionType'), - ['BthCI'], + ['RpaBI', 'DraRI', 'SdeAI', 'RceI', 'WviI', 'BfiI', 'CstMI', 'PspOMII', 'CchII', 'PlaDI', 'SstE37I', 'RpaB5I', 'MaqI', 'CdpI', 'CchIII', 'Tth111II', 'CjeNIII', 'NlaCI', 'AquII', 'AquIV', 'ApyPI', 'RpaI', 'PspPRI', 'AquIII', 'RdeGBII'], ) typedict['type238'] = _temp() def _temp(): return ( ('NonPalindromic', 'OneCut', 'Ov3', 'Ambiguous', 'Meth_Undep', 'Commercially_available', 'AbstractCut', 'RestrictionType'), - ['EciI', 'AgsI', 'DrdI', 'Mva1269I', 'TscAI', 'Bse1I', 'BstMWI', 'Eco24I', 'AlwNI', 'BstXI', 'BseSI', 'BpuEI', 'Van91I', 'DseDI', 'SetI', 'BmeRI', 'TaaI', 'BtsCI', 'BstMCI', 'TaqII', 'HpyF10VI', 'Bst4CI', 'AsuHPI', 'AspEI', 'BsgI', 'BsrSI', 'TspGWI', 'BaeGI', 'SduI', 'BseGI', 'Alw21I', 'Bse3DI', 'AccB7I', 'BasI', 'AdeI', 'BsiEI', 'GsuI', 'BseLI', 'FriOI', 'AasI', 'BsrDI', 'BciVI', 'Eam1105I', 'TsoI', 'BseMII', 'BtsI', 'BfuI', 'TauI', 'AfiI', 'CaiI', 'AhdI', 'BsmI', 'Bbv12I', 'BseMI', 'Eco57MI', 'BstAPI', 'HpyCH4III', 'BstSLI', 'BlsI', 'BseRI', 'TspDTI', 'BmuI', 'PctI', 'BpmI', 'BsaMI', 'AcuI', 'MhlI', 'DriI', 'Bsh1285I', 'PflMI', 'BseNI', 'NmeAIII'], + ['EciI', 'Mva1269I', 'Bse1I', 'BtsIMutI', 'BtsCI', 'BsuI', 'AsuHPI', 'BsrSI', 'BseGI', 'Bse3DI', 'GsuI', 'BsrDI', 'AbaSI', 'BciVI', 'BtsI', 'BfuI', 'BsmI', 'BseMI', 'TspDTI', 'BmuI', 'PctI', 'BseNI'], ) typedict['type239'] = _temp() def _temp(): return ( ('NonPalindromic', 'OneCut', 'Ov3', 'Ambiguous', 'Meth_Undep', 'Not_available', 'AbstractCut', 'RestrictionType'), - ['Nli3877I', 'Bce83I', 'SdeAI', 'Psp03I', 'RceI', 'DraRI', 'BsiYI', 'ApaBI', 'Tsp4CI', 'Hin4II', 'CstMI', 'PspOMII', 'DrdIV', 'PlaDI', 'FmuI', 'RpaB5I', 'McrI', 'MaqI', 'CdpI', 'Tth111II', 'HgiJII', 'BsbI', 'NlaCI', 'AquII', 'AquIV', 'ApyPI', 'PspPRI', 'AquIII', 'PssI', 'HgiAI', 'RleAI'], + ['BmeDI', 'Bce83I', 'Hin4II', 'TsoI', 'Eco57MI', 'BsbI', 'YkrI', 'RleAI'], ) typedict['type240'] = _temp() def _temp(): return ( ('NonPalindromic', 'TwoCuts', 'Ov5', 'Ambiguous', 'Meth_Dep', 'Not_available', 'AbstractCut', 'RestrictionType'), - ['NmeDI'], + ['R2_BceSIV'], ) typedict['type274'] = _temp() def _temp(): return ( ('NonPalindromic', 'TwoCuts', 'Ov3', 'Ambiguous', 'Meth_Dep', 'Commercially_available', 'AbstractCut', 'RestrictionType'), - ['AloI', 'BcgI'], + ['CspCI', 'AloI', 'BcgI'], ) typedict['type285'] = _temp() def _temp(): return ( + ('NonPalindromic', 'TwoCuts', 'Ov3', 'Ambiguous', 'Meth_Dep', 'Not_available', 'AbstractCut', 'RestrictionType'), + ['TstI', 'NgoAVIII', 'PpiI', 'SdeOSI', 'CjeI'], + ) +typedict['type286'] = _temp() + +def _temp(): + return ( ('NonPalindromic', 'TwoCuts', 'Ov3', 'Ambiguous', 'Meth_Undep', 'Commercially_available', 'AbstractCut', 'RestrictionType'), - ['TstI', 'PsrI', 'FalI', 'CspCI', 'PpiI', 'AjuI', 'BaeI', 'BdaI', 'ArsI', 'BplI', 'Hin4I', 'AlfI', 'BarI', 'BsaXI'], + ['PsrI', 'AjuI', 'BaeI', 'ArsI', 'BarI', 'BsaXI'], ) typedict['type287'] = _temp() def _temp(): return ( ('NonPalindromic', 'TwoCuts', 'Ov3', 'Ambiguous', 'Meth_Undep', 'Not_available', 'AbstractCut', 'RestrictionType'), - ['CjeI', 'CjePI', 'NgoAVIII', 'Bsp24I', 'SdeOSI'], + ['CjePI', 'Bsp24I', 'Hin4I'], ) typedict['type288'] = _temp() +def _temp(): + return ( + ('Palindromic', 'NoCut', 'Unknown', 'NotDefined', 'Meth_Undep', 'Not_available', 'AbstractCut', 'RestrictionType'), + ['CjuI', 'AvaIII', 'TssI', 'SnaI', 'HgiEII'], + ) +typedict['type4'] = _temp() + +def _temp(): + return ( + ('Palindromic', 'OneCut', 'Blunt', 'Defined', 'Meth_Dep', 'Commercially_available', 'AbstractCut', 'RestrictionType'), + ['SnaBI', 'MspA1I', 'CviJI', 'DraI', 'PshAI', 'SwaI', 'NaeI', 'RsaI', 'HincII', 'BstC8I', 'PmlI', 'AluI', 'Hpy8I', 'SmaI', 'FspI', 'PvuII', 'BsuRI', 'EcoRV', 'BstUI', 'HaeIII', 'SspI', 'ScaI', 'BalI', 'NlaIV', 'HpaI', 'Cac8I', 'HindII', 'BsaAI'], + ) +typedict['type65'] = _temp() + +def _temp(): + return ( + ('Palindromic', 'OneCut', 'Blunt', 'Defined', 'Meth_Dep', 'Not_available', 'AbstractCut', 'RestrictionType'), + ['FnuDII', 'EsaBC3I', 'CviRI'], + ) +typedict['type66'] = _temp() + +def _temp(): + return ( + ('Palindromic', 'OneCut', 'Blunt', 'Defined', 'Meth_Undep', 'Commercially_available', 'AbstractCut', 'RestrictionType'), + ['PspN4I', 'MslI', 'Bsp68I', 'PmaCI', 'BsaBI', 'SmiI', 'BseJI', 'BshFI', 'BmcAI', 'XmnI', 'Eco47III', 'Hpy166II', 'AluBI', 'AcvI', 'RruI', 'EgeI', 'RseI', 'DpnI', 'AssI', 'Bst1107I', 'BstSNI', 'MlsI', 'AccII', 'BtuMI', 'Aor51HI', 'NruI', 'SmiMI', 'Bsh1236I', 'MalI', 'MssI', 'BsnI', 'SfoI', 'FspAI', 'BmiI', 'BoxI', 'BssNAI', 'GlaI', 'MvnI', 'ZraI', 'Eco72I', 'MscI', 'SseBI', 'Ppu21I', 'StuI', 'BbrPI', 'Eco53kI', 'EheI', 'BstPAI', 'Ecl136II', 'Acc16I', 'MluNI', 'PsiI', 'MroXI', 'ZrmI', 'DinI', 'BstFNI', 'BspLI', 'Eco105I', 'NsbI', 'Bse8I', 'BspFNI', 'BstZ17I', 'Msp20I', 'AfeI', 'Eco32I', 'KspAI', 'AanI', 'PmeI', 'FaiI', 'Eco147I', 'CviKI_1', 'OliI', 'PdmI', 'HpyCH4V', 'PceI', 'BstBAI', 'AfaI', 'Asp700I', 'EcoICRI', 'PspCI', 'PdiI', 'AleI'], + ) +typedict['type67'] = _temp() + +def _temp(): + return ( + ('Palindromic', 'OneCut', 'Blunt', 'Defined', 'Meth_Undep', 'Not_available', 'AbstractCut', 'RestrictionType'), + ['NspBII', 'HaeI', 'SciI', 'LpnI', 'SrfI', 'AhaIII', 'Sth302II', 'MstI'], + ) +typedict['type68'] = _temp() + +def _temp(): + return ( + ('Palindromic', 'OneCut', 'Ov5', 'Defined', 'Meth_Dep', 'Commercially_available', 'AbstractCut', 'RestrictionType'), + ['BssHII', 'BsrFI', 'DpnII', 'MluI', 'NgoMIV', 'HpaII', 'Cfr9I', 'BclI', 'BsaWI', 'SalI', 'MspI', 'Bsu15I', 'NcoI', 'ClaI', 'XmaI', 'TaqI', 'EaeI', 'AseI', 'AclI', 'ApoI', 'HpyCH4IV', 'NdeI', 'HapII', 'BglII', 'MseI', 'BsaHI', 'XbaI', 'Sau3AI', 'Cfr10I', 'MboI', 'CviQI', 'CviAII', 'MfeI', 'ApaLI', 'HinP1I', 'HspAI', 'EcoRI', 'XhoI', 'BseCI', 'MunI', 'EagI', 'AscI', 'VspI', 'KasI', 'Kpn2I', 'BspHI', 'BstYI', 'AgeI', 'BfuCI', 'XhoII', 'Sse9I', 'NotI', 'HindIII', 'FatI', 'BamHI', 'PaeR7I'], + ) +typedict['type77'] = _temp() + +def _temp(): + return ( + ('Palindromic', 'OneCut', 'Ov5', 'Defined', 'Meth_Dep', 'Not_available', 'AbstractCut', 'RestrictionType'), + ['XmaIII', 'CfrI'], + ) +typedict['type78'] = _temp() + +def _temp(): + return ( + ('Palindromic', 'OneCut', 'Ov5', 'Defined', 'Meth_Undep', 'Commercially_available', 'AbstractCut', 'RestrictionType'), + ['BssMI', 'AsuNHI', 'CciI', 'TspMI', 'MreI', 'AhlI', 'XspI', 'KroI', 'BfaI', 'PauI', 'Asp718I', 'VneI', 'PspXI', 'AsiGI', 'CciNI', 'Sfr274I', 'PteI', 'Ksp22I', 'BshTI', 'Bsp19I', 'MauBI', 'AbsI', 'AsuII', 'FauNDI', 'Vha464I', 'BstACI', 'AcoI', 'BssAI', 'BseAI', 'Hin6I', 'PalAI', 'BstAUI', 'Bpu14I', 'Eco52I', 'BspT104I', 'SspDI', 'PinAI', 'AflII', 'TasI', 'AcsI', 'BseX3I', 'FspBI', 'RsaNI', 'Acc65I', 'AvrII', 'MaeI', 'XapI', 'PscI', 'Bsp1407I', 'PciI', 'Bse118I', 'SlaI', 'NarI', 'BsePI', 'MaeII', 'Bsp13I', 'BsiSI', 'StrI', 'Bsp119I', 'BstX2I', 'SgsI', 'MluCI', 'PsuI', 'NheI', 'AspA2I', 'BcuI', 'BspTI', 'BsiWI', 'Mly113I', 'MflI', 'BshVI', 'Hin1I', 'SpeI', 'SgrDI', 'XmaJI', 'MspCI', 'Psp1406I', 'Kzo9I', 'Csp6I', 'Bsp143I', 'Bsa29I', 'AccIII', 'Tru1I', 'Aor13HI', 'EclXI', 'BspEI', 'BstZI', 'Alw44I', 'Hsp92I', 'PspLI', 'BlnI', 'NdeII', 'BsrGI', 'CspAI', 'FbaI', 'SgrAI', 'BstMBI', 'PspOMI', 'SaqAI', 'PshBI', 'SfuI', 'NspV', 'BfrI', 'BstBI', 'BssNI', 'HpySE526I', 'Tru9I', 'Bsp120I', 'MroI', 'MroNI', 'AcyI', 'BspDI', 'BstAFI', 'TatI', 'Pfl23II', 'PagI'], + ) +typedict['type79'] = _temp() + +def _temp(): + return ( + ('Palindromic', 'OneCut', 'Ov5', 'Defined', 'Meth_Undep', 'Not_available', 'AbstractCut', 'RestrictionType'), + ['SelI', 'BspLU11I', 'TspEI', 'Asi256I', 'Ppu10I', 'Sse232I', 'BetI', 'SplI', 'AoxI', 'BspMII'], + ) +typedict['type80'] = _temp() + +def _temp(): + return ( + ('Palindromic', 'OneCut', 'Ov5', 'Ambiguous', 'Meth_Dep', 'Commercially_available', 'AbstractCut', 'RestrictionType'), + ['PspPI', 'AspS9I', 'StyD4I', 'PspGI', 'BsoBI', 'BlpI', 'BssECI', 'AjnI', 'AvaI', 'SexAI', 'Sau96I', 'BstNI', 'Cfr13I', 'TseI', 'MvaI', 'BssKI', 'AflIII', 'TfiI', 'BanI', 'RsrII', 'BcnI', 'ScrFI', 'EcoRII', 'EcoNI', 'NciI', 'ApeKI', 'HinfI', 'Fsp4HI', 'EcoO109I', 'PpuMI', 'AccI', 'Tth111I', 'DdeI', 'AvaII', 'BsaJI', 'Fnu4HI', 'Tsp45I'], + ) +typedict['type81'] = _temp() + +def _temp(): + return ( + ('Palindromic', 'OneCut', 'Ov5', 'Ambiguous', 'Meth_Dep', 'Not_available', 'AbstractCut', 'RestrictionType'), + ['HgiCI', 'EcoHI'], + ) +typedict['type82'] = _temp() + +def _temp(): + return ( + ('Palindromic', 'OneCut', 'Ov5', 'Ambiguous', 'Meth_Undep', 'Commercially_available', 'AbstractCut', 'RestrictionType'), + ['AxyI', 'BstSFI', 'BspT107I', 'BstOI', 'PspEI', 'BisI', 'BstPI', 'BstEII', 'BmgT120I', 'BssT1I', 'PsyI', 'BtgI', 'Eco91I', 'Bst2UI', 'BstDEI', 'GluI', 'BstENI', 'Ama87I', 'BstDSI', 'PflFI', 'Bme1390I', 'Psp5II', 'EcoO65I', 'BmrFI', 'EcoT14I', 'PspPPI', 'SmlI', 'BseBI', 'PfoI', 'BshNI', 'Rsr2I', 'BmeT110I', 'PasI', 'TseFI', 'CpoI', 'Eco130I', 'CspI', 'BfmI', 'Eco47I', 'Bsu36I', 'Bme18I', 'MabI', 'Hpy188III', 'Bse21I', 'BstSCI', 'BpuMI', 'SgeI', 'SmoI', 'Bsp1720I', 'MaeIII', 'ErhI', 'XagI', 'AsuC2I', 'BsiHKCI', 'XmiI', 'MspR9I', 'VpaK11BI', 'PfeI', 'Bpu1102I', 'SfcI', 'SatI', 'BciT130I', 'KflI', 'BseDI', 'Eco81I', 'Eco88I', 'FblI', 'AccB1I', 'CsiI', 'Psp6I', 'HpyF3I', 'StyI', 'NmuCI'], + ) +typedict['type83'] = _temp() + +def _temp(): + return ( + ('Palindromic', 'OneCut', 'Ov5', 'Ambiguous', 'Meth_Undep', 'Not_available', 'AbstractCut', 'RestrictionType'), + ['SanDI', 'DsaI', 'DraII', 'SauI', 'UnbI', 'VpaK11AI', 'SfeI', 'CauII', 'Hpy178III', 'AsuI', 'SecI', 'EspI', 'Sse8647I'], + ) +typedict['type84'] = _temp() + +def _temp(): + return ( + ('Palindromic', 'OneCut', 'Ov3', 'Defined', 'Meth_Dep', 'Commercially_available', 'AbstractCut', 'RestrictionType'), + ['SacI', 'KpnI', 'HaeII', 'SacII', 'AatII', 'PluTI', 'NlaIII', 'PstI', 'Cfr42I', 'FseI', 'ApaI', 'NspI', 'HhaI', 'AsiSI'], + ) +typedict['type89'] = _temp() + +def _temp(): + return ( + ('Palindromic', 'OneCut', 'Ov3', 'Defined', 'Meth_Dep', 'Not_available', 'AbstractCut', 'RestrictionType'), + ['PabI', 'McaTI'], + ) +typedict['type90'] = _temp() + +def _temp(): + return ( + ('Palindromic', 'OneCut', 'Ov3', 'Defined', 'Meth_Undep', 'Commercially_available', 'AbstractCut', 'RestrictionType'), + ['SgrBI', 'BstHHI', 'BstH2I', 'BmtI', 'BpvUI', 'PvuI', 'BspOI', 'AspLEI', 'Zsp2I', 'FaeI', 'SdaI', 'BstNSI', 'Ple19I', 'Hin1II', 'Sse8387I', 'TaiI', 'Psp124BI', 'Sfr303I', 'Mph1103I', 'CfoI', 'PaeI', 'BstKTI', 'SstI', 'SphI', 'MvrI', 'SfaAI', 'RgaI', 'SgfI', 'SbfI', 'XceI', 'NsiI', 'EcoT22I', 'PacI', 'KspI', 'Hsp92II', 'BfoI', 'RigI'], + ) +typedict['type91'] = _temp() + +def _temp(): + return ( + ('Palindromic', 'OneCut', 'Ov3', 'Defined', 'Meth_Undep', 'Not_available', 'AbstractCut', 'RestrictionType'), + ['ChaI'], + ) +typedict['type92'] = _temp() + +def _temp(): + return ( + ('Palindromic', 'OneCut', 'Ov3', 'Ambiguous', 'Meth_Dep', 'Commercially_available', 'AbstractCut', 'RestrictionType'), + ['MwoI', 'EcoT38I', 'BglI', 'BanII', 'TspRI', 'Hpy99I', 'BstXI', 'BsiHKAI', 'BaeGI', 'Hpy188I', 'Bsc4I', 'DraIII', 'Bsp1286I', 'AhdI', 'SfiI', 'XcmI', 'BslI'], + ) +typedict['type93'] = _temp() + +def _temp(): + return ( + ('Palindromic', 'OneCut', 'Ov3', 'Ambiguous', 'Meth_Dep', 'Not_available', 'AbstractCut', 'RestrictionType'), + ['BthCI', 'HauII'], + ) +typedict['type94'] = _temp() + +def _temp(): + return ( + ('Palindromic', 'OneCut', 'Ov3', 'Ambiguous', 'Meth_Undep', 'Commercially_available', 'AbstractCut', 'RestrictionType'), + ['AgsI', 'DrdI', 'TscAI', 'BstMWI', 'Eco24I', 'AlwNI', 'BseSI', 'AdeI', 'Van91I', 'DseDI', 'SetI', 'BmeRI', 'TaaI', 'BstMCI', 'HpyF10VI', 'Bst4CI', 'SduI', 'Alw21I', 'AccB7I', 'BasI', 'BsiEI', 'BseLI', 'FriOI', 'AasI', 'Eam1105I', 'TauI', 'AfiI', 'CaiI', 'Bbv12I', 'BstAPI', 'HpyCH4III', 'BstSLI', 'BlsI', 'PcsI', 'PstNI', 'MhlI', 'DriI', 'Bsh1285I', 'PflMI'], + ) +typedict['type95'] = _temp() + +def _temp(): + return ( + ('Palindromic', 'OneCut', 'Ov3', 'Ambiguous', 'Meth_Undep', 'Not_available', 'AbstractCut', 'RestrictionType'), + ['Nli3877I', 'Psp03I', 'BsiYI', 'ApaBI', 'Tsp4CI', 'FmuI', 'McrI', 'HgiJII', 'PssI', 'HgiAI'], + ) +typedict['type96'] = _temp() + del _temp + diff -Nru python-biopython-1.62/Bio/Restriction/_Update/RestrictionCompiler.py python-biopython-1.63/Bio/Restriction/_Update/RestrictionCompiler.py --- python-biopython-1.62/Bio/Restriction/_Update/RestrictionCompiler.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Restriction/_Update/RestrictionCompiler.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,998 +0,0 @@ -#!/usr/bin/env python -# -# Restriction Analysis Libraries. -# Copyright (C) 2004. Frederic Sohm. -# -# This code is part of the Biopython distribution and governed by its -# license. Please see the LICENSE file that should have been included -# as part of this package. -# -# this script is used to produce the dictionary which will contains the data -# about the restriction enzymes from the Emboss/Rebase data files -# namely -# emboss_e.### (description of the sites), -# emboss_r.### (origin, methylation, references) -# emboss_s.### (suppliers) -# where ### is a number of three digits : 1 for the year two for the month -# -# very dirty implementation but it does the job, so... -# Not very quick either but you are not supposed to use it frequently. -# -# The results are stored in -# path/to/site-packages/Bio/Restriction/Restriction_Dictionary.py -# the file contains two dictionary: -# 'rest_dict' which contains the data for the enzymes -# and -# 'suppliers' which map the name of the suppliers to their abbreviation. -# - -"""Convert a serie of Rebase files into a Restriction_Dictionary.py module. - -The Rebase files are in the emboss format: - - emboss_e.### -> contains information about the restriction sites. - emboss_r.### -> contains general information about the enzymes. - emboss_s.### -> contains information about the suppliers. - -### is a 3 digit number. The first digit is the year and the two last the month. -""" - -import os -import itertools -import time -import sys -import shutil - -from Bio.Seq import Seq - -import Bio.Restriction.Restriction -from Bio.Restriction.Restriction import AbstractCut, RestrictionType, NoCut, OneCut -from Bio.Restriction.Restriction import TwoCuts, Meth_Dep, Meth_Undep, Palindromic -from Bio.Restriction.Restriction import NonPalindromic, Unknown, Blunt, Ov5, Ov3 -from Bio.Restriction.Restriction import NotDefined, Defined, Ambiguous -from Bio.Restriction.Restriction import Commercially_available, Not_available - -import Bio.Restriction.RanaConfig as config -from Bio.Restriction._Update.Update import RebaseUpdate -from Bio.Restriction.Restriction import * -from Bio.Restriction.DNAUtils import antiparallel - -DNA=Seq -dna_alphabet = {'A':'A', 'C':'C', 'G':'G', 'T':'T', - 'R':'AG', 'Y':'CT', 'W':'AT', 'S':'CG', 'M':'AC', 'K':'GT', - 'H':'ACT', 'B':'CGT', 'V':'ACG', 'D':'AGT', - 'N':'ACGT', - 'a': 'a', 'c': 'c', 'g': 'g', 't': 't', - 'r':'ag', 'y':'ct', 'w':'at', 's':'cg', 'm':'ac', 'k':'gt', - 'h':'act', 'b':'cgt', 'v':'acg', 'd':'agt', - 'n':'acgt'} - - -complement_alphabet = {'A':'T', 'T':'A', 'C':'G', 'G':'C','R':'Y', 'Y':'R', - 'W':'W', 'S':'S', 'M':'K', 'K':'M', 'H':'D', 'D':'H', - 'B':'V', 'V':'B', 'N':'N','a':'t', 'c':'g', 'g':'c', - 't':'a', 'r':'y', 'y':'r', 'w':'w', 's':'s','m':'k', - 'k':'m', 'h':'d', 'd':'h', 'b':'v', 'v':'b', 'n':'n'} -enzymedict = {} -suppliersdict = {} -classdict = {} -typedict = {} - - -class OverhangError(ValueError): - """Exception for dealing with overhang.""" - pass - - -def BaseExpand(base): - """BaseExpand(base) -> string. - - given a degenerated base, returns its meaning in IUPAC alphabet. - - i.e: - b= 'A' -> 'A' - b= 'N' -> 'ACGT' - etc...""" - base = base.upper() - return dna_alphabet[base] - - -def regex(site): - """regex(site) -> string. - - Construct a regular expression from a DNA sequence. - i.e.: - site = 'ABCGN' -> 'A[CGT]CG.'""" - reg_ex = site - for base in reg_ex: - if base in ('A', 'T', 'C', 'G', 'a', 'c', 'g', 't'): - pass - if base in ('N', 'n'): - reg_ex = '.'.join(reg_ex.split('N')) - reg_ex = '.'.join(reg_ex.split('n')) - if base in ('R', 'Y', 'W', 'M', 'S', 'K', 'H', 'D', 'B', 'V'): - expand = '['+ str(BaseExpand(base))+']' - reg_ex = expand.join(reg_ex.split(base)) - return reg_ex - - -def Antiparallel(sequence): - """Antiparallel(sequence) -> string. - - returns a string which represents the reverse complementary strand of - a DNA sequence.""" - return antiparallel(str(sequence)) - - -def is_palindrom(sequence): - """is_palindrom(sequence) -> bool. - - True is the sequence is a palindrom. - sequence is a DNA object.""" - return sequence == DNA(Antiparallel(sequence)) - - -def LocalTime(): - """LocalTime() -> string. - - LocalTime calculate the extension for emboss file for the current year and - month.""" - t = time.gmtime() - year = str(t.tm_year)[-1] - month = str(t.tm_mon) - if len(month) == 1: - month = '0' + month - return year+month - - -class newenzyme(object): - """construct the attributes of the enzyme corresponding to 'name'.""" - def __init__(cls, name): - cls.opt_temp = 37 - cls.inact_temp = 65 - cls.substrat = 'DNA' - target = enzymedict[name] - cls.site = target[0] - cls.size = target[1] - cls.suppl = tuple(target[9]) - cls.freq = target[11] - cls.ovhg = target[13] - cls.ovhgseq = target[14] - cls.bases = () - # - # Is the site palindromic? - # Important for the way the DNA is search for the site. - # Palindromic sites needs to be looked for only over 1 strand. - # Non Palindromic needs to be search for on the reverse complement - # as well. - # - if target[10]: - cls.bases += ('Palindromic',) - else: - cls.bases += ('NonPalindromic',) - # - # Number of cut the enzyme produce. - # 0 => unknown, the enzyme has not been fully characterised. - # 2 => 1 cut, (because one cut is realised by cutting 2 strands - # 4 => 2 cuts, same logic. - # A little bit confusing but it is the way EMBOSS/Rebase works. - # - if not target[2]: - # - # => undefined enzymes, nothing to be done. - # - cls.bases += ('NoCut','Unknown', 'NotDefined') - cls.fst5 = None - cls.fst3 = None - cls.scd5 = None - cls.scd3 = None - cls.ovhg = None - cls.ovhgseq = None - else: - # - # we will need to calculate the overhang. - # - if target[2] == 2: - cls.bases += ('OneCut',) - cls.fst5 = target[4] - cls.fst3 = target[5] - cls.scd5 = None - cls.scd3 = None - else: - cls.bases += ('TwoCuts',) - cls.fst5 = target[4] - cls.fst3 = target[5] - cls.scd5 = target[6] - cls.scd3 = target[7] - # - # Now, prepare the overhangs which will be added to the DNA - # after the cut. - # Undefined enzymes will not be allowed to catalyse, - # they are not available commercially anyway. - # I assumed that if an enzyme cut twice the overhang will be of - # the same kind. The only exception is HaeIV. I do not deal - # with that at the moment (ie I don't include it, - # need to be fixed). - # They generally cut outside their recognition site and - # therefore the overhang is undetermined and dependent of - # the DNA sequence upon which the enzyme act. - # - if target[3]: - # - # rebase field for blunt: blunt == 1, other == 0. - # The enzyme is blunt. No overhang. - # - cls.bases += ('Blunt', 'Defined') - cls.ovhg = 0 - elif isinstance(cls.ovhg, int): - # - # => overhang is sequence dependent - # - if cls.ovhg > 0: - # - # 3' overhang, ambiguous site (outside recognition site - # or site containing ambiguous bases (N, W, R,...) - # - cls.bases += ('Ov3', 'Ambiguous') - elif cls.ovhg < 0: - # - # 5' overhang, ambiguous site (outside recognition site - # or site containing ambiguous bases (N, W, R,...) - # - cls.bases += ('Ov5', 'Ambiguous') - else: - # - # cls.ovhg is a string => overhang is constant - # - if cls.fst5 - (cls.fst3 + cls.size) < 0: - cls.bases += ('Ov5', 'Defined') - cls.ovhg = - len(cls.ovhg) - else: - cls.bases += ('Ov3', 'Defined') - cls.ovhg = + len(cls.ovhg) - # - # Next class : sensibility to methylation. - # Set by EmbossMixer from emboss_r.txt file - # Not really methylation dependent at the moment, stands rather for - # 'is the site methylable?'. - # Proper methylation sensibility has yet to be implemented. - # But the class is there for further development. - # - if target[8]: - cls.bases += ('Meth_Dep', ) - cls.compsite = target[12] - else: - cls.bases += ('Meth_Undep',) - cls.compsite = target[12] - # - # Next class will allow to select enzymes in function of their - # suppliers. Not essential but can be useful. - # - if cls.suppl: - cls.bases += ('Commercially_available', ) - else: - cls.bases += ('Not_available', ) - cls.bases += ('AbstractCut', 'RestrictionType') - cls.__name__ = name - cls.results = None - cls.dna = None - cls.__bases__ = cls.bases - cls.charac = (cls.fst5, cls.fst3, cls.scd5, cls.scd3, cls.site) - if not target[2] and cls.suppl: - supp = ', '.join([suppliersdict[s][0] for s in cls.suppl]) - print 'WARNING : It seems that %s is both commercially available\ - \n\tand its characteristics are unknown. \ - \n\tThis seems counter-intuitive.\ - \n\tThere is certainly an error either in ranacompiler or\ - \n\tin this REBASE release.\ - \n\tThe supplier is : %s.' % (name, supp) - return - - -class TypeCompiler(object): - """Build the different types possible for Restriction Enzymes""" - - def __init__(self): - """TypeCompiler() -> new TypeCompiler instance.""" - pass - - def buildtype(self): - """TC.buildtype() -> generator. - - build the new types that will be needed for constructing the - restriction enzymes.""" - baT = (AbstractCut, RestrictionType) - cuT = (NoCut, OneCut, TwoCuts) - meT = (Meth_Dep, Meth_Undep) - paT = (Palindromic, NonPalindromic) - ovT = (Unknown, Blunt, Ov5, Ov3) - deT = (NotDefined, Defined, Ambiguous) - coT = (Commercially_available, Not_available) - All = (baT, cuT, meT, paT, ovT, deT, coT) - # - # Now build the types. Only the most obvious are left out. - # Modified even the most obvious are not so obvious. - # emboss_*.403 AspCNI is unknown and commercially available. - # So now do not remove the most obvious. - # - types = [(p,c,o,d,m,co,baT[0],baT[1]) - for p in paT for c in cuT for o in ovT - for d in deT for m in meT for co in coT] - n= 1 - for ty in types: - dct = {} - for t in ty: - dct.update(t.__dict__) - # - # here we need to customize the dictionary. - # i.e. types deriving from OneCut have always scd5 and scd3 - # equal to None. No need therefore to store that in a specific - # enzyme of this type. but it then need to be in the type. - # - dct['results'] = [] - dct['substrat'] = 'DNA' - dct['dna'] = None - if t == NoCut: - dct.update({'fst5':None,'fst3':None, - 'scd5':None,'scd3':None, - 'ovhg':None,'ovhgseq':None}) - elif t == OneCut: - dct.update({'scd5':None, 'scd3':None}) - - class klass(type): - def __new__(cls): - return type.__new__(cls, 'type%i'%n,ty,dct) - - def __init__(cls): - super(klass, cls).__init__('type%i'%n,ty,dct) - - yield klass() - n+=1 - -start = '\n\ -#!/usr/bin/env python\n\ -#\n\ -# Restriction Analysis Libraries.\n\ -# Copyright (C) 2004. Frederic Sohm.\n\ -#\n\ -# This code is part of the Biopython distribution and governed by its\n\ -# license. Please see the LICENSE file that should have been included\n\ -# as part of this package.\n\ -#\n\ -# This file is automatically generated - do not edit it by hand! Instead,\n\ -# use the tool Scripts/Restriction/ranacompiler.py which in turn uses\n\ -# Bio/Restriction/_Update/RestrictionCompiler.py\n\ -#\n\ -# The following dictionaries used to be defined in one go, but that does\n\ -# not work on Jython due to JVM limitations. Therefore we break this up\n\ -# into steps, using temporary functions to avoid the JVM limits.\n\ -\n\n' - - -class DictionaryBuilder(object): - - def __init__(self, e_mail='', ftp_proxy=''): - """DictionaryBuilder([e_mail[, ftp_proxy]) -> DictionaryBuilder instance. - - If the emboss files used for the construction need to be updated this - class will download them if the ftp connection is correctly set. - either in RanaConfig.py or given at run time. - - e_mail is the e-mail address used as password for the anonymous - ftp connection. - - proxy is the ftp_proxy to use if any.""" - self.rebase_pass = e_mail or config.Rebase_password - self.proxy = ftp_proxy or config.ftp_proxy - - def build_dict(self): - """DB.build_dict() -> None. - - Construct the dictionary and build the files containing the new - dictionaries.""" - # - # first parse the emboss files. - # - emboss_e, emboss_r, emboss_s = self.lastrebasefile() - # - # the results will be stored into enzymedict. - # - self.information_mixer(emboss_r, emboss_e, emboss_s) - emboss_r.close() - emboss_e.close() - emboss_s.close() - # - # we build all the possible type - # - tdct = {} - for klass in TypeCompiler().buildtype(): - exec klass.__name__ +'= klass' - exec "tdct['"+klass.__name__+"'] = klass" - - # - # Now we build the enzymes from enzymedict - # and store them in a dictionary. - # The type we will need will also be stored. - # - - for name in enzymedict: - # - # the class attributes first: - # - cls = newenzyme(name) - # - # Now select the right type for the enzyme. - # - bases = cls.bases - clsbases = tuple([eval(x) for x in bases]) - typestuff = '' - for n, t in tdct.iteritems(): - # - # if the bases are the same. it is the right type. - # create the enzyme and remember the type - # - if t.__bases__ == clsbases: - typestuff = t - typename = t.__name__ - continue - # - # now we build the dictionaries. - # - dct = dict(cls.__dict__) - del dct['bases'] - del dct['__bases__'] - del dct['__name__']# no need to keep that, it's already in the type. - classdict[name] = dct - - commonattr = ['fst5', 'fst3', 'scd5', 'scd3', 'substrat', - 'ovhg', 'ovhgseq','results', 'dna'] - if typename in typedict: - typedict[typename][1].append(name) - else: - enzlst= [] - tydct = dict(typestuff.__dict__) - tydct = dict([(k,v) for k,v in tydct.iteritems() if k in commonattr]) - enzlst.append(name) - typedict[typename] = (bases, enzlst) - for letter in cls.__dict__['suppl']: - supplier = suppliersdict[letter] - suppliersdict[letter][1].append(name) - if not classdict or not suppliersdict or not typedict: - print 'One of the new dictionaries is empty.' - print 'Check the integrity of the emboss file before continuing.' - print 'Update aborted.' - sys.exit() - # - # How many enzymes this time? - # - print '\nThe new database contains %i enzymes.\n' % len(classdict) - # - # the dictionaries are done. Build the file - # - #update = config.updatefolder - - update = os.getcwd() - results = open(os.path.join(update, 'Restriction_Dictionary.py'), 'w') - print 'Writing the dictionary containing the new Restriction classes.\t', - results.write(start) - results.write('rest_dict = {}\n') - for name in sorted(classdict) : - results.write("def _temp():\n") - results.write(" return {\n") - for key, value in classdict[name].iteritems() : - results.write(" %s : %s,\n" % (repr(key), repr(value))) - results.write(" }\n") - results.write("rest_dict[%s] = _temp()\n" % repr(name)) - results.write("\n") - print 'OK.\n' - print 'Writing the dictionary containing the suppliers data.\t\t', - results.write('suppliers = {}\n') - for name in sorted(suppliersdict) : - results.write("def _temp():\n") - results.write(" return (\n") - for value in suppliersdict[name] : - results.write(" %s,\n" % repr(value)) - results.write(" )\n") - results.write("suppliers[%s] = _temp()\n" % repr(name)) - results.write("\n") - print 'OK.\n' - print 'Writing the dictionary containing the Restriction types.\t', - results.write('typedict = {}\n') - for name in sorted(typedict) : - results.write("def _temp():\n") - results.write(" return (\n") - for value in typedict[name] : - results.write(" %s,\n" % repr(value)) - results.write(" )\n") - results.write("typedict[%s] = _temp()\n" % repr(name)) - results.write("\n") - #I had wanted to do "del _temp" at each stage (just for clarity), but - #that pushed the code size just over the Jython JVM limit. We include - #one the final "del _temp" to clean up the namespace. - results.write("del _temp\n") - results.write("\n") - print 'OK.\n' - results.close() - return - - def install_dict(self): - """DB.install_dict() -> None. - - Install the newly created dictionary in the site-packages folder. - - May need super user privilege on some architectures.""" - print '\n ' +'*'*78 + ' \n' - print '\n\t\tInstalling Restriction_Dictionary.py' - try: - import Bio.Restriction.Restriction_Dictionary as rd - except ImportError: - print '\ - \n Unable to locate the previous Restriction_Dictionary.py module\ - \n Aborting installation.' - sys.exit() - # - # first save the old file in Updates - # - old = os.path.join(os.path.split(rd.__file__)[0], - 'Restriction_Dictionary.py') - #update_folder = config.updatefolder - update_folder = os.getcwd() - shutil.copyfile(old, os.path.join(update_folder, - 'Restriction_Dictionary.old')) - # - # Now test and install. - # - new = os.path.join(update_folder, 'Restriction_Dictionary.py') - try: - execfile(new) - print '\ - \n\tThe new file seems ok. Proceeding with the installation.' - except SyntaxError: - print '\ - \n The new dictionary file is corrupted. Aborting the installation.' - return - try: - shutil.copyfile(new, old) - print'\n\t Everything ok. If you need it a version of the old\ - \n\t dictionary have been saved in the Updates folder under\ - \n\t the name Restriction_Dictionary.old.' - print '\n ' +'*'*78 + ' \n' - except IOError: - print '\n ' +'*'*78 + ' \n' - print '\ - \n\t WARNING : Impossible to install the new dictionary.\ - \n\t Are you sure you have write permission to the folder :\n\ - \n\t %s ?\n\n' % os.path.split(old)[0] - return self.no_install() - return - - def no_install(self): - """BD.no_install() -> None. - - build the new dictionary but do not install the dictionary.""" - print '\n ' +'*'*78 + '\n' - #update = config.updatefolder - try: - import Bio.Restriction.Restriction_Dictionary as rd - except ImportError: - print '\ - \n Unable to locate the previous Restriction_Dictionary.py module\ - \n Aborting installation.' - sys.exit() - # - # first save the old file in Updates - # - old = os.path.join(os.path.split(rd.__file__)[0], - 'Restriction_Dictionary.py') - update = os.getcwd() - shutil.copyfile(old, os.path.join(update, 'Restriction_Dictionary.old')) - places = update, os.path.split(Bio.Restriction.Restriction.__file__)[0] - print "\t\tCompilation of the new dictionary : OK.\ - \n\t\tInstallation : No.\n\ - \n You will find the newly created 'Restriction_Dictionary.py' file\ - \n in the folder : \n\ - \n\t%s\n\ - \n Make a copy of 'Restriction_Dictionary.py' and place it with \ - \n the other Restriction libraries.\n\ - \n note : \ - \n This folder should be :\n\ - \n\t%s\n" % places - print '\n ' +'*'*78 + '\n' - return - - def lastrebasefile(self): - """BD.lastrebasefile() -> None. - - Check the emboss files are up to date and download them if they are not. - """ - embossnames = ('emboss_e', 'emboss_r', 'emboss_s') - # - # first check if we have the last update: - # - emboss_now = ['.'.join((x,LocalTime())) for x in embossnames] - update_needed = False - #dircontent = os.listdir(config.Rebase) # local database content - dircontent = os.listdir(os.getcwd()) - base = os.getcwd() # added for biopython current directory - for name in emboss_now: - if name in dircontent: - pass - else: - update_needed = True - - if not update_needed: - # - # nothing to be done - # - print '\n Using the files : %s'% ', '.join(emboss_now) - return tuple([open(os.path.join(base, n)) for n in emboss_now]) - else: - # - # may be download the files. - # - print '\n The rebase files are more than one month old.\ - \n Would you like to update them before proceeding?(y/n)' - r = raw_input(' update [n] >>> ') - if r in ['y', 'yes', 'Y', 'Yes']: - updt = RebaseUpdate(self.rebase_pass, self.proxy) - updt.openRebase() - updt.getfiles() - updt.close() - print '\n Update complete. Creating the dictionaries.\n' - print '\n Using the files : %s'% ', '.join(emboss_now) - return tuple([open(os.path.join(base, n)) for n in emboss_now]) - else: - # - # we will use the last files found without updating. - # But first we check we have some file to use. - # - class NotFoundError(Exception): - pass - for name in embossnames: - try: - for file in dircontent: - if file.startswith(name): - break - else: - pass - raise NotFoundError - except NotFoundError: - print "\nNo %s file found. Upgrade is impossible.\n"%name - sys.exit() - continue - pass - # - # now find the last file. - # - last = [0] - for file in dircontent: - fs = file.split('.') - try: - if fs[0] in embossnames and int(fs[1]) > int(last[-1]): - if last[0]: - last.append(fs[1]) - else: - last[0] = fs[1] - else: - continue - except ValueError: - continue - last.sort() - last = last[::-1] - if int(last[-1]) < 100: - last[0], last[-1] = last[-1], last[0] - - for number in last: - files = [(name, name+'.%s'%number) for name in embossnames] - strmess = '\nLast EMBOSS files found are :\n' - try: - for name,file in files: - if os.path.isfile(os.path.join(base, file)): - strmess += '\t%s.\n'%file - else: - raise ValueError - print strmess - emboss_e = open(os.path.join(base, 'emboss_e.%s'%number),'r') - emboss_r = open(os.path.join(base, 'emboss_r.%s'%number),'r') - emboss_s = open(os.path.join(base, 'emboss_s.%s'%number),'r') - return emboss_e, emboss_r, emboss_s - except ValueError: - continue - - def parseline(self, line): - line = [line[0]]+[line[1].upper()]+[int(i) for i in line[2:9]]+line[9:] - name = line[0].replace("-","_") - site = line[1] # sequence of the recognition site - dna = DNA(site) - size = line[2] # size of the recognition site - # - # Calculate the overhang. - # - fst5 = line[5] # first site sense strand - fst3 = line[6] # first site antisense strand - scd5 = line[7] # second site sense strand - scd3 = line[8] # second site antisense strand - - # - # the overhang is the difference between the two cut - # - ovhg1 = fst5 - fst3 - ovhg2 = scd5 - scd3 - - # - # 0 has the meaning 'do not cut' in rebase. So we get short of 1 - # for the negative numbers so we add 1 to negative sites for now. - # We will deal with the record later. - # - - if fst5 < 0: - fst5 += 1 - if fst3 < 0: - fst3 += 1 - if scd5 < 0: - scd5 += 1 - if scd3 < 0: - scd3 += 1 - - if ovhg2 != 0 and ovhg1 != ovhg2: - # - # different length of the overhang of the first and second cut - # it's a pain to deal with and at the moment it concerns only - # one enzyme which is not commercially available (HaeIV). - # So we don't deal with it but we check the progression - # of the affair. - # Should HaeIV become commercially available or other similar - # new enzymes be added, this might be modified. - # - print '\ - \nWARNING : %s cut twice with different overhang length each time.\ - \n\tUnable to deal with this behaviour. \ - \n\tThis enzyme will not be included in the database. Sorry.' %name - print '\tChecking :', - raise OverhangError - if 0 <= fst5 <= size and 0 <= fst3 <= size: - # - # cut inside recognition site - # - if fst5 < fst3: - # - # 5' overhang - # - ovhg1 = ovhgseq = site[fst5:fst3] - elif fst5 > fst3: - # - # 3' overhang - # - ovhg1 = ovhgseq = site[fst3:fst5] - else: - # - # blunt - # - ovhg1 = ovhgseq = '' - for base in 'NRYWMSKHDBV': - if base in ovhg1: - # - # site and overhang degenerated - # - ovhgseq = ovhg1 - if fst5 < fst3: - ovhg1 = - len(ovhg1) - else: - ovhg1 = len(ovhg1) - break - else: - continue - elif 0 <= fst5 <= size: - # - # 5' cut inside the site 3' outside - # - if fst5 < fst3: - # - # 3' cut after the site - # - ovhgseq = site[fst5:] + (fst3 - size) * 'N' - elif fst5 > fst3: - # - # 3' cut before the site - # - ovhgseq = abs(fst3) * 'N' + site[:fst5] - else: - # - # blunt outside - # - ovhg1 = ovhgseq = '' - elif 0 <= fst3 <= size: - # - # 3' cut inside the site, 5' outside - # - if fst5 < fst3: - # - # 5' cut before the site - # - ovhgseq = abs(fst5) * 'N' + site[:fst3] - elif fst5 > fst3: - # - # 5' cut after the site - # - ovhgseq = site[fst3:] + (fst5 - size) * 'N' - else: - # - # should not happend - # - raise ValueError('Error in #1') - elif fst3 < 0 and size < fst5: - # - # 3' overhang. site is included. - # - ovhgseq = abs(fst3)*'N' + site + (fst5-size)*'N' - elif fst5 < 0 and size 0: - line[x] -= size - elif line[x] < 0: - line[x] = line[x] - size + 1 - # - # now is the site palindromic? - # produce the regular expression which correspond to the site. - # tag of the regex will be the name of the enzyme for palindromic - # enzymesband two tags for the other, the name for the sense sequence - # and the name with '_as' at the end for the antisense sequence. - # - rg = '' - if is_palindrom(dna): - line.append(True) - rg = ''.join(['(?P<', name, '>', regex(site.upper()), ')']) - else: - line.append(False) - sense = ''.join(['(?P<', name, '>', regex(site.upper()), ')']) - antisense = ''.join(['(?P<', name, '_as>', - regex(Antiparallel(dna)), ')']) - rg = sense + '|' + antisense - # - # exact frequency of the site. (ie freq(N) == 1, ...) - # - f = [4/len(dna_alphabet[l]) for l in site.upper()] - freq = reduce(lambda x, y : x*y, f) - line.append(freq) - # - # append regex and ovhg1, they have not been appended before not to - # break the factory class. simply to leazy to make the changes there. - # - line.append(rg) - line.append(ovhg1) - line.append(ovhgseq) - return line - - def removestart(self, file): - # - # remove the heading of the file. - # - return [l for l in itertools.dropwhile(lambda l:l.startswith('#'),file)] - - def getblock(self, file, index): - # - # emboss_r.txt, separation between blocks is // - # - take = itertools.takewhile - block = [l for l in take(lambda l :not l.startswith('//'),file[index:])] - index += len(block)+1 - return block, index - - def get(self, block): - # - # take what we want from the block. - # Each block correspond to one enzyme. - # block[0] => enzyme name - # block[3] => methylation (position and type) - # block[5] => suppliers (as a string of single letter) - # - bl3 = block[3].strip() - if not bl3: - bl3 = False # site is not methylable - return (block[0].strip(), bl3, block[5].strip()) - - def information_mixer(self, file1, file2, file3): - # - # Mix all the information from the 3 files and produce a coherent - # restriction record. - # - methfile = self.removestart(file1) - sitefile = self.removestart(file2) - supplier = self.removestart(file3) - - i1, i2= 0, 0 - try: - while True: - block, i1 = self.getblock(methfile, i1) - bl = self.get(block) - line = (sitefile[i2].strip()).split() - name = line[0] - if name == bl[0]: - line.append(bl[1]) # -> methylation - line.append(bl[2]) # -> suppliers - else: - bl = self.get(oldblock) - if line[0] == bl[0]: - line.append(bl[1]) - line.append(bl[2]) - i2 += 1 - else: - raise TypeError - oldblock = block - i2 += 1 - try: - line = self.parseline(line) - except OverhangError: # overhang error - n = name # do not include the enzyme - if not bl[2]: - print 'Anyway, %s is not commercially available.\n' %n - else: - print 'Unfortunately, %s is commercially available.\n'%n - - continue - #Hyphens can't be used as a Python name, nor as a - #group name in a regular expression. - name = name.replace("-","_") - if name in enzymedict: - # - # deal with TaqII and its two sites. - # - print '\nWARNING :', - print name, 'has two different sites.\n' - other = line[0].replace("-","_") - dna = DNA(line[1]) - sense1 = regex(str(dna)) - antisense1 = regex(Antiparallel(dna)) - dna = DNA(enzymedict[other][0]) - sense2 = regex(str(dna)) - antisense2 = regex(Antiparallel(dna)) - sense = '(?P<'+other+'>'+sense1+'|'+sense2+')' - antisense = '(?P<'+other+'_as>'+antisense1+'|'+antisense2 + ')' - reg = sense + '|' + antisense - line[1] = line[1] + '|' + enzymedict[other][0] - line[-1] = reg - # - # the data to produce the enzyme class are then stored in - # enzymedict. - # - enzymedict[name] = line[1:] # element zero was the name - except IndexError: - pass - for i in supplier: - # - # construction of the list of suppliers. - # - t = i.strip().split(' ', 1) - suppliersdict[t[0]] = (t[1], []) - return diff -Nru python-biopython-1.62/Bio/Restriction/_Update/Update.py python-biopython-1.63/Bio/Restriction/_Update/Update.py --- python-biopython-1.62/Bio/Restriction/_Update/Update.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Restriction/_Update/Update.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,116 +0,0 @@ -#!/usr/bin/env python -# -# Restriction Analysis Libraries. -# Copyright (C) 2004. Frederic Sohm. -# -# This code is part of the Biopython distribution and governed by its -# license. Please see the LICENSE file that should have been included -# as part of this package. -# - -"""Update the Rebase emboss files used by Restriction to build the -Restriction_Dictionary.py module.""" - -import os -import sys -import time -from urllib import FancyURLopener - -from Bio.Restriction.RanaConfig import * - - -class RebaseUpdate(FancyURLopener): - - def __init__(self, e_mail='', ftpproxy=''): - """RebaseUpdate([e_mail[, ftpproxy]]) -> new RebaseUpdate instance. - - if e_mail and ftpproxy are not given RebaseUpdate uses the corresponding - variable from RanaConfig. - - e_mail is the password for the anonymous ftp connection to Rebase. - ftpproxy is the proxy to use if any.""" - proxy = {'ftp' : ftpproxy or ftp_proxy} - global Rebase_password - Rebase_password = e_mail or Rebase_password - if not Rebase_password: - raise FtpPasswordError('Rebase') - if not Rebase_name: - raise FtpNameError('Rebase') - FancyURLopener.__init__(self, proxy) - - def prompt_user_passwd(self, host, realm): - return (Rebase_name, Rebase_password) - - def openRebase(self, name = ftp_Rebase): - print '\n Please wait, trying to connect to Rebase\n' - try: - self.open(name) - except: - raise ConnectionError('Rebase') - return - - def getfiles(self, *files): - print '\n', - for file in self.update(*files): - print 'copying', file - fn = os.path.basename(file) - #filename = os.path.join(Rebase, fn) - filename = os.path.join(os.getcwd(), fn) - print 'to', filename - self.retrieve(file, filename) - self.close() - return - - def localtime(self): - t = time.gmtime() - year = str(t.tm_year)[-1] - month = str(t.tm_mon) - if len(month) == 1: - month = '0' + month - return year+month - - def update(self, *files): - if not files: - files = [ftp_emb_e, ftp_emb_s, ftp_emb_r] - return [x.replace('###', self.localtime()) for x in files] - - def __del__(self): - if hasattr(self, 'tmpcache'): - self.close() - # - # self.tmpcache is created by URLopener.__init__ method. - # - return - - -class FtpNameError(ValueError): - - def __init__(self, which_server): - print " In order to connect to %s ftp server, you must provide a name.\ - \n Please edit Bio.Restriction.RanaConfig\n" % which_server - sys.exit() - - -class FtpPasswordError(ValueError): - - def __init__(self, which_server): - print "\n\ - \n In order to connect to %s ftp server, you must provide a password.\ - \n Use the --e-mail switch to enter your e-mail address.\ - \n\n" % which_server - sys.exit() - - -class ConnectionError(IOError): - - def __init__(self, which_server): - print '\ - \n Unable to connect to the %s ftp server, make sure your computer\ - \n is connected to the internet and that you have correctly configured\ - \n the ftp proxy.\ - \n Use the --proxy switch to enter the address of your proxy\ - \n' % which_server - sys.exit() - - -__all__ = ['RebaseUpdate', 'FtpNameError', 'FtpPasswordError'] diff -Nru python-biopython-1.62/Bio/Restriction/__init__.py python-biopython-1.63/Bio/Restriction/__init__.py --- python-biopython-1.62/Bio/Restriction/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Restriction/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -136,7 +136,7 @@ ### ##CommOnly = RestrictionBatch() # commercial enzymes ##NonComm = RestrictionBatch() # not available commercially -##for TYPE, (bases, enzymes) in typedict.iteritems(): +##for TYPE, (bases, enzymes) in typedict.items(): ## # ## # The keys are the pseudo-types TYPE (stored as type1, type2...) ## # The names are not important and are only present to differentiate @@ -154,7 +154,7 @@ ## # ## # First eval the bases. ## # -## bases = tuple([eval(x) for x in bases]) +## bases = tuple(eval(x) for x in bases) ## # ## # now create the particular value of RestrictionType for the classes ## # in enzymes. diff -Nru python-biopython-1.62/Bio/SCOP/Cla.py python-biopython-1.63/Bio/SCOP/Cla.py --- python-biopython-1.62/Bio/SCOP/Cla.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SCOP/Cla.py 2013-12-05 14:10:43.000000000 +0000 @@ -17,7 +17,7 @@ """ -import Residues +from . import Residues class Record(object): @@ -69,9 +69,9 @@ s.append(self.sunid) s.append(','.join('='.join((key, str(value))) for key, value - in self.hierarchy.iteritems())) + in self.hierarchy.items())) - return "\t".join(map(str,s)) + "\n" + return "\t".join(map(str, s)) + "\n" def parse(handle): @@ -99,8 +99,7 @@ """ dict.__init__(self) self.filename = filename - f = open(self.filename, "rU") - try: + with open(self.filename, "rU") as f: position = 0 while True: line = f.readline() @@ -113,18 +112,13 @@ if key is not None: self[key] = position position = f.tell() - finally: - f.close() def __getitem__(self, key): """Return an item from the indexed file.""" - position = dict.__getitem__(self,key) + position = dict.__getitem__(self, key) - f = open(self.filename, "rU") - try: + with open(self.filename, "rU") as f: f.seek(position) line = f.readline() record = Record(line) - finally: - f.close() return record diff -Nru python-biopython-1.62/Bio/SCOP/Des.py python-biopython-1.63/Bio/SCOP/Des.py --- python-biopython-1.62/Bio/SCOP/Des.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SCOP/Des.py 2013-12-05 14:10:43.000000000 +0000 @@ -75,7 +75,7 @@ else: s.append("-") s.append(self.description) - return "\t".join(map(str,s)) + "\n" + return "\t".join(map(str, s)) + "\n" def parse(handle): diff -Nru python-biopython-1.62/Bio/SCOP/Dom.py python-biopython-1.63/Bio/SCOP/Dom.py --- python-biopython-1.62/Bio/SCOP/Dom.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SCOP/Dom.py 2013-12-05 14:10:43.000000000 +0000 @@ -15,7 +15,7 @@ "elsewhere at SCOP.":http://scop.mrc-lmb.cam.ac.uk/scop/parse/ """ -from Residues import Residues +from .Residues import Residues class Record(object): @@ -58,7 +58,7 @@ def __str__(self): s = [] s.append(self.sid) - s.append(str(self.residues).replace(" ","\t") ) + s.append(str(self.residues).replace(" ", "\t") ) s.append(self.hierarchy) return "\t".join(s) + "\n" diff -Nru python-biopython-1.62/Bio/SCOP/Hie.py python-biopython-1.63/Bio/SCOP/Hie.py --- python-biopython-1.62/Bio/SCOP/Hie.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SCOP/Hie.py 2013-12-05 14:10:43.000000000 +0000 @@ -64,7 +64,7 @@ self.children = () else: children = children.split(',') - self.children = map(int, children) + self.children = [int(x) for x in children] def __str__(self): s = [] @@ -79,8 +79,7 @@ s.append('-') if self.children: - child_str = map(str, self.children) - s.append(",".join(child_str)) + s.append(",".join(str(x) for x in self.children)) else: s.append('-') diff -Nru python-biopython-1.62/Bio/SCOP/Raf.py python-biopython-1.63/Bio/SCOP/Raf.py --- python-biopython-1.62/Bio/SCOP/Raf.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SCOP/Raf.py 2013-12-05 14:10:43.000000000 +0000 @@ -26,6 +26,9 @@ include chemically modified residues. """ +from __future__ import print_function +from Bio._py3k import basestring + from copy import copy from Bio.Data.SCOPData import protein_letters_3to1 @@ -64,8 +67,7 @@ dict.__init__(self) self.filename = filename - f = open(self.filename, "rU") - try: + with open(self.filename, "rU") as f: position = 0 while True: line = f.readline() @@ -75,20 +77,15 @@ if key is not None: self[key]=position position = f.tell() - finally: - f.close() def __getitem__(self, key): """ Return an item from the indexed file. """ - position = dict.__getitem__(self,key) + position = dict.__getitem__(self, key) - f = open(self.filename, "rU") - try: + with open(self.filename, "rU") as f: f.seek(position) line = f.readline() record = SeqMap(line) - finally: - f.close() return record def getSeqMap(self, residues): @@ -103,7 +100,7 @@ pdbid = residues.pdbid frags = residues.fragments if not frags: - frags =(('_','',''),) # All residues of unnamed chain + frags =(('_', '', ''),) # All residues of unnamed chain seqMap = None for frag in frags: @@ -264,10 +261,10 @@ if chainid == '_': chainid = ' ' resid = r.resid - resSet[(chainid,resid)] = r + resSet[(chainid, resid)] = r resFound = {} - for line in pdb_handle.xreadlines(): + for line in pdb_handle: if line.startswith("ATOM ") or line.startswith("HETATM"): chainid = line[21:22] resid = line[22:27].strip() @@ -282,9 +279,9 @@ resFound[key] = res if len(resSet) != len(resFound): - #for k in resFound.keys(): + #for k in resFound: # del resSet[k] - #print resSet + #print(resSet) raise RuntimeError('I could not find at least one ATOM or HETATM' +' record for each and every residue in this sequence map.') diff -Nru python-biopython-1.62/Bio/SCOP/__init__.py python-biopython-1.63/Bio/SCOP/__init__.py --- python-biopython-1.62/Bio/SCOP/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SCOP/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -48,13 +48,15 @@ """ +from __future__ import print_function + import os import re -import Des -import Cla -import Hie -import Residues +from . import Des +from . import Cla +from . import Hie +from . import Residues from Bio import SeqIO from Bio.Seq import Seq @@ -68,7 +70,7 @@ nodeCodeOrder = [ 'ro', 'cl', 'cf', 'sf', 'fa', 'dm', 'sp', 'px' ] -astralBibIds = [10,20,25,30,35,40,50,70,90,95,100] +astralBibIds = [10, 20, 25, 30, 35, 40, 50, 70, 90, 95, 100] astralEvs = [10, 5, 1, 0.5, 0.1, 0.05, 0.01, 0.005, 0.001, 1e-4, 1e-5, 1e-10, 1e-15, 1e-20, 1e-25, 1e-50] @@ -87,7 +89,7 @@ #See if the cmp function exists (will on Python 2) _cmp = cmp except NameError: - def _cmp(a,b): + def _cmp(a, b): """Implementation of cmp(x,y) for Python 3 (PRIVATE). Based on Python 3 docs which say if you really need the cmp() @@ -114,10 +116,10 @@ if s1[0] != s2[0]: return _cmp(s1[0], s2[0]) - s1 = list(map(int, s1[1:])) - s2 = list(map(int, s2[1:])) + s1 = [int(x) for x in s1[1:]] + s2 = [int(x) for x in s2[1:]] - return _cmp(s1,s2) + return _cmp(s1, s2) _domain_re = re.compile(r">?([\w_\.]*)\s+([\w\.]*)\s+\(([^)]*)\) (.*)") @@ -153,7 +155,7 @@ def _open_scop_file(scop_dir_path, version, filetype): - filename = "dir.%s.scop.txt_%s" % (filetype,version) + filename = "dir.%s.scop.txt_%s" % (filetype, version) handle = open(os.path.join( scop_dir_path, filename)) return handle @@ -235,7 +237,7 @@ records = Hie.parse(hie_handle) for record in records: if record.sunid not in sunidDict: - print record.sunid + print(record.sunid) n = sunidDict[record.sunid] @@ -310,27 +312,21 @@ def write_hie(self, handle): """Build an HIE SCOP parsable file from this object""" - nodes = self._sunidDict.values() # We order nodes to ease comparison with original file - nodes.sort(key = lambda n: n.sunid) - for n in nodes: + for n in sorted(self._sunidDict.values(), key=lambda n: n.sunid): handle.write(str(n.toHieRecord())) def write_des(self, handle): """Build a DES SCOP parsable file from this object""" - nodes = self._sunidDict.values() # Origional SCOP file is not ordered? - nodes.sort(key = lambda n: n.sunid) - for n in nodes: + for n in sorted(self._sunidDict.values(), key=lambda n: n.sunid): if n != self.root: handle.write(str(n.toDesRecord())) def write_cla(self, handle): """Build a CLA SCOP parsable file from this object""" - nodes = self._sidDict.values() # We order nodes to ease comparison with original file - nodes.sort(key = lambda n: n.sunid) - for n in nodes: + for n in sorted(self._sidDict.values(), key=lambda n: n.sunid): handle.write(str(n.toClaRecord())) def getDomainFromSQL(self, sunid=None, sid=None): @@ -367,12 +363,12 @@ cur.execute("select sid, residues, pdbid from cla where sunid=%s", sunid) - [n.sid,n.residues,pdbid] = cur.fetchone() + [n.sid, n.residues, pdbid] = cur.fetchone() n.residues = Residues.Residues(n.residues) n.residues.pdbid=pdbid self._sidDict[n.sid] = n - [n.sunid,n.type,n.sccs,n.description] = data + [n.sunid, n.type, n.sccs, n.description] = data if data[1] != 'ro': cur.execute("SELECT parent FROM hie WHERE child=%s", sunid) @@ -408,7 +404,7 @@ # SQL cla table knows nothing about 'ro' if node.type == 'ro': for c in node.getChildren(): - for d in self.getDescendentsFromSQL(c,type): + for d in self.getDescendentsFromSQL(c, type): des_list.append(d) return des_list @@ -421,7 +417,7 @@ for d in data: if int(d[0]) not in self._sunidDict: n = Node(scop=self) - [n.sunid,n.type,n.sccs,n.description] = d + [n.sunid, n.type, n.sccs, n.description] = d n.sunid=int(n.sunid) self._sunidDict[n.sunid] = n @@ -447,7 +443,7 @@ n = Domain(scop=self) #[n.sunid, n.sid, n.pdbid, n.residues, n.sccs, n.type, #n.description,n.parent] = data - [n.sunid,n.sid, pdbid,n.residues,n.sccs,n.type,n.description, + [n.sunid, n.sid, pdbid, n.residues, n.sccs, n.type, n.description, n.parent] = d[0:8] n.residues = Residues.Residues(n.residues) n.residues.pdbid = pdbid @@ -467,7 +463,7 @@ cur.execute("CREATE TABLE hie (parent INT, child INT, PRIMARY KEY (child),\ INDEX (parent) )") - for p in self._sunidDict.itervalues(): + for p in self._sunidDict.values(): for c in p.children: cur.execute("INSERT INTO hie VALUES (%s,%s)" % (p.sunid, c.sunid)) @@ -480,7 +476,7 @@ residues VARCHAR(50), sccs CHAR(10), cl INT, cf INT, sf INT, fa INT,\ dm INT, sp INT, px INT, PRIMARY KEY (sunid), INDEX (SID) )") - for n in self._sidDict.itervalues(): + for n in self._sidDict.values(): c = n.toClaRecord() cur.execute( "INSERT INTO cla VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)", (n.sunid, n.sid, c.residues.pdbid, c.residues, n.sccs, @@ -498,7 +494,7 @@ description VARCHAR(255),\ PRIMARY KEY (sunid) )") - for n in self._sunidDict.itervalues(): + for n in self._sunidDict.values(): cur.execute( "INSERT INTO des VALUES (%s,%s,%s,%s)", ( n.sunid, n.type, n.sccs, n.description ) ) @@ -567,7 +563,7 @@ if self.scop is None: return self.children else: - return map( self.scop.getNodeBySunid, self.children ) + return [self.scop.getNodeBySunid(x) for x in self.children] def getParent(self): """Return the parent of this Node""" @@ -585,7 +581,7 @@ nodes = [self] if self.scop: - return self.scop.getDescendentsFromSQL(self,node_type) + return self.scop.getDescendentsFromSQL(self, node_type) while nodes[0].type != node_type: if nodes[0].type == 'px': return [] # Fell of the bottom of the hierarchy @@ -604,7 +600,7 @@ node_type = _nodetype_to_code[node_type] if self.scop: - return self.scop.getAscendentFromSQL(self,node_type) + return self.scop.getAscendentFromSQL(self, node_type) else: n = self if n.type == node_type: @@ -627,7 +623,7 @@ of PDB atoms that make up this domain. """ def __init__(self,scop=None): - Node.__init__(self,scop=scop) + Node.__init__(self, scop=scop) self.sid = '' self.residues = None @@ -728,7 +724,7 @@ self.IdDatasets = {} self.IdDatahash = {} - def domainsClusteredByEv(self,id): + def domainsClusteredByEv(self, id): """get domains clustered by evalue""" if id not in self.EvDatasets: if self.db_handle: @@ -739,13 +735,13 @@ raise RuntimeError("No scopseq directory specified") file_prefix = "astral-scopdom-seqres-sel-gs" - filename = "%s-e100m-%s-%s.id" % (file_prefix, astralEv_to_file[id] , + filename = "%s-e100m-%s-%s.id" % (file_prefix, astralEv_to_file[id], self.version) - filename = os.path.join(self.path,filename) + filename = os.path.join(self.path, filename) self.EvDatasets[id] = self.getAstralDomainsFromFile(filename) return self.EvDatasets[id] - def domainsClusteredById(self,id): + def domainsClusteredById(self, id): """get domains clustered by percent id""" if id not in self.IdDatasets: if self.db_handle: @@ -756,7 +752,7 @@ file_prefix = "astral-scopdom-seqres-sel-gs" filename = "%s-bib-%s-%s.id" % (file_prefix, id, self.version) - filename = os.path.join(self.path,filename) + filename = os.path.join(self.path, filename) self.IdDatasets[id] = self.getAstralDomainsFromFile(filename) return self.IdDatasets[id] @@ -767,7 +763,7 @@ if not file_handle: file_handle = open(filename) doms = [] - while 1: + while True: line = file_handle.readline() if not line: break @@ -776,8 +772,8 @@ if filename: file_handle.close() - doms = filter( lambda a: a[0]=='d', doms ) - doms = map( self.scop.getDomainBySid, doms ) + doms = [a for a in doms if a[0]=='d'] + doms = [self.scop.getDomainBySid(x) for x in doms] return doms def getAstralDomainsFromSQL(self, column): @@ -786,11 +782,11 @@ cur = self.db_handle.cursor() cur.execute("SELECT sid FROM astral WHERE "+column+"=1") data = cur.fetchall() - data = map( lambda x: self.scop.getDomainBySid(x[0]), data) + data = [self.scop.getDomainBySid(x[0]) for x in data] return data - def getSeqBySid(self,domain): + def getSeqBySid(self, domain): """get the seq record of a given domain from its sid""" if self.db_handle is None: return self.fasta_dict[domain].seq @@ -799,11 +795,11 @@ cur.execute("SELECT seq FROM astral WHERE sid=%s", domain) return Seq(cur.fetchone()[0]) - def getSeq(self,domain): + def getSeq(self, domain): """Return seq associated with domain""" return self.getSeqBySid(domain.sid) - def hashedDomainsById(self,id): + def hashedDomainsById(self, id): """Get domains clustered by sequence identity in a dict""" if id not in self.IdDatahash: self.IdDatahash[id] = {} @@ -811,7 +807,7 @@ self.IdDatahash[id][d] = 1 return self.IdDatahash[id] - def hashedDomainsByEv(self,id): + def hashedDomainsByEv(self, id): """Get domains clustered by evalue in a dict""" if id not in self.EvDatahash: self.EvDatahash[id] = {} @@ -819,11 +815,11 @@ self.EvDatahash[id][d] = 1 return self.EvDatahash[id] - def isDomainInId(self,dom,id): + def isDomainInId(self, dom, id): """Returns true if the domain is in the astral clusters for percent ID""" return dom in self.hashedDomainsById(id) - def isDomainInEv(self,dom,id): + def isDomainInEv(self, dom, id): """Returns true if the domain is in the ASTRAL clusters for evalues""" return dom in self.hashedDomainsByEv(id) @@ -868,7 +864,7 @@ params = {'pdb' : pdb, 'key' : key, 'sid' : sid, 'disp' : disp, 'dir' : dir, 'loc' : loc} variables = {} - for k, v in params.iteritems(): + for k, v in params.items(): if v is not None: variables[k] = v variables.update(keywds) @@ -884,17 +880,14 @@ simple error checking, and will raise an IOError if it encounters one. """ - import urllib - import urllib2 + from Bio._py3k import urlopen, urlencode + # Open a handle to SCOP. - options = urllib.urlencode(params) - try: - if get: # do a GET - if options: - cgi += "?" + options - handle = urllib2.urlopen(cgi) - else: # do a POST - handle = urllib2.urlopen(cgi, data=options) - except urllib2.HTTPError, exception: - raise exception + options = urlencode(params) + if get: # do a GET + if options: + cgi += "?" + options + handle = urlopen(cgi) + else: # do a POST + handle = urlopen(cgi, data=options) return handle diff -Nru python-biopython-1.62/Bio/SVDSuperimposer/SVDSuperimposer.py python-biopython-1.63/Bio/SVDSuperimposer/SVDSuperimposer.py --- python-biopython-1.62/Bio/SVDSuperimposer/SVDSuperimposer.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SVDSuperimposer/SVDSuperimposer.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,161 +0,0 @@ -# Copyright (C) 2002, Thomas Hamelryck (thamelry@vub.ac.be) -# This code is part of the Biopython distribution and governed by its -# license. Please see the LICENSE file that should have been included -# as part of this package. - -from numpy import dot, transpose, sqrt, array -from numpy.linalg import svd, det - - -class SVDSuperimposer(object): - """ - SVDSuperimposer finds the best rotation and translation to put - two point sets on top of each other (minimizing the RMSD). This is - eg. useful to superimpose crystal structures. - - SVD stands for Singular Value Decomposition, which is used to calculate - the superposition. - - Reference: - - Matrix computations, 2nd ed. Golub, G. & Van Loan, CF., The Johns - Hopkins University Press, Baltimore, 1989 - """ - def __init__(self): - self._clear() - - # Private methods - - def _clear(self): - self.reference_coords = None - self.coords = None - self.transformed_coords = None - self.rot = None - self.tran = None - self.rms = None - self.init_rms = None - - def _rms(self, coords1, coords2): - "Return rms deviations between coords1 and coords2." - diff = coords1 - coords2 - l = coords1.shape[0] - return sqrt(sum(sum(diff*diff))/l) - - # Public methods - - def set(self, reference_coords, coords): - """ - Set the coordinates to be superimposed. - coords will be put on top of reference_coords. - - o reference_coords: an NxDIM array - o coords: an NxDIM array - - DIM is the dimension of the points, N is the number - of points to be superimposed. - """ - # clear everything from previous runs - self._clear() - # store cordinates - self.reference_coords = reference_coords - self.coords = coords - n = reference_coords.shape - m = coords.shape - if n != m or not(n[1] == m[1] == 3): - raise Exception("Coordinate number/dimension mismatch.") - self.n = n[0] - - def run(self): - "Superimpose the coordinate sets." - if self.coords is None or self.reference_coords is None: - raise Exception("No coordinates set.") - coords = self.coords - reference_coords = self.reference_coords - # center on centroid - av1 = sum(coords) / self.n - av2 = sum(reference_coords) / self.n - coords = coords - av1 - reference_coords = reference_coords - av2 - # correlation matrix - a = dot(transpose(coords), reference_coords) - u, d, vt = svd(a) - self.rot = transpose(dot(transpose(vt), transpose(u))) - # check if we have found a reflection - if det(self.rot) < 0: - vt[2] = -vt[2] - self.rot = transpose(dot(transpose(vt), transpose(u))) - self.tran = av2 - dot(av1, self.rot) - - def get_transformed(self): - "Get the transformed coordinate set." - if self.coords is None or self.reference_coords is None: - raise Exception("No coordinates set.") - if self.rot is None: - raise Exception("Nothing superimposed yet.") - if self.transformed_coords is None: - self.transformed_coords = dot(self.coords, self.rot) + self.tran - return self.transformed_coords - - def get_rotran(self): - "Right multiplying rotation matrix and translation." - if self.rot is None: - raise Exception("Nothing superimposed yet.") - return self.rot, self.tran - - def get_init_rms(self): - "Root mean square deviation of untransformed coordinates." - if self.coords is None: - raise Exception("No coordinates set yet.") - if self.init_rms is None: - self.init_rms = self._rms(self.coords, self.reference_coords) - return self.init_rms - - def get_rms(self): - "Root mean square deviation of superimposed coordinates." - if self.rms is None: - transformed_coords = self.get_transformed() - self.rms = self._rms(transformed_coords, self.reference_coords) - return self.rms - - -if __name__ == "__main__": - - # start with two coordinate sets (Nx3 arrays - float) - - x = array([[51.65, -1.90, 50.07], - [50.40, -1.23, 50.65], - [50.68, -0.04, 51.54], - [50.22, -0.02, 52.85]], 'f') - - y = array([[51.30, -2.99, 46.54], - [51.09, -1.88, 47.58], - [52.36, -1.20, 48.03], - [52.71, -1.18, 49.38]], 'f') - - # start! - sup = SVDSuperimposer() - - # set the coords - # y will be rotated and translated on x - sup.set(x, y) - - # do the lsq fit - sup.run() - - # get the rmsd - rms = sup.get_rms() - - # get rotation (right multiplying!) and the translation - rot, tran = sup.get_rotran() - - # rotate y on x - y_on_x1 = dot(y, rot) + tran - - # same thing - y_on_x2 = sup.get_transformed() - - print y_on_x1 - print - print y_on_x2 - print - print "%.2f" % rms diff -Nru python-biopython-1.62/Bio/SVDSuperimposer/__init__.py python-biopython-1.63/Bio/SVDSuperimposer/__init__.py --- python-biopython-1.62/Bio/SVDSuperimposer/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SVDSuperimposer/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,7 @@ +# Copyright (C) 2002, Thomas Hamelryck (thamelry@vub.ac.be) +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. """ SVDSuperimposer finds the best rotation and translation to put two point sets on top of each other (minimizing the RMSD). This is @@ -5,4 +9,161 @@ value decomposition, which is used in the algorithm. """ -from SVDSuperimposer import * +from __future__ import print_function + +from numpy import dot, transpose, sqrt, array +from numpy.linalg import svd, det + + +class SVDSuperimposer(object): + """ + SVDSuperimposer finds the best rotation and translation to put + two point sets on top of each other (minimizing the RMSD). This is + eg. useful to superimpose crystal structures. + + SVD stands for Singular Value Decomposition, which is used to calculate + the superposition. + + Reference: + + Matrix computations, 2nd ed. Golub, G. & Van Loan, CF., The Johns + Hopkins University Press, Baltimore, 1989 + """ + def __init__(self): + self._clear() + + # Private methods + + def _clear(self): + self.reference_coords = None + self.coords = None + self.transformed_coords = None + self.rot = None + self.tran = None + self.rms = None + self.init_rms = None + + def _rms(self, coords1, coords2): + "Return rms deviations between coords1 and coords2." + diff = coords1 - coords2 + l = coords1.shape[0] + return sqrt(sum(sum(diff*diff))/l) + + # Public methods + + def set(self, reference_coords, coords): + """ + Set the coordinates to be superimposed. + coords will be put on top of reference_coords. + + o reference_coords: an NxDIM array + o coords: an NxDIM array + + DIM is the dimension of the points, N is the number + of points to be superimposed. + """ + # clear everything from previous runs + self._clear() + # store cordinates + self.reference_coords = reference_coords + self.coords = coords + n = reference_coords.shape + m = coords.shape + if n != m or not(n[1] == m[1] == 3): + raise Exception("Coordinate number/dimension mismatch.") + self.n = n[0] + + def run(self): + "Superimpose the coordinate sets." + if self.coords is None or self.reference_coords is None: + raise Exception("No coordinates set.") + coords = self.coords + reference_coords = self.reference_coords + # center on centroid + av1 = sum(coords) / self.n + av2 = sum(reference_coords) / self.n + coords = coords - av1 + reference_coords = reference_coords - av2 + # correlation matrix + a = dot(transpose(coords), reference_coords) + u, d, vt = svd(a) + self.rot = transpose(dot(transpose(vt), transpose(u))) + # check if we have found a reflection + if det(self.rot) < 0: + vt[2] = -vt[2] + self.rot = transpose(dot(transpose(vt), transpose(u))) + self.tran = av2 - dot(av1, self.rot) + + def get_transformed(self): + "Get the transformed coordinate set." + if self.coords is None or self.reference_coords is None: + raise Exception("No coordinates set.") + if self.rot is None: + raise Exception("Nothing superimposed yet.") + if self.transformed_coords is None: + self.transformed_coords = dot(self.coords, self.rot) + self.tran + return self.transformed_coords + + def get_rotran(self): + "Right multiplying rotation matrix and translation." + if self.rot is None: + raise Exception("Nothing superimposed yet.") + return self.rot, self.tran + + def get_init_rms(self): + "Root mean square deviation of untransformed coordinates." + if self.coords is None: + raise Exception("No coordinates set yet.") + if self.init_rms is None: + self.init_rms = self._rms(self.coords, self.reference_coords) + return self.init_rms + + def get_rms(self): + "Root mean square deviation of superimposed coordinates." + if self.rms is None: + transformed_coords = self.get_transformed() + self.rms = self._rms(transformed_coords, self.reference_coords) + return self.rms + + +if __name__ == "__main__": + + # start with two coordinate sets (Nx3 arrays - float) + + x = array([[51.65, -1.90, 50.07], + [50.40, -1.23, 50.65], + [50.68, -0.04, 51.54], + [50.22, -0.02, 52.85]], 'f') + + y = array([[51.30, -2.99, 46.54], + [51.09, -1.88, 47.58], + [52.36, -1.20, 48.03], + [52.71, -1.18, 49.38]], 'f') + + # start! + sup = SVDSuperimposer() + + # set the coords + # y will be rotated and translated on x + sup.set(x, y) + + # do the lsq fit + sup.run() + + # get the rmsd + rms = sup.get_rms() + + # get rotation (right multiplying!) and the translation + rot, tran = sup.get_rotran() + + # rotate y on x + y_on_x1 = dot(y, rot) + tran + + # same thing + y_on_x2 = sup.get_transformed() + + print(y_on_x1) + print("") + print(y_on_x2) + print("") + print("%.2f" % rms) diff -Nru python-biopython-1.62/Bio/Search.py python-biopython-1.63/Bio/Search.py --- python-biopython-1.62/Bio/Search.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Search.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + import warnings from Bio import BiopythonDeprecationWarning warnings.warn("Long obsolete module Bio/Search.py is deprecated.", diff -Nru python-biopython-1.62/Bio/SearchIO/BlastIO/__init__.py python-biopython-1.63/Bio/SearchIO/BlastIO/__init__.py --- python-biopython-1.62/Bio/SearchIO/BlastIO/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SearchIO/BlastIO/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -196,14 +196,14 @@ # pass the custom column names as a Python list >>> fname = 'Blast/tab_2226_tblastn_009.txt' >>> custom_fields = ['qseqid', 'sseqid'] - >>> qresult = SearchIO.parse(fname, 'blast-tab', fields=custom_fields).next() + >>> qresult = next(SearchIO.parse(fname, 'blast-tab', fields=custom_fields)) >>> qresult QueryResult(id='gi|16080617|ref|NP_391444.1|', 3 hits) # pass the custom column names as a space-separated string >>> fname = 'Blast/tab_2226_tblastn_009.txt' >>> custom_fields = 'qseqid sseqid' - >>> qresult = SearchIO.parse(fname, 'blast-tab', fields=custom_fields).next() + >>> qresult = next(SearchIO.parse(fname, 'blast-tab', fields=custom_fields)) >>> qresult QueryResult(id='gi|16080617|ref|NP_391444.1|', 3 hits) @@ -395,10 +395,9 @@ """ -from blast_tab import * -from blast_xml import * -from blast_text import * - +from .blast_tab import BlastTabParser, BlastTabIndexer, BlastTabWriter +from .blast_xml import BlastXmlParser, BlastXmlIndexer, BlastXmlWriter +from .blast_text import BlastTextParser # if not used as a module, run the doctest if __name__ == "__main__": diff -Nru python-biopython-1.62/Bio/SearchIO/BlastIO/blast_tab.py python-biopython-1.63/Bio/SearchIO/BlastIO/blast_tab.py --- python-biopython-1.62/Bio/SearchIO/BlastIO/blast_tab.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SearchIO/BlastIO/blast_tab.py 2013-12-05 14:10:43.000000000 +0000 @@ -8,6 +8,8 @@ import re from Bio._py3k import _as_bytes, _bytes_to_string +from Bio._py3k import basestring + from Bio.SearchIO._index import SearchIndexer from Bio.SearchIO._model import QueryResult, Hit, HSP, HSPFragment @@ -123,8 +125,8 @@ 'qseq': ('query', str), 'sseq': ('hit', str), } -_SUPPORTED_FIELDS = set(_COLUMN_QRESULT.keys() + _COLUMN_HIT.keys() + - _COLUMN_HSP.keys() + _COLUMN_FRAG.keys()) +_SUPPORTED_FIELDS = set(list(_COLUMN_QRESULT) + list(_COLUMN_HIT) + + list(_COLUMN_HSP) + list(_COLUMN_FRAG)) # column order in the non-commented tabular output variant # values must be keys inside the column-attribute maps above @@ -672,8 +674,8 @@ if not self.has_comments: qresult_counter += 1 hit_counter += len(qresult) - hsp_counter += sum([len(hit) for hit in qresult]) - frag_counter += sum([len(hit.fragments) for hit in qresult]) + hsp_counter += sum(len(hit) for hit in qresult) + frag_counter += sum(len(hit.fragments) for hit in qresult) # if it's commented and there are no hits in the qresult, we still # increment the counter if self.has_comments: @@ -815,8 +817,7 @@ comments = [] # inverse mapping of the long-short name map, required # for writing comments - inv_field_map = dict((value, key) for key, value in - _LONG_SHORT_MAP.items()) + inv_field_map = dict((v, k) for k, v in _LONG_SHORT_MAP.items()) # try to anticipate qress without version if not hasattr(qres, 'version'): @@ -838,7 +839,7 @@ # qresults without hits don't show the Fields comment if qres: comments.append('# Fields: %s' % - ', '.join([inv_field_map[field] for field in self.fields])) + ', '.join(inv_field_map[field] for field in self.fields)) comments.append('# %i hits found' % len(qres)) return '\n'.join(comments) + '\n' diff -Nru python-biopython-1.62/Bio/SearchIO/BlastIO/blast_text.py python-biopython-1.63/Bio/SearchIO/BlastIO/blast_text.py --- python-biopython-1.62/Bio/SearchIO/BlastIO/blast_text.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SearchIO/BlastIO/blast_text.py 2013-12-05 14:10:43.000000000 +0000 @@ -6,14 +6,19 @@ """Bio.SearchIO parser for BLAST+ plain text output formats. At the moment this is a wrapper around Biopython's NCBIStandalone text -parser. +parser (which is now deprecated). """ from Bio.Alphabet import generic_dna, generic_protein -from Bio.Blast import NCBIStandalone from Bio.SearchIO._model import QueryResult, Hit, HSP, HSPFragment +import warnings +from Bio import BiopythonDeprecationWarning +with warnings.catch_warnings(): + warnings.simplefilter('ignore', BiopythonDeprecationWarning) + from Bio.Blast import NCBIStandalone + __all__ = ['BlastTextParser'] @@ -101,7 +106,7 @@ for seqtrio in zip(bhsp.query, bhsp.sbjct, bhsp.match): qchar, hchar, mchar = seqtrio if qchar == ' ' or hchar == ' ': - assert all([' ' == x for x in seqtrio]) + assert all(' ' == x for x in seqtrio) else: qseq += qchar hseq += hchar diff -Nru python-biopython-1.62/Bio/SearchIO/BlastIO/blast_xml.py python-biopython-1.63/Bio/SearchIO/BlastIO/blast_xml.py --- python-biopython-1.62/Bio/SearchIO/BlastIO/blast_xml.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SearchIO/BlastIO/blast_xml.py 2013-12-05 14:10:43.000000000 +0000 @@ -24,7 +24,7 @@ from xml.etree import ElementTree as ElementTree -from Bio._py3k import _as_bytes, _bytes_to_string +from Bio._py3k import _as_bytes, _bytes_to_string, unicode _empty_bytes_string = _as_bytes("") from Bio.Alphabet import generic_dna, generic_protein @@ -568,7 +568,7 @@ generator = self._parser(handle, **self._kwargs) generator._meta = self._meta generator._fallback = self._fallback - return iter(generator).next() + return next(iter(generator)) def get_raw(self, offset): qend_mark = self.qend_mark @@ -689,7 +689,7 @@ self.frag_counter = 0, 0, 0, 0 # get the first qresult, since the preamble requires its attr values - first_qresult = qresults.next() + first_qresult = next(qresults) # start the XML document, set the root element, and create the preamble xml.startDocument() xml.startParent('BlastOutput') @@ -843,7 +843,7 @@ """Adjusts output to mimic native BLAST+ XML as much as possible.""" # adjust coordinates - if attr in ('query_start' ,'query_end' ,'hit_start', 'hit_end', + if attr in ('query_start', 'query_end', 'hit_start', 'hit_end', 'pattern_start', 'pattern_end'): content = getattr(hsp, attr) + 1 if '_start' in attr: diff -Nru python-biopython-1.62/Bio/SearchIO/BlatIO.py python-biopython-1.63/Bio/SearchIO/BlatIO.py --- python-biopython-1.62/Bio/SearchIO/BlatIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SearchIO/BlatIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -177,11 +177,12 @@ HSP and HSPFragment documentation for more details on these properties. """ - import re from math import log from Bio._py3k import _as_bytes, _bytes_to_string +from Bio._py3k import zip + from Bio.Alphabet import generic_dna from Bio.SearchIO._index import SearchIndexer from Bio.SearchIO._model import QueryResult, Hit, HSP, HSPFragment @@ -204,11 +205,10 @@ caster -- Cast function to use on each list item. """ - filtered = (x for x in filter(None, csv_string.split(','))) if caster is None: - return list(filtered) + return [x for x in csv_string.split(',') if x] else: - return [caster(x) for x in filtered] + return [caster(x) for x in csv_string.split(',') if x] def _reorient_starts(starts, blksizes, seqlen, strand): @@ -308,10 +308,10 @@ # set query and hit coords # this assumes each block has no gaps (which seems to be the case) assert len(qstarts) == len(hstarts) == len(psl['blocksizes']) - query_range_all = zip(qstarts, [x + y for x, y in - zip(qstarts, psl['blocksizes'])]) - hit_range_all = zip(hstarts, [x + y for x, y in - zip(hstarts, psl['blocksizes'])]) + query_range_all = list(zip(qstarts, [x + y for x, y in + zip(qstarts, psl['blocksizes'])])) + hit_range_all = list(zip(hstarts, [x + y for x, y in + zip(hstarts, psl['blocksizes'])])) # check length of sequences and coordinates, all must match if 'tseqs' in psl and 'qseqs' in psl: assert len(psl['tseqs']) == len(psl['qseqs']) == \ @@ -399,7 +399,7 @@ def _parse_row(self): """Returns a dictionary of parsed column values.""" assert self.line - cols = filter(None, self.line.strip().split('\t')) + cols = [x for x in self.line.strip().split('\t') if x] self._validate_cols(cols) psl = {} @@ -539,11 +539,11 @@ while True: end_offset = handle.tell() - cols = line.strip().split(tab_char) + cols = [x for x in line.strip().split(tab_char) if x] if qresult_key is None: - qresult_key = list(filter(None, cols))[query_id_idx] + qresult_key = cols[query_id_idx] else: - curr_key = list(filter(None, cols))[query_id_idx] + curr_key = cols[query_id_idx] if curr_key != qresult_key: yield _bytes_to_string(qresult_key), start_offset, \ @@ -570,11 +570,11 @@ line = handle.readline() if not line: break - cols = line.strip().split(tab_char) + cols = [x for x in line.strip().split(tab_char) if x] if qresult_key is None: - qresult_key = list(filter(None, cols))[query_id_idx] + qresult_key = cols[query_id_idx] else: - curr_key = list(filter(None, cols))[query_id_idx] + curr_key = cols[query_id_idx] if curr_key != qresult_key: break qresult_raw += line @@ -604,8 +604,8 @@ handle.write(self._build_row(qresult)) qresult_counter += 1 hit_counter += len(qresult) - hsp_counter += sum([len(hit) for hit in qresult]) - frag_counter += sum([len(hit.fragments) for hit in qresult]) + hsp_counter += sum(len(hit) for hit in qresult) + frag_counter += sum(len(hit.fragments) for hit in qresult) return qresult_counter, hit_counter, hsp_counter, frag_counter diff -Nru python-biopython-1.62/Bio/SearchIO/ExonerateIO/__init__.py python-biopython-1.63/Bio/SearchIO/ExonerateIO/__init__.py --- python-biopython-1.62/Bio/SearchIO/ExonerateIO/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SearchIO/ExonerateIO/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -193,7 +193,7 @@ >>> from Bio import SearchIO >>> fname = 'Exonerate/exn_22_m_coding2coding_fshifts.exn' - >>> qresult = SearchIO.parse(fname, 'exonerate-text').next() + >>> qresult = next(SearchIO.parse(fname, 'exonerate-text')) >>> hsp = qresult[0][0] # first hit, first hsp >>> hsp HSP(...) @@ -240,9 +240,9 @@ # - Cigar and vulgar parsing results will most likely be different, due to the # different type of data stored by both formats -from exonerate_text import * -from exonerate_vulgar import * -from exonerate_cigar import * +from .exonerate_text import ExonerateTextParser, ExonerateTextIndexer +from .exonerate_vulgar import ExonerateVulgarParser, ExonerateVulgarIndexer +from .exonerate_cigar import ExonerateCigarParser, ExonerateCigarIndexer # if not used as a module, run the doctest diff -Nru python-biopython-1.62/Bio/SearchIO/ExonerateIO/_base.py python-biopython-1.63/Bio/SearchIO/ExonerateIO/_base.py --- python-biopython-1.62/Bio/SearchIO/ExonerateIO/_base.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SearchIO/ExonerateIO/_base.py 2013-12-05 14:10:43.000000000 +0000 @@ -254,7 +254,8 @@ def _parse_alignment_header(self): # read all header lines and store them aln_header = [] - while not self.line == '\n': + # header is everything before the first empty line + while self.line.strip(): aln_header.append(self.line.strip()) self.line = self.handle.readline() # then parse them diff -Nru python-biopython-1.62/Bio/SearchIO/ExonerateIO/exonerate_cigar.py python-biopython-1.63/Bio/SearchIO/ExonerateIO/exonerate_cigar.py --- python-biopython-1.62/Bio/SearchIO/ExonerateIO/exonerate_cigar.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SearchIO/ExonerateIO/exonerate_cigar.py 2013-12-05 14:10:43.000000000 +0000 @@ -9,8 +9,8 @@ from Bio._py3k import _as_bytes, _bytes_to_string -from _base import _BaseExonerateParser, _STRAND_MAP -from exonerate_vulgar import ExonerateVulgarIndexer +from ._base import _BaseExonerateParser, _STRAND_MAP +from .exonerate_vulgar import ExonerateVulgarIndexer __all__ = ['ExonerateCigarParser', 'ExonerateCigarIndexer'] diff -Nru python-biopython-1.62/Bio/SearchIO/ExonerateIO/exonerate_text.py python-biopython-1.63/Bio/SearchIO/ExonerateIO/exonerate_text.py --- python-biopython-1.62/Bio/SearchIO/ExonerateIO/exonerate_text.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SearchIO/ExonerateIO/exonerate_text.py 2013-12-05 14:10:43.000000000 +0000 @@ -9,11 +9,14 @@ from itertools import chain from Bio._py3k import _as_bytes, _bytes_to_string +from Bio._py3k import zip + + from Bio.Alphabet import generic_protein -from _base import _BaseExonerateParser, _BaseExonerateIndexer, _STRAND_MAP, \ +from ._base import _BaseExonerateParser, _BaseExonerateIndexer, _STRAND_MAP, \ _parse_hit_or_query_line -from exonerate_vulgar import parse_vulgar_comp, _RE_VULGAR +from .exonerate_vulgar import parse_vulgar_comp, _RE_VULGAR __all__ = ['ExonerateTextParser', 'ExonerateTextIndexer'] @@ -81,10 +84,10 @@ if strand == -1: sorted_coords = [(max(a, b), min(a, b)) for a, b in coords] inter_coords = list(chain(*sorted_coords))[1:-1] - return zip(inter_coords[1::2], inter_coords[::2]) + return list(zip(inter_coords[1::2], inter_coords[::2])) else: inter_coords = list(chain(*coords))[1:-1] - return zip(inter_coords[::2], inter_coords[1::2]) + return list(zip(inter_coords[::2], inter_coords[1::2])) def _stitch_rows(raw_rows): @@ -93,7 +96,7 @@ # (i.e. alignments with codons using cdna2genome model) # by creating additional rows to contain the codons try: - max_len = max([len(x) for x in raw_rows]) + max_len = max(len(x) for x in raw_rows) for row in raw_rows: assert len(row) == max_len except AssertionError: @@ -253,7 +256,7 @@ fstart = hsp['%s_start' % seq_type] # fend is fstart + number of residues in the sequence, minus gaps fend = fstart + len( - hsp[seq_type][0].replace('-','').replace('>', + hsp[seq_type][0].replace('-', '').replace('>', '').replace('<', '')) * seq_step coords = [(fstart, fend)] # and start from the second block, after the first inter seq @@ -311,7 +314,7 @@ hit = header['hit'] hsp = header['hsp'] # check for values that must have been set by previous methods - for val_name in ('query_start', 'query_end' ,'hit_start', 'hit_end', + for val_name in ('query_start', 'query_end', 'hit_start', 'hit_end', 'query_strand', 'hit_strand'): assert val_name in hsp, hsp diff -Nru python-biopython-1.62/Bio/SearchIO/ExonerateIO/exonerate_vulgar.py python-biopython-1.63/Bio/SearchIO/ExonerateIO/exonerate_vulgar.py --- python-biopython-1.62/Bio/SearchIO/ExonerateIO/exonerate_vulgar.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SearchIO/ExonerateIO/exonerate_vulgar.py 2013-12-05 14:10:43.000000000 +0000 @@ -8,8 +8,9 @@ import re from Bio._py3k import _as_bytes, _bytes_to_string +from Bio._py3k import zip -from _base import _BaseExonerateParser, _BaseExonerateIndexer, _STRAND_MAP +from ._base import _BaseExonerateParser, _BaseExonerateIndexer, _STRAND_MAP __all__ = ['ExonerateVulgarParser', 'ExonerateVulgarIndexer'] @@ -102,8 +103,8 @@ hstarts, hends = hends, hstarts # set start and end ranges - hsp['query_ranges'] = zip(qstarts, qends) - hsp['hit_ranges'] = zip(hstarts, hends) + hsp['query_ranges'] = list(zip(qstarts, qends)) + hsp['hit_ranges'] = list(zip(hstarts, hends)) return hsp @@ -153,7 +154,8 @@ # cast score into int hsp['score'] = int(hsp['score']) # store vulgar line and parse it - hsp['vulgar_comp'] = vulgars.group(10) + # rstrip to remove line endings (otherwise gives errors in Windows) + hsp['vulgar_comp'] = vulgars.group(10).rstrip() hsp = parse_vulgar_comp(hsp, hsp['vulgar_comp']) return {'qresult': qresult, 'hit': hit, 'hsp': hsp} diff -Nru python-biopython-1.62/Bio/SearchIO/FastaIO.py python-biopython-1.63/Bio/SearchIO/FastaIO.py --- python-biopython-1.62/Bio/SearchIO/FastaIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SearchIO/FastaIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -119,12 +119,15 @@ # precompile regex patterns # regex for program name _RE_FLAVS = re.compile(r't?fast[afmsxy]|pr[sf][sx]|lalign|[gs]?[glso]search') -# regex for sequence ID and length -_PTR_ID_DESC_SEQLEN = r'>>>(.+?)\s+(.*?) *- (\d+) (?:aa|nt)$' +# regex for sequence ID and length ~ deals with both \n and \r\n +_PTR_ID_DESC_SEQLEN = r'>>>(.+?)\s+(.*?) *- (\d+) (?:aa|nt)\s*$' _RE_ID_DESC_SEQLEN = re.compile(_PTR_ID_DESC_SEQLEN) _RE_ID_DESC_SEQLEN_IDX = re.compile(_as_bytes(_PTR_ID_DESC_SEQLEN)) # regex for qresult, hit, or hsp attribute value _RE_ATTR = re.compile(r'^; [a-z]+(_[ \w-]+):\s+(.*)$') +# regex for capturing excess start and end sequences in alignments +_RE_START_EXC = re.compile(r'^-*') +_RE_END_EXC = re.compile(r'-*$') # attribute name mappings _HSP_ATTR_MAP = { @@ -176,10 +179,26 @@ """ # get aligned sequences and check if they have equal lengths + start = 0 for seq_type in ('hit', 'query'): if 'tfast' not in program: - parsed[seq_type]['seq'] = _extract_alignment(parsed[seq_type]) - assert len(parsed['query']['seq']) == len(parsed['hit']['seq']), parsed + pseq = parsed[seq_type] + # adjust start and end coordinates based on the amount of + # filler characters + start, stop = _get_aln_slice_coords(pseq) + start_adj = len(re.search(_RE_START_EXC, pseq['seq']).group(0)) + stop_adj = len(re.search(_RE_END_EXC, pseq['seq']).group(0)) + start = start + start_adj + stop = stop + start_adj - stop_adj + parsed[seq_type]['seq'] = pseq['seq'][start:stop] + assert len(parsed['query']['seq']) == len(parsed['hit']['seq']), "%r %r" \ + % (len(parsed['query']['seq']), len(parsed['hit']['seq'])) + if 'homology' in hsp.aln_annotation: + # only using 'start' since FASTA seems to have trimmed the 'excess' + # end part + hsp.aln_annotation['homology'] = hsp.aln_annotation['homology'][start:] + # hit or query works equally well here + assert len(hsp.aln_annotation['homology']) == len(parsed['hit']['seq']) # query and hit sequence types must be the same assert parsed['query']['_type'] == parsed['hit']['_type'] @@ -208,7 +227,7 @@ setattr(hsp.fragment, seq_type + '_strand', 0) -def _extract_alignment(parsed_hsp): +def _get_aln_slice_coords(parsed_hsp): """Helper function for the main parsing code. To get the actual pairwise alignment sequences, we must first @@ -237,7 +256,7 @@ assert 0 <= start and start < stop and stop <= len(seq_stripped), \ "Problem with sequence start/stop,\n%s[%i:%i]\n%s" \ % (seq, start, stop, parsed_hsp) - return seq_stripped[start:stop] + return start, stop class FastaM10Parser(object): @@ -333,8 +352,7 @@ qresult.seq_len = int(seq_len) # get target from the next line self.line = self.handle.readline() - qresult.target = list(filter(None, - self.line.split(' ')))[1].strip() + qresult.target = [x for x in self.line.split(' ') if x][1].strip() if desc is not None: qresult.description = desc # set values from preamble @@ -379,7 +397,7 @@ parsed_hsp['hit']['seq'] += self.line.strip() elif state == _STATE_CONS_BLOCK: hsp.aln_annotation['homology'] += \ - self.line.strip('\n') + self.line.strip('\r\n') # process HSP alignment and coordinates _set_hsp_seqs(hsp, parsed_hsp, self._preamble['program']) hit = Hit(hsp_list) @@ -477,7 +495,7 @@ parsed_hsp['query']['seq'] += self.line.strip() elif state == _STATE_CONS_BLOCK: hsp.fragment.aln_annotation['homology'] += \ - self.line.strip('\n') + self.line.strip('\r\n') # we should not get here! else: raise ValueError("Unexpected line: %r" % self.line) diff -Nru python-biopython-1.62/Bio/SearchIO/HmmerIO/__init__.py python-biopython-1.63/Bio/SearchIO/HmmerIO/__init__.py --- python-biopython-1.62/Bio/SearchIO/HmmerIO/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SearchIO/HmmerIO/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -283,10 +283,12 @@ """ -from hmmer2_text import * -from hmmer3_domtab import * -from hmmer3_text import * -from hmmer3_tab import * +from .hmmer2_text import Hmmer2TextParser, Hmmer2TextIndexer +from .hmmer3_domtab import Hmmer3DomtabParser, Hmmer3DomtabHmmhitParser, Hmmer3DomtabHmmqueryParser +from .hmmer3_domtab import Hmmer3DomtabHmmhitIndexer, Hmmer3DomtabHmmqueryIndexer +from .hmmer3_domtab import Hmmer3DomtabHmmhitWriter, Hmmer3DomtabHmmqueryWriter +from .hmmer3_text import Hmmer3TextParser, Hmmer3TextIndexer +from .hmmer3_tab import Hmmer3TabParser, Hmmer3TabIndexer, Hmmer3TabWriter # if not used as a module, run the doctest diff -Nru python-biopython-1.62/Bio/SearchIO/HmmerIO/hmmer2_text.py python-biopython-1.63/Bio/SearchIO/HmmerIO/hmmer2_text.py --- python-biopython-1.62/Bio/SearchIO/HmmerIO/hmmer2_text.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SearchIO/HmmerIO/hmmer2_text.py 2013-12-05 14:10:43.000000000 +0000 @@ -12,7 +12,7 @@ from Bio.Alphabet import generic_protein from Bio.SearchIO._model import QueryResult, Hit, HSP, HSPFragment -from _base import _BaseHmmerTextIndexer +from ._base import _BaseHmmerTextIndexer __all__ = ['Hmmer2TextParser', 'Hmmer2TextIndexer'] diff -Nru python-biopython-1.62/Bio/SearchIO/HmmerIO/hmmer3_domtab.py python-biopython-1.63/Bio/SearchIO/HmmerIO/hmmer3_domtab.py --- python-biopython-1.62/Bio/SearchIO/HmmerIO/hmmer3_domtab.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SearchIO/HmmerIO/hmmer3_domtab.py 2013-12-05 14:10:43.000000000 +0000 @@ -10,7 +10,7 @@ from Bio.Alphabet import generic_protein from Bio.SearchIO._model import QueryResult, Hit, HSP, HSPFragment -from hmmer3_tab import Hmmer3TabParser, Hmmer3TabIndexer +from .hmmer3_tab import Hmmer3TabParser, Hmmer3TabIndexer class Hmmer3DomtabParser(Hmmer3TabParser): @@ -20,7 +20,7 @@ def _parse_row(self): """Returns a dictionary of parsed row values.""" assert self.line - cols = filter(None, self.line.strip().split(' ')) + cols = [x for x in self.line.strip().split(' ') if x] # if len(cols) > 23, we have extra description columns # combine them all into one string in the 19th column if len(cols) > 23: @@ -205,7 +205,7 @@ qresult_counter, hit_counter, hsp_counter, frag_counter = 0, 0, 0, 0 try: - first_qresult = qresults.next() + first_qresult = next(qresults) except StopIteration: handle.write(self._build_header()) else: @@ -217,8 +217,8 @@ handle.write(self._build_row(qresult)) qresult_counter += 1 hit_counter += len(qresult) - hsp_counter += sum([len(hit) for hit in qresult]) - frag_counter += sum([len(hit.fragments) for hit in qresult]) + hsp_counter += sum(len(hit) for hit in qresult) + frag_counter += sum(len(hit.fragments) for hit in qresult) return qresult_counter, hit_counter, hsp_counter, frag_counter diff -Nru python-biopython-1.62/Bio/SearchIO/HmmerIO/hmmer3_tab.py python-biopython-1.63/Bio/SearchIO/HmmerIO/hmmer3_tab.py --- python-biopython-1.62/Bio/SearchIO/HmmerIO/hmmer3_tab.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SearchIO/HmmerIO/hmmer3_tab.py 2013-12-05 14:10:43.000000000 +0000 @@ -36,7 +36,7 @@ def _parse_row(self): """Returns a dictionary of parsed row values.""" - cols = filter(None, self.line.strip().split(' ')) + cols = [x for x in self.line.strip().split(' ') if x] # if len(cols) > 19, we have extra description columns # combine them all into one string in the 19th column if len(cols) > 19: @@ -174,11 +174,11 @@ if not line: break - cols = line.strip().split(split_mark) + cols = [x for x in line.strip().split(split_mark) if x] if qresult_key is None: - qresult_key = list(filter(None, cols))[query_id_idx] + qresult_key = cols[query_id_idx] else: - curr_key = list(filter(None, cols))[query_id_idx] + curr_key = cols[query_id_idx] if curr_key != qresult_key: adj_end = end_offset - len(line) @@ -206,7 +206,7 @@ line = handle.readline() if not line: break - cols = list(filter(None, line.strip().split(split_mark))) + cols = [x for x in line.strip().split(split_mark) if x] if qresult_key is None: qresult_key = cols[query_id_idx] else: @@ -235,7 +235,7 @@ qresult_counter, hit_counter, hsp_counter, frag_counter = 0, 0, 0, 0 try: - first_qresult = qresults.next() + first_qresult = next(qresults) except StopIteration: handle.write(self._build_header()) else: @@ -247,8 +247,8 @@ handle.write(self._build_row(qresult)) qresult_counter += 1 hit_counter += len(qresult) - hsp_counter += sum([len(hit) for hit in qresult]) - frag_counter += sum([len(hit.fragments) for hit in qresult]) + hsp_counter += sum(len(hit) for hit in qresult) + frag_counter += sum(len(hit.fragments) for hit in qresult) return qresult_counter, hit_counter, hsp_counter, frag_counter diff -Nru python-biopython-1.62/Bio/SearchIO/HmmerIO/hmmer3_text.py python-biopython-1.63/Bio/SearchIO/HmmerIO/hmmer3_text.py --- python-biopython-1.62/Bio/SearchIO/HmmerIO/hmmer3_text.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SearchIO/HmmerIO/hmmer3_text.py 2013-12-05 14:10:43.000000000 +0000 @@ -12,7 +12,7 @@ from Bio.Alphabet import generic_protein from Bio.SearchIO._model import QueryResult, Hit, HSP, HSPFragment -from _base import _BaseHmmerTextIndexer +from ._base import _BaseHmmerTextIndexer __all__ = ['Hmmer3TextParser', 'Hmmer3TextIndexer'] @@ -89,7 +89,7 @@ regx = re.search(_RE_OPT, self.line) # if target in regx.group(1), then we store the key as target if 'target' in regx.group(1): - meta['target'] = regx.group(2) + meta['target'] = regx.group(2).strip() else: meta[regx.group(1)] = regx.group(2) @@ -182,7 +182,7 @@ return hit_list # entering hit results row # parse the columns into a list - row = filter(None, self.line.strip().split(' ')) + row = [x for x in self.line.strip().split(' ') if x] # join the description words if it's >1 word if len(row) > 10: row[9] = ' '.join(row[9:]) @@ -248,7 +248,7 @@ hit_list.append(hit) break - parsed = filter(None, self.line.strip().split(' ')) + parsed = [x for x in self.line.strip().split(' ') if x] assert len(parsed) == 16 # parsed column order: # index, is_included, bitscore, bias, evalue_cond, evalue diff -Nru python-biopython-1.62/Bio/SearchIO/__init__.py python-biopython-1.63/Bio/SearchIO/__init__.py --- python-biopython-1.62/Bio/SearchIO/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SearchIO/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -40,8 +40,8 @@ >>> from Bio import SearchIO >>> for qresult in SearchIO.parse('Blast/mirna.xml', 'blast-xml'): - ... print qresult.id, qresult.description - ... + ... print("%s %s" % (qresult.id, qresult.description)) + ... 33211 mir_1 33212 mir_2 33213 mir_3 @@ -52,8 +52,8 @@ than one queries: >>> qresult = SearchIO.read('Blast/xml_2226_blastp_004.xml', 'blast-xml') - >>> print qresult.id, qresult.description - ... + >>> print("%s %s" % (qresult.id, qresult.description)) + ... gi|11464971:4-101 pleckstrin [Mus musculus] >>> SearchIO.read('Blast/mirna.xml', 'blast-xml') @@ -177,7 +177,7 @@ - exonerate-text - Exonerate plain text output. - exonerate-vulgar - Exonerate vulgar line. - - exonerate-text - Exonerate cigar line. + - exonerate-cigar - Exonerate cigar line. - fasta-m10 - Bill Pearson's FASTA -m 10 output. - hmmer3-text - HMMER3 regular text output format. Supported HMMER3 subprograms are hmmscan, hmmsearch, and phmmer. @@ -194,8 +194,8 @@ """ -# For using with statement in Python 2.5 or Jython -from __future__ import with_statement +from __future__ import print_function +from Bio._py3k import basestring __docformat__ = 'epytext en' @@ -281,8 +281,8 @@ >>> qresults >>> for qresult in qresults: - ... print "Search %s has %i hits" % (qresult.id, len(qresult)) - ... + ... print("Search %s has %i hits" % (qresult.id, len(qresult))) + ... Search 33211 has 100 hits Search 33212 has 44 hits Search 33213 has 95 hits @@ -294,8 +294,8 @@ >>> from Bio import SearchIO >>> for qresult in SearchIO.parse('Blast/mirna.tab', 'blast-tab', comments=True): - ... print "Search %s has %i hits" % (qresult.id, len(qresult)) - ... + ... print("Search %s has %i hits" % (qresult.id, len(qresult))) + ... Search 33211 has 100 hits Search 33212 has 44 hits Search 33213 has 95 hits @@ -328,8 +328,8 @@ >>> from Bio import SearchIO >>> qresult = SearchIO.read('Blast/xml_2226_blastp_004.xml', 'blast-xml') - >>> print qresult.id, qresult.description - ... + >>> print("%s %s" % (qresult.id, qresult.description)) + ... gi|11464971:4-101 pleckstrin [Mus musculus] If the given handle has no results, an exception will be raised: @@ -356,12 +356,12 @@ generator = parse(handle, format, **kwargs) try: - first = generator.next() + first = next(generator) except StopIteration: raise ValueError("No query results found in handle") else: try: - second = generator.next() + second = next(generator) except StopIteration: second = None @@ -385,7 +385,7 @@ >>> from Bio import SearchIO >>> qresults = SearchIO.parse('Blast/wnts.xml', 'blast-xml') >>> search_dict = SearchIO.to_dict(qresults) - >>> sorted(search_dict.keys()) + >>> sorted(search_dict) ['gi|156630997:105-1160', ..., 'gi|371502086:108-1205', 'gi|53729353:216-1313'] >>> search_dict['gi|156630997:105-1160'] QueryResult(id='gi|156630997:105-1160', 5 hits) @@ -399,7 +399,7 @@ >>> qresults = SearchIO.parse('Blast/wnts.xml', 'blast-xml') >>> key_func = lambda qresult: qresult.id.split('|')[1] >>> search_dict = SearchIO.to_dict(qresults, key_func) - >>> sorted(search_dict.keys()) + >>> sorted(search_dict) ['156630997:105-1160', ..., '371502086:108-1205', '53729353:216-1313'] >>> search_dict['156630997:105-1160'] QueryResult(id='gi|156630997:105-1160', 5 hits) @@ -444,7 +444,7 @@ >>> search_idx = SearchIO.index('Blast/wnts.xml', 'blast-xml') >>> search_idx SearchIO.index('Blast/wnts.xml', 'blast-xml', key_function=None) - >>> sorted(search_idx.keys()) + >>> sorted(search_idx) ['gi|156630997:105-1160', 'gi|195230749:301-1383', ..., 'gi|53729353:216-1313'] >>> search_idx['gi|195230749:301-1383'] QueryResult(id='gi|195230749:301-1383', 5 hits) @@ -470,7 +470,7 @@ >>> search_idx = SearchIO.index('Blast/wnts.xml', 'blast-xml', key_func) >>> search_idx SearchIO.index('Blast/wnts.xml', 'blast-xml', key_function= at ...>) - >>> sorted(search_idx.keys()) + >>> sorted(search_idx) ['156630997:105-1160', ..., '371502086:108-1205', '53729353:216-1313'] >>> search_idx['156630997:105-1160'] QueryResult(id='gi|156630997:105-1160', 5 hits) @@ -515,7 +515,7 @@ >>> from Bio import SearchIO >>> db_idx = SearchIO.index_db(':memory:', 'Blast/mirna.xml', 'blast-xml') - >>> sorted(db_idx.keys()) + >>> sorted(db_idx) ['33211', '33212', '33213'] >>> db_idx['33212'] QueryResult(id='33212', 44 hits) @@ -527,7 +527,7 @@ >>> from Bio import SearchIO >>> files = ['Blast/mirna.xml', 'Blast/wnts.xml'] >>> db_idx = SearchIO.index_db(':memory:', files, 'blast-xml') - >>> sorted(db_idx.keys()) + >>> sorted(db_idx) ['33211', '33212', '33213', 'gi|156630997:105-1160', ..., 'gi|53729353:216-1313'] >>> db_idx['33212'] QueryResult(id='33212', 44 hits) @@ -674,3 +674,4 @@ if __name__ == "__main__": from Bio._utils import run_doctest run_doctest() + diff -Nru python-biopython-1.62/Bio/SearchIO/_index.py python-biopython-1.63/Bio/SearchIO/_index.py --- python-biopython-1.62/Bio/SearchIO/_index.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SearchIO/_index.py 2013-12-05 14:10:43.000000000 +0000 @@ -4,11 +4,9 @@ # license. Please see the LICENSE file that should have been included # as part of this package. -#TODO: factor out this module with SeqIO's _index to stay DRY - """Custom indexing for Bio.SearchIO objects.""" -from StringIO import StringIO +from Bio._py3k import StringIO from Bio._py3k import _bytes_to_string from Bio import bgzf from Bio.File import _IndexedSeqFileProxy, _open_for_random_access @@ -26,7 +24,7 @@ self._kwargs = kwargs def _parse(self, handle): - return iter(self._parser(handle, **self._kwargs)).next() + return next(iter(self._parser(handle, **self._kwargs))) def get(self, offset): return self._parse(StringIO(_bytes_to_string(self.get_raw(offset)))) diff -Nru python-biopython-1.62/Bio/SearchIO/_model/__init__.py python-biopython-1.63/Bio/SearchIO/_model/__init__.py --- python-biopython-1.62/Bio/SearchIO/_model/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SearchIO/_model/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -44,9 +44,9 @@ """ -from query import QueryResult -from hit import Hit -from hsp import HSP, HSPFragment +from .query import QueryResult +from .hit import Hit +from .hsp import HSP, HSPFragment __all__ = ['QueryResult', 'Hit', 'HSP', 'HSPFragment'] diff -Nru python-biopython-1.62/Bio/SearchIO/_model/_base.py python-biopython-1.63/Bio/SearchIO/_model/_base.py --- python-biopython-1.62/Bio/SearchIO/_model/_base.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SearchIO/_model/_base.py 2013-12-05 14:10:43.000000000 +0000 @@ -30,7 +30,7 @@ """ # list of attribute names we don't want to transfer - for attr in self.__dict__.keys(): + for attr in self.__dict__: if attr not in self._NON_STICKY_ATTRS: setattr(obj, attr, self.__dict__[attr]) diff -Nru python-biopython-1.62/Bio/SearchIO/_model/hit.py python-biopython-1.63/Bio/SearchIO/_model/hit.py --- python-biopython-1.62/Bio/SearchIO/_model/hit.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SearchIO/_model/hit.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,13 +5,17 @@ """Bio.SearchIO object to model a single database hit.""" +from __future__ import print_function + from itertools import chain +from Bio._py3k import filter + from Bio._utils import getattr_str, trim_str from Bio.SearchIO._utils import allitems, optionalcascade -from _base import _BaseSearchObject -from hsp import HSP +from ._base import _BaseSearchObject +from .hsp import HSP class Hit(_BaseSearchObject): @@ -26,9 +30,9 @@ To have a quick look at a Hit and its contents, invoke `print` on it: >>> from Bio import SearchIO - >>> qresult = SearchIO.parse('Blast/mirna.xml', 'blast-xml').next() + >>> qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml')) >>> hit = qresult[3] - >>> print hit + >>> print(hit) Query: 33211 mir_1 Hit: gi|301171322|ref|NR_035857.1| (86) @@ -57,7 +61,7 @@ Hit(id='gi|301171322|ref|NR_035857.1|', query_id='33211', 2 hsps) >>> hit[:1] Hit(id='gi|301171322|ref|NR_035857.1|', query_id='33211', 1 hsps) - >>> print hit[1:] + >>> print(hit[1:]) Query: 33211 mir_1 Hit: gi|301171322|ref|NR_035857.1| (86) @@ -80,7 +84,7 @@ 2 >>> len(filtered_hit) 1 - >>> print filtered_hit + >>> print(filtered_hit) Query: 33211 mir_1 Hit: gi|301171322|ref|NR_035857.1| (86) @@ -124,7 +128,7 @@ # This makes it easier to work with file formats with unpredictable # hit-hsp ordering. The empty hit object itself is nonfunctional, # however, since all its cascading properties are empty. - if len(set([getattr(hsp, attr) for hsp in hsps])) > 1: + if len(set(getattr(hsp, attr) for hsp in hsps)) > 1: raise ValueError("Hit object can not contain HSPs with " "more than one %s." % attr) @@ -145,9 +149,13 @@ def __len__(self): return len(self.hsps) - def __nonzero__(self): + #Python 3: + def __bool__(self): return bool(self.hsps) + #Python 2: + __nonzero__= __bool__ + def __contains__(self, hsp): return hsp in self._items @@ -313,7 +321,7 @@ than 60: >>> from Bio import SearchIO - >>> qresult = SearchIO.parse('Blast/mirna.xml', 'blast-xml').next() + >>> qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml')) >>> hit = qresult[3] >>> evalue_filter = lambda hsp: hsp.bitscore > 60 >>> filtered_hit = hit.filter(evalue_filter) @@ -321,7 +329,7 @@ 2 >>> len(filtered_hit) 1 - >>> print filtered_hit + >>> print(filtered_hit) Query: 33211 mir_1 Hit: gi|301171322|ref|NR_035857.1| (86) @@ -332,7 +340,7 @@ 0 8.9e-20 100.47 60 [1:61] [13:73] """ - hsps = filter(func, self.hsps) + hsps = list(filter(func, self.hsps)) if hsps: obj = self.__class__(hsps) self._transfer_attrs(obj) @@ -359,7 +367,7 @@ """ if func is not None: - hsps = map(func, self.hsps[:]) # this creates a shallow copy + hsps = [func(x) for x in self.hsps[:]] # this creates a shallow copy else: hsps = self.hsps[:] if hsps: diff -Nru python-biopython-1.62/Bio/SearchIO/_model/hsp.py python-biopython-1.63/Bio/SearchIO/_model/hsp.py --- python-biopython-1.62/Bio/SearchIO/_model/hsp.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SearchIO/_model/hsp.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,6 +5,9 @@ """Bio.SearchIO objects to model high scoring regions between query and hit.""" +from __future__ import print_function +from Bio._py3k import basestring + import warnings from operator import ge, le @@ -18,7 +21,7 @@ from Bio.SearchIO._utils import singleitem, allitems, fullcascade, \ fragcascade -from _base import _BaseHSP +from ._base import _BaseHSP class HSP(_BaseHSP): @@ -41,11 +44,11 @@ search: >>> from Bio import SearchIO - >>> blast_qresult = SearchIO.parse('Blast/mirna.xml', 'blast-xml').next() + >>> blast_qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml')) >>> blast_hsp = blast_qresult[1][0] # the first HSP from the second hit >>> blast_hsp HSP(hit_id='gi|301171311|ref|NR_035856.1|', query_id='33211', 1 fragments) - >>> print blast_hsp + >>> print(blast_hsp) Query: 33211 mir_1 Hit: gi|301171311|ref|NR_035856.1| Pan troglodytes microRNA mir-520b ... Query range: [1:61] (1) @@ -66,7 +69,7 @@ >>> blat_hsp = blat_qresult[1][0] # the first HSP from the second hit >>> blat_hsp HSP(hit_id='chr11', query_id='blat_1', 2 fragments) - >>> print blat_hsp + >>> print(blat_hsp) Query: blat_1 Hit: chr11 Query range: [42:67] (-1) @@ -93,7 +96,7 @@ access a single fragment in an HSP using its integer index: >>> blat_fragment = blat_hsp[0] - >>> print blat_fragment + >>> print(blat_fragment) Query: blat_1 Hit: chr11 Query range: [61:67] (-1) @@ -105,7 +108,7 @@ This applies to HSPs objects with a single fragment as well: >>> blast_fragment = blast_hsp[0] - >>> print blast_fragment + >>> print(blast_fragment) Query: 33211 mir_1 Hit: gi|301171311|ref|NR_035856.1| Pan troglodytes microRNA mir-520b ... Query range: [1:61] (1) @@ -264,7 +267,7 @@ # check that all fragments contain the same IDs, descriptions, alphabet for attr in ('query_id', 'query_description', 'hit_id', 'hit_description', 'alphabet'): - if len(set([getattr(frag, attr) for frag in fragments])) != 1: + if len(set(getattr(frag, attr) for frag in fragments)) != 1: raise ValueError("HSP object can not contain fragments with " "more than one %s." % attr) @@ -286,9 +289,13 @@ def __len__(self): return len(self._items) - def __nonzero__(self): + #Python 3: + def __bool__(self): return bool(self._items) + #Python 2: + __nonzero__= __bool__ + def __str__(self): lines = [] @@ -384,7 +391,7 @@ # length of all alignments # alignment span can be its own attribute, or computed from # query / hit length - return sum([frg.aln_span for frg in self.fragments]) + return sum(frg.aln_span for frg in self.fragments) aln_span = property(fget=_aln_span_get, doc="""Total number of columns in all HSPFragment objects.""") @@ -628,9 +635,9 @@ SeqRecord objects (see SeqRecord): >>> from Bio import SearchIO - >>> qresult = SearchIO.parse('Blast/mirna.xml', 'blast-xml').next() + >>> qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml')) >>> fragment = qresult[0][0][0] # first hit, first hsp, first fragment - >>> print fragment + >>> print(fragment) Query: 33211 mir_1 Hit: gi|262205317|ref|NR_030195.1| Homo sapiens microRNA 520b (MIR520... Query range: [0:61] (1) @@ -643,7 +650,7 @@ # the query sequence is a SeqRecord object >>> fragment.query.__class__ - >>> print fragment.query + >>> print(fragment.query) ID: 33211 Name: aligned query sequence Description: mir_1 @@ -653,7 +660,7 @@ # the hit sequence is a SeqRecord object as well >>> fragment.hit.__class__ - >>> print fragment.hit + >>> print(fragment.hit) ID: gi|262205317|ref|NR_030195.1| Name: aligned hit sequence Description: Homo sapiens microRNA 520b (MIR520B), microRNA @@ -663,7 +670,7 @@ # when both query and hit are present, we get a MultipleSeqAlignment object >>> fragment.aln.__class__ - >>> print fragment.aln + >>> print(fragment.aln) DNAAlphabet() alignment with 2 rows and 61 columns CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAG...GGG 33211 CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAG...GGG gi|262205317|ref|NR_030195.1| diff -Nru python-biopython-1.62/Bio/SearchIO/_model/query.py python-biopython-1.63/Bio/SearchIO/_model/query.py --- python-biopython-1.62/Bio/SearchIO/_model/query.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SearchIO/_model/query.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,15 +5,20 @@ """Bio.SearchIO object to model search results from a single query.""" +from __future__ import print_function +from Bio._py3k import basestring + from copy import deepcopy from itertools import chain from Bio._py3k import OrderedDict +from Bio._py3k import filter + from Bio._utils import trim_str from Bio.SearchIO._utils import optionalcascade -from _base import _BaseSearchObject -from hit import Hit +from ._base import _BaseSearchObject +from .hit import Hit class QueryResult(_BaseSearchObject): @@ -30,8 +35,8 @@ invoking `print` on it: >>> from Bio import SearchIO - >>> qresult = SearchIO.parse('Blast/mirna.xml', 'blast-xml').next() - >>> print qresult + >>> qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml')) + >>> print(qresult) Program: blastn (2.2.27+) Query: 33211 (61) mir_1 @@ -77,7 +82,7 @@ 100 >>> len(sliced_qresult) 3 - >>> print sliced_qresult + >>> print(sliced_qresult) Program: blastn (2.2.27+) Query: 33211 (61) mir_1 @@ -134,7 +139,7 @@ ... hit.id = hit.id.split('|')[3] ... return hit >>> mapped_qresult = qresult.hit_map(renamer) - >>> print mapped_qresult + >>> print(mapped_qresult) Program: blastn (2.2.27+) Query: 33211 (61) mir_1 @@ -228,17 +233,17 @@ def iterhits(self): """Returns an iterator over the Hit objects.""" - for hit in self._items.itervalues(): + for hit in self._items.values(): yield hit def iterhit_keys(self): """Returns an iterator over the ID of the Hit objects.""" - for hit_id in self._items.iterkeys(): + for hit_id in self._items.keys(): yield hit_id def iteritems(self): """Returns an iterator yielding tuples of Hit ID and Hit objects.""" - for item in self._items.iteritems(): + for item in self._items.items(): yield item else: @@ -268,7 +273,7 @@ def iterhit_keys(self): """Returns an iterator over the ID of the Hit objects.""" - for hit_id in self._items.keys(): + for hit_id in self._items: yield hit_id def iteritems(self): @@ -284,9 +289,13 @@ def __len__(self): return len(self._items) - def __nonzero__(self): + #Python 3: + def __bool__(self): return bool(self._items) + #Python 2: + __nonzero__= __bool__ + def __repr__(self): return "QueryResult(id=%r, %r hits)" % (self.id, len(self)) @@ -467,7 +476,7 @@ description begins with the string 'Homo sapiens', case sensitive: >>> from Bio import SearchIO - >>> qresult = SearchIO.parse('Blast/mirna.xml', 'blast-xml').next() + >>> qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml')) >>> def desc_filter(hit): ... return hit.description.startswith('Homo sapiens') ... @@ -476,7 +485,7 @@ >>> filtered = qresult.hit_filter(desc_filter) >>> len(filtered) 39 - >>> print filtered[:4] + >>> print(filtered[:4]) Program: blastn (2.2.27+) Query: 33211 (61) mir_1 @@ -498,7 +507,7 @@ True """ - hits = filter(func, self.hits) + hits = list(filter(func, self.hits)) obj = self.__class__(hits, self.id, self._hit_key_function) self._transfer_attrs(obj) return obj @@ -515,8 +524,8 @@ HSPs in a Hit except for the first one: >>> from Bio import SearchIO - >>> qresult = SearchIO.parse('Blast/mirna.xml', 'blast-xml').next() - >>> print qresult[:8] + >>> qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml')) + >>> print(qresult[:8]) Program: blastn (2.2.27+) Query: 33211 (61) mir_1 @@ -535,7 +544,7 @@ >>> top_hsp = lambda hit: hit[:1] >>> mapped_qresult = qresult.hit_map(top_hsp) - >>> print mapped_qresult[:8] + >>> print(mapped_qresult[:8]) Program: blastn (2.2.27+) Query: 33211 (61) mir_1 @@ -555,7 +564,7 @@ """ hits = [deepcopy(hit) for hit in self.hits] if func is not None: - hits = map(func, hits) + hits = [func(x) for x in hits] obj = self.__class__(hits, self.id, self._hit_key_function) self._transfer_attrs(obj) return obj @@ -565,12 +574,12 @@ function. `hsp_filter` is the same as `hit_filter`, except that it filters - directly on each HSP object in every Hit. If a the filtering removes - all HSP object in a given Hit, the entire Hit will be discarded. This + directly on each HSP object in every Hit. If the filtering removes + all HSP objects in a given Hit, the entire Hit will be discarded. This will result in the QueryResult having less Hit after filtering. """ - hits = filter(None, (hit.filter(func) for hit in self.hits)) + hits = [x for x in (hit.filter(func) for hit in self.hits) if x] obj = self.__class__(hits, self.id, self._hit_key_function) self._transfer_attrs(obj) return obj @@ -583,7 +592,7 @@ function to all HSP objects in every Hit, instead of the Hit objects. """ - hits = filter(None, (hit.map(func) for hit in list(self.hits)[:])) + hits = [x for x in (hit.map(func) for hit in list(self.hits)[:]) if x] obj = self.__class__(hits, self.id, self._hit_key_function) self._transfer_attrs(obj) return obj @@ -607,12 +616,12 @@ integer index or hit key. >>> from Bio import SearchIO - >>> qresult = SearchIO.parse('Blast/mirna.xml', 'blast-xml').next() + >>> qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml')) >>> len(qresult) 100 >>> for hit in qresult[:5]: - ... print hit.id - ... + ... print(hit.id) + ... gi|262205317|ref|NR_030195.1| gi|301171311|ref|NR_035856.1| gi|270133242|ref|NR_032573.1| @@ -659,7 +668,7 @@ correlated with search rank) of a given hit key. >>> from Bio import SearchIO - >>> qresult = SearchIO.parse('Blast/mirna.xml', 'blast-xml').next() + >>> qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml')) >>> qresult.index('gi|301171259|ref|NR_035850.1|') 7 diff -Nru python-biopython-1.62/Bio/SearchIO/_utils.py python-biopython-1.63/Bio/SearchIO/_utils.py --- python-biopython-1.62/Bio/SearchIO/_utils.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SearchIO/_utils.py 2013-12-05 14:10:43.000000000 +0000 @@ -2,9 +2,10 @@ # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. - """Common SearchIO utility functions.""" +from Bio._py3k import basestring + def get_processor(format, mapping): """Returns the object to process the given format according to the mapping. @@ -28,7 +29,7 @@ format) else: raise ValueError("Unknown format %r. Supported formats are " - "%r" % (format, "', '".join(mapping.keys()))) + "%r" % (format, "', '".join(mapping))) mod_name, obj_name = obj_info mod = __import__('Bio.SearchIO.%s' % mod_name, fromlist=['']) diff -Nru python-biopython-1.62/Bio/Seq.py python-biopython-1.63/Bio/Seq.py --- python-biopython-1.62/Bio/Seq.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Seq.py 2013-12-05 14:10:43.000000000 +0000 @@ -11,6 +11,8 @@ - U{http://biopython.org/DIST/docs/tutorial/Tutorial.html} - U{http://biopython.org/DIST/docs/tutorial/Tutorial.pdf} """ +from __future__ import print_function + __docformat__ ="epytext en" # Don't just use plain text in epydoc API pages! import string # for maketrans only @@ -18,6 +20,9 @@ import sys import warnings +from Bio._py3k import range +from Bio._py3k import basestring + from Bio import Alphabet from Bio.Alphabet import IUPAC from Bio.Data.IUPACData import ambiguous_dna_complement, ambiguous_rna_complement @@ -90,7 +95,7 @@ ... IUPAC.protein) >>> my_seq Seq('MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF', IUPACProtein()) - >>> print my_seq + >>> print(my_seq) MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF >>> my_seq.alphabet IUPACProtein() @@ -336,7 +341,7 @@ #Return as a string return str(other_sequence) - def count(self, sub, start=0, end=sys.maxint): + def count(self, sub, start=0, end=sys.maxsize): """Non-overlapping count method, like that of a python string. This behaves like the python string method of the same name, @@ -356,13 +361,13 @@ >>> from Bio.Seq import Seq >>> my_seq = Seq("AAAATGA") - >>> print my_seq.count("A") + >>> print(my_seq.count("A")) 5 - >>> print my_seq.count("ATG") + >>> print(my_seq.count("ATG")) 1 - >>> print my_seq.count(Seq("AT")) + >>> print(my_seq.count(Seq("AT"))) 1 - >>> print my_seq.count("AT", 2, -1) + >>> print(my_seq.count("AT", 2, -1)) 1 HOWEVER, please note because python strings and Seq objects (and @@ -371,7 +376,7 @@ >>> "AAAA".count("AA") 2 - >>> print Seq("AAAA").count("AA") + >>> print(Seq("AAAA").count("AA")) 2 A non-overlapping search would give the answer as three! @@ -411,7 +416,7 @@ sub_str = self._get_seq_str_and_check_alphabet(char) return sub_str in str(self) - def find(self, sub, start=0, end=sys.maxint): + def find(self, sub, start=0, end=sys.maxsize): """Find method, like that of a python string. This behaves like the python string method of the same name. @@ -437,7 +442,7 @@ sub_str = self._get_seq_str_and_check_alphabet(sub) return str(self).find(sub_str, start, end) - def rfind(self, sub, start=0, end=sys.maxint): + def rfind(self, sub, start=0, end=sys.maxsize): """Find from right method, like that of a python string. This behaves like the python string method of the same name. @@ -463,7 +468,7 @@ sub_str = self._get_seq_str_and_check_alphabet(sub) return str(self).rfind(sub_str, start, end) - def startswith(self, prefix, start=0, end=sys.maxint): + def startswith(self, prefix, start=0, end=sys.maxsize): """Does the Seq start with the given prefix? Returns True/False. This behaves like the python string method of the same name. @@ -482,7 +487,7 @@ False >>> my_rna.startswith("AUG", 3) True - >>> my_rna.startswith(("UCC","UCA","UCG"),1) + >>> my_rna.startswith(("UCC", "UCA", "UCG"), 1) True """ #If it has one, check the alphabet: @@ -494,7 +499,7 @@ prefix_str = self._get_seq_str_and_check_alphabet(prefix) return str(self).startswith(prefix_str, start, end) - def endswith(self, suffix, start=0, end=sys.maxint): + def endswith(self, suffix, start=0, end=sys.maxsize): """Does the Seq end with the given suffix? Returns True/False. This behaves like the python string method of the same name. @@ -513,7 +518,7 @@ False >>> my_rna.endswith("AUG", 0, 18) True - >>> my_rna.endswith(("UCC","UCA","UUG")) + >>> my_rna.endswith(("UCC", "UCA", "UUG")) True """ #If it has one, check the alphabet: @@ -548,12 +553,12 @@ Seq('VMAIVMGR*KGAR*L', HasStopCodon(ExtendedIUPACProtein(), '*')) >>> my_aa.split("*") [Seq('VMAIVMGR', HasStopCodon(ExtendedIUPACProtein(), '*')), Seq('KGAR', HasStopCodon(ExtendedIUPACProtein(), '*')), Seq('L', HasStopCodon(ExtendedIUPACProtein(), '*'))] - >>> my_aa.split("*",1) + >>> my_aa.split("*", 1) [Seq('VMAIVMGR', HasStopCodon(ExtendedIUPACProtein(), '*')), Seq('KGAR*L', HasStopCodon(ExtendedIUPACProtein(), '*'))] See also the rsplit method: - >>> my_aa.rsplit("*",1) + >>> my_aa.rsplit("*", 1) [Seq('VMAIVMGR*KGAR', HasStopCodon(ExtendedIUPACProtein(), '*')), Seq('L', HasStopCodon(ExtendedIUPACProtein(), '*'))] """ #If it has one, check the alphabet: @@ -577,7 +582,7 @@ white space (tabs, spaces, newlines) but this is unlikely to apply to biological sequences. - e.g. print my_seq.rsplit("*",1) + e.g. print(my_seq.rsplit("*",1)) See also the split method. """ @@ -595,7 +600,7 @@ omitted or None (default) then as for the python string method, this defaults to removing any white space. - e.g. print my_seq.strip("-") + e.g. print(my_seq.strip("-")) See also the lstrip and rstrip methods. """ @@ -612,7 +617,7 @@ omitted or None (default) then as for the python string method, this defaults to removing any white space. - e.g. print my_seq.lstrip("-") + e.g. print(my_seq.lstrip("-")) See also the strip and rstrip methods. """ @@ -1060,7 +1065,7 @@ Seq('NNNNN', Alphabet()) >>> len(my_seq) 5 - >>> print my_seq + >>> print(my_seq) NNNNN However, this is rather wasteful of memory (especially for large @@ -1183,13 +1188,13 @@ """Get a subsequence from the UnknownSeq object. >>> unk = UnknownSeq(8, character="N") - >>> print unk[:] + >>> print(unk[:]) NNNNNNNN - >>> print unk[5:3] + >>> print(unk[5:3]) - >>> print unk[1:-1] + >>> print(unk[1:-1]) NNNNNN - >>> print unk[1:-1:2] + >>> print(unk[1:-1:2]) NNN """ if isinstance(index, int): @@ -1224,7 +1229,7 @@ # new_length, len(("X"*old_length)[index])) return UnknownSeq(new_length, self.alphabet, self._character) - def count(self, sub, start=0, end=sys.maxint): + def count(self, sub, start=0, end=sys.maxsize): """Non-overlapping count method, like that of a python string. This behaves like the python string (and Seq object) method of the @@ -1286,11 +1291,11 @@ >>> my_nuc = UnknownSeq(8) >>> my_nuc UnknownSeq(8, alphabet = Alphabet(), character = '?') - >>> print my_nuc + >>> print(my_nuc) ???????? >>> my_nuc.complement() UnknownSeq(8, alphabet = Alphabet(), character = '?') - >>> print my_nuc.complement() + >>> print(my_nuc.complement()) ???????? """ if isinstance(Alphabet._get_base_alphabet(self.alphabet), @@ -1304,11 +1309,11 @@ >>> my_nuc = UnknownSeq(10) >>> my_nuc UnknownSeq(10, alphabet = Alphabet(), character = '?') - >>> print my_nuc + >>> print(my_nuc) ?????????? >>> my_nuc.reverse_complement() UnknownSeq(10, alphabet = Alphabet(), character = '?') - >>> print my_nuc.reverse_complement() + >>> print(my_nuc.reverse_complement()) ?????????? """ if isinstance(Alphabet._get_base_alphabet(self.alphabet), @@ -1322,12 +1327,12 @@ >>> my_dna = UnknownSeq(10, character="N") >>> my_dna UnknownSeq(10, alphabet = Alphabet(), character = 'N') - >>> print my_dna + >>> print(my_dna) NNNNNNNNNN >>> my_rna = my_dna.transcribe() >>> my_rna UnknownSeq(10, alphabet = RNAAlphabet(), character = 'N') - >>> print my_rna + >>> print(my_rna) NNNNNNNNNN """ #Offload the alphabet stuff @@ -1340,12 +1345,12 @@ >>> my_rna = UnknownSeq(20, character="N") >>> my_rna UnknownSeq(20, alphabet = Alphabet(), character = 'N') - >>> print my_rna + >>> print(my_rna) NNNNNNNNNNNNNNNNNNNN >>> my_dna = my_rna.back_transcribe() >>> my_dna UnknownSeq(20, alphabet = DNAAlphabet(), character = 'N') - >>> print my_dna + >>> print(my_dna) NNNNNNNNNNNNNNNNNNNN """ #Offload the alphabet stuff @@ -1360,11 +1365,11 @@ >>> my_seq = UnknownSeq(20, generic_dna, character="n") >>> my_seq UnknownSeq(20, alphabet = DNAAlphabet(), character = 'n') - >>> print my_seq + >>> print(my_seq) nnnnnnnnnnnnnnnnnnnn >>> my_seq.upper() UnknownSeq(20, alphabet = DNAAlphabet(), character = 'N') - >>> print my_seq.upper() + >>> print(my_seq.upper()) NNNNNNNNNNNNNNNNNNNN This will adjust the alphabet if required. See also the lower method. @@ -1381,11 +1386,11 @@ >>> my_seq = UnknownSeq(20, IUPAC.extended_protein) >>> my_seq UnknownSeq(20, alphabet = ExtendedIUPACProtein(), character = 'X') - >>> print my_seq + >>> print(my_seq) XXXXXXXXXXXXXXXXXXXX >>> my_seq.lower() UnknownSeq(20, alphabet = ProteinAlphabet(), character = 'x') - >>> print my_seq.lower() + >>> print(my_seq.lower()) xxxxxxxxxxxxxxxxxxxx See also the upper method. @@ -1398,23 +1403,23 @@ e.g. >>> my_seq = UnknownSeq(9, character="N") - >>> print my_seq + >>> print(my_seq) NNNNNNNNN >>> my_protein = my_seq.translate() >>> my_protein UnknownSeq(3, alphabet = ProteinAlphabet(), character = 'X') - >>> print my_protein + >>> print(my_protein) XXX In comparison, using a normal Seq object: >>> my_seq = Seq("NNNNNNNNN") - >>> print my_seq + >>> print(my_seq) NNNNNNNNN >>> my_protein = my_seq.translate() >>> my_protein Seq('XXX', ExtendedIUPACProtein()) - >>> print my_protein + >>> print(my_protein) XXX """ @@ -1431,7 +1436,7 @@ >>> from Bio.Seq import UnknownSeq >>> from Bio.Alphabet import Gapped, generic_dna - >>> my_dna = UnknownSeq(20, Gapped(generic_dna,"-")) + >>> my_dna = UnknownSeq(20, Gapped(generic_dna, "-")) >>> my_dna UnknownSeq(20, alphabet = Gapped(DNAAlphabet(), '-'), character = 'N') >>> my_dna.ungap() @@ -1442,7 +1447,7 @@ If the UnknownSeq is using the gap character, then an empty Seq is returned: - >>> my_gap = UnknownSeq(20, Gapped(generic_dna,"-"), character="-") + >>> my_gap = UnknownSeq(20, Gapped(generic_dna, "-"), character="-") >>> my_gap UnknownSeq(20, alphabet = Gapped(DNAAlphabet(), '-'), character = '-') >>> my_gap.ungap() @@ -1675,7 +1680,7 @@ return raise ValueError("MutableSeq.remove(x): x not in list") - def count(self, sub, start=0, end=sys.maxint): + def count(self, sub, start=0, end=sys.maxsize): """Non-overlapping count method, like that of a python string. This behaves like the python string method of the same name, @@ -1695,13 +1700,13 @@ >>> from Bio.Seq import MutableSeq >>> my_mseq = MutableSeq("AAAATGA") - >>> print my_mseq.count("A") + >>> print(my_mseq.count("A")) 5 - >>> print my_mseq.count("ATG") + >>> print(my_mseq.count("ATG")) 1 - >>> print my_mseq.count(Seq("AT")) + >>> print(my_mseq.count(Seq("AT"))) 1 - >>> print my_mseq.count("AT", 2, -1) + >>> print(my_mseq.count("AT", 2, -1)) 1 HOWEVER, please note because that python strings, Seq objects and @@ -1710,7 +1715,7 @@ >>> "AAAA".count("AA") 2 - >>> print MutableSeq("AAAA").count("AA") + >>> print(MutableSeq("AAAA").count("AA")) 2 A non-overlapping search would give the answer as three! @@ -1769,9 +1774,9 @@ d = ambiguous_rna_complement else: d = ambiguous_dna_complement - c = dict([(x.lower(), y.lower()) for x, y in d.iteritems()]) + c = dict([(x.lower(), y.lower()) for x, y in d.items()]) d.update(c) - self.data = map(lambda c: d[c], self.data) + self.data = [d[c] for c in self.data] self.data = array.array(self.array_indicator, self.data) def reverse_complement(self): @@ -1804,11 +1809,11 @@ Because str(my_seq) will give you the full sequence as a python string, there is often no need to make an explicit conversion. For example, - print "ID={%s}, sequence={%s}" % (my_name, my_seq) + print("ID={%s}, sequence={%s}" % (my_name, my_seq)) On Biopython 1.44 or older you would have to have done this: - print "ID={%s}, sequence={%s}" % (my_name, my_seq.tostring()) + print("ID={%s}, sequence={%s}" % (my_name, my_seq.tostring())) """ return "".join(self.data) @@ -1969,7 +1974,7 @@ "Explicitly trim the sequence or add trailing N before " "translation. This may become an error in future.", BiopythonWarning) - for i in xrange(0, n-n%3, 3): + for i in range(0, n - n%3, 3): codon = sequence[i:i+3] try: amino_acids.append(forward_table[codon]) @@ -2117,13 +2122,14 @@ def _test(): """Run the Bio.Seq module's doctests (PRIVATE).""" if sys.version_info[0:2] == (3, 1): - print "Not running Bio.Seq doctest on Python 3.1" - print "See http://bugs.python.org/issue7490" + print("Not running Bio.Seq doctest on Python 3.1") + print("See http://bugs.python.org/issue7490") else: - print "Running doctests..." + print("Running doctests...") import doctest doctest.testmod(optionflags=doctest.IGNORE_EXCEPTION_DETAIL) - print "Done" + print("Done") if __name__ == "__main__": _test() + diff -Nru python-biopython-1.62/Bio/SeqFeature.py python-biopython-1.63/Bio/SeqFeature.py --- python-biopython-1.62/Bio/SeqFeature.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SeqFeature.py 2013-12-05 14:10:43.000000000 +0000 @@ -49,6 +49,8 @@ o UnknownPosition - Represents missing information like '?' in UniProt. """ +from __future__ import print_function + from Bio.Seq import MutableSeq, reverse_complement @@ -288,7 +290,7 @@ type = self.type, location_operator = self.location_operator, id = self.id, - qualifiers = dict(self.qualifiers.iteritems())) + qualifiers = dict(self.qualifiers.items())) #This is to avoid the deprecation warning: answer._sub_features = [f._shift(offset) for f in self._sub_features] return answer @@ -307,7 +309,7 @@ type = self.type, location_operator = self.location_operator, id = self.id, - qualifiers = dict(self.qualifiers.iteritems())) + qualifiers = dict(self.qualifiers.items())) #This is to avoid the deprecation warning: answer._sub_features = [f._flip(length) for f in self._sub_features[::-1]] return answer @@ -328,7 +330,7 @@ >>> from Bio.Alphabet import generic_protein >>> from Bio.SeqFeature import SeqFeature, FeatureLocation >>> seq = Seq("MKQHKAMIVALIVICITAVVAAL", generic_protein) - >>> f = SeqFeature(FeatureLocation(8,15), type="domain") + >>> f = SeqFeature(FeatureLocation(8, 15), type="domain") >>> f.extract(seq) Seq('VALIVIC', ProteinAlphabet()) @@ -336,8 +338,9 @@ """ return self.location.extract(parent_sequence) - def __nonzero__(self): - """Returns True regardless of the length of the feature. + #Python 3: + def __bool__(self): + """Boolean value of an instance of this class (True). This behaviour is for backwards compatibility, since until the __len__ method was added, a SeqFeature always evaluated as True. @@ -350,6 +353,9 @@ """ return True + #Python 2: + __nonzero__= __bool__ + def __len__(self): """Returns the length of the region described by a feature. @@ -357,7 +363,7 @@ >>> from Bio.Alphabet import generic_protein >>> from Bio.SeqFeature import SeqFeature, FeatureLocation >>> seq = Seq("MKQHKAMIVALIVICITAVVAAL", generic_protein) - >>> f = SeqFeature(FeatureLocation(8,15), type="domain") + >>> f = SeqFeature(FeatureLocation(8, 15), type="domain") >>> len(f) 7 >>> f.extract(seq) @@ -386,10 +392,10 @@ along the feature using the parent sequence coordinates: >>> from Bio.SeqFeature import SeqFeature, FeatureLocation - >>> f = SeqFeature(FeatureLocation(5,10), type="domain", strand=-1) + >>> f = SeqFeature(FeatureLocation(5, 10), type="domain", strand=-1) >>> len(f) 5 - >>> for i in f: print i + >>> for i in f: print(i) 9 8 7 @@ -409,7 +415,7 @@ """Check if an integer position is within the feature. >>> from Bio.SeqFeature import SeqFeature, FeatureLocation - >>> f = SeqFeature(FeatureLocation(5,10), type="domain", strand=-1) + >>> f = SeqFeature(FeatureLocation(5, 10), type="domain", strand=-1) >>> len(f) 5 >>> [i for i in range(15) if i in f] @@ -422,7 +428,7 @@ >>> record = SeqIO.read("GenBank/NC_000932.gb", "gb") >>> for f in record.features: ... if 1750 in f: - ... print f.type, f.location + ... print("%s %s" % (f.type, f.location)) source [0:154478](+) gene [1716:4347](-) tRNA join{[4310:4347](-), [1716:1751](-)} @@ -435,7 +441,7 @@ >>> for f in record.features: ... if 1760 in f: - ... print f.type, f.location + ... print("%s %s" % (f.type, f.location)) source [0:154478](+) gene [1716:4347](-) @@ -444,7 +450,7 @@ >>> from Bio.SeqFeature import SeqFeature, FeatureLocation >>> from Bio.SeqFeature import BeforePosition - >>> f = SeqFeature(FeatureLocation(BeforePosition(3),8), type="domain") + >>> f = SeqFeature(FeatureLocation(BeforePosition(3), 8), type="domain") >>> len(f) 5 >>> [i for i in range(10) if i in f] @@ -527,13 +533,13 @@ >>> from Bio.SeqFeature import FeatureLocation >>> f = FeatureLocation(122, 150) - >>> print f + >>> print(f) [122:150] - >>> print f.start + >>> print(f.start) 122 - >>> print f.end + >>> print(f.end) 150 - >>> print f.strand + >>> print(f.strand) None Note the strand defaults to None. If you are working with nucleotide @@ -541,9 +547,9 @@ >>> from Bio.SeqFeature import FeatureLocation >>> f = FeatureLocation(122, 150, strand=+1) - >>> print f + >>> print(f) [122:150](+) - >>> print f.strand + >>> print(f.strand) 1 Note that for a parent sequence of length n, the FeatureLocation @@ -554,13 +560,13 @@ >>> from Bio.SeqFeature import FeatureLocation >>> r = FeatureLocation(122, 150, strand=-1) - >>> print r + >>> print(r) [122:150](-) - >>> print r.start + >>> print(r.start) 122 - >>> print r.end + >>> print(r.end) 150 - >>> print r.strand + >>> print(r.strand) -1 i.e. Rather than thinking of the 'start' and 'end' biologically in a @@ -588,14 +594,14 @@ >>> from Bio.SeqFeature import FeatureLocation >>> loc = FeatureLocation(5, 10, strand=-1) - >>> print loc + >>> print(loc) [5:10](-) Explicit form: >>> from Bio.SeqFeature import FeatureLocation, ExactPosition >>> loc = FeatureLocation(ExactPosition(5), ExactPosition(10), strand=-1) - >>> print loc + >>> print(loc) [5:10](-) Other fuzzy positions are used similarly, @@ -603,7 +609,7 @@ >>> from Bio.SeqFeature import FeatureLocation >>> from Bio.SeqFeature import BeforePosition, AfterPosition >>> loc2 = FeatureLocation(BeforePosition(5), AfterPosition(10), strand=-1) - >>> print loc2 + >>> print(loc2) [<5:>10](-) For nucleotide features you will also want to specify the strand, @@ -613,9 +619,9 @@ proteins. >>> loc = FeatureLocation(5, 10, strand=+1) - >>> print loc + >>> print(loc) [5:10](+) - >>> print loc.strand + >>> print(loc.strand) 1 Normally feature locations are given relative to the parent @@ -623,9 +629,9 @@ be given with the optional ref and db_ref strings: >>> loc = FeatureLocation(105172, 108462, ref="AL391218.9", strand=1) - >>> print loc + >>> print(loc) AL391218.9[105172:108462](+) - >>> print loc.ref + >>> print(loc.ref) AL391218.9 """ @@ -699,23 +705,23 @@ You can add two feature locations to make a join CompoundLocation: >>> from Bio.SeqFeature import FeatureLocation - >>> f1 = FeatureLocation(5,10) - >>> f2 = FeatureLocation(20,30) + >>> f1 = FeatureLocation(5, 10) + >>> f2 = FeatureLocation(20, 30) >>> combined = f1 + f2 - >>> print combined + >>> print(combined) join{[5:10], [20:30]} This is thus equivalent to: >>> from Bio.SeqFeature import CompoundLocation >>> join = CompoundLocation([f1, f2]) - >>> print join + >>> print(join) join{[5:10], [20:30]} You can also use sum(...) in this way: >>> join = sum([f1, f2]) - >>> print join + >>> print(join) join{[5:10], [20:30]} Furthermore, you can combine a FeatureLocation with a CompoundLocation @@ -724,11 +730,11 @@ Separately, adding an integer will give a new FeatureLocation with its start and end offset by that amount. For example: - >>> print f1 + >>> print(f1) [5:10] - >>> print f1 + 100 + >>> print(f1 + 100) [105:110] - >>> print 200 + f1 + >>> print(200 + f1) [205:210] This can be useful when editing annotation. @@ -768,7 +774,7 @@ >>> from Bio.SeqFeature import FeatureLocation >>> from Bio.SeqFeature import BeforePosition, AfterPosition - >>> loc = FeatureLocation(BeforePosition(5),AfterPosition(10)) + >>> loc = FeatureLocation(BeforePosition(5), AfterPosition(10)) >>> len(loc) 5 """ @@ -781,7 +787,7 @@ >>> from Bio.SeqFeature import FeatureLocation >>> from Bio.SeqFeature import BeforePosition, AfterPosition - >>> loc = FeatureLocation(BeforePosition(5),AfterPosition(10)) + >>> loc = FeatureLocation(BeforePosition(5), AfterPosition(10)) >>> len(loc) 5 >>> [i for i in range(15) if i in loc] @@ -800,10 +806,10 @@ >>> from Bio.SeqFeature import FeatureLocation >>> from Bio.SeqFeature import BeforePosition, AfterPosition - >>> loc = FeatureLocation(BeforePosition(5),AfterPosition(10)) + >>> loc = FeatureLocation(BeforePosition(5), AfterPosition(10)) >>> len(loc) 5 - >>> for i in loc: print i + >>> for i in loc: print(i) 5 6 7 @@ -934,7 +940,7 @@ >>> f = CompoundLocation([f1, f2]) >>> len(f) == len(f1) + len(f2) == 39 == len(list(f)) True - >>> print f.operator + >>> print(f.operator) join >>> 5 in f False @@ -949,7 +955,7 @@ >>> f = CompoundLocation([FeatureLocation(3, 6, strand=+1), ... FeatureLocation(10, 13, strand=-1)]) - >>> print f.strand + >>> print(f.strand) None >>> len(f) 6 @@ -1027,8 +1033,8 @@ for mixed strands, this returns None. >>> from Bio.SeqFeature import FeatureLocation, CompoundLocation - >>> f1 = FeatureLocation(15,17, strand=1) - >>> f2 = FeatureLocation(20,30, strand=-1) + >>> f1 = FeatureLocation(15, 17, strand=1) + >>> f2 = FeatureLocation(20, 30, strand=-1) >>> f = f1 + f2 >>> f1.strand 1 @@ -1055,33 +1061,33 @@ """Combine locations, or shift the location by an integer offset. >>> from Bio.SeqFeature import FeatureLocation, CompoundLocation - >>> f1 = FeatureLocation(15,17) + FeatureLocation(20,30) - >>> print f1 + >>> f1 = FeatureLocation(15, 17) + FeatureLocation(20, 30) + >>> print(f1) join{[15:17], [20:30]} You can add another FeatureLocation: - >>> print f1 + FeatureLocation(40,50) + >>> print(f1 + FeatureLocation(40, 50)) join{[15:17], [20:30], [40:50]} - >>> print FeatureLocation(5,10) + f1 + >>> print(FeatureLocation(5, 10) + f1) join{[5:10], [15:17], [20:30]} You can also add another CompoundLocation: - >>> f2 = FeatureLocation(40,50) + FeatureLocation(60,70) - >>> print f2 + >>> f2 = FeatureLocation(40, 50) + FeatureLocation(60, 70) + >>> print(f2) join{[40:50], [60:70]} - >>> print f1 + f2 + >>> print(f1 + f2) join{[15:17], [20:30], [40:50], [60:70]} Also, as with the FeatureLocation, adding an integer shifts the location's co-ordinates by that offset: - >>> print f1 + 100 + >>> print(f1 + 100) join{[115:117], [120:130]} - >>> print 200 + f1 + >>> print(200 + f1) join{[215:217], [220:230]} - >>> print f1 + (-5) + >>> print(f1 + (-5)) join{[10:12], [15:25]} """ if isinstance(other, FeatureLocation): @@ -1232,7 +1238,7 @@ >>> p = ExactPosition(5) >>> p ExactPosition(5) - >>> print p + >>> print(p) 5 >>> isinstance(p, AbstractPosition) @@ -1333,10 +1339,10 @@ and 4. Since this is a start coordinate, it should acts like it is at position 1 (or in Python counting, 0). - >>> p = WithinPosition(10,10,13) + >>> p = WithinPosition(10, 10, 13) >>> p WithinPosition(10, left=10, right=13) - >>> print p + >>> print(p) (10.13) >>> int(p) 10 @@ -1346,7 +1352,7 @@ >>> p == 10 True - >>> p in [9,10,11] + >>> p in [9, 10, 11] True >>> p < 11 True @@ -1374,10 +1380,10 @@ If this were an end point, you would want the position to be 13: - >>> p2 = WithinPosition(13,10,13) + >>> p2 = WithinPosition(13, 10, 13) >>> p2 WithinPosition(13, left=10, right=13) - >>> print p2 + >>> print(p2) (10.13) >>> int(p2) 13 @@ -1460,7 +1466,7 @@ >>> p = BetweenPosition(456, 123, 456) >>> p BetweenPosition(456, left=123, right=456) - >>> print p + >>> print(p) (123^456) >>> int(p) 456 @@ -1560,7 +1566,7 @@ >>> p = BeforePosition(5) >>> p BeforePosition(5) - >>> print p + >>> print(p) <5 >>> int(p) 5 @@ -1623,7 +1629,7 @@ >>> p = AfterPosition(7) >>> p AfterPosition(7) - >>> print p + >>> print(p) >7 >>> int(p) 7 @@ -1795,3 +1801,4 @@ if __name__ == "__main__": from Bio._utils import run_doctest run_doctest() + diff -Nru python-biopython-1.62/Bio/SeqIO/AbiIO.py python-biopython-1.63/Bio/SeqIO/AbiIO.py --- python-biopython-1.62/Bio/SeqIO/AbiIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SeqIO/AbiIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -25,7 +25,9 @@ from Bio.Alphabet.IUPAC import ambiguous_dna, unambiguous_dna from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord + from Bio._py3k import _bytes_to_string, _as_bytes +from Bio._py3k import zip # dictionary for determining which tags goes into SeqRecord annotation # each key is tag_name + tag_number @@ -194,7 +196,7 @@ # only parse desired dirs key = _bytes_to_string(dir_entry[0]) key += str(dir_entry[1]) - if key in (list(_EXTRACT.keys()) + _SPCTAGS): + if key in (list(_EXTRACT) + _SPCTAGS): tag_name = _bytes_to_string(dir_entry[0]) tag_number = dir_entry[1] elem_code = dir_entry[2] diff -Nru python-biopython-1.62/Bio/SeqIO/AceIO.py python-biopython-1.63/Bio/SeqIO/AceIO.py --- python-biopython-1.62/Bio/SeqIO/AceIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SeqIO/AceIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -11,6 +11,8 @@ the contig consensus sequences in an ACE file as SeqRecord objects. """ +from __future__ import print_function + from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord from Bio.Alphabet import generic_nucleotide, generic_dna, generic_rna, Gapped @@ -30,10 +32,10 @@ letter_annotations dictionary under the "phred_quality" key. >>> from Bio import SeqIO - >>> handle = open("Ace/consed_sample.ace", "rU") - >>> for record in SeqIO.parse(handle, "ace"): - ... print record.id, record.seq[:10]+"...", len(record) - ... print max(record.letter_annotations["phred_quality"]) + >>> with open("Ace/consed_sample.ace", "rU") as handle: + ... for record in SeqIO.parse(handle, "ace"): + ... print("%s %s... %i" % (record.id, record.seq[:10], len(record))) + ... print(max(record.letter_annotations["phred_quality"])) Contig1 agccccgggc... 1475 90 @@ -45,11 +47,11 @@ prevented output of the gapped sequence as FASTQ format. >>> from Bio import SeqIO - >>> handle = open("Ace/contig1.ace", "rU") - >>> for record in SeqIO.parse(handle, "ace"): - ... print record.id, "..." + record.seq[85:95]+"..." - ... print record.letter_annotations["phred_quality"][85:95] - ... print max(record.letter_annotations["phred_quality"]) + >>> with open("Ace/contig1.ace", "rU") as handle: + ... for record in SeqIO.parse(handle, "ace"): + ... print("%s ...%s..." % (record.id, record.seq[85:95])) + ... print(record.letter_annotations["phred_quality"][85:95]) + ... print(max(record.letter_annotations["phred_quality"])) Contig1 ...AGAGG-ATGC... [57, 57, 54, 57, 57, 0, 57, 72, 72, 72] 90 @@ -113,3 +115,4 @@ if __name__ == "__main__": from Bio._utils import run_doctest run_doctest() + diff -Nru python-biopython-1.62/Bio/SeqIO/FastaIO.py python-biopython-1.63/Bio/SeqIO/FastaIO.py --- python-biopython-1.62/Bio/SeqIO/FastaIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SeqIO/FastaIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -11,6 +11,8 @@ You are expected to use this module via the Bio.SeqIO functions.""" +from __future__ import print_function + from Bio.Alphabet import single_letter_alphabet from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord @@ -26,7 +28,7 @@ identifier (the first word) and comment or description. >>> for values in SimpleFastaParser(open("Fasta/dups.fasta")): - ... print values + ... print(values) ('alpha', 'ACGTA') ('beta', 'CGTC') ('gamma', 'CCGCC') @@ -84,7 +86,7 @@ with no custom handling of the title lines: >>> for record in FastaIterator(open("Fasta/dups.fasta")): - ... print record.id + ... print(record.id) alpha beta gamma @@ -94,9 +96,9 @@ However, you can supply a title2ids function to alter this: >>> def take_upper(title): - ... return title.split(None,1)[0].upper(), "", title + ... return title.split(None, 1)[0].upper(), "", title >>> for record in FastaIterator(open("Fasta/dups.fasta"), title2ids=take_upper): - ... print record.id + ... print(record.id) ALPHA BETA GAMMA @@ -133,7 +135,7 @@ Use zero (or None) for no wrapping, giving a single long line for the sequence. record2title - Optional function to return the text to be - used for the title line of each record. By default the + used for the title line of each record. By default a combination of the record.id and record.description is used. If the record.description starts with the record.id, then just the record.description is used. @@ -198,7 +200,7 @@ self.handle.write(data + "\n") if __name__ == "__main__": - print "Running quick self test" + print("Running quick self test") import os from Bio.Alphabet import generic_protein, generic_nucleotide @@ -217,31 +219,31 @@ def print_record(record): #See also bug 2057 #http://bugzilla.open-bio.org/show_bug.cgi?id=2057 - print "ID:" + record.id - print "Name:" + record.name - print "Descr:" + record.description - print record.seq + print("ID:" + record.id) + print("Name:" + record.name) + print("Descr:" + record.description) + print(record.seq) for feature in record.annotations: - print '/%s=%s' % (feature, record.annotations[feature]) + print('/%s=%s' % (feature, record.annotations[feature])) if record.dbxrefs: - print "Database cross references:" + print("Database cross references:") for x in record.dbxrefs: - print " - %s" % x + print(" - %s" % x) if os.path.isfile(fna_filename): - print "--------" - print "FastaIterator (single sequence)" + print("--------") + print("FastaIterator (single sequence)") iterator = FastaIterator(open(fna_filename, "r"), alphabet=generic_nucleotide, title2ids=genbank_name_function) count = 0 for record in iterator: count += 1 print_record(record) assert count == 1 - print str(record.__class__) + print(str(record.__class__)) if os.path.isfile(faa_filename): - print "--------" - print "FastaIterator (multiple sequences)" + print("--------") + print("FastaIterator (multiple sequences)") iterator = FastaIterator(open(faa_filename, "r"), alphabet=generic_protein, title2ids=genbank_name_function) count = 0 for record in iterator: @@ -249,11 +251,11 @@ print_record(record) break assert count > 0 - print str(record.__class__) + print(str(record.__class__)) - from cStringIO import StringIO - print "--------" - print "FastaIterator (empty input file)" + from Bio._py3k import StringIO + print("--------") + print("FastaIterator (empty input file)") #Just to make sure no errors happen iterator = FastaIterator(StringIO("")) count = 0 @@ -261,4 +263,5 @@ count += 1 assert count == 0 - print "Done" + print("Done") + diff -Nru python-biopython-1.62/Bio/SeqIO/IgIO.py python-biopython-1.63/Bio/SeqIO/IgIO.py --- python-biopython-1.62/Bio/SeqIO/IgIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SeqIO/IgIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -9,7 +9,10 @@ """Bio.SeqIO support for the "ig" (IntelliGenetics or MASE) file format. -You are expected to use this module via the Bio.SeqIO functions.""" +You are expected to use this module via the Bio.SeqIO functions. +""" + +from __future__ import print_function from Bio.Alphabet import single_letter_alphabet from Bio.Seq import Seq @@ -83,20 +86,19 @@ assert not line if __name__ == "__main__": - print "Running quick self test" + print("Running quick self test") import os path = "../../Tests/IntelliGenetics/" if os.path.isdir(path): for filename in os.listdir(path): if os.path.splitext(filename)[-1] == ".txt": - print - print filename - print "-" * len(filename) - handle = open(os.path.join(path, filename)) - for record in IgIterator(handle): - print record.id, len(record) - handle.close() - print "Done" + print("") + print(filename) + print("-" * len(filename)) + with open(os.path.join(path, filename)) as handle: + for record in IgIterator(handle): + print("%s %i" % (record.id, len(record))) + print("Done") else: - print "Could not find input files" + print("Could not find input files") diff -Nru python-biopython-1.62/Bio/SeqIO/InsdcIO.py python-biopython-1.63/Bio/SeqIO/InsdcIO.py --- python-biopython-1.62/Bio/SeqIO/InsdcIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SeqIO/InsdcIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -31,13 +31,16 @@ """ +from __future__ import print_function + from Bio.Seq import UnknownSeq from Bio.GenBank.Scanner import GenBankScanner, EmblScanner, _ImgtScanner from Bio import Alphabet -from Interfaces import SequentialSequenceWriter +from .Interfaces import SequentialSequenceWriter from Bio import SeqFeature from Bio._py3k import _is_int_or_long +from Bio._py3k import basestring # NOTE # ==== @@ -124,8 +127,8 @@ return ">%i" % (pos.position + offset) elif isinstance(pos, SeqFeature.OneOfPosition): return "one-of(%s)" \ - % ",".join([_insdc_feature_position_string(p, offset) - for p in pos.position_choices]) + % ",".join(_insdc_feature_position_string(p, offset) + for p in pos.position_choices) elif isinstance(pos, SeqFeature.AbstractPosition): raise NotImplementedError("Please report this as a bug in Biopython.") else: @@ -263,9 +266,9 @@ # assert f.strand == +1 #This covers typical forward strand features, and also an evil mixed strand: assert feature.location_operator != "" - return "%s(%s)" % (feature.location_operator, - ",".join([_insdc_feature_location_string(f, rec_length) - for f in feature._sub_features])) + return "%s(%s)" % (feature.location_operator, + ",".join(_insdc_feature_location_string(f, rec_length) + for f in feature._sub_features)) class _InsdcWriter(SequentialSequenceWriter): @@ -334,12 +337,12 @@ """Write a single SeqFeature object to features table.""" assert feature.type, feature location = _insdc_location_string(feature.location, record_length) - f_type = feature.type.replace(" ","_") + f_type = feature.type.replace(" ", "_") line = (self.QUALIFIER_INDENT_TMP % f_type)[:self.QUALIFIER_INDENT] \ + self._wrap_location(location) + "\n" self.handle.write(line) #Now the qualifiers... - for key, values in feature.qualifiers.iteritems(): + for key, values in feature.qualifiers.items(): if isinstance(values, list) or isinstance(values, tuple): for value in values: self._write_feature_qualifier(key, value) @@ -1114,9 +1117,9 @@ FEATURE_HEADER = "FH Key Location/Qualifiers\n" if __name__ == "__main__": - print "Quick self test" + print("Quick self test") import os - from StringIO import StringIO + from Bio._py3k import StringIO def compare_record(old, new): if old.id != new.id and old.name != new.name: @@ -1211,8 +1214,8 @@ handle = StringIO() try: EmblWriter(handle).write_file(records) - except ValueError, err: - print err + except ValueError as err: + print(err) return handle.seek(0) @@ -1222,11 +1225,10 @@ for filename in os.listdir("../../Tests/GenBank"): if not filename.endswith(".gbk") and not filename.endswith(".gb"): continue - print filename + print(filename) - handle = open("../../Tests/GenBank/%s" % filename) - records = list(GenBankIterator(handle)) - handle.close() + with open("../../Tests/GenBank/%s" % filename) as handle: + records = list(GenBankIterator(handle)) check_genbank_writer(records) check_embl_writer(records) @@ -1234,11 +1236,10 @@ for filename in os.listdir("../../Tests/EMBL"): if not filename.endswith(".embl"): continue - print filename + print(filename) - handle = open("../../Tests/EMBL/%s" % filename) - records = list(EmblIterator(handle)) - handle.close() + with open("../../Tests/EMBL/%s" % filename) as handle: + records = list(EmblIterator(handle)) check_genbank_writer(records) check_embl_writer(records) @@ -1247,10 +1248,9 @@ for filename in os.listdir("../../Tests/SwissProt"): if not filename.startswith("sp"): continue - print filename + print(filename) - handle = open("../../Tests/SwissProt/%s" % filename) - records = list(SeqIO.parse(handle, "swiss")) - handle.close() + with open("../../Tests/SwissProt/%s" % filename) as handle: + records = list(SeqIO.parse(handle, "swiss")) check_genbank_writer(records) diff -Nru python-biopython-1.62/Bio/SeqIO/Interfaces.py python-biopython-1.63/Bio/SeqIO/Interfaces.py --- python-biopython-1.62/Bio/SeqIO/Interfaces.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SeqIO/Interfaces.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,19 +1,21 @@ -# Copyright 2006-2009 by Peter Cock. All rights reserved. +# Copyright 2006-2013 by Peter Cock. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. -""" -Bio.SeqIO support module (not for general use). +"""Bio.SeqIO support module (not for general use). Unless you are writing a new parser or writer for Bio.SeqIO, you should not use this module. It provides base classes to try and simplify things. """ +from __future__ import print_function + +import sys #for checking if Python 2 + from Bio.Alphabet import generic_alphabet from Bio.Seq import Seq, MutableSeq from Bio.SeqRecord import SeqRecord - class SequenceIterator(object): """Base class for building SeqRecord iterators. @@ -40,7 +42,7 @@ # or if additional arguments are required. # ##################################################### - def next(self): + def __next__(self): """Return the next record in the file. This method should be replaced by any derived class to do something useful.""" @@ -51,18 +53,28 @@ # into useful objects, e.g. return SeqRecord object # ##################################################### + if sys.version_info[0] < 3: + def next(self): + """Deprecated Python 2 style alias for Python 3 style __next__ method.""" + import warnings + from Bio import BiopythonDeprecationWarning + warnings.warn("Please use next(my_iterator) instead of my_iterator.next(), " + "the .next() method is deprecated and will be removed in a " + "future release of Biopython.", BiopythonDeprecationWarning) + return self.__next__() + def __iter__(self): """Iterate over the entries as a SeqRecord objects. Example usage for Fasta files: - myFile = open("example.fasta","r") - myFastaReader = FastaIterator(myFile) - for record in myFastaReader: - print record.id - print record.seq - myFile.close()""" - return iter(self.next, None) + with open("example.fasta","r") as myFile: + myFastaReader = FastaIterator(myFile) + for record in myFastaReader: + print(record.id) + print(record.seq) + """ + return iter(self.__next__, None) class InterlacedSequenceIterator(SequenceIterator): @@ -106,7 +118,7 @@ def move_start(self): self._n = 0 - def next(self): + def __next__(self): next_record = self._n if next_record < len(self): self._n = next_record + 1 @@ -116,7 +128,7 @@ return None def __iter__(self): - return iter(self.next, None) + return iter(self.__next__, None) class SequenceWriter(object): diff -Nru python-biopython-1.62/Bio/SeqIO/PdbIO.py python-biopython-1.63/Bio/SeqIO/PdbIO.py --- python-biopython-1.62/Bio/SeqIO/PdbIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SeqIO/PdbIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -2,8 +2,6 @@ # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. -from __future__ import with_statement - import collections import warnings @@ -77,7 +75,7 @@ 'db_acc': db_acc, 'db_id_code': db_id_code}) # ENH: 'SEQADV' 'MODRES' - for chn_id, residues in sorted(chains.iteritems()): + for chn_id, residues in sorted(chains.items()): record = SeqRecord(Seq(''.join(residues), generic_protein)) record.annotations = {"chain": chn_id} if chn_id in metadata: @@ -145,7 +143,7 @@ struct = PDBParser().get_structure(pdb_id, undo_handle) model = struct[0] - for chn_id, chain in sorted(model.child_dict.iteritems()): + for chn_id, chain in sorted(model.child_dict.items()): # HETATM mod. res. policy: remove mod if in sequence, else discard residues = [res for res in chain.get_unpacked_list() if seq1(res.get_resname().upper(), @@ -166,7 +164,7 @@ for i, pregap, postgap in gaps: if postgap > pregap: gapsize = postgap - pregap - 1 - res_out.extend(map(restype, residues[prev_idx:i])) + res_out.extend(restype(x) for x in residues[prev_idx:i]) prev_idx = i res_out.append('X'*gapsize) else: @@ -174,14 +172,14 @@ UserWarning) # Keep the normal part, drop the out-of-order segment # (presumably modified or hetatm residues, e.g. 3BEG) - res_out.extend(map(restype, residues[prev_idx:i])) + res_out.extend(restype(x) for x in residues[prev_idx:i]) break else: # Last segment - res_out.extend(map(restype, residues[prev_idx:])) + res_out.extend(restype(x) for x in residues[prev_idx:]) else: # No gaps - res_out = map(restype, residues) + res_out = [restype(x) for x in residues] record_id = "%s:%s" % (pdb_id, chn_id) # ENH - model number in SeqRecord id if multiple models? # id = "Chain%s" % str(chain.id) diff -Nru python-biopython-1.62/Bio/SeqIO/PhdIO.py python-biopython-1.63/Bio/SeqIO/PhdIO.py --- python-biopython-1.62/Bio/SeqIO/PhdIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SeqIO/PhdIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -17,24 +17,24 @@ >>> from Bio import SeqIO >>> for record in SeqIO.parse(open("Phd/phd1"), "phd"): - ... print record.id - ... print record.seq[:10], "..." - ... print record.letter_annotations["phred_quality"][:10], "..." + ... print(record.id) + ... print("%s..." % record.seq[:10]) + ... print("%s..." % record.letter_annotations["phred_quality"][:10]) 34_222_(80-A03-19).b.ab1 - ctccgtcgga ... - [9, 9, 10, 19, 22, 37, 28, 28, 24, 22] ... + ctccgtcgga... + [9, 9, 10, 19, 22, 37, 28, 28, 24, 22]... 425_103_(81-A03-19).g.ab1 - cgggatccca ... - [14, 17, 22, 10, 10, 10, 15, 8, 8, 9] ... + cgggatccca... + [14, 17, 22, 10, 10, 10, 15, 8, 8, 9]... 425_7_(71-A03-19).b.ab1 - acataaatca ... - [10, 10, 10, 10, 8, 8, 6, 6, 6, 6] ... + acataaatca... + [10, 10, 10, 10, 8, 8, 6, 6, 6, 6]... Since PHRED files contain quality scores, you can save them as FASTQ or as QUAL files, for example using Bio.SeqIO.write(...), or simply with the format method of the SeqRecord object: - >>> print record[:50].format("fastq") + >>> print(record[:50].format("fastq")) @425_7_(71-A03-19).b.ab1 acataaatcaaattactnaccaacacacaaaccngtctcgcgtagtggag + @@ -43,7 +43,7 @@ Or, - >>> print record[:50].format("qual") + >>> print(record[:50].format("qual")) >425_7_(71-A03-19).b.ab1 10 10 10 10 8 8 6 6 6 6 8 7 6 6 6 8 3 0 3 6 6 6 8 6 6 6 6 7 10 13 6 6 3 0 3 8 8 8 8 10 8 8 8 6 6 6 6 6 6 6 @@ -52,6 +52,8 @@ Note these examples only show the first 50 bases to keep the output short. """ +from __future__ import print_function + from Bio.SeqRecord import SeqRecord from Bio.Sequencing import Phd from Bio.SeqIO.Interfaces import SequentialSequenceWriter @@ -150,3 +152,4 @@ if __name__ == "__main__": from Bio._utils import run_doctest run_doctest() + diff -Nru python-biopython-1.62/Bio/SeqIO/PirIO.py python-biopython-1.63/Bio/SeqIO/PirIO.py --- python-biopython-1.62/Bio/SeqIO/PirIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SeqIO/PirIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -86,6 +86,8 @@ XX - Unknown """ +from __future__ import print_function + from Bio.Alphabet import single_letter_alphabet, generic_protein, \ generic_dna, generic_rna from Bio.Seq import Seq @@ -167,15 +169,15 @@ assert False, "Should not reach this line" if __name__ == "__main__": - print "Running quick self test" + print("Running quick self test") import os for name in ["clustalw", "DMA_nuc", "DMB_prot", "B_nuc", "Cw_prot"]: - print name + print(name) filename = "../../Tests/NBRF/%s.pir" % name if not os.path.isfile(filename): - print "Missing %s" % filename + print("Missing %s" % filename) continue records = list(PirIterator(open(filename))) @@ -185,4 +187,4 @@ parts = record.description.split() if "bases," in parts: assert len(record) == int(parts[parts.index("bases,") - 1]) - print "Could read %s (%i records)" % (name, count) + print("Could read %s (%i records)" % (name, count)) diff -Nru python-biopython-1.62/Bio/SeqIO/QualityIO.py python-biopython-1.63/Bio/SeqIO/QualityIO.py --- python-biopython-1.62/Bio/SeqIO/QualityIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SeqIO/QualityIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -113,26 +113,26 @@ >>> from Bio import SeqIO >>> for record in SeqIO.parse("Quality/example.fastq", "fastq"): - ... print record.id, record.seq + ... print("%s %s" % (record.id, record.seq)) EAS54_6_R1_2_1_413_324 CCCTTCTTGTCTTCAGCGTTTCTCC EAS54_6_R1_2_1_540_792 TTGGCAGGCCAAGGCCGATGGATCA EAS54_6_R1_2_1_443_348 GTTGCTTCTGGCGTGGGTGGGGGGG The qualities are held as a list of integers in each record's annotation: - >>> print record + >>> print(record) ID: EAS54_6_R1_2_1_443_348 Name: EAS54_6_R1_2_1_443_348 Description: EAS54_6_R1_2_1_443_348 Number of features: 0 Per letter annotation for: phred_quality Seq('GTTGCTTCTGGCGTGGGTGGGGGGG', SingleLetterAlphabet()) - >>> print record.letter_annotations["phred_quality"] + >>> print(record.letter_annotations["phred_quality"]) [26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 24, 26, 22, 26, 26, 13, 22, 26, 18, 24, 18, 18, 18, 18] You can use the SeqRecord format method to show this in the QUAL format: - >>> print record.format("qual") + >>> print(record.format("qual")) >EAS54_6_R1_2_1_443_348 26 26 26 26 26 26 26 26 26 26 26 24 26 22 26 26 13 22 26 18 24 18 18 18 18 @@ -140,7 +140,7 @@ Or go back to the FASTQ format, use "fastq" (or "fastq-sanger"): - >>> print record.format("fastq") + >>> print(record.format("fastq")) @EAS54_6_R1_2_1_443_348 GTTGCTTCTGGCGTGGGTGGGGGGG + @@ -150,7 +150,7 @@ Or, using the Illumina 1.3+ FASTQ encoding (PHRED values with an ASCII offset of 64): - >>> print record.format("fastq-illumina") + >>> print(record.format("fastq-illumina")) @EAS54_6_R1_2_1_443_348 GTTGCTTCTGGCGTGGGTGGGGGGG + @@ -160,7 +160,7 @@ You can also get Biopython to convert the scores and show a Solexa style FASTQ file: - >>> print record.format("fastq-solexa") + >>> print(record.format("fastq-solexa")) @EAS54_6_R1_2_1_443_348 GTTGCTTCTGGCGTGGGTGGGGGGG + @@ -177,16 +177,16 @@ or to remove a primer sequence), try slicing the SeqRecord objects. e.g. >>> sub_rec = record[5:15] - >>> print sub_rec + >>> print(sub_rec) ID: EAS54_6_R1_2_1_443_348 Name: EAS54_6_R1_2_1_443_348 Description: EAS54_6_R1_2_1_443_348 Number of features: 0 Per letter annotation for: phred_quality Seq('TTCTGGCGTG', SingleLetterAlphabet()) - >>> print sub_rec.letter_annotations["phred_quality"] + >>> print(sub_rec.letter_annotations["phred_quality"]) [26, 26, 26, 26, 26, 26, 24, 26, 22, 26] - >>> print sub_rec.format("fastq") + >>> print(sub_rec.format("fastq")) @EAS54_6_R1_2_1_443_348 TTCTGGCGTG + @@ -197,16 +197,15 @@ >>> from Bio import SeqIO >>> record_iterator = SeqIO.parse("Quality/example.fastq", "fastq") - >>> out_handle = open("Quality/temp.qual", "w") - >>> SeqIO.write(record_iterator, out_handle, "qual") + >>> with open("Quality/temp.qual", "w") as out_handle: + ... SeqIO.write(record_iterator, out_handle, "qual") 3 - >>> out_handle.close() You can of course read in a QUAL file, such as the one we just created: >>> from Bio import SeqIO >>> for record in SeqIO.parse("Quality/temp.qual", "qual"): - ... print record.id, record.seq + ... print("%s %s" % (record.id, record.seq)) EAS54_6_R1_2_1_413_324 ????????????????????????? EAS54_6_R1_2_1_540_792 ????????????????????????? EAS54_6_R1_2_1_443_348 ????????????????????????? @@ -214,14 +213,14 @@ Notice that QUAL files don't have a proper sequence present! But the quality information is there: - >>> print record + >>> print(record) ID: EAS54_6_R1_2_1_443_348 Name: EAS54_6_R1_2_1_443_348 Description: EAS54_6_R1_2_1_443_348 Number of features: 0 Per letter annotation for: phred_quality UnknownSeq(25, alphabet = SingleLetterAlphabet(), character = '?') - >>> print record.letter_annotations["phred_quality"] + >>> print(record.letter_annotations["phred_quality"]) [26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 24, 26, 22, 26, 26, 13, 22, 26, 18, 24, 18, 18, 18, 18] Just to keep things tidy, if you are following this example yourself, you can @@ -247,7 +246,7 @@ You can then access any record by its key, and get both the sequence and the quality scores. - >>> print reads["EAS54_6_R1_2_1_540_792"].format("fastq") + >>> print(reads["EAS54_6_R1_2_1_540_792"].format("fastq")) @EAS54_6_R1_2_1_540_792 TTGGCAGGCCAAGGCCGATGGATCA + @@ -267,11 +266,11 @@ >>> from Bio.SeqRecord import SeqRecord >>> test = SeqRecord(Seq("NACGTACGTA", generic_dna), id="Test", ... description="Made up!") - >>> print test.format("fasta") + >>> print(test.format("fasta")) >Test Made up! NACGTACGTA - >>> print test.format("fastq") + >>> print(test.format("fastq")) Traceback (most recent call last): ... ValueError: No suitable quality scores found in letter_annotations of SeqRecord (id=Test). @@ -280,12 +279,12 @@ or FASTQ format we need to provide some quality scores. These are held as a list of integers (one for each base) in the letter_annotations dictionary: - >>> test.letter_annotations["phred_quality"] = [0,1,2,3,4,5,10,20,30,40] - >>> print test.format("qual") + >>> test.letter_annotations["phred_quality"] = [0, 1, 2, 3, 4, 5, 10, 20, 30, 40] + >>> print(test.format("qual")) >Test Made up! 0 1 2 3 4 5 10 20 30 40 - >>> print test.format("fastq") + >>> print(test.format("fastq")) @Test Made up! NACGTACGTA + @@ -306,7 +305,7 @@ Similarly, we could produce an Illumina 1.3 to 1.7 style FASTQ file using PHRED scores with an offset of 64: - >>> print test.format("fastq-illumina") + >>> print(test.format("fastq-illumina")) @Test Made up! NACGTACGTA + @@ -330,8 +329,8 @@ First let's see what Biopython says if we convert the PHRED scores into Solexa scores (rounding to one decimal place): - >>> for q in [0,1,2,3,4,5,10,20,30,40]: - ... print "PHRED %i maps to Solexa %0.1f" % (q, solexa_quality_from_phred(q)) + >>> for q in [0, 1, 2, 3, 4, 5, 10, 20, 30, 40]: + ... print("PHRED %i maps to Solexa %0.1f" % (q, solexa_quality_from_phred(q))) PHRED 0 maps to Solexa -5.0 PHRED 1 maps to Solexa -5.0 PHRED 2 maps to Solexa -2.3 @@ -345,7 +344,7 @@ Now here is the record using the old Solexa style FASTQ file: - >>> print test.format("fastq-solexa") + >>> print(test.format("fastq-solexa")) @Test Made up! NACGTACGTA + @@ -362,6 +361,8 @@ are approximately equal. """ +from __future__ import print_function + __docformat__ = "epytext en" # Don't just use plain text in epydoc API pages! from Bio.Alphabet import single_letter_alphabet @@ -425,25 +426,25 @@ Note this function will return a floating point number, it is up to you to round this to the nearest integer if appropriate. e.g. - >>> print "%0.2f" % round(solexa_quality_from_phred(80),2) + >>> print("%0.2f" % round(solexa_quality_from_phred(80), 2)) 80.00 - >>> print "%0.2f" % round(solexa_quality_from_phred(50),2) + >>> print("%0.2f" % round(solexa_quality_from_phred(50), 2)) 50.00 - >>> print "%0.2f" % round(solexa_quality_from_phred(20),2) + >>> print("%0.2f" % round(solexa_quality_from_phred(20), 2)) 19.96 - >>> print "%0.2f" % round(solexa_quality_from_phred(10),2) + >>> print("%0.2f" % round(solexa_quality_from_phred(10), 2)) 9.54 - >>> print "%0.2f" % round(solexa_quality_from_phred(5),2) + >>> print("%0.2f" % round(solexa_quality_from_phred(5), 2)) 3.35 - >>> print "%0.2f" % round(solexa_quality_from_phred(4),2) + >>> print("%0.2f" % round(solexa_quality_from_phred(4), 2)) 1.80 - >>> print "%0.2f" % round(solexa_quality_from_phred(3),2) + >>> print("%0.2f" % round(solexa_quality_from_phred(3), 2)) -0.02 - >>> print "%0.2f" % round(solexa_quality_from_phred(2),2) + >>> print("%0.2f" % round(solexa_quality_from_phred(2), 2)) -2.33 - >>> print "%0.2f" % round(solexa_quality_from_phred(1),2) + >>> print("%0.2f" % round(solexa_quality_from_phred(1), 2)) -5.00 - >>> print "%0.2f" % round(solexa_quality_from_phred(0),2) + >>> print("%0.2f" % round(solexa_quality_from_phred(0), 2)) -5.00 Notice that for high quality reads PHRED and Solexa scores are numerically @@ -453,7 +454,7 @@ Finally, as a special case where None is used for a "missing value", None is returned: - >>> print solexa_quality_from_phred(None) + >>> print(solexa_quality_from_phred(None)) None """ if phred_quality is None: @@ -489,15 +490,15 @@ This will return a floating point number, it is up to you to round this to the nearest integer if appropriate. e.g. - >>> print "%0.2f" % round(phred_quality_from_solexa(80),2) + >>> print("%0.2f" % round(phred_quality_from_solexa(80), 2)) 80.00 - >>> print "%0.2f" % round(phred_quality_from_solexa(20),2) + >>> print("%0.2f" % round(phred_quality_from_solexa(20), 2)) 20.04 - >>> print "%0.2f" % round(phred_quality_from_solexa(10),2) + >>> print("%0.2f" % round(phred_quality_from_solexa(10), 2)) 10.41 - >>> print "%0.2f" % round(phred_quality_from_solexa(0),2) + >>> print("%0.2f" % round(phred_quality_from_solexa(0), 2)) 3.01 - >>> print "%0.2f" % round(phred_quality_from_solexa(-5),2) + >>> print("%0.2f" % round(phred_quality_from_solexa(-5), 2)) 1.19 Note that a solexa_quality less then -5 is not expected, will trigger a @@ -507,7 +508,7 @@ As a special case where None is used for a "missing value", None is returned: - >>> print phred_quality_from_solexa(None) + >>> print(phred_quality_from_solexa(None)) None """ if solexa_quality is None: @@ -553,7 +554,7 @@ >>> from Bio.Seq import Seq >>> from Bio.SeqRecord import SeqRecord >>> r = SeqRecord(Seq("ACGTAN"), id="Test", - ... letter_annotations = {"phred_quality":[50,40,30,20,10,0]}) + ... letter_annotations = {"phred_quality":[50, 40, 30, 20, 10, 0]}) >>> _get_sanger_quality_str(r) 'SI?5+!' @@ -563,14 +564,14 @@ it has to do the appropriate rounding - which is slower: >>> r2 = SeqRecord(Seq("ACGTAN"), id="Test2", - ... letter_annotations = {"phred_quality":[50.0,40.05,29.99,20,9.55,0.01]}) + ... letter_annotations = {"phred_quality":[50.0, 40.05, 29.99, 20, 9.55, 0.01]}) >>> _get_sanger_quality_str(r2) 'SI?5+!' If your scores include a None value, this raises an exception: >>> r3 = SeqRecord(Seq("ACGTAN"), id="Test3", - ... letter_annotations = {"phred_quality":[50,40,30,20,10,None]}) + ... letter_annotations = {"phred_quality":[50, 40, 30, 20, 10, None]}) >>> _get_sanger_quality_str(r3) Traceback (most recent call last): ... @@ -580,8 +581,8 @@ scores are used in preference: >>> r4 = SeqRecord(Seq("ACGTAN"), id="Test4", - ... letter_annotations = {"phred_quality":[50,40,30,20,10,0], - ... "solexa_quality":[-5,-4,0,None,0,40]}) + ... letter_annotations = {"phred_quality":[50, 40, 30, 20, 10, 0], + ... "solexa_quality":[-5, -4, 0, None, 0, 40]}) >>> _get_sanger_quality_str(r4) 'SI?5+!' @@ -589,7 +590,7 @@ instead (after the approriate conversion): >>> r5 = SeqRecord(Seq("ACGTAN"), id="Test5", - ... letter_annotations = {"solexa_quality":[40,30,20,10,0,-5]}) + ... letter_annotations = {"solexa_quality":[40, 30, 20, 10, 0, -5]}) >>> _get_sanger_quality_str(r5) 'I?5+$"' @@ -597,7 +598,7 @@ this very fast. You can still use approximate floating point scores: >>> r6 = SeqRecord(Seq("ACGTAN"), id="Test6", - ... letter_annotations = {"solexa_quality":[40.1,29.7,20.01,10,0.0,-4.9]}) + ... letter_annotations = {"solexa_quality":[40.1, 29.7, 20.01, 10, 0.0, -4.9]}) >>> _get_sanger_quality_str(r6) 'I?5+$"' @@ -618,8 +619,8 @@ else: #Try and use the precomputed mapping: try: - return "".join([_phred_to_sanger_quality_str[qp] - for qp in qualities]) + return "".join(_phred_to_sanger_quality_str[qp] + for qp in qualities) except KeyError: #Could be a float, or a None in the list, or a high value. pass @@ -629,8 +630,8 @@ warnings.warn("Data loss - max PHRED quality 93 in Sanger FASTQ", BiopythonWarning) #This will apply the truncation at 93, giving max ASCII 126 - return "".join([chr(min(126, int(round(qp)) + SANGER_SCORE_OFFSET)) - for qp in qualities]) + return "".join(chr(min(126, int(round(qp)) + SANGER_SCORE_OFFSET)) + for qp in qualities) #Fall back on the Solexa scores... try: qualities = record.letter_annotations["solexa_quality"] @@ -640,8 +641,8 @@ % record.id) #Try and use the precomputed mapping: try: - return "".join([_solexa_to_sanger_quality_str[qs] - for qs in qualities]) + return "".join(_solexa_to_sanger_quality_str[qs] + for qs in qualities) except KeyError: #Either no PHRED scores, or something odd like a float or None pass @@ -653,8 +654,8 @@ warnings.warn("Data loss - max PHRED quality 93 in Sanger FASTQ", BiopythonWarning) #This will apply the truncation at 93, giving max ASCII 126 - return "".join([chr(min(126, int(round(phred_quality_from_solexa(qs))) + SANGER_SCORE_OFFSET)) - for qs in qualities]) + return "".join(chr(min(126, int(round(phred_quality_from_solexa(qs))) + SANGER_SCORE_OFFSET)) + for qs in qualities) #Only map 0 to 62, we need to give a warning on truncating at 62 assert 62 + SOLEXA_SCORE_OFFSET == 126 @@ -686,8 +687,8 @@ else: #Try and use the precomputed mapping: try: - return "".join([_phred_to_illumina_quality_str[qp] - for qp in qualities]) + return "".join(_phred_to_illumina_quality_str[qp] + for qp in qualities) except KeyError: #Could be a float, or a None in the list, or a high value. pass @@ -697,8 +698,8 @@ warnings.warn("Data loss - max PHRED quality 62 in Illumina FASTQ", BiopythonWarning) #This will apply the truncation at 62, giving max ASCII 126 - return "".join([chr(min(126, int(round(qp)) + SOLEXA_SCORE_OFFSET)) - for qp in qualities]) + return "".join(chr(min(126, int(round(qp)) + SOLEXA_SCORE_OFFSET)) + for qp in qualities) #Fall back on the Solexa scores... try: qualities = record.letter_annotations["solexa_quality"] @@ -708,8 +709,8 @@ % record.id) #Try and use the precomputed mapping: try: - return "".join([_solexa_to_illumina_quality_str[qs] - for qs in qualities]) + return "".join(_solexa_to_illumina_quality_str[qs] + for qs in qualities) except KeyError: #Either no PHRED scores, or something odd like a float or None pass @@ -721,8 +722,8 @@ warnings.warn("Data loss - max PHRED quality 62 in Illumina FASTQ", BiopythonWarning) #This will apply the truncation at 62, giving max ASCII 126 - return "".join([chr(min(126, int(round(phred_quality_from_solexa(qs))) + SOLEXA_SCORE_OFFSET)) - for qs in qualities]) + return "".join(chr(min(126, int(round(phred_quality_from_solexa(qs))) + SOLEXA_SCORE_OFFSET)) + for qs in qualities) #Only map 0 to 62, we need to give a warning on truncating at 62 assert 62 + SOLEXA_SCORE_OFFSET == 126 @@ -755,8 +756,8 @@ else: #Try and use the precomputed mapping: try: - return "".join([_solexa_to_solexa_quality_str[qs] - for qs in qualities]) + return "".join(_solexa_to_solexa_quality_str[qs] + for qs in qualities) except KeyError: #Could be a float, or a None in the list, or a high value. pass @@ -766,8 +767,8 @@ warnings.warn("Data loss - max Solexa quality 62 in Solexa FASTQ", BiopythonWarning) #This will apply the truncation at 62, giving max ASCII 126 - return "".join([chr(min(126, int(round(qs)) + SOLEXA_SCORE_OFFSET)) - for qs in qualities]) + return "".join(chr(min(126, int(round(qs)) + SOLEXA_SCORE_OFFSET)) + for qs in qualities) #Fall back on the PHRED scores... try: qualities = record.letter_annotations["phred_quality"] @@ -777,8 +778,8 @@ % record.id) #Try and use the precomputed mapping: try: - return "".join([_phred_to_solexa_quality_str[qp] - for qp in qualities]) + return "".join(_phred_to_solexa_quality_str[qp] + for qp in qualities) except KeyError: #Either no PHRED scores, or something odd like a float or None #or too big to be in the cache @@ -790,10 +791,8 @@ if max(qualities) >= 62.5: warnings.warn("Data loss - max Solexa quality 62 in Solexa FASTQ", BiopythonWarning) - return "".join([chr(min(126, - int(round(solexa_quality_from_phred(qp))) + - SOLEXA_SCORE_OFFSET)) - for qp in qualities]) + return "".join(chr(min(126, int(round(solexa_quality_from_phred(qp))) + SOLEXA_SCORE_OFFSET)) + for qp in qualities) #TODO - Default to nucleotide or even DNA? @@ -867,10 +866,11 @@ Using this tricky example file as input, this short bit of code demonstrates what this parsing function would return: - >>> handle = open("Quality/tricky.fastq", "rU") - >>> for (title, sequence, quality) in FastqGeneralIterator(handle): - ... print title - ... print sequence, quality + >>> with open("Quality/tricky.fastq", "rU") as handle: + ... for (title, sequence, quality) in FastqGeneralIterator(handle): + ... print(title) + ... print("%s %s" % (sequence, quality)) + ... 071113_EAS56_0053:1:1:998:236 TTTCTTGCCCCCATAGACTGAGACCTTCCCTAAATA IIIIIIIIIIIIIIIIIIIIIIIIIIIIICII+III 071113_EAS56_0053:1:1:182:712 @@ -879,7 +879,6 @@ TGTTCTGAAGGAAGGTGTGCGTGCGTGTGTGTGTGT IIIIIIIIIIIICIIGIIIII>IAIIIE65I=II:6 071113_EAS56_0053:1:3:990:501 TGGGAGGTTTTATGTGGAAAGCAGCAATGTACAAGA IIIIIII.IIIIII1@44@-7.%<&+/$/%4(++(% - >>> handle.close() Finally we note that some sources state that the quality string should start with "!" (which using the PHRED mapping means the first letter always @@ -997,30 +996,28 @@ Using this module directly you might run: - >>> handle = open("Quality/example.fastq", "rU") - >>> for record in FastqPhredIterator(handle): - ... print record.id, record.seq + >>> with open("Quality/example.fastq", "rU") as handle: + ... for record in FastqPhredIterator(handle): + ... print("%s %s" % (record.id, record.seq)) EAS54_6_R1_2_1_413_324 CCCTTCTTGTCTTCAGCGTTTCTCC EAS54_6_R1_2_1_540_792 TTGGCAGGCCAAGGCCGATGGATCA EAS54_6_R1_2_1_443_348 GTTGCTTCTGGCGTGGGTGGGGGGG - >>> handle.close() Typically however, you would call this via Bio.SeqIO instead with "fastq" (or "fastq-sanger") as the format: >>> from Bio import SeqIO - >>> handle = open("Quality/example.fastq", "rU") - >>> for record in SeqIO.parse(handle, "fastq"): - ... print record.id, record.seq + >>> with open("Quality/example.fastq", "rU") as handle: + ... for record in SeqIO.parse(handle, "fastq"): + ... print("%s %s" % (record.id, record.seq)) EAS54_6_R1_2_1_413_324 CCCTTCTTGTCTTCAGCGTTTCTCC EAS54_6_R1_2_1_540_792 TTGGCAGGCCAAGGCCGATGGATCA EAS54_6_R1_2_1_443_348 GTTGCTTCTGGCGTGGGTGGGGGGG - >>> handle.close() If you want to look at the qualities, they are record in each record's per-letter-annotation dictionary as a simple list of integers: - >>> print record.letter_annotations["phred_quality"] + >>> print(record.letter_annotations["phred_quality"]) [26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 24, 26, 22, 26, 26, 13, 22, 26, 18, 24, 18, 18, 18, 18] """ @@ -1093,40 +1090,38 @@ Using this module directly you might run: - >>> handle = open("Quality/solexa_example.fastq", "rU") - >>> for record in FastqSolexaIterator(handle): - ... print record.id, record.seq + >>> with open("Quality/solexa_example.fastq", "rU") as handle: + ... for record in FastqSolexaIterator(handle): + ... print("%s %s" % (record.id, record.seq)) SLXA-B3_649_FC8437_R1_1_1_610_79 GATGTGCAATACCTTTGTAGAGGAA SLXA-B3_649_FC8437_R1_1_1_397_389 GGTTTGAGAAAGAGAAATGAGATAA SLXA-B3_649_FC8437_R1_1_1_850_123 GAGGGTGTTGATCATGATGATGGCG SLXA-B3_649_FC8437_R1_1_1_362_549 GGAAACAAAGTTTTTCTCAACATAG SLXA-B3_649_FC8437_R1_1_1_183_714 GTATTATTTAATGGCATACACTCAA - >>> handle.close() Typically however, you would call this via Bio.SeqIO instead with "fastq-solexa" as the format: >>> from Bio import SeqIO - >>> handle = open("Quality/solexa_example.fastq", "rU") - >>> for record in SeqIO.parse(handle, "fastq-solexa"): - ... print record.id, record.seq + >>> with open("Quality/solexa_example.fastq", "rU") as handle: + ... for record in SeqIO.parse(handle, "fastq-solexa"): + ... print("%s %s" % (record.id, record.seq)) SLXA-B3_649_FC8437_R1_1_1_610_79 GATGTGCAATACCTTTGTAGAGGAA SLXA-B3_649_FC8437_R1_1_1_397_389 GGTTTGAGAAAGAGAAATGAGATAA SLXA-B3_649_FC8437_R1_1_1_850_123 GAGGGTGTTGATCATGATGATGGCG SLXA-B3_649_FC8437_R1_1_1_362_549 GGAAACAAAGTTTTTCTCAACATAG SLXA-B3_649_FC8437_R1_1_1_183_714 GTATTATTTAATGGCATACACTCAA - >>> handle.close() If you want to look at the qualities, they are recorded in each record's per-letter-annotation dictionary as a simple list of integers: - >>> print record.letter_annotations["solexa_quality"] + >>> print(record.letter_annotations["solexa_quality"]) [25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 23, 25, 25, 25, 25, 23, 25, 23, 23, 21, 23, 23, 23, 17, 17] These scores aren't very good, but they are high enough that they map almost exactly onto PHRED scores: - >>> print "%0.2f" % phred_quality_from_solexa(25) + >>> print("%0.2f" % phred_quality_from_solexa(25)) 25.01 Let's look at faked example read which is even worse, where there are @@ -1144,26 +1139,25 @@ use the Bio.SeqIO.read() function: >>> from Bio import SeqIO - >>> handle = open("Quality/solexa_faked.fastq", "rU") - >>> record = SeqIO.read(handle, "fastq-solexa") - >>> handle.close() - >>> print record.id, record.seq + >>> with open("Quality/solexa_faked.fastq", "rU") as handle: + ... record = SeqIO.read(handle, "fastq-solexa") + >>> print("%s %s" % (record.id, record.seq)) slxa_0001_1_0001_01 ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN - >>> print record.letter_annotations["solexa_quality"] + >>> print(record.letter_annotations["solexa_quality"]) [40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5] These quality scores are so low that when converted from the Solexa scheme into PHRED scores they look quite different: - >>> print "%0.2f" % phred_quality_from_solexa(-1) + >>> print("%0.2f" % phred_quality_from_solexa(-1)) 2.54 - >>> print "%0.2f" % phred_quality_from_solexa(-5) + >>> print("%0.2f" % phred_quality_from_solexa(-5)) 1.19 Note you can use the Bio.SeqIO.write() function or the SeqRecord's format method to output the record(s): - >>> print record.format("fastq-solexa") + >>> print(record.format("fastq-solexa")) @slxa_0001_1_0001_01 ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN + @@ -1175,14 +1169,14 @@ line. If you want the to use PHRED scores, use "fastq" or "qual" as the output format instead, and Biopython will do the conversion for you: - >>> print record.format("fastq") + >>> print(record.format("fastq")) @slxa_0001_1_0001_01 ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN + IHGFEDCBA@?>=<;:9876543210/.-,++*)('&&%%$$##"" - >>> print record.format("qual") + >>> print(record.format("qual")) >slxa_0001_1_0001_01 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 10 9 8 7 6 5 5 4 4 3 3 2 2 @@ -1225,7 +1219,7 @@ >>> from Bio import SeqIO >>> record = SeqIO.read(open("Quality/illumina_faked.fastq"), "fastq-illumina") - >>> print record.id, record.seq + >>> print("%s %s" % (record.id, record.seq)) Test ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTN >>> max(record.letter_annotations["phred_quality"]) 40 @@ -1283,25 +1277,23 @@ Using this module directly you might run: - >>> handle = open("Quality/example.qual", "rU") - >>> for record in QualPhredIterator(handle): - ... print record.id, record.seq + >>> with open("Quality/example.qual", "rU") as handle: + ... for record in QualPhredIterator(handle): + ... print("%s %s" % (record.id, record.seq)) EAS54_6_R1_2_1_413_324 ????????????????????????? EAS54_6_R1_2_1_540_792 ????????????????????????? EAS54_6_R1_2_1_443_348 ????????????????????????? - >>> handle.close() Typically however, you would call this via Bio.SeqIO instead with "qual" as the format: >>> from Bio import SeqIO - >>> handle = open("Quality/example.qual", "rU") - >>> for record in SeqIO.parse(handle, "qual"): - ... print record.id, record.seq + >>> with open("Quality/example.qual", "rU") as handle: + ... for record in SeqIO.parse(handle, "qual"): + ... print("%s %s" % (record.id, record.seq)) EAS54_6_R1_2_1_413_324 ????????????????????????? EAS54_6_R1_2_1_540_792 ????????????????????????? EAS54_6_R1_2_1_443_348 ????????????????????????? - >>> handle.close() Becase QUAL files don't contain the sequence string itself, the seq property is set to an UnknownSeq object. As no alphabet was given, this @@ -1312,24 +1304,23 @@ >>> from Bio import SeqIO >>> from Bio.Alphabet import generic_dna - >>> handle = open("Quality/example.qual", "rU") - >>> for record in SeqIO.parse(handle, "qual", alphabet=generic_dna): - ... print record.id, record.seq + >>> with open("Quality/example.qual", "rU") as handle: + ... for record in SeqIO.parse(handle, "qual", alphabet=generic_dna): + ... print("%s %s" % (record.id, record.seq)) EAS54_6_R1_2_1_413_324 NNNNNNNNNNNNNNNNNNNNNNNNN EAS54_6_R1_2_1_540_792 NNNNNNNNNNNNNNNNNNNNNNNNN EAS54_6_R1_2_1_443_348 NNNNNNNNNNNNNNNNNNNNNNNNN - >>> handle.close() However, the quality scores themselves are available as a list of integers in each record's per-letter-annotation: - >>> print record.letter_annotations["phred_quality"] + >>> print(record.letter_annotations["phred_quality"]) [26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 24, 26, 22, 26, 26, 13, 22, 26, 18, 24, 18, 18, 18, 18] You can still slice one of these SeqRecord objects with an UnknownSeq: >>> sub_record = record[5:10] - >>> print sub_record.id, sub_record.letter_annotations["phred_quality"] + >>> print("%s %s" % (sub_record.id, sub_record.letter_annotations["phred_quality"])) EAS54_6_R1_2_1_443_348 [26, 26, 26, 26, 26] As of Biopython 1.59, this parser will accept files with negatives quality @@ -1362,7 +1353,7 @@ break if line[0] == ">": break - qualities.extend([int(word) for word in line.split()]) + qualities.extend(int(word) for word in line.split()) line = handle.readline() if qualities and min(qualities) < 0: @@ -1396,10 +1387,9 @@ >>> from Bio import SeqIO >>> record_iterator = SeqIO.parse(open("Quality/example.fastq"), "fastq") - >>> out_handle = open("Quality/temp.fastq", "w") - >>> SeqIO.write(record_iterator, out_handle, "fastq") + >>> with open("Quality/temp.fastq", "w") as out_handle: + ... SeqIO.write(record_iterator, out_handle, "fastq") 3 - >>> out_handle.close() You might want to do this if the original file included extra line breaks, which while valid may not be supported by all tools. The output file from @@ -1413,10 +1403,9 @@ >>> from Bio import SeqIO >>> record_iterator = SeqIO.parse(open("Quality/solexa_example.fastq"), "fastq-solexa") - >>> out_handle = open("Quality/temp.fastq", "w") - >>> SeqIO.write(record_iterator, out_handle, "fastq") + >>> with open("Quality/temp.fastq", "w") as out_handle: + ... SeqIO.write(record_iterator, out_handle, "fastq") 5 - >>> out_handle.close() This code is also called if you use the .format("fastq") method of a SeqRecord, or .format("fastq-sanger") if you prefer that alias. @@ -1471,10 +1460,9 @@ >>> from Bio import SeqIO >>> record_iterator = SeqIO.parse(open("Quality/example.fastq"), "fastq") - >>> out_handle = open("Quality/temp.qual", "w") - >>> SeqIO.write(record_iterator, out_handle, "qual") + >>> with open("Quality/temp.qual", "w") as out_handle: + ... SeqIO.write(record_iterator, out_handle, "qual") 3 - >>> out_handle.close() This code is also called if you use the .format("qual") method of a SeqRecord. @@ -1540,7 +1528,7 @@ #This rounds to the nearest integer. #TODO - can we record a float in a qual file? qualities_strs = [("%i" % round(q, 0)) for q in qualities] - except TypeError, e: + except TypeError as e: if None in qualities: raise TypeError("A quality value of None was found") else: @@ -1591,10 +1579,9 @@ >>> from Bio import SeqIO >>> record_iterator = SeqIO.parse(open("Quality/solexa_example.fastq"), "fastq-solexa") - >>> out_handle = open("Quality/temp.fastq", "w") - >>> SeqIO.write(record_iterator, out_handle, "fastq-solexa") + >>> with open("Quality/temp.fastq", "w") as out_handle: + ... SeqIO.write(record_iterator, out_handle, "fastq-solexa") 5 - >>> out_handle.close() You might want to do this if the original file included extra line breaks, which (while valid) may not be supported by all tools. The output file @@ -1606,7 +1593,7 @@ a SeqRecord. For example, >>> record = SeqIO.read(open("Quality/sanger_faked.fastq"), "fastq-sanger") - >>> print record.format("fastq-solexa") + >>> print(record.format("fastq-solexa")) @Test PHRED qualities from 40 to 0 inclusive ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTN + @@ -1667,7 +1654,7 @@ >>> from Bio import SeqIO >>> record = SeqIO.read(open("Quality/sanger_faked.fastq"), "fastq-sanger") - >>> print record.format("fastq-illumina") + >>> print(record.format("fastq-illumina")) @Test PHRED qualities from 40 to 0 inclusive ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTN + @@ -1742,7 +1729,7 @@ >>> rec_iter = PairedFastaQualIterator(open("Quality/example.fasta", "rU"), ... open("Quality/example.qual", "rU")) >>> for record in rec_iter: - ... print record.id, record.seq + ... print("%s %s" % (record.id, record.seq)) EAS54_6_R1_2_1_413_324 CCCTTCTTGTCTTCAGCGTTTCTCC EAS54_6_R1_2_1_540_792 TTGGCAGGCCAAGGCCGATGGATCA EAS54_6_R1_2_1_443_348 GTTGCTTCTGGCGTGGGTGGGGGGG @@ -1751,7 +1738,7 @@ they are in each record's per-letter-annotation dictionary as a simple list of integers: - >>> print record.letter_annotations["phred_quality"] + >>> print(record.letter_annotations["phred_quality"]) [26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 24, 26, 22, 26, 26, 13, 22, 26, 18, 24, 18, 18, 18, 18] If you have access to data as a FASTQ format file, using that directly @@ -1761,10 +1748,9 @@ >>> from Bio import SeqIO >>> rec_iter = PairedFastaQualIterator(open("Quality/example.fasta", "rU"), ... open("Quality/example.qual", "rU")) - >>> out_handle = open("Quality/temp.fastq", "w") - >>> SeqIO.write(rec_iter, out_handle, "fastq") + >>> with open("Quality/temp.fastq", "w") as out_handle: + ... SeqIO.write(rec_iter, out_handle, "fastq") 3 - >>> out_handle.close() And don't forget to clean up the temp file if you don't need it anymore: @@ -1777,15 +1763,15 @@ qual_iter = QualPhredIterator(qual_handle, alphabet=alphabet, title2ids=title2ids) - #Using zip(...) would create a list loading everything into memory! - #It would also not catch any extra records found in only one file. + #Using (Python 3 style) zip wouldn't load everything into memory, + #but also would not catch any extra records found in only one file. while True: try: - f_rec = fasta_iter.next() + f_rec = next(fasta_iter) except StopIteration: f_rec = None try: - q_rec = qual_iter.next() + q_rec = next(qual_iter) except StopIteration: q_rec = None if f_rec is None and q_rec is None: @@ -1811,3 +1797,5 @@ if __name__ == "__main__": from Bio._utils import run_doctest run_doctest(verbose=0) + + diff -Nru python-biopython-1.62/Bio/SeqIO/SeqXmlIO.py python-biopython-1.63/Bio/SeqIO/SeqXmlIO.py --- python-biopython-1.62/Bio/SeqIO/SeqXmlIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SeqIO/SeqXmlIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -12,16 +12,21 @@ (2011), http://dx.doi.org/10.1093/bib/bbr025 """ +from __future__ import print_function + from xml.sax.saxutils import XMLGenerator from xml.sax.xmlreader import AttributesImpl from xml.dom import pulldom from xml.sax import SAXParseException +from Bio._py3k import range +from Bio._py3k import basestring + from Bio import Alphabet from Bio.Seq import Seq from Bio.Seq import UnknownSeq from Bio.SeqRecord import SeqRecord -from Interfaces import SequentialSequenceWriter +from .Interfaces import SequentialSequenceWriter class XMLRecordIterator: @@ -73,7 +78,7 @@ elif event == "END_ELEMENT" and node.namespaceURI == self._namespace and node.localName == self._recordTag: yield record - except SAXParseException, e: + except SAXParseException as e: if e.getLineNumber() == 1 and e.getColumnNumber() == 0: #empty file @@ -90,7 +95,8 @@ def _attributes(self, node): """Return the attributes of a DOM node as dictionary.""" - return dict((node.attributes.item(i).name, node.attributes.item(i).value) for i in xrange(node.attributes.length)) + return dict((node.attributes.item(i).name, node.attributes.item(i).value) + for i in range(node.attributes.length)) class SeqXmlIterator(XMLRecordIterator): @@ -400,23 +406,23 @@ self.xml_generator.endElement("property") if __name__ == "__main__": - print "Running quick self test" + print("Running quick self test") from Bio import SeqIO import sys - fileHandle = open("Tests/SeqXML/protein_example.xml", "r") - records = list(SeqIO.parse(fileHandle, "seqxml")) + with open("Tests/SeqXML/protein_example.xml", "r") as fileHandle: + records = list(SeqIO.parse(fileHandle, "seqxml")) - from StringIO import StringIO + from Bio._py3k import StringIO stringHandle = StringIO() SeqIO.write(records, stringHandle, "seqxml") SeqIO.write(records, sys.stdout, "seqxml") - print + print("") stringHandle.seek(0) records = list(SeqIO.parse(stringHandle, "seqxml")) SeqIO.write(records, sys.stdout, "seqxml") - print + print("") diff -Nru python-biopython-1.62/Bio/SeqIO/SffIO.py python-biopython-1.63/Bio/SeqIO/SffIO.py --- python-biopython-1.62/Bio/SeqIO/SffIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SeqIO/SffIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -16,7 +16,7 @@ >>> from Bio import SeqIO >>> for record in SeqIO.parse("Roche/E3MFGYR02_random_10_reads.sff", "sff"): - ... print record.id, len(record), record.seq[:20]+"..." + ... print("%s %i %s..." % (record.id, len(record), record.seq[:20])) E3MFGYR02JWQ7T 265 tcagGGTCTACATGTTGGTT... E3MFGYR02JA6IL 271 tcagTTTTTTTTGGAAAGGA... E3MFGYR02JHD4H 310 tcagAAAGACAAGTGGTATC... @@ -31,26 +31,26 @@ Each SeqRecord object will contain all the annotation from the SFF file, including the PHRED quality scores. - >>> print record.id, len(record) + >>> print("%s %i" % (record.id, len(record))) E3MFGYR02F7Z7G 219 - >>> print record.seq[:10], "..." - tcagAATCAT ... - >>> print record.letter_annotations["phred_quality"][:10], "..." - [22, 21, 23, 28, 26, 15, 12, 21, 28, 21] ... + >>> print("%s..." % record.seq[:10]) + tcagAATCAT... + >>> print("%r..." % (record.letter_annotations["phred_quality"][:10])) + [22, 21, 23, 28, 26, 15, 12, 21, 28, 21]... Notice that the sequence is given in mixed case, the central upper case region corresponds to the trimmed sequence. This matches the output of the Roche tools (and the 3rd party tool sff_extract) for SFF to FASTA. - >>> print record.annotations["clip_qual_left"] + >>> print(record.annotations["clip_qual_left"]) 4 - >>> print record.annotations["clip_qual_right"] + >>> print(record.annotations["clip_qual_right"]) 134 - >>> print record.seq[:4] + >>> print(record.seq[:4]) tcag - >>> print record.seq[4:20], "...", record.seq[120:134] - AATCATCCACTTTTTA ... CAAAACACAAACAG - >>> print record.seq[134:] + >>> print("%s...%s" % (record.seq[4:20], record.seq[120:134])) + AATCATCCACTTTTTA...CAAAACACAAACAG + >>> print(record.seq[134:]) atcttatcaacaaaactcaaagttcctaactgagacacgcaacaggggataagacaaggcacacaggggataggnnnnnnnnnnn The annotations dictionary also contains any adapter clip positions @@ -58,23 +58,23 @@ >>> len(record.annotations) 11 - >>> print record.annotations["flow_key"] + >>> print(record.annotations["flow_key"]) TCAG - >>> print record.annotations["flow_values"][:10], "..." - (83, 1, 128, 7, 4, 84, 6, 106, 3, 172) ... - >>> print len(record.annotations["flow_values"]) + >>> print(record.annotations["flow_values"][:10]) + (83, 1, 128, 7, 4, 84, 6, 106, 3, 172) + >>> print(len(record.annotations["flow_values"])) 400 - >>> print record.annotations["flow_index"][:10], "..." - (1, 2, 3, 2, 2, 0, 3, 2, 3, 3) ... - >>> print len(record.annotations["flow_index"]) + >>> print(record.annotations["flow_index"][:10]) + (1, 2, 3, 2, 2, 0, 3, 2, 3, 3) + >>> print(len(record.annotations["flow_index"])) 219 Note that to convert from a raw reading in flow_values to the corresponding homopolymer stretch estimate, the value should be rounded to the nearest 100: - >>> print [int(round(value, -2)) // 100 - ... for value in record.annotations["flow_values"][:10]], '...' - [1, 0, 1, 0, 0, 1, 0, 1, 0, 2] ... + >>> print("%r..." % [int(round(value, -2)) // 100 + ... for value in record.annotations["flow_values"][:10]]) + [1, 0, 1, 0, 0, 1, 0, 1, 0, 2]... If a read name is exactly 14 alphanumeric characters, the annotations dictionary will also contain meta-data about the read extracted by @@ -83,11 +83,11 @@ characters but was not generated automatically, these annotation records will contain nonsense information. - >>> print record.annotations["region"] + >>> print(record.annotations["region"]) 2 - >>> print record.annotations["time"] + >>> print(record.annotations["time"]) [2008, 1, 9, 16, 16, 0] - >>> print record.annotations["coords"] + >>> print(record.annotations["coords"]) (2434, 1658) As a convenience method, you can read the file with SeqIO format name "sff-trim" @@ -96,7 +96,7 @@ >>> from Bio import SeqIO >>> for record in SeqIO.parse("Roche/E3MFGYR02_random_10_reads.sff", "sff-trim"): - ... print record.id, len(record), record.seq[:20]+"..." + ... print("%s %i %s..." % (record.id, len(record), record.seq[:20])) E3MFGYR02JWQ7T 260 GGTCTACATGTTGGTTAACC... E3MFGYR02JA6IL 265 TTTTTTTTGGAAAGGAAAAC... E3MFGYR02JHD4H 292 AAAGACAAGTGGTATCAACG... @@ -111,35 +111,39 @@ Looking at the final record in more detail, note how this differs to the example above: - >>> print record.id, len(record) + >>> print("%s %i" % (record.id, len(record))) E3MFGYR02F7Z7G 130 - >>> print record.seq[:10], "..." - AATCATCCAC ... - >>> print record.letter_annotations["phred_quality"][:10], "..." - [26, 15, 12, 21, 28, 21, 36, 28, 27, 27] ... + >>> print("%s..." % record.seq[:10]) + AATCATCCAC... + >>> print("%r..." % record.letter_annotations["phred_quality"][:10]) + [26, 15, 12, 21, 28, 21, 36, 28, 27, 27]... >>> len(record.annotations) 3 - >>> print record.annotations["region"] + >>> print(record.annotations["region"]) 2 - >>> print record.annotations["coords"] + >>> print(record.annotations["coords"]) (2434, 1658) - >>> print record.annotations["time"] + >>> print(record.annotations["time"]) [2008, 1, 9, 16, 16, 0] You might use the Bio.SeqIO.convert() function to convert the (trimmed) SFF reads into a FASTQ file (or a FASTA file and a QUAL file), e.g. >>> from Bio import SeqIO - >>> from StringIO import StringIO + >>> try: + ... from StringIO import StringIO # Python 2 + ... except ImportError: + ... from io import StringIO # Python 3 + ... >>> out_handle = StringIO() >>> count = SeqIO.convert("Roche/E3MFGYR02_random_10_reads.sff", "sff", ... out_handle, "fastq") - >>> print "Converted %i records" % count + >>> print("Converted %i records" % count) Converted 10 records The output FASTQ file would start like this: - >>> print "%s..." % out_handle.getvalue()[:50] + >>> print("%s..." % out_handle.getvalue()[:50]) @E3MFGYR02JWQ7T tcagGGTCTACATGTTGGTTAACCCGTACTGATT... @@ -152,7 +156,7 @@ >>> from Bio import SeqIO >>> reads = SeqIO.index("Roche/E3MFGYR02_random_10_reads.sff", "sff") >>> record = reads["E3MFGYR02JHD4H"] - >>> print record.id, len(record), record.seq[:20]+"..." + >>> print("%s %i %s..." % (record.id, len(record), record.seq[:20])) E3MFGYR02JHD4H 310 tcagAAAGACAAGTGGTATC... Or, using the trimmed reads: @@ -160,7 +164,7 @@ >>> from Bio import SeqIO >>> reads = SeqIO.index("Roche/E3MFGYR02_random_10_reads.sff", "sff-trim") >>> record = reads["E3MFGYR02JHD4H"] - >>> print record.id, len(record), record.seq[:20]+"..." + >>> print("%s %i %s..." % (record.id, len(record), record.seq[:20])) E3MFGYR02JHD4H 292 AAAGACAAGTGGTATCAACG... >>> reads.close() @@ -177,10 +181,10 @@ >>> from Bio import SeqIO >>> records = (record for record in - ... SeqIO.parse("Roche/E3MFGYR02_random_10_reads.sff","sff") + ... SeqIO.parse("Roche/E3MFGYR02_random_10_reads.sff", "sff") ... if record.seq[record.annotations["clip_qual_left"]:].startswith("AAAGA")) >>> count = SeqIO.write(records, "temp_filtered.sff", "sff") - >>> print "Selected %i records" % count + >>> print("Selected %i records" % count) Selected 2 records Of course, for an assembly you would probably want to remove these primers. @@ -195,20 +199,20 @@ ... record.annotations["clip_qual_left"] += len(primer) ... yield record >>> records = SeqIO.parse("Roche/E3MFGYR02_random_10_reads.sff", "sff") - >>> count = SeqIO.write(filter_and_trim(records,"AAAGA"), + >>> count = SeqIO.write(filter_and_trim(records, "AAAGA"), ... "temp_filtered.sff", "sff") - >>> print "Selected %i records" % count + >>> print("Selected %i records" % count) Selected 2 records We can check the results, note the lower case clipped region now includes the "AAAGA" sequence: >>> for record in SeqIO.parse("temp_filtered.sff", "sff"): - ... print record.id, len(record), record.seq[:20]+"..." + ... print("%s %i %s..." % (record.id, len(record), record.seq[:20])) E3MFGYR02JHD4H 310 tcagaaagaCAAGTGGTATC... E3MFGYR02GAZMS 278 tcagaaagaAGTAAGGTAAA... >>> for record in SeqIO.parse("temp_filtered.sff", "sff-trim"): - ... print record.id, len(record), record.seq[:20]+"..." + ... print("%s %i %s..." % (record.id, len(record), record.seq[:20])) E3MFGYR02JHD4H 287 CAAGTGGTATCAACGCAGAG... E3MFGYR02GAZMS 266 AGTAAGGTAAATAACAAACG... >>> import os @@ -218,6 +222,9 @@ http://www.ncbi.nlm.nih.gov/Traces/trace.cgi?cmd=show&f=formats&m=doc&s=formats """ + +from __future__ import print_function + from Bio.SeqIO.Interfaces import SequenceWriter from Bio import Alphabet from Bio.Seq import Seq @@ -227,12 +234,12 @@ import re from Bio._py3k import _bytes_to_string, _as_bytes -_null = _as_bytes("\0") -_sff = _as_bytes(".sff") -_hsh = _as_bytes(".hsh") -_srt = _as_bytes(".srt") -_mft = _as_bytes(".mft") -_flag = _as_bytes("\xff") +_null = b"\0" +_sff = b".sff" +_hsh = b".hsh" +_srt = b".srt" +_mft = b".mft" +_flag = b"\xff" def _sff_file_header(handle): @@ -243,18 +250,17 @@ Returns a tuple of values from the header (header_length, index_offset, index_length, number_of_reads, flows_per_read, flow_chars, key_sequence) - >>> handle = open("Roche/greek.sff", "rb") - >>> values = _sff_file_header(handle) - >>> handle.close() - >>> print values[0] + >>> with open("Roche/greek.sff", "rb") as handle: + ... values = _sff_file_header(handle) + >>> print(values[0]) 840 - >>> print values[1] + >>> print(values[1]) 65040 - >>> print values[2] + >>> print(values[2]) 256 - >>> print values[3] + >>> print(values[3]) 24 - >>> print values[4] + >>> print(values[4]) 800 >>> values[-1] 'TCAG' @@ -383,9 +389,12 @@ if padding: padding = 8 - padding if handle.read(padding).count(_null) != padding: - raise ValueError("Post quality %i byte padding region contained data" - % padding) - #print read, name, record_offset + import warnings + from Bio import BiopythonParserWarning + warnings.warn("Your SFF file is invalid, post quality %i " + "byte padding region contained data" % padding, + BiopythonParserWarning) + #print("%s %s %i" % (read, name, record_offset)) yield name, record_offset if handle.tell() % 8 != 0: raise ValueError( @@ -575,8 +584,11 @@ name = _bytes_to_string(handle.read(name_length)) padding = read_header_length - read_header_size - name_length if handle.read(padding).count(_null) != padding: - raise ValueError("Post name %i byte padding region contained data" - % padding) + import warnings + from Bio import BiopythonParserWarning + warnings.warn("Your SFF file is invalid, post name %i " + "byte padding region contained data" % padding, + BiopythonParserWarning) #now the flowgram values, flowgram index, bases and qualities #NOTE - assuming flowgram_format==1, which means struct type H flow_values = handle.read(read_flow_size) # unpack later if needed @@ -589,8 +601,11 @@ if padding: padding = 8 - padding if handle.read(padding).count(_null) != padding: - raise ValueError("Post quality %i byte padding region contained data" - % padding) + import warnings + from Bio import BiopythonParserWarning + warnings.warn("Your SFF file is invalid, post quality %i " + "byte padding region contained data" % padding, + BiopythonParserWarning) #Follow Roche and apply most aggressive of qual and adapter clipping. #Note Roche seems to ignore adapter clip fields when writing SFF, #and uses just the quality clipping values for any clipping. @@ -712,8 +727,11 @@ padding = read_header_length - read_header_size - 8 - name_length pad = handle.read(padding) if pad.count(_null) != padding: - raise ValueError("Post name %i byte padding region contained data" - % padding) + import warnings + from Bio import BiopythonParserWarning + warnings.warn("Your SFF file is invalid, post name %i " + "byte padding region contained data" % padding, + BiopythonParserWarning) raw += pad #now the flowgram values, flowgram index, bases and qualities raw += handle.read(read_flow_size + seq_len * 3) @@ -723,8 +741,11 @@ padding = 8 - padding pad = handle.read(padding) if pad.count(_null) != padding: - raise ValueError("Post quality %i byte padding region contained data" - % padding) + import warnings + from Bio import BiopythonParserWarning + warnings.warn("Your SFF file is invalid, post quality %i " + "byte padding region contained data" % padding, + BiopythonParserWarning) raw += pad #Return the raw bytes return raw @@ -776,7 +797,7 @@ >>> from Bio import SeqIO >>> for record in SeqIO.parse("Roche/E3MFGYR02_random_10_reads.sff", "sff"): - ... print record.id, len(record) + ... print("%s %i" % (record.id, len(record))) E3MFGYR02JWQ7T 265 E3MFGYR02JA6IL 271 E3MFGYR02JHD4H 310 @@ -790,9 +811,9 @@ You can also call it directly: - >>> handle = open("Roche/E3MFGYR02_random_10_reads.sff", "rb") - >>> for record in SffIterator(handle): - ... print record.id, len(record) + >>> with open("Roche/E3MFGYR02_random_10_reads.sff", "rb") as handle: + ... for record in SffIterator(handle): + ... print("%s %i" % (record.id, len(record))) E3MFGYR02JWQ7T 265 E3MFGYR02JA6IL 271 E3MFGYR02JHD4H 310 @@ -803,13 +824,12 @@ E3MFGYR02HHZ8O 221 E3MFGYR02GPGB1 269 E3MFGYR02F7Z7G 219 - >>> handle.close() Or, with the trim option: - >>> handle = open("Roche/E3MFGYR02_random_10_reads.sff", "rb") - >>> for record in SffIterator(handle, trim=True): - ... print record.id, len(record) + >>> with open("Roche/E3MFGYR02_random_10_reads.sff", "rb") as handle: + ... for record in SffIterator(handle, trim=True): + ... print("%s %i" % (record.id, len(record))) E3MFGYR02JWQ7T 260 E3MFGYR02JA6IL 265 E3MFGYR02JHD4H 292 @@ -820,10 +840,8 @@ E3MFGYR02HHZ8O 150 E3MFGYR02GPGB1 221 E3MFGYR02F7Z7G 130 - >>> handle.close() """ - #TODO - Once drop Python 2.5, update doctest to use 'with' to close handle if isinstance(Alphabet._get_base_alphabet(alphabet), Alphabet.ProteinAlphabet): raise ValueError("Invalid alphabet, SFF files do not hold proteins.") @@ -875,17 +893,64 @@ key_sequence, alphabet, trim) - #The following is not essential, but avoids confusing error messages - #for the user if they try and re-parse the same handle. - if index_offset and handle.tell() == index_offset: + _check_eof(handle, index_offset, index_length) + + +def _check_eof(handle, index_offset, index_length): + """Check final padding is OK (8 byte alignment) and file ends (PRIVATE). + + Will attempt to spot apparent SFF file concatenation and give an error. + + Will not attempt to seek, only moves the handle forward. + """ + offset = handle.tell() + extra = b"" + padding = 0 + + if index_offset and offset <= index_offset: + # Index block then end of file... + if offset < index_offset: + raise ValueError("Gap of %i bytes after final record end %i, " + "before %i where index starts?" + % (index_offset - offset, offset, index_offset)) + # Doing read to jump the index rather than a seek + # in case this is a network handle or similar + handle.read(index_offset + index_length - offset) offset = index_offset + index_length - if offset % 8: - offset += 8 - (offset % 8) - assert offset % 8 == 0 - handle.seek(offset) - #Should now be at the end of the file... - if handle.read(1): - raise ValueError("Additional data at end of SFF file") + assert offset == handle.tell(), \ + "Wanted %i, got %i, index is %i to %i" \ + % (offset, handle.tell(), index_offset, index_offset + index_length) + + if offset % 8: + padding = 8 - (offset % 8) + extra = handle.read(padding) + + if padding >= 4 and extra[-4:] == _sff: + #Seen this in one user supplied file, should have been + #four bytes of null padding but was actually .sff and + #the start of a new concatenated SFF file! + raise ValueError("Your SFF file is invalid, post index %i byte " + "null padding region ended '.sff' which could " + "be the start of a concatenated SFF file? " + "See offset %i" % (padding, offset)) + if extra.count(_null) != padding: + import warnings + from Bio import BiopythonParserWarning + warnings.warn("Your SFF file is invalid, post index %i byte " + "null padding region contained data." % padding, + BiopythonParserWarning) + + offset = handle.tell() + assert offset % 8 == 0 + # Should now be at the end of the file... + extra = handle.read(4) + if extra == _sff: + raise ValueError("Additional data at end of SFF file, " + "perhaps multiple SFF files concatenated? " + "See offset %i" % offset) + elif extra: + raise ValueError("Additional data at end of SFF file, " + "see offset %i" % offset) #This is a generator function! @@ -942,7 +1007,7 @@ #Get the first record in order to find the flow information #we will need for the header. try: - record = records.next() + record = next(records) except StopIteration: record = None if record is None: @@ -1180,19 +1245,15 @@ if __name__ == "__main__": - print "Running quick self test" + print("Running quick self test") filename = "../../Tests/Roche/E3MFGYR02_random_10_reads.sff" metadata = ReadRocheXmlManifest(open(filename, "rb")) index1 = sorted(_sff_read_roche_index(open(filename, "rb"))) index2 = sorted(_sff_do_slow_index(open(filename, "rb"))) assert index1 == index2 assert len(index1) == len(list(SffIterator(open(filename, "rb")))) - from StringIO import StringIO - try: - #This is in Python 2.6+, and is essential on Python 3 - from io import BytesIO - except ImportError: - BytesIO = StringIO + from Bio._py3k import StringIO + from io import BytesIO assert len(index1) == len( list(SffIterator(BytesIO(open(filename, "rb").read())))) @@ -1247,7 +1308,7 @@ sff_trim = list(SffIterator(open(filename, "rb"), trim=True)) - print ReadRocheXmlManifest(open(filename, "rb")) + print(ReadRocheXmlManifest(open(filename, "rb"))) from Bio import SeqIO filename = "../../Tests/Roche/E3MFGYR02_random_10_reads_no_trim.fasta" @@ -1262,10 +1323,10 @@ for s, sT, f, q, fT, qT in zip(sff, sff_trim, fasta_no_trim, qual_no_trim, fasta_trim, qual_trim): - #print - print s.id - #print s.seq - #print s.letter_annotations["phred_quality"] + #print("") + print(s.id) + #print(s.seq) + #print(s.letter_annotations["phred_quality"]) assert s.id == f.id == q.id assert str(s.seq) == str(f.seq) @@ -1277,47 +1338,46 @@ assert sT.letter_annotations[ "phred_quality"] == qT.letter_annotations["phred_quality"] - print "Writing with a list of SeqRecords..." + print("Writing with a list of SeqRecords...") handle = StringIO() w = SffWriter(handle, xml=metadata) w.write_file(sff) # list data = handle.getvalue() - print "And again with an iterator..." + print("And again with an iterator...") handle = StringIO() w = SffWriter(handle, xml=metadata) w.write_file(iter(sff)) assert data == handle.getvalue() #Check 100% identical to the original: filename = "../../Tests/Roche/E3MFGYR02_random_10_reads.sff" - original = open(filename, "rb").read() - assert len(data) == len(original) - assert data == original - del data - handle.close() + with open(filename, "rb").read() as original: + assert len(data) == len(original) + assert data == original + del data - print "-" * 50 + print("-" * 50) filename = "../../Tests/Roche/greek.sff" for record in SffIterator(open(filename, "rb")): - print record.id + print(record.id) index1 = sorted(_sff_read_roche_index(open(filename, "rb"))) index2 = sorted(_sff_do_slow_index(open(filename, "rb"))) assert index1 == index2 try: - print ReadRocheXmlManifest(open(filename, "rb")) + print(ReadRocheXmlManifest(open(filename, "rb"))) assert False, "Should fail!" except ValueError: pass - handle = open(filename, "rb") - for record in SffIterator(handle): - pass - try: + with open(filename, "rb") as handle: for record in SffIterator(handle): - print record.id - assert False, "Should have failed" - except ValueError, err: - print "Checking what happens on re-reading a handle:" - print err + pass + try: + for record in SffIterator(handle): + print(record.id) + assert False, "Should have failed" + except ValueError as err: + print("Checking what happens on re-reading a handle:") + print(err) """ #Ugly code to make test files... @@ -1401,31 +1461,30 @@ #Ugly bit of code to make a fake index at end records = list(SffIterator( open("../../Tests/Roche/E3MFGYR02_random_10_reads.sff", "rb"))) - out_handle = open("../../Tests/Roche/E3MFGYR02_alt_index_at_end.sff", "w") - w = SffWriter(out_handle, index=False, xml=None) - #Fake the header... - w._number_of_reads = len(records) - w._index_start = 0 - w._index_length = 0 - w._key_sequence = records[0].annotations["flow_key"] - w._flow_chars = records[0].annotations["flow_chars"] - w._number_of_flows_per_read = len(w._flow_chars) - w.write_header() - for record in records: - w.write_record(record) - w._index_start = out_handle.tell() - w._index_length = len(index) - out_handle.write(index) - out_handle.seek(0) - w.write_header() #this time with index info - out_handle.close() + with open("../../Tests/Roche/E3MFGYR02_alt_index_at_end.sff", "w") as out_handle: + w = SffWriter(out_handle, index=False, xml=None) + #Fake the header... + w._number_of_reads = len(records) + w._index_start = 0 + w._index_length = 0 + w._key_sequence = records[0].annotations["flow_key"] + w._flow_chars = records[0].annotations["flow_chars"] + w._number_of_flows_per_read = len(w._flow_chars) + w.write_header() + for record in records: + w.write_record(record) + w._index_start = out_handle.tell() + w._index_length = len(index) + out_handle.write(index) + out_handle.seek(0) + w.write_header() #this time with index info records2 = list(SffIterator( open("../../Tests/Roche/E3MFGYR02_alt_index_at_end.sff", "rb"))) for old, new in zip(records, records2): assert str(old.seq)==str(new.seq) try: - print ReadRocheXmlManifest( - open("../../Tests/Roche/E3MFGYR02_alt_index_at_end.sff", "rb")) + print(ReadRocheXmlManifest( + open("../../Tests/Roche/E3MFGYR02_alt_index_at_end.sff", "rb"))) assert False, "Should fail!" except ValueError: pass @@ -1433,4 +1492,6 @@ open("../../Tests/Roche/E3MFGYR02_alt_index_at_end.sff", "rb"))) """ - print "Done" + print("Done") + + diff -Nru python-biopython-1.62/Bio/SeqIO/SwissIO.py python-biopython-1.63/Bio/SeqIO/SwissIO.py --- python-biopython-1.62/Bio/SeqIO/SwissIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SeqIO/SwissIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -14,6 +14,8 @@ See also Bio.SeqIO.UniprotIO.py which supports the "uniprot-xml" format. """ +from __future__ import print_function + from Bio import Seq from Bio import SeqRecord from Bio import Alphabet @@ -118,9 +120,7 @@ annotations['references'] = [] for reference in swiss_record.references: feature = SeqFeature.Reference() - feature.comment = " ".join(["%s=%s;" % (key, value) - for key, value - in reference.comments]) + feature.comment = " ".join("%s=%s;" % k_v for k_v in reference.comments) for key, value in reference.references: if key == 'PubMed': feature.pubmed_id = value @@ -142,23 +142,22 @@ yield record if __name__ == "__main__": - print "Quick self test..." + print("Quick self test...") example_filename = "../../Tests/SwissProt/sp008" import os if not os.path.isfile(example_filename): - print "Missing test file %s" % example_filename + print("Missing test file %s" % example_filename) else: #Try parsing it! - handle = open(example_filename) - records = SwissIterator(handle) - for record in records: - print record.name - print record.id - print record.annotations['keywords'] - print repr(record.annotations['organism']) - print str(record.seq)[:20] + "..." - for f in record.features: - print f - handle.close() + with open(example_filename) as handle: + records = SwissIterator(handle) + for record in records: + print(record.name) + print(record.id) + print(record.annotations['keywords']) + print(repr(record.annotations['organism'])) + print(str(record.seq)[:20] + "...") + for f in record.features: + print(f) diff -Nru python-biopython-1.62/Bio/SeqIO/TabIO.py python-biopython-1.63/Bio/SeqIO/TabIO.py --- python-biopython-1.62/Bio/SeqIO/TabIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SeqIO/TabIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -31,6 +31,8 @@ example above. """ +from __future__ import print_function + from Bio.Alphabet import single_letter_alphabet from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord @@ -93,8 +95,8 @@ if __name__ == "__main__": - print "Running quick self test" - from StringIO import StringIO + print("Running quick self test") + from Bio._py3k import StringIO #This example has a trailing blank line which should be ignored handle = StringIO("Alpha\tAAAAAAA\nBeta\tCCCCCCC\n\n") @@ -109,4 +111,4 @@ #Good! pass - print "Done" + print("Done") diff -Nru python-biopython-1.62/Bio/SeqIO/UniprotIO.py python-biopython-1.63/Bio/SeqIO/UniprotIO.py --- python-biopython-1.62/Bio/SeqIO/UniprotIO.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SeqIO/UniprotIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -21,10 +21,8 @@ from Bio import SeqFeature from Bio import Alphabet from Bio.SeqRecord import SeqRecord -try: - from cStringIO import StringIO -except ImportError: - from StringIO import StringIO +from Bio._py3k import StringIO + #For speed try to use cElementTree rather than ElementTree try: @@ -399,7 +397,7 @@ def _parse_position(element, offset=0): try: position = int(element.attrib['position']) + offset - except KeyError, err: + except KeyError as err: position = None status = element.attrib.get('status', '') if status == 'unknown': diff -Nru python-biopython-1.62/Bio/SeqIO/__init__.py python-biopython-1.63/Bio/SeqIO/__init__.py --- python-biopython-1.62/Bio/SeqIO/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SeqIO/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -6,7 +6,7 @@ #Nice link: # http://www.ebi.ac.uk/help/formats_frame.html -"""Sequence input/output as SeqRecord objects. +r"""Sequence input/output as SeqRecord objects. Bio.SeqIO is also documented at U{http://biopython.org/wiki/SeqIO} and by a whole chapter in our tutorial: @@ -21,7 +21,7 @@ >>> from Bio import SeqIO >>> for record in SeqIO.parse("Fasta/f002", "fasta"): - ... print record.id, len(record) + ... print("%s %i" % (record.id, len(record))) gi|1348912|gb|G26680|G26680 633 gi|1348917|gb|G26685|G26685 413 gi|1592936|gb|G29385|G29385 471 @@ -38,7 +38,7 @@ >>> from Bio import SeqIO >>> record = SeqIO.read("Fasta/f001", "fasta") - >>> print record.id, len(record) + >>> print("%s %i" % (record.id, len(record))) gi|3318709|pdb|1A91| 79 This style is useful when you expect a single record only (and would @@ -48,11 +48,12 @@ record from the internet. However, if you just want the first record from a file containing multiple -record, use the iterator's next() method: +record, use the next() function on the iterator (or under Python 2, the +iterator's next() method): >>> from Bio import SeqIO - >>> record = SeqIO.parse("Fasta/f002", "fasta").next() - >>> print record.id, len(record) + >>> record = next(SeqIO.parse("Fasta/f002", "fasta")) + >>> print("%s %i" % (record.id, len(record))) gi|1348912|gb|G26680|G26680 633 The above code will work as long as the file contains at least one record. @@ -73,7 +74,7 @@ >>> records = list(SeqIO.parse("Fasta/f002", "fasta")) >>> len(records) 3 - >>> print records[1].id + >>> print(records[1].id) gi|1348917|gb|G26685|G26685 If you want random access to the records by a key such as the record id, @@ -83,7 +84,7 @@ >>> record_dict = SeqIO.to_dict(SeqIO.parse("Fasta/f002", "fasta")) >>> len(record_dict) 3 - >>> print len(record_dict["gi|1348917|gb|G26685|G26685"]) + >>> print(len(record_dict["gi|1348917|gb|G26685|G26685"])) 413 However, using list() or the to_dict() function will load all the records @@ -95,7 +96,7 @@ >>> record_dict = SeqIO.index("Fasta/f002", "fasta") >>> len(record_dict) 3 - >>> print len(record_dict["gi|1348917|gb|G26685|G26685"]) + >>> print(len(record_dict["gi|1348917|gb|G26685|G26685"])) 413 Many but not all of the supported input file formats can be indexed like @@ -112,7 +113,7 @@ >>> record_dict = SeqIO.index("Fasta/f002", "fasta") >>> len(record_dict) 3 - >>> print record_dict.get_raw("gi|1348917|gb|G26685|G26685").decode() + >>> print(record_dict.get_raw("gi|1348917|gb|G26685|G26685").decode()) >gi|1348917|gb|G26685|G26685 human STS STS_D11734. CGGAGCCAGCGAGCATATGCTGCATGAGGACCTTTCTATCTTACATTATGGCTGGGAATCTTACTCTTTC ATCTGATACCTTGTTCAGATTTCAAAATAGTTGTAGCCTTATCCTGGTTTTACAGATGTGAAACTTTCAA @@ -121,7 +122,7 @@ TCATATTACTNTAAGTTCTATAGCATACTTGCNATCCTTTANCCATGCTTATCATANGTACCATTTGAGG AATTGNTTTGCCCTTTTGGGTTTNTTNTTGGTAAANNNTTCCCGGGTGGGGGNGGTNNNGAAA - >>> print record_dict["gi|1348917|gb|G26685|G26685"].format("fasta") + >>> print(record_dict["gi|1348917|gb|G26685|G26685"].format("fasta")) >gi|1348917|gb|G26685|G26685 human STS STS_D11734. CGGAGCCAGCGAGCATATGCTGCATGAGGACCTTTCTATCTTACATTATGGCTGGGAATC TTACTCTTTCATCTGATACCTTGTTCAGATTTCAAAATAGTTGTAGCCTTATCCTGGTTT @@ -137,6 +138,42 @@ bytes string, hence the use of decode to turn it into a (unicode) string. This is uncessary on Python 2. +Also note that the get_raw method will preserve the newline endings. This +example FASTQ file uses Unix style endings (b"\n" only), + + >>> from Bio import SeqIO + >>> fastq_dict = SeqIO.index("Quality/example.fastq", "fastq") + >>> len(fastq_dict) + 3 + >>> raw = fastq_dict.get_raw("EAS54_6_R1_2_1_540_792") + >>> raw.count(b"\n") + 4 + >>> raw.count(b"\r\n") + 0 + >>> b"\r" in raw + False + >>> len(raw) + 78 + +Here is the same file but using DOS/Windows new lines (b"\r\n" instead), + + >>> from Bio import SeqIO + >>> fastq_dict = SeqIO.index("Quality/example_dos.fastq", "fastq") + >>> len(fastq_dict) + 3 + >>> raw = fastq_dict.get_raw("EAS54_6_R1_2_1_540_792") + >>> raw.count(b"\n") + 4 + >>> raw.count(b"\r\n") + 4 + >>> b"\r\n" in raw + True + >>> len(raw) + 82 + +Because this uses two bytes for each new line, the file is longer than +the Unix equivalent with only one byte. + Input - Alignments ================== @@ -146,13 +183,14 @@ >>> from Bio import SeqIO >>> for record in SeqIO.parse("Clustalw/hedgehog.aln", "clustal"): - ... print record.id, len(record) + ... print("%s %i" % (record.id, len(record))) gi|167877390|gb|EDS40773.1| 447 gi|167234445|ref|NP_001107837. 447 gi|74100009|gb|AAZ99217.1| 447 gi|13990994|dbj|BAA33523.2| 447 gi|56122354|gb|AAV74328.1| 447 + Output ====== Use the function Bio.SeqIO.write(...), which takes a complete set of @@ -168,9 +206,8 @@ from Bio import SeqIO records = ... - handle = open("example.faa", "w") - SeqIO.write(records, handle, "fasta") - handle.close() + with open("example.faa", "w") as handle: + SeqIO.write(records, handle, "fasta") You are expected to call this function once (with all your records) and if using a handle, make sure you close it to flush the data to the hard disk. @@ -259,8 +296,8 @@ making up each alignment as SeqRecords. """ -# For using with statement in Python 2.5 or Jython -from __future__ import with_statement +from __future__ import print_function +from Bio._py3k import basestring __docformat__ = "epytext en" # not just plaintext @@ -314,20 +351,20 @@ from Bio.Align import MultipleSeqAlignment from Bio.Alphabet import Alphabet, AlphabetEncoder, _get_base_alphabet -import AbiIO -import AceIO -import FastaIO -import IgIO # IntelliGenetics or MASE format -import InsdcIO # EMBL and GenBank -import PdbIO -import PhdIO -import PirIO -import SeqXmlIO -import SffIO -import SwissIO -import TabIO -import QualityIO # FastQ and qual files -import UniprotIO +from . import AbiIO +from . import AceIO +from . import FastaIO +from . import IgIO # IntelliGenetics or MASE format +from . import InsdcIO # EMBL and GenBank +from . import PdbIO +from . import PhdIO +from . import PirIO +from . import SeqXmlIO +from . import SffIO +from . import SwissIO +from . import TabIO +from . import QualityIO # FastQ and qual files +from . import UniprotIO #Convention for format names is "mainname-subtype" in lower case. @@ -462,9 +499,9 @@ >>> from Bio import SeqIO >>> filename = "Fasta/sweetpea.nu" >>> for record in SeqIO.parse(filename, "fasta"): - ... print "ID", record.id - ... print "Sequence length", len(record) - ... print "Sequence alphabet", record.seq.alphabet + ... print("ID %s" % record.id) + ... print("Sequence length %i" % len(record)) + ... print("Sequence alphabet %s" % record.seq.alphabet) ID gi|3176602|gb|U78617.1|LOU78617 Sequence length 309 Sequence alphabet SingleLetterAlphabet() @@ -476,9 +513,9 @@ >>> from Bio.Alphabet import generic_dna >>> filename = "Fasta/sweetpea.nu" >>> for record in SeqIO.parse(filename, "fasta", generic_dna): - ... print "ID", record.id - ... print "Sequence length", len(record) - ... print "Sequence alphabet", record.seq.alphabet + ... print("ID %s" % record.id) + ... print("Sequence length %i" % len(record)) + ... print("Sequence alphabet %s" % record.seq.alphabet) ID gi|3176602|gb|U78617.1|LOU78617 Sequence length 309 Sequence alphabet DNAAlphabet() @@ -488,9 +525,13 @@ >>> data = ">Alpha\nACCGGATGTA\n>Beta\nAGGCTCGGTTA\n" >>> from Bio import SeqIO - >>> from StringIO import StringIO + >>> try: + ... from StringIO import StringIO # Python 2 + ... except ImportError: + ... from io import StringIO # Python 3 + ... >>> for record in SeqIO.parse(StringIO(data), "fasta"): - ... print record.id, record.seq + ... print("%s %s" % (record.id, record.seq)) Alpha ACCGGATGTA Beta AGGCTCGGTTA @@ -572,11 +613,11 @@ >>> from Bio import SeqIO >>> record = SeqIO.read("GenBank/arab1.gb", "genbank") - >>> print "ID", record.id + >>> print("ID %s" % record.id) ID AC007323.5 - >>> print "Sequence length", len(record) + >>> print("Sequence length %i" % len(record)) Sequence length 86436 - >>> print "Sequence alphabet", record.seq.alphabet + >>> print("Sequence alphabet %s" % record.seq.alphabet) Sequence alphabet IUPACAmbiguousDNA() If the handle contains no records, or more than one record, @@ -593,8 +634,8 @@ shown in the example above). Instead use: >>> from Bio import SeqIO - >>> record = SeqIO.parse("GenBank/cor6_6.gb", "genbank").next() - >>> print "First record's ID", record.id + >>> record = next(SeqIO.parse("GenBank/cor6_6.gb", "genbank")) + >>> print("First record's ID %s" % record.id) First record's ID X55053.1 Use the Bio.SeqIO.parse(handle, format) function if you want @@ -602,13 +643,13 @@ """ iterator = parse(handle, format, alphabet) try: - first = iterator.next() + first = next(iterator) except StopIteration: first = None if first is None: raise ValueError("No records found in handle") try: - second = iterator.next() + second = next(iterator) except StopIteration: second = None if second is not None: @@ -638,9 +679,9 @@ >>> filename = "GenBank/cor6_6.gb" >>> format = "genbank" >>> id_dict = SeqIO.to_dict(SeqIO.parse(filename, format)) - >>> print sorted(id_dict) + >>> print(sorted(id_dict)) ['AF297471.1', 'AJ237582.1', 'L31939.1', 'M81224.1', 'X55053.1', 'X62281.1'] - >>> print id_dict["L31939.1"].description + >>> print(id_dict["L31939.1"].description) Brassica rapa (clone bif72) kin mRNA, complete cds. A more complex example, using the key_function argument in order to @@ -652,8 +693,8 @@ >>> format = "genbank" >>> seguid_dict = SeqIO.to_dict(SeqIO.parse(filename, format), ... key_function = lambda rec : seguid(rec.seq)) - >>> for key, record in sorted(seguid_dict.iteritems()): - ... print key, record.id + >>> for key, record in sorted(seguid_dict.items()): + ... print("%s %s" % (key, record.id)) /wQvmrl87QWcm9llO4/efg23Vgg AJ237582.1 BUg6YxXSKWEcFFH0L08JzaLGhQs L31939.1 SabZaA4V2eLE9/2Fm5FnyYy07J4 X55053.1 @@ -698,13 +739,13 @@ 3 >>> sorted(records) ['EAS54_6_R1_2_1_413_324', 'EAS54_6_R1_2_1_443_348', 'EAS54_6_R1_2_1_540_792'] - >>> print records["EAS54_6_R1_2_1_540_792"].format("fasta") + >>> print(records["EAS54_6_R1_2_1_540_792"].format("fasta")) >EAS54_6_R1_2_1_540_792 TTGGCAGGCCAAGGCCGATGGATCA >>> "EAS54_6_R1_2_1_540_792" in records True - >>> print records.get("Missing", None) + >>> print(records.get("Missing", None)) None If the file is BGZF compressed, this is detected automatically. Ordinary @@ -714,7 +755,7 @@ >>> records = SeqIO.index("Quality/example.fastq.bgz", "fastq") >>> len(records) 3 - >>> print records["EAS54_6_R1_2_1_540_792"].seq + >>> print(records["EAS54_6_R1_2_1_540_792"].seq) TTGGCAGGCCAAGGCCGATGGATCA Note that this pseudo dictionary will not support all the methods of a @@ -740,7 +781,7 @@ 3 >>> sorted(records) ['EAS54_6_R1_2_1_413_324', 'EAS54_6_R1_2_1_443_348', 'EAS54_6_R1_2_1_540_792'] - >>> print records["EAS54_6_R1_2_1_540_792"].format("fasta") + >>> print(records["EAS54_6_R1_2_1_540_792"].format("fasta")) >EAS54_6_R1_2_1_540_792 TTGGCAGGCCAAGGCCGATGGATCA @@ -759,7 +800,7 @@ 3 >>> sorted(records) [(413, 324), (443, 348), (540, 792)] - >>> print records[(540, 792)].format("fasta") + >>> print(records[(540, 792)].format("fasta")) >EAS54_6_R1_2_1_540_792 TTGGCAGGCCAAGGCCGATGGATCA @@ -767,7 +808,7 @@ True >>> "EAS54_6_R1_2_1_540_792" in records False - >>> print records.get("Missing", None) + >>> print(records.get("Missing", None)) None Another common use case would be indexing an NCBI style FASTA file, @@ -796,7 +837,7 @@ raise ValueError("Invalid alphabet, %s" % repr(alphabet)) #Map the file format to a sequence iterator: - from _index import _FormatToRandomAccess # Lazy import + from ._index import _FormatToRandomAccess # Lazy import from Bio.File import _IndexedSeqFileDict try: proxy_class = _FormatToRandomAccess[format] @@ -874,7 +915,7 @@ raise ValueError("Invalid alphabet, %s" % repr(alphabet)) #Map the file format to a sequence iterator: - from _index import _FormatToRandomAccess # Lazy import + from ._index import _FormatToRandomAccess # Lazy import from Bio.File import _SQLiteManySeqFilesDict repr = "SeqIO.index_db(%r, filenames=%r, format=%r, alphabet=%r, key_function=%r)" \ % (index_filename, filenames, format, alphabet, key_function) @@ -907,11 +948,15 @@ For example, going from a filename to a handle: >>> from Bio import SeqIO - >>> from StringIO import StringIO + >>> try: + ... from StringIO import StringIO # Python 2 + ... except ImportError: + ... from io import StringIO # Python 3 + ... >>> handle = StringIO("") >>> SeqIO.convert("Quality/example.fastq", "fastq", handle, "fasta") 3 - >>> print handle.getvalue() + >>> print(handle.getvalue()) >EAS54_6_R1_2_1_413_324 CCCTTCTTGTCTTCAGCGTTTCTCC >EAS54_6_R1_2_1_540_792 @@ -934,7 +979,7 @@ #This will check the arguments and issue error messages, #after we have opened the file which is a shame. - from _convert import _handle_convert # Lazy import + from ._convert import _handle_convert # Lazy import with as_handle(in_file, in_mode) as in_handle: with as_handle(out_file, out_mode) as out_handle: count = _handle_convert(in_handle, in_format, diff -Nru python-biopython-1.62/Bio/SeqIO/_index.py python-biopython-1.63/Bio/SeqIO/_index.py --- python-biopython-1.62/Bio/SeqIO/_index.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SeqIO/_index.py 2013-12-05 14:10:43.000000000 +0000 @@ -23,9 +23,10 @@ temp lookup file might be one idea (e.g. using SQLite or an OBDA style index). """ -import re -from StringIO import StringIO +from __future__ import print_function +import re +from Bio._py3k import StringIO from Bio._py3k import _bytes_to_string, _as_bytes from Bio import SeqIO @@ -47,16 +48,15 @@ if alphabet is None: def _parse(handle): """Dynamically generated parser function (PRIVATE).""" - return i(handle).next() + return next(i(handle)) else: #TODO - Detect alphabet support ONCE at __init__ def _parse(handle): """Dynamically generated parser function (PRIVATE).""" try: - return i(handle, alphabet=alphabet).next() + return next(i(handle, alphabet=alphabet)) except TypeError: - return SeqIO._force_alphabet(i(handle), - alphabet).next() + return next(SeqIO._force_alphabet(i(handle), alphabet)) self._parse = _parse def get(self, offset): @@ -93,19 +93,34 @@ if index_offset and index_length: #There is an index provided, try this the fast way: count = 0 + max_offset = 0 try: for name, offset in SeqIO.SffIO._sff_read_roche_index(handle): + max_offset = max(max_offset, offset) yield name, offset, 0 count += 1 assert count == number_of_reads, \ "Indexed %i records, expected %i" \ % (count, number_of_reads) - return - except ValueError, err: + # If that worked, call _check_eof ... + except ValueError as err: import warnings - warnings.warn("Could not parse the SFF index: %s" % err) + from Bio import BiopythonParserWarning + warnings.warn("Could not parse the SFF index: %s" % err, + BiopythonParserWarning) assert count == 0, "Partially populated index" handle.seek(0) + # Drop out to the slow way... + else: + # Fast way worked, check EOF + if index_offset + index_length <= max_offset: + # Can have an index at start (or mid-file) + handle.seek(max_offset) + # Parse the final read, + SeqIO.SffIO._sff_read_raw_record(handle, self._flows_per_read) + # Should now be at the end of the file! + SeqIO.SffIO._check_eof(handle, index_offset, index_length) + return #We used to give a warning in this case, but Ion Torrent's #SFF files don't have an index so that would be annoying. #Fall back on the slow way! @@ -115,6 +130,8 @@ count += 1 assert count == number_of_reads, \ "Indexed %i records, expected %i" % (count, number_of_reads) + SeqIO.SffIO._check_eof(handle, index_offset, index_length) + def get(self, offset): handle = self._handle @@ -421,7 +438,7 @@ """ % _bytes_to_string(self.get_raw(offset)) #TODO - For consistency, this function should not accept a string: - return SeqIO.UniprotIO.UniprotIterator(data).next() + return next(SeqIO.UniprotIO.UniprotIterator(data)) class IntelliGeneticsRandomAccess(SeqFileRandomAccess): @@ -483,7 +500,7 @@ break # End of file try: key = line.split(tab_char)[0] - except ValueError, err: + except ValueError as err: if not line.strip(): #Ignore blank lines continue @@ -556,7 +573,7 @@ raise ValueError("Problem with quality section") yield _bytes_to_string(id), start_offset, length start_offset = end_offset - #print "EOF" + #print("EOF") def get_raw(self, offset): """Similar to the get method, but returns the record as a raw string.""" diff -Nru python-biopython-1.62/Bio/SeqRecord.py python-biopython-1.63/Bio/SeqRecord.py --- python-biopython-1.62/Bio/SeqRecord.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SeqRecord.py 2013-12-05 14:10:43.000000000 +0000 @@ -6,6 +6,10 @@ # license. Please see the LICENSE file that should have been included # as part of this package. """Represent a Sequence Record, a sequence with annotation.""" + + +from Bio._py3k import basestring + __docformat__ = "epytext en" # Simple markup to show doctests nicely # NEEDS TO BE SYNCH WITH THE REST OF BIOPYTHON AND BIOPERL @@ -81,7 +85,7 @@ def update(self, new_dict): #Force this to go via our strict __setitem__ method - for (key, value) in new_dict.iteritems(): + for (key, value) in new_dict.items(): self[key] = value @@ -117,7 +121,7 @@ ... IUPAC.protein), ... id="YP_025292.1", name="HokC", ... description="toxic membrane protein") - >>> print record + >>> print(record) ID: YP_025292.1 Name: HokC Description: toxic membrane protein @@ -129,7 +133,7 @@ a string in a particular file format there is a format method which uses Bio.SeqIO internally: - >>> print record.format("fasta") + >>> print(record.format("fasta")) >YP_025292.1 toxic membrane protein MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF @@ -139,9 +143,9 @@ >>> len(record) 44 >>> edited = record[:10] + record[11:] - >>> print edited.seq + >>> print(edited.seq) MKQHKAMIVAIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF - >>> print record.seq + >>> print(record.seq) MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF """ @@ -250,20 +254,20 @@ >>> from Bio import SeqIO >>> record = SeqIO.read("Quality/solexa_faked.fastq", "fastq-solexa") - >>> print record.id, record.seq + >>> print("%s %s" % (record.id, record.seq)) slxa_0001_1_0001_01 ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN - >>> print record.letter_annotations.keys() + >>> print(list(record.letter_annotations.keys())) ['solexa_quality'] - >>> print record.letter_annotations["solexa_quality"] + >>> print(record.letter_annotations["solexa_quality"]) [40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5] The letter_annotations get sliced automatically if you slice the parent SeqRecord, for example taking the last ten bases: >>> sub_record = record[-10:] - >>> print sub_record.id, sub_record.seq + >>> print("%s %s" % (sub_record.id, sub_record.seq)) slxa_0001_1_0001_01 ACGTNNNNNN - >>> print sub_record.letter_annotations["solexa_quality"] + >>> print(sub_record.letter_annotations["solexa_quality"]) [4, 3, 2, 1, 0, -1, -2, -3, -4, -5] Any python sequence (i.e. list, tuple or string) can be recorded in @@ -340,43 +344,43 @@ ... id="1JOY", name="EnvZ", ... description="Homodimeric domain of EnvZ from E. coli") >>> rec.letter_annotations["secondary_structure"] = " S SSSSSSHHHHHTTTHHHHHHHHHHHHHHHHHHHHHHTHHHHHHHHHHHHHHHHHHHHHTT " - >>> rec.features.append(SeqFeature(FeatureLocation(20,21), + >>> rec.features.append(SeqFeature(FeatureLocation(20, 21), ... type = "Site")) Now let's have a quick look at the full record, - >>> print rec + >>> print(rec) ID: 1JOY Name: EnvZ Description: Homodimeric domain of EnvZ from E. coli Number of features: 1 Per letter annotation for: secondary_structure Seq('MAAGVKQLADDRTLLMAGVSHDLRTPLTRIRLATEMMSEQDGYLAESINKDIEE...YLR', IUPACProtein()) - >>> print rec.letter_annotations["secondary_structure"] + >>> print(rec.letter_annotations["secondary_structure"]) S SSSSSSHHHHHTTTHHHHHHHHHHHHHHHHHHHHHHTHHHHHHHHHHHHHHHHHHHHHTT - >>> print rec.features[0].location + >>> print(rec.features[0].location) [20:21] Now let's take a sub sequence, here chosen as the first (fractured) alpha helix which includes the histidine phosphorylation site: >>> sub = rec[11:41] - >>> print sub + >>> print(sub) ID: 1JOY Name: EnvZ Description: Homodimeric domain of EnvZ from E. coli Number of features: 1 Per letter annotation for: secondary_structure Seq('RTLLMAGVSHDLRTPLTRIRLATEMMSEQD', IUPACProtein()) - >>> print sub.letter_annotations["secondary_structure"] + >>> print(sub.letter_annotations["secondary_structure"]) HHHHHTTTHHHHHHHHHHHHHHHHHHHHHH - >>> print sub.features[0].location + >>> print(sub.features[0].location) [9:10] You can also of course omit the start or end values, for example to get the first ten letters only: - >>> print rec[:10] + >>> print(rec[:10]) ID: 1JOY Name: EnvZ Description: Homodimeric domain of EnvZ from E. coli @@ -386,7 +390,7 @@ Or for the last ten letters: - >>> print rec[-10:] + >>> print(rec[-10:]) ID: 1JOY Name: EnvZ Description: Homodimeric domain of EnvZ from E. coli @@ -397,7 +401,7 @@ If you omit both, then you get a copy of the original record (although lacking the annotations and dbxrefs): - >>> print rec[:] + >>> print(rec[:]) ID: 1JOY Name: EnvZ Description: Homodimeric domain of EnvZ from E. coli @@ -432,7 +436,7 @@ #Don't copy the annotation dict and dbxefs list, #they may not apply to a subsequence. - #answer.annotations = dict(self.annotations.iteritems()) + #answer.annotations = dict(self.annotations.items()) #answer.dbxrefs = self.dbxrefs[:] #TODO - Review this in light of adding SeqRecord objects? @@ -455,7 +459,7 @@ #Slice all the values to match the sliced sequence #(this should also work with strides, even negative strides): - for key, value in self.letter_annotations.iteritems(): + for key, value in self.letter_annotations.items(): answer._per_letter_annotations[key] = value[index] return answer @@ -469,25 +473,25 @@ >>> from Bio import SeqIO >>> record = SeqIO.read("Fasta/loveliesbleeding.pro", "fasta") >>> for amino in record: - ... print amino + ... print(amino) ... if amino == "L": break X A G L - >>> print record.seq[3] + >>> print(record.seq[3]) L This is just a shortcut for iterating over the sequence directly: >>> for amino in record.seq: - ... print amino + ... print(amino) ... if amino == "L": break X A G L - >>> print record.seq[3] + >>> print(record.seq[3]) L Note that this does not facilitate iteration together with any @@ -497,13 +501,13 @@ >>> from Bio import SeqIO >>> rec = SeqIO.read("Quality/solexa_faked.fastq", "fastq-solexa") - >>> print rec.id, rec.seq + >>> print("%s %s" % (rec.id, rec.seq)) slxa_0001_1_0001_01 ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN - >>> print rec.letter_annotations.keys() + >>> print(list(rec.letter_annotations.keys())) ['solexa_quality'] - >>> for nuc, qual in zip(rec,rec.letter_annotations["solexa_quality"]): + >>> for nuc, qual in zip(rec, rec.letter_annotations["solexa_quality"]): ... if qual > 35: - ... print nuc, qual + ... print("%s %i" % (nuc, qual)) A 40 C 39 G 38 @@ -560,7 +564,7 @@ ... IUPAC.protein), ... id="YP_025292.1", name="HokC", ... description="toxic membrane protein, small") - >>> print str(record) + >>> print(str(record)) ID: YP_025292.1 Name: HokC Description: toxic membrane protein, small @@ -570,7 +574,7 @@ In this example you don't actually need to call str explicity, as the print command does this automatically: - >>> print record + >>> print(record) ID: YP_025292.1 Name: HokC Description: toxic membrane protein, small @@ -617,7 +621,7 @@ ... id="NP_418483.1", name="b4059", ... description="ssDNA-binding protein", ... dbxrefs=["ASAP:13298", "GI:16131885", "GeneID:948570"]) - >>> print repr(rec) + >>> print(repr(rec)) SeqRecord(seq=Seq('MASRGVNKVILVGNLGQDPEVRYMPNGGAVANITLATSESWRDKATGEMKEQTE...IPF', ProteinAlphabet()), id='NP_418483.1', name='b4059', description='ssDNA-binding protein', dbxrefs=['ASAP:13298', 'GI:16131885', 'GeneID:948570']) At the python prompt you can also use this shorthand: @@ -650,7 +654,7 @@ ... description="toxic membrane protein") >>> record.format("fasta") '>YP_025292.1 toxic membrane protein\nMKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF\n' - >>> print record.format("fasta") + >>> print(record.format("fasta")) >YP_025292.1 toxic membrane protein MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF @@ -675,6 +679,9 @@ Python 2.6/3.0. The format_spec should be a lower case string supported by Bio.SeqIO as an output file format. See also the SeqRecord's format() method. + + Under Python 3 please note that for binary formats a bytes + string is returned, otherwise a (unicode) string is returned. """ if not format_spec: #Follow python convention and default to using __str__ @@ -682,16 +689,10 @@ from Bio import SeqIO if format_spec in SeqIO._BinaryFormats: #Return bytes on Python 3 - try: - #This is in Python 2.6+, but we need it on Python 3 - from io import BytesIO - handle = BytesIO() - except ImportError: - #Must be on Python 2.5 or older - from StringIO import StringIO - handle = StringIO() + from io import BytesIO + handle = BytesIO() else: - from StringIO import StringIO + from Bio._py3k import StringIO handle = StringIO() SeqIO.write(self, handle, format_spec) return handle.getvalue() @@ -710,8 +711,9 @@ """ return len(self.seq) - def __nonzero__(self): - """Returns True regardless of the length of the sequence. + #Python 3: + def __bool__(self): + """Boolean value of an instance of this class (True). This behaviour is for backwards compatibility, since until the __len__ method was added, a SeqRecord always evaluated as True. @@ -725,6 +727,9 @@ """ return True + #Python 2: + __nonzero__= __bool__ + def __add__(self, other): """Add another sequence or string to this sequence. @@ -736,15 +741,15 @@ >>> from Bio import SeqIO >>> record = SeqIO.read("Quality/solexa_faked.fastq", "fastq-solexa") - >>> print record.id, record.seq + >>> print("%s %s" % (record.id, record.seq)) slxa_0001_1_0001_01 ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN - >>> print record.letter_annotations.keys() + >>> print(list(record.letter_annotations.keys())) ['solexa_quality'] >>> new = record + "ACT" - >>> print new.id, new.seq + >>> print("%s %s" % (new.id, new.seq)) slxa_0001_1_0001_01 ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNNACT - >>> print new.letter_annotations.keys() + >>> print(list(new.letter_annotations.keys())) [] The new record will attempt to combine the annotation, but for any @@ -752,10 +757,9 @@ annotation. >>> from Bio import SeqIO - >>> handle = open("GenBank/pBAD30.gb") - >>> plasmid = SeqIO.read(handle, "gb") - >>> handle.close() - >>> print plasmid.id, len(plasmid) + >>> with open("GenBank/pBAD30.gb") as handle: + ... plasmid = SeqIO.read(handle, "gb") + >>> print("%s %i" % (plasmid.id, len(plasmid))) pBAD30 4923 Now let's cut the plasmid into two pieces, and join them back up the @@ -766,7 +770,7 @@ >>> left = plasmid[:3765] >>> right = plasmid[3765:] >>> new = right + left - >>> print new.id, len(new) + >>> print("%s %i" % (new.id, len(new))) pBAD30 4923 >>> str(new.seq) == str(right.seq + left.seq) True @@ -824,11 +828,11 @@ answer.name = self.name if self.description == other.description: answer.description = self.description - for k, v in self.annotations.iteritems(): + for k, v in self.annotations.items(): if k in other.annotations and other.annotations[k] == v: answer.annotations[k] = v #Can append matching per-letter-annotation - for k, v in self.letter_annotations.iteritems(): + for k, v in self.letter_annotations.items(): if k in other.letter_annotations: answer.letter_annotations[k] = v + other.letter_annotations[k] return answer @@ -842,15 +846,15 @@ >>> from Bio import SeqIO >>> record = SeqIO.read("Quality/solexa_faked.fastq", "fastq-solexa") - >>> print record.id, record.seq + >>> print("%s %s" % (record.id, record.seq)) slxa_0001_1_0001_01 ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN - >>> print record.letter_annotations.keys() + >>> print(list(record.letter_annotations.keys())) ['solexa_quality'] >>> new = "ACT" + record - >>> print new.id, new.seq + >>> print("%s %s" % (new.id, new.seq)) slxa_0001_1_0001_01 ACTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN - >>> print new.letter_annotations.keys() + >>> print(list(new.letter_annotations.keys())) [] """ if isinstance(other, SeqRecord): @@ -876,8 +880,8 @@ >>> from Bio.SeqRecord import SeqRecord >>> record = SeqRecord(Seq("acgtACGT", generic_dna), id="Test", ... description = "Made up for this example") - >>> record.letter_annotations["phred_quality"] = [1,2,3,4,5,6,7,8] - >>> print record.upper().format("fastq") + >>> record.letter_annotations["phred_quality"] = [1, 2, 3, 4, 5, 6, 7, 8] + >>> print(record.upper().format("fastq")) @Test Made up for this example ACGTACGT + @@ -886,7 +890,7 @@ Naturally, there is a matching lower method: - >>> print record.lower().format("fastq") + >>> print(record.lower().format("fastq")) @Test Made up for this example acgtacgt + @@ -908,12 +912,12 @@ >>> from Bio import SeqIO >>> record = SeqIO.read("Fasta/aster.pro", "fasta") - >>> print record.format("fasta") + >>> print(record.format("fasta")) >gi|3298468|dbj|BAA31520.1| SAMIPF GGHVNPAVTFGAFVGGNITLLRGIVYIIAQLLGSTVACLLLKFVTNDMAVGVFSLSAGVG VTNALVFEIVMTFGLVYTVYATAIDPKKGSLGTIAPIAIGFIVGANI - >>> print record.lower().format("fasta") + >>> print(record.lower().format("fasta")) >gi|3298468|dbj|BAA31520.1| SAMIPF gghvnpavtfgafvggnitllrgivyiiaqllgstvaclllkfvtndmavgvfslsagvg vtnalvfeivmtfglvytvyataidpkkgslgtiapiaigfivgani @@ -965,23 +969,23 @@ >>> from Bio import SeqIO >>> record = SeqIO.read("Quality/solexa_faked.fastq", "fastq-solexa") - >>> print record.id, record.seq + >>> print("%s %s" % (record.id, record.seq)) slxa_0001_1_0001_01 ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN - >>> print record.letter_annotations.keys() + >>> print(list(record.letter_annotations.keys())) ['solexa_quality'] - >>> print record.letter_annotations["solexa_quality"] + >>> print(record.letter_annotations["solexa_quality"]) [40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5] Now take the reverse complement, >>> rc_record = record.reverse_complement(id=record.id+"_rc") - >>> print rc_record.id, rc_record.seq + >>> print("%s %s" % (rc_record.id, rc_record.seq)) slxa_0001_1_0001_01_rc NNNNNNACGTACGTACGTACGTACGTACGTACGTACGTACGTACGT Notice that the per-letter-annotations have also been reversed, although this may not be appropriate for all cases. - >>> print rc_record.letter_annotations["solexa_quality"] + >>> print(rc_record.letter_annotations["solexa_quality"]) [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40] Now for the features, we need a different example. Parsing a GenBank @@ -989,10 +993,9 @@ in it... >>> from Bio import SeqIO - >>> handle = open("GenBank/pBAD30.gb") - >>> plasmid = SeqIO.read(handle, "gb") - >>> handle.close() - >>> print plasmid.id, len(plasmid) + >>> with open("GenBank/pBAD30.gb") as handle: + ... plasmid = SeqIO.read(handle, "gb") + >>> print("%s %i" % (plasmid.id, len(plasmid))) pBAD30 4923 >>> plasmid.seq Seq('GCTAGCGGAGTGTATACTGGCTTACTATGTTGGCACTGATGAGGGTGTCAGTGA...ATG', IUPACAmbiguousDNA()) @@ -1002,7 +1005,7 @@ Now, let's take the reverse complement of this whole plasmid: >>> rc_plasmid = plasmid.reverse_complement(id=plasmid.id+"_rc") - >>> print rc_plasmid.id, len(rc_plasmid) + >>> print("%s %i" % (rc_plasmid.id, len(rc_plasmid))) pBAD30_rc 4923 >>> rc_plasmid.seq Seq('CATGGGCAAATATTATACGCAAGGCGACAAGGTGCTGATGCCGCTGGCGATTCA...AGC', IUPACAmbiguousDNA()) @@ -1013,7 +1016,7 @@ second feature (index 1) to the second last feature (index -2), its strand has changed, and the location switched round. - >>> print plasmid.features[1] + >>> print(plasmid.features[1]) type: CDS location: [1081:1960](-) qualifiers: @@ -1021,7 +1024,7 @@ Key: note, Value: ['araC regulator of the arabinose BAD promoter'] Key: vntifkey, Value: ['4'] - >>> print rc_plasmid.features[-2] + >>> print(rc_plasmid.features[-2]) type: CDS location: [2963:3842](+) qualifiers: @@ -1060,10 +1063,10 @@ >>> from Bio.Alphabet import generic_dna >>> rec = SeqRecord(MutableSeq("ACGT", generic_dna), id="Test") >>> rec.seq[0] = "T" - >>> print rec.id, rec.seq + >>> print("%s %s" % (rec.id, rec.seq)) Test TCGT >>> rc = rec.reverse_complement(id=True) - >>> print rc.id, rc.seq + >>> print("%s %s" % (rc.id, rc.seq)) Test ACGA """ from Bio.Seq import MutableSeq # Lazy to avoid circular imports @@ -1110,7 +1113,7 @@ answer.letter_annotations = letter_annotations elif letter_annotations: #Copy the old per letter annotations, reversing them - for key, value in self.letter_annotations.iteritems(): + for key, value in self.letter_annotations.items(): answer._per_letter_annotations[key] = value[::-1] return answer @@ -1118,3 +1121,5 @@ if __name__ == "__main__": from Bio._utils import run_doctest run_doctest() + + diff -Nru python-biopython-1.62/Bio/SeqUtils/CheckSum.py python-biopython-1.63/Bio/SeqUtils/CheckSum.py --- python-biopython-1.62/Bio/SeqUtils/CheckSum.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SeqUtils/CheckSum.py 2013-12-05 14:10:43.000000000 +0000 @@ -10,6 +10,8 @@ # crc32, crc64, gcg, and seguid # crc64 is adapted from BioPerl +from __future__ import print_function + from binascii import crc32 as _crc32 from Bio._py3k import _as_bytes @@ -36,10 +38,10 @@ rflag = l & 1 l >>= 1 if part_h & 1: - l |= (1L << 31) - part_h >>= 1L + l |= (1 << 31) + part_h >>= 1 if rflag: - part_h ^= 0xd8000000L + part_h ^= 0xd8000000 _table_h.append(part_h) return _table_h @@ -115,7 +117,7 @@ if __name__ == "__main__": - print "Quick self test" + print("Quick self test") str_light_chain_one = "QSALTQPASVSGSPGQSITISCTGTSSDVGSYNLVSWYQQHPGK" \ + "APKLMIYEGSKRPSGVSNRFSGSKSGNTASLTISGLQAEDEADY" \ @@ -131,4 +133,4 @@ assert 'BpBeDdcNUYNsdk46JoJdw7Pd3BI' == seguid(str_light_chain_one) assert 'X5XEaayob1nZLOc7eVT9qyczarY' == seguid(str_light_chain_two) - print "Done" + print("Done") diff -Nru python-biopython-1.62/Bio/SeqUtils/CodonUsage.py python-biopython-1.63/Bio/SeqUtils/CodonUsage.py --- python-biopython-1.62/Bio/SeqUtils/CodonUsage.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SeqUtils/CodonUsage.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,5 +1,12 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + +from __future__ import print_function + import math -from CodonUsageIndices import SharpEcoliIndex +from .CodonUsageIndices import SharpEcoliIndex from Bio import SeqIO # To parse a FASTA file @@ -128,28 +135,27 @@ return math.exp(cai_value / (cai_length - 1.0)) def _count_codons(self, fasta_file): - handle = open(fasta_file, 'r') + with open(fasta_file, 'r') as handle: - # make the codon dictionary local - self.codon_count = CodonsDict.copy() + # make the codon dictionary local + self.codon_count = CodonsDict.copy() - # iterate over sequence and count all the codons in the FastaFile. - for cur_record in SeqIO.parse(handle, "fasta"): - # make sure the sequence is lower case - if str(cur_record.seq).islower(): - dna_sequence = str(cur_record.seq).upper() - else: - dna_sequence = str(cur_record.seq) - for i in range(0, len(dna_sequence), 3): - codon = dna_sequence[i:i+3] - if codon in self.codon_count: - self.codon_count[codon] += 1 + # iterate over sequence and count all the codons in the FastaFile. + for cur_record in SeqIO.parse(handle, "fasta"): + # make sure the sequence is lower case + if str(cur_record.seq).islower(): + dna_sequence = str(cur_record.seq).upper() else: - raise TypeError("illegal codon %s in gene: %s" % (codon, cur_record.id)) - handle.close() + dna_sequence = str(cur_record.seq) + for i in range(0, len(dna_sequence), 3): + codon = dna_sequence[i:i+3] + if codon in self.codon_count: + self.codon_count[codon] += 1 + else: + raise TypeError("illegal codon %s in gene: %s" % (codon, cur_record.id)) # this just gives the index when the objects is printed. def print_index(self): """Prints out the index used.""" for i in sorted(self.index): - print "%s\t%.3f" % (i, self.index[i]) + print("%s\t%.3f" % (i, self.index[i])) diff -Nru python-biopython-1.62/Bio/SeqUtils/IsoelectricPoint.py python-biopython-1.63/Bio/SeqUtils/IsoelectricPoint.py --- python-biopython-1.62/Bio/SeqUtils/IsoelectricPoint.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SeqUtils/IsoelectricPoint.py 2013-12-05 14:10:43.000000000 +0000 @@ -47,13 +47,13 @@ #This function calculates the total charge of the protein at a given pH. def _chargeR(self, pH, pos_pKs, neg_pKs): PositiveCharge = 0.0 - for aa, pK in pos_pKs.iteritems(): + for aa, pK in pos_pKs.items(): CR = 10**(pK-pH) partial_charge = CR/(CR+1.0) PositiveCharge += self.charged_aas_content[aa] * partial_charge NegativeCharge = 0.0 - for aa, pK in neg_pKs.iteritems(): + for aa, pK in neg_pKs.items(): CR = 10**(pH-pK) partial_charge = CR/(CR+1.0) NegativeCharge += self.charged_aas_content[aa] * partial_charge @@ -66,9 +66,9 @@ neg_pKs = dict(negative_pKs) nterm = self.sequence[0] cterm = self.sequence[-1] - if nterm in pKnterminal.keys(): + if nterm in pKnterminal: pos_pKs['Nterm'] = pKnterminal[nterm] - if cterm in pKcterminal.keys(): + if cterm in pKcterminal: neg_pKs['Cterm'] = pKcterminal[cterm] # Bracket between pH1 and pH2 diff -Nru python-biopython-1.62/Bio/SeqUtils/MeltingTemp.py python-biopython-1.63/Bio/SeqUtils/MeltingTemp.py --- python-biopython-1.62/Bio/SeqUtils/MeltingTemp.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SeqUtils/MeltingTemp.py 2013-12-05 14:10:43.000000000 +0000 @@ -6,6 +6,8 @@ """Calculate the thermodynamic melting temperatures of nucleotide sequences.""" +from __future__ import print_function + import math @@ -21,9 +23,9 @@ Example: - >>> print "%0.2f" % Tm_staluc('CAGTCAGTACGTACGTGTACTGCCGTA') + >>> print("%0.2f" % Tm_staluc('CAGTCAGTACGTACGTGTACTGCCGTA')) 59.87 - >>> print "%0.2f" % Tm_staluc('CAGTCAGTACGTACGTGTACTGCCGTA', rna=True) + >>> print("%0.2f" % Tm_staluc('CAGTCAGTACGTACGTGTACTGCCGTA', rna=True)) 68.14 You can also use a Seq object instead of a string, @@ -31,9 +33,9 @@ >>> from Bio.Seq import Seq >>> from Bio.Alphabet import generic_nucleotide >>> s = Seq('CAGTCAGTACGTACGTGTACTGCCGTA', generic_nucleotide) - >>> print "%0.2f" % Tm_staluc(s) + >>> print("%0.2f" % Tm_staluc(s)) 59.87 - >>> print "%0.2f" % Tm_staluc(s, rna=True) + >>> print("%0.2f" % Tm_staluc(s, rna=True)) 68.14 """ @@ -97,7 +99,7 @@ deltas += 10.5 dhL = dh + deltah dsL = ds + deltas - # print "delta h=",dhL + # print("delta h=%f" % dhL) return dsL, dhL else: raise ValueError("rna = %r not supported" % rna) @@ -170,17 +172,17 @@ ds = ds-0.368*(len(s)-1)*math.log(saltc/1e3) tm = ((1000* (-dh))/(-ds+(R * (math.log(k)))))-273.15 - # print "ds="+str(ds) - # print "dh="+str(dh) + # print("ds=%f" % ds) + # print("dh=%f" % dh) return tm def _test(): """Run the module's doctests (PRIVATE).""" import doctest - print "Running doctests..." + print("Running doctests...") doctest.testmod() - print "Done" + print("Done") if __name__ == "__main__": _test() diff -Nru python-biopython-1.62/Bio/SeqUtils/ProtParam.py python-biopython-1.63/Bio/SeqUtils/ProtParam.py --- python-biopython-1.62/Bio/SeqUtils/ProtParam.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SeqUtils/ProtParam.py 2013-12-05 14:10:43.000000000 +0000 @@ -6,20 +6,23 @@ Example, X = ProteinAnalysis("MAEGEITTFTALTEKFNLPPGNYKKPKLLYCSNGGHFLRILPDGTVDGTRDRSDQHIQLQLSAESVGEVYIKSTETGQYLAMDTSGLLYGSQTPSEECLFLERLEENHYNTYTSKKHAEKNWFVGLKKNGSCKRGPRTHYGQKAILFLPLPV") -print X.count_amino_acids() -print X.get_amino_acids_percent() -print X.molecular_weight() -print X.aromaticity() -print X.instability_index() -print X.flexibility() -print X.isoelectric_point() -print X.secondary_structure_fraction() -print X.protein_scale(ProtParamData.kd, 9, 0.4) +print(X.count_amino_acids()) +print(X.get_amino_acids_percent()) +print(X.molecular_weight()) +print(X.aromaticity()) +print(X.instability_index()) +print(X.flexibility()) +print(X.isoelectric_point()) +print(X.secondary_structure_fraction()) +print(X.protein_scale(ProtParamData.kd, 9, 0.4)) """ +#TODO - Turn that into a working doctest + +from __future__ import print_function import sys -import ProtParamData # Local -import IsoelectricPoint # Local +from . import ProtParamData # Local +from . import IsoelectricPoint # Local from Bio.Seq import Seq from Bio.Alphabet import IUPAC from Bio.Data import IUPACData @@ -61,7 +64,7 @@ It is not recalculated upon subsequent calls. """ if self.amino_acids_content is None: - prot_dic = dict([(k, 0) for k in IUPACData.protein_letters]) + prot_dic = dict((k, 0) for k in IUPACData.protein_letters) for aa in prot_dic: prot_dic[aa] = self.sequence.count(aa) @@ -121,7 +124,7 @@ aromatic_aas = 'YWF' aa_percentages = self.get_amino_acids_percent() - aromaticity = sum([aa_percentages[aa] for aa in aromatic_aas]) + aromaticity = sum(aa_percentages[aa] for aa in aromatic_aas) return aromaticity @@ -285,8 +288,8 @@ """ aa_percentages = self.get_amino_acids_percent() - helix = sum([aa_percentages[r] for r in 'VIYFWL']) - turn = sum([aa_percentages[r] for r in 'NPGS']) - sheet = sum([aa_percentages[r] for r in 'EMAL']) + helix = sum(aa_percentages[r] for r in 'VIYFWL') + turn = sum(aa_percentages[r] for r in 'NPGS') + sheet = sum(aa_percentages[r] for r in 'EMAL') return helix, turn, sheet diff -Nru python-biopython-1.62/Bio/SeqUtils/__init__.py python-biopython-1.63/Bio/SeqUtils/__init__.py --- python-biopython-1.62/Bio/SeqUtils/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SeqUtils/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -9,6 +9,8 @@ """Miscellaneous functions for dealing with sequences.""" +from __future__ import print_function + import re from math import pi, sin, cos @@ -37,7 +39,7 @@ Note that this will return zero for an empty sequence. """ try: - gc = sum(map(seq.count, ['G', 'C', 'g', 'c', 'S', 's'])) + gc = sum(seq.count(x) for x in ['G', 'C', 'g', 'c', 'S', 's']) return gc*100.0/len(seq) except ZeroDivisionError: return 0.0 @@ -107,20 +109,23 @@ def xGC_skew(seq, window=1000, zoom=100, r=300, px=100, py=100): """Calculates and plots normal and accumulated GC skew (GRAPHICS !!!).""" - from Tkinter import Scrollbar, Canvas, BOTTOM, BOTH, ALL, \ - VERTICAL, HORIZONTAL, RIGHT, LEFT, X, Y - yscroll = Scrollbar(orient=VERTICAL) - xscroll = Scrollbar(orient=HORIZONTAL) - canvas = Canvas(yscrollcommand=yscroll.set, - xscrollcommand=xscroll.set, background='white') + try: + import Tkinter as tkinter # Python 2 + except ImportError: + import tkinter # Python 3 + + yscroll = tkinter.Scrollbar(orient=tkinter.VERTICAL) + xscroll = tkinter.Scrollbar(orient=tkinter.HORIZONTAL) + canvas = tkinter.Canvas(yscrollcommand=yscroll.set, + xscrollcommand=xscroll.set, background='white') win = canvas.winfo_toplevel() win.geometry('700x700') yscroll.config(command=canvas.yview) xscroll.config(command=canvas.xview) - yscroll.pack(side=RIGHT, fill=Y) - xscroll.pack(side=BOTTOM, fill=X) - canvas.pack(fill=BOTH, side=LEFT, expand=1) + yscroll.pack(side=tkinter.RIGHT, fill=tkinter.Y) + xscroll.pack(side=tkinter.BOTTOM, fill=tkinter.X) + canvas.pack(fill=tkinter.BOTH, side=tkinter.LEFT, expand=1) canvas.update() X0, Y0 = r + px, r + py @@ -162,7 +167,7 @@ canvas.update() start += window - canvas.configure(scrollregion=canvas.bbox(ALL)) + canvas.configure(scrollregion=canvas.bbox(tkinter.ALL)) def molecular_weight(seq): @@ -247,11 +252,11 @@ """ # not doing .update() on IUPACData dict with custom_map dict # to preserve its initial state (may be imported in other modules) - threecode = dict(IUPACData.protein_letters_1to3_extended.items() + - custom_map.items()) + threecode = dict(list(IUPACData.protein_letters_1to3_extended.items()) + + list(custom_map.items())) #We use a default of 'Xaa' for undefined letters #Note this will map '-' to 'Xaa' which may be undesirable! - return ''.join([threecode.get(aa, undef_code) for aa in seq]) + return ''.join(threecode.get(aa, undef_code) for aa in seq) def seq1(seq, custom_map={'Ter': '*'}, undef_code='X'): @@ -300,11 +305,11 @@ # reverse map of threecode # upper() on all keys to enable caps-insensitive input seq handling onecode = dict((k.upper(), v) for k, v in - IUPACData.protein_letters_3to1_extended.items()) + IUPACData.protein_letters_3to1_extended.items()) # add the given termination codon code and custom maps - onecode.update((k.upper(), v) for (k, v) in custom_map.iteritems()) + onecode.update((k.upper(), v) for (k, v) in custom_map.items()) seqlist = [seq[3*i:3*(i+1)] for i in range(len(seq) // 3)] - return ''.join([onecode.get(aa.upper(), undef_code) for aa in seqlist]) + return ''.join(onecode.get(aa.upper(), undef_code) for aa in seqlist) # }}} @@ -322,7 +327,7 @@ similar to DNA Striders six-frame translation >>> from Bio.SeqUtils import six_frame_translations - >>> print six_frame_translations("AUGGCCAUUGUAAUGGGCCGCUGA") + >>> print(six_frame_translations("AUGGCCAUUGUAAUGGGCCGCUGA")) GC_Frame: a:5 t:0 g:8 c:5 Sequence: auggccauug ... gggccgcuga, 24 nt, 54.17 %GC @@ -367,16 +372,16 @@ csubseq = comp[i:i+60] p = i//3 res += '%d/%d\n' % (i+1, i/3+1) - res += ' ' + ' '.join(map(None, frames[3][p:p+20])) + '\n' - res += ' ' + ' '.join(map(None, frames[2][p:p+20])) + '\n' - res += ' '.join(map(None, frames[1][p:p+20])) + '\n' + res += ' ' + ' '.join(frames[3][p:p+20]) + '\n' + res += ' ' + ' '.join(frames[2][p:p+20]) + '\n' + res += ' '.join(frames[1][p:p+20]) + '\n' # seq res += subseq.lower() + '%5d %%\n' % int(GC(subseq)) res += csubseq.lower() + '\n' # - frames - res += ' '.join(map(None, frames[-2][p:p+20])) +' \n' - res += ' ' + ' '.join(map(None, frames[-1][p:p+20])) + '\n' - res += ' ' + ' '.join(map(None, frames[-3][p:p+20])) + '\n\n' + res += ' '.join(frames[-2][p:p+20]) +' \n' + res += ' ' + ' '.join(frames[-1][p:p+20]) + '\n' + res += ' ' + ' '.join(frames[-3][p:p+20]) + '\n\n' return res # }}} @@ -397,7 +402,7 @@ >>> seqs = quick_FASTA_reader("Fasta/dups.fasta") >>> for title, sequence in seqs: - ... print title, sequence + ... print("%s %s" % (title, sequence)) alpha ACGTA beta CGTC gamma CCGCC @@ -417,12 +422,9 @@ If you want to use simple strings, use the function SimpleFastaParser added to Bio.SeqIO.FastaIO in Biopython 1.61 instead. """ - handle = open(file) - entries = [] from Bio.SeqIO.FastaIO import SimpleFastaParser - for title, sequence in SimpleFastaParser(handle): - entries.append((title, sequence)) - handle.close() + with open(file) as handle: + entries = list(SimpleFastaParser(handle)) return entries @@ -434,21 +436,21 @@ import os import doctest if os.path.isdir(os.path.join("..", "Tests")): - print "Running doctests..." + print("Running doctests...") cur_dir = os.path.abspath(os.curdir) os.chdir(os.path.join("..", "Tests")) doctest.testmod() os.chdir(cur_dir) del cur_dir - print "Done" + print("Done") elif os.path.isdir(os.path.join("Tests")): - print "Running doctests..." + print("Running doctests...") cur_dir = os.path.abspath(os.curdir) os.chdir(os.path.join("Tests")) doctest.testmod() os.chdir(cur_dir) del cur_dir - print "Done" + print("Done") if __name__ == "__main__": diff -Nru python-biopython-1.62/Bio/Sequencing/Ace.py python-biopython-1.63/Bio/Sequencing/Ace.py --- python-biopython-1.62/Bio/Sequencing/Ace.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Sequencing/Ace.py 2013-12-05 14:10:43.000000000 +0000 @@ -2,8 +2,7 @@ # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. -""" -Parser for ACE files output by PHRAP. +"""Parser for ACE files output by PHRAP. Written by Frank Kauff (fkauff@duke.edu) and Cymon J. Cox (cymon@duke.edu) @@ -42,7 +41,7 @@ from Bio.Sequencing import Ace contigs=Ace.parse(open('my_ace_file.ace')) for contig in contigs: - print contig.name + print(contig.name) ... Please note that for memory efficiency, when using the iterator approach, only one @@ -54,6 +53,8 @@ are needed, the 'read' function rather than the 'parse' function might be more appropriate. """ +from __future__ import print_function +from Bio._py3k import zip class rd(object): """RD (reads), store a read with its name, sequence etc. @@ -76,11 +77,11 @@ self.align_clipping_start = None self.align_clipping_end = None if line: - header = map(eval, line.split()[1:]) - self.qual_clipping_start = header[0] - self.qual_clipping_end = header[1] - self.align_clipping_start = header[2] - self.align_clipping_end = header[3] + header = line.split() + self.qual_clipping_start = int(header[1]) + self.qual_clipping_end = int(header[2]) + self.align_clipping_start = int(header[3]) + self.align_clipping_end = int(header[4]) class ds(object): @@ -95,12 +96,11 @@ self.direction = '' if line: tags = ['CHROMAT_FILE', 'PHD_FILE', 'TIME', 'CHEM', 'DYE', 'TEMPLATE', 'DIRECTION'] - poss = map(line.find, tags) + poss = [line.find(x) for x in tags] tagpos = dict(zip(poss, tags)) if -1 in tagpos: del tagpos[-1] - ps = tagpos.keys() - ps.sort() + ps = sorted(tagpos) # the keys for (p1, p2) in zip(ps, ps[1:]+[len(line)+1]): setattr(self, tagpos[p1].lower(), line[p1+len(tagpos[p1])+1:p2].strip()) @@ -274,7 +274,7 @@ while True: if line.startswith('CO'): break - line = handle.next() + line = next(handle) except StopIteration: return @@ -295,7 +295,7 @@ for line in handle: if not line.strip(): break - record.quality.extend(map(int, line.split())) + record.quality.extend(int(x) for x in line.split()) for line in handle: if line.strip(): @@ -306,7 +306,7 @@ break record.af.append(af(line)) try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError("Unexpected end of AF block") @@ -314,7 +314,7 @@ if line.strip(): break try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError("Unexpected end of file") @@ -323,7 +323,7 @@ break record.bs.append(bs(line)) try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError("Failed to find end of BS block") @@ -341,7 +341,7 @@ # If I've met the condition, then stop reading the line. if line.startswith("RD "): break - line = handle.next() + line = next(handle) except StopIteration: raise ValueError("Failed to find RD line") @@ -378,7 +378,7 @@ while True: if line.strip(): break - line = handle.next() + line = next(handle) except StopIteration: # file ends here break @@ -418,7 +418,7 @@ if record.wa is None: record.wa = [] try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError("Failed to read WA block") record.wa.append(wa(line)) @@ -432,7 +432,7 @@ if record.ct is None: record.ct = [] try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError("Failed to read CT block") record.ct.append(ct(line)) @@ -530,7 +530,7 @@ record = ACEFileRecord() try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError("Premature end of file") @@ -539,7 +539,8 @@ raise ValueError("File does not start with 'AS'.") words = line.split() - record.ncontigs, record.nreads = map(int, words[1:3]) + record.ncontigs = int(words[1]) + record.nreads = int(words[2]) # now read all the records record.contigs = list(parse(handle)) diff -Nru python-biopython-1.62/Bio/Sequencing/Applications/_Novoalign.py python-biopython-1.63/Bio/Sequencing/Applications/_Novoalign.py --- python-biopython-1.62/Bio/Sequencing/Applications/_Novoalign.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Sequencing/Applications/_Novoalign.py 2013-12-05 14:10:43.000000000 +0000 @@ -4,6 +4,9 @@ # license. Please see the LICENSE file that should have been included # as part of this package. """Command line wrapper for the short read aligner Novoalign by Novocraft.""" + +from __future__ import print_function + import types from Bio.Application import _Option, AbstractCommandline @@ -18,7 +21,7 @@ >>> from Bio.Sequencing.Applications import NovoalignCommandline >>> novoalign_cline = NovoalignCommandline(database='some_db', ... readfile='some_seq.txt') - >>> print novoalign_cline + >>> print(novoalign_cline) novoalign -d some_db -f some_seq.txt As with all the Biopython application wrappers, you can also add or @@ -28,7 +31,7 @@ >>> novoalign_cline.r_method='0.99' # limited valid values >>> novoalign_cline.fragment = '250 20' # must be given as a string >>> novoalign_cline.miRNA = 100 - >>> print novoalign_cline + >>> print(novoalign_cline) novoalign -d some_db -f some_seq.txt -F PRBnSEQ -r 0.99 -i 250 20 -m 100 You would typically run the command line with novoalign_cline() or via @@ -61,51 +64,51 @@ # Alignment scoring options _Option(["-t", "threshold"], "Threshold for alignment score", - checker_function=lambda x: isinstance(x, types.IntType), + checker_function=lambda x: isinstance(x, int), equate=False), _Option(["-g", "gap_open"], "Gap opening penalty [default: 40]", - checker_function=lambda x: isinstance(x, types.IntType), + checker_function=lambda x: isinstance(x, int), equate=False), _Option(["-x", "gap_extend"], "Gap extend penalty [default: 15]", - checker_function=lambda x: isinstance(x, types.IntType), + checker_function=lambda x: isinstance(x, int), equate=False), _Option(["-u", "unconverted"], "Experimental: unconverted cytosines penalty in bisulfite mode\n\n" "Default: no penalty", - checker_function=lambda x: isinstance(x, types.IntType), + checker_function=lambda x: isinstance(x, int), equate=False), # Quality control and read filtering _Option(["-l", "good_bases"], "Minimum number of good quality bases [default: log(N_g, 4) + 5]", - checker_function=lambda x: isinstance(x, types.IntType), + checker_function=lambda x: isinstance(x, int), equate=False), _Option(["-h", "homopolymer"], "Homopolymer read filter [default: 20; disable: negative value]", - checker_function=lambda x: isinstance(x, types.IntType), + checker_function=lambda x: isinstance(x, int), equate=False), # Read preprocessing options _Option(["-a", "adapter3"], "Strips a 3' adapter sequence prior to alignment.\n\n" "With paired ends two adapters can be specified", - checker_function=lambda x: isinstance(x, types.StringType), + checker_function=lambda x: isinstance(x, str), equate=False), _Option(["-n", "truncate"], "Truncate to specific length before alignment", - checker_function=lambda x: isinstance(x, types.IntType), + checker_function=lambda x: isinstance(x, int), equate=False), _Option(["-s", "trimming"], "If fail to align, trim by s bases until they map or become shorter than l.\n\n" "Ddefault: 2", - checker_function=lambda x: isinstance(x, types.IntType), + checker_function=lambda x: isinstance(x, int), equate=False), _Option(["-5", "adapter5"], "Strips a 5' adapter sequence.\n\n" "Similar to -a (adaptor3), but on the 5' end.", - checker_function=lambda x: isinstance(x, types.StringType), + checker_function=lambda x: isinstance(x, str), equate=False), # Reporting options _Option(["-o", "report"], @@ -115,12 +118,12 @@ equate=False), _Option(["-Q", "quality"], "Lower threshold for an alignment to be reported [default: 0]", - checker_function=lambda x: isinstance(x, types.IntType), + checker_function=lambda x: isinstance(x, int), equate=False), _Option(["-R", "repeats"], "If score difference is higher, report repeats.\n\n" "Otherwise -r read method applies [default: 5]", - checker_function=lambda x: isinstance(x, types.IntType), + checker_function=lambda x: isinstance(x, int), equate=False), _Option(["-r", "r_method"], "Methods to report reads with multiple matches.\n\n" @@ -132,11 +135,11 @@ _Option(["-e", "recorded"], "Alignments recorded with score equal to the best.\n\n" "Default: 1000 in default read method, otherwise no limit.", - checker_function=lambda x: isinstance(x, types.IntType), + checker_function=lambda x: isinstance(x, int), equate=False), _Option(["-q", "qual_digits"], "Decimal digits for quality scores [default: 0]", - checker_function=lambda x: isinstance(x, types.IntType), + checker_function=lambda x: isinstance(x, int), equate=False), # Paired end options @@ -146,29 +149,29 @@ equate=False), _Option(["-v", "variation"], "Structural variation penalty [default: 70]", - checker_function=lambda x: isinstance(x, types.IntType), + checker_function=lambda x: isinstance(x, int), equate=False), # miRNA mode _Option(["-m", "miRNA"], "Sets miRNA mode and optionally sets a value for the region scanned [default: off]", - checker_function=lambda x: isinstance(x, types.IntType), + checker_function=lambda x: isinstance(x, int), equate=False), # Multithreading _Option(["-c", "cores"], "Number of threads, disabled on free versions [default: number of cores]", - checker_function=lambda x: isinstance(x, types.IntType), + checker_function=lambda x: isinstance(x, int), equate=False), # Quality calibrations _Option(["-k", "read_cal"], "Read quality calibration from file (mismatch counts)", - checker_function=lambda x: isinstance(x, types.StringType), + checker_function=lambda x: isinstance(x, str), equate=False), _Option(["-K", "write_cal"], "Accumulate mismatch counts and write to file", - checker_function=lambda x: isinstance(x, types.StringType), + checker_function=lambda x: isinstance(x, str), equate=False), ] AbstractCommandline.__init__(self, cmd, **kwargs) @@ -176,10 +179,10 @@ def _test(): """Run the module's doctests (PRIVATE).""" - print "Running Novoalign doctests..." + print("Running Novoalign doctests...") import doctest doctest.testmod() - print "Done" + print("Done") if __name__ == "__main__": _test() diff -Nru python-biopython-1.62/Bio/Sequencing/Applications/__init__.py python-biopython-1.63/Bio/Sequencing/Applications/__init__.py --- python-biopython-1.62/Bio/Sequencing/Applications/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Sequencing/Applications/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,8 +1,13 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Main entry point for application command line wrappers related to sequencing. """ -from _Novoalign import NovoalignCommandline -from _bwa import BwaIndexCommandline, BwaAlignCommandline, BwaSamseCommandline -from _bwa import BwaSampeCommandline, BwaBwaswCommandline +from ._Novoalign import NovoalignCommandline +from ._bwa import BwaIndexCommandline, BwaAlignCommandline, BwaSamseCommandline +from ._bwa import BwaSampeCommandline, BwaBwaswCommandline #Make this explicit, then they show up in the API docs __all__ = ["BwaIndexCommandline", "BwaAlignCommandline", diff -Nru python-biopython-1.62/Bio/Sequencing/Applications/_bwa.py python-biopython-1.63/Bio/Sequencing/Applications/_bwa.py --- python-biopython-1.62/Bio/Sequencing/Applications/_bwa.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Sequencing/Applications/_bwa.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,6 +1,14 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Command line wrapper for bwa """ +from __future__ import print_function +from Bio._py3k import basestring + __docformat__ = "epytext en" from Bio.Application import _Option, _Argument, _Switch, AbstractCommandline @@ -21,7 +29,7 @@ >>> from Bio.Sequencing.Applications import BwaIndexCommandline >>> reference_genome = "/path/to/reference_genome.fasta" >>> index_cmd = BwaIndexCommandline(infile=reference_genome, algorithm="bwtsw") - >>> print index_cmd + >>> print(index_cmd) bwa index -a bwtsw /path/to/reference_genome.fasta You would typically run the command using index_cmd() or via the @@ -73,7 +81,7 @@ >>> output_sai_file = "/path/to/read_1.sai" >>> read_group="@RG\tID:foo\tSM:bar" >>> align_cmd = BwaAlignCommandline(reference=reference_genome, read_file=read_file) - >>> print align_cmd + >>> print(align_cmd) bwa aln /path/to/reference_genome.fasta /path/to/read_1.fq You would typically run the command line using align_cmd(stdout=output_sai_file) @@ -116,7 +124,7 @@ -k 2. [inf]""", checker_function=lambda x: isinstance(x, int), equate=False), - _Option(["-k","k"], "Maximum edit distance in the seed [2]", + _Option(["-k", "k"], "Maximum edit distance in the seed [2]", checker_function=lambda x: isinstance(x, int), equate=False), _Option(["-t", "t"], "Number of threads (multi-threading mode) [1]", @@ -149,13 +157,13 @@ equate=False), _Option(["-B", "B"], "Length of barcode starting from the 5-end. When INT is positive, the barcode of each read will be trimmed before mapping and will be written at the BC SAM tag. For paired-end reads, the barcode from both ends are concatenated. [0]", - checker_function=lambda x: isinstance(x,int), + checker_function=lambda x: isinstance(x, int), equate=False), _Switch(["-c", "c"], "Reverse query but not complement it, which is required for alignment in the color space."), _Switch(["-N", "N"], "Disable iterative search. All hits with no more than maxDiff differences will be found. This mode is much slower than the default."), - _Switch(["-I","I"], + _Switch(["-I", "I"], "The input is in the Illumina 1.3+ read format (quality equals ASCII-64)."), _Switch(["-b", "b"], "Specify the input read sequence file is the BAM format"), @@ -186,7 +194,7 @@ >>> output_sam_file = "/path/to/read_1.sam" >>> samse_cmd = BwaSamseCommandline(reference=reference_genome, ... read_file=read_file, sai_file=sai_file) - >>> print samse_cmd + >>> print(samse_cmd) bwa samse /path/to/reference_genome.fasta /path/to/read_1.sai /path/to/read_1.fq You would typically run the command line using samse_cmd(stdout=output_sam_file) @@ -238,7 +246,7 @@ ... sai_file1=sai_file1, sai_file2=sai_file2, ... read_file1=read_file1, read_file2=read_file2, ... r=read_group) - >>> print sampe_cmd + >>> print(sampe_cmd) bwa sampe /path/to/reference_genome.fasta /path/to/read_1.sai /path/to/read_2.sai /path/to/read_1.fq /path/to/read_2.fq -r @RG ID:foo SM:bar You would typically run the command line using sampe_cmd(stdout=output_sam_file) @@ -282,7 +290,7 @@ checker_function=lambda x: isinstance(x, int), equate=False), _Option(["-r", "r"], "Specify the read group in a format like '@RG\tID:foo\tSM:bar'. [null]", - checker_function=lambda x: isinstance(x,basestring), + checker_function=lambda x: isinstance(x, basestring), equate=False), ] AbstractCommandline.__init__(self, cmd, **kwargs) @@ -303,10 +311,10 @@ >>> reference_genome = "/path/to/reference_genome.fasta" >>> read_file = "/path/to/read_1.fq" >>> bwasw_cmd = BwaBwaswCommandline(reference=reference_genome, read_file=read_file) - >>> print bwasw_cmd + >>> print(bwasw_cmd) bwa bwasw /path/to/reference_genome.fasta /path/to/read_1.fq - You would typically run the command line using bwasw_cmd() or via the + You would typically run the command line using bwasw_cmd() or via the Python subprocess module, as described in the Biopython tutorial. """ def __init__(self, cmd="bwa", **kwargs): @@ -314,9 +322,9 @@ self.parameters = \ [ _StaticArgument("bwasw"), - _Argument(["reference"],"Reference file name", filename=True, is_required=True), - _Argument(["read_file"],"Read file", filename=True, is_required=True), - _Argument(["mate_file"],"Mate file", filename=True, is_required=False), + _Argument(["reference"], "Reference file name", filename=True, is_required=True), + _Argument(["read_file"], "Read file", filename=True, is_required=True), + _Argument(["mate_file"], "Mate file", filename=True, is_required=False), _Option(["-a", "a"], "Score of a match [1]", checker_function=lambda x: isinstance(x, int), @@ -372,10 +380,10 @@ def _test(): """Run the module's doctests (PRIVATE).""" - print "Running modules doctests..." + print("Running modules doctests...") import doctest doctest.testmod() - print "Done" + print("Done") if __name__ == "__main__": diff -Nru python-biopython-1.62/Bio/Sequencing/Phd.py python-biopython-1.63/Bio/Sequencing/Phd.py --- python-biopython-1.62/Bio/Sequencing/Phd.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Sequencing/Phd.py 2013-12-05 14:10:43.000000000 +0000 @@ -113,7 +113,7 @@ else: raise ValueError("Failed to find END_SEQUENCE line") - record.seq = Seq.Seq(''.join([n[0] for n in record.sites]), generic_dna) + record.seq = Seq.Seq(''.join(n[0] for n in record.sites), generic_dna) if record.comments['trim'] is not None: first, last = record.comments['trim'][:2] record.seq_trimmed = record.seq[first:last] diff -Nru python-biopython-1.62/Bio/Sequencing/__init__.py python-biopython-1.63/Bio/Sequencing/__init__.py --- python-biopython-1.62/Bio/Sequencing/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Sequencing/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Code to deal with various programs for sequencing and assembly. This code deals with programs such as Phred, Phrap and Consed -- which provide diff -Nru python-biopython-1.62/Bio/Statistics/lowess.py python-biopython-1.63/Bio/Statistics/lowess.py --- python-biopython-1.62/Bio/Statistics/lowess.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Statistics/lowess.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,8 +3,7 @@ # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. -""" -This module implements the Lowess function for nonparametric regression. +"""Implements the Lowess function for nonparametric regression. Functions: lowess Fit a smooth nonparametric regression curve to a scatterplot. @@ -20,13 +19,17 @@ Statistical Association, September 1988, volume 83, number 403, pp. 596-610. """ +from __future__ import print_function + +from Bio._py3k import range + import numpy try: from Bio.Cluster import median # The function median in Bio.Cluster is faster than the function median # in NumPy, as it does not require a full sort. -except ImportError, x: +except ImportError as x: # Use the median function in NumPy if Bio.Cluster is not available from numpy import median @@ -60,7 +63,7 @@ >>> result = lowess(x, y) >>> len(result) 50 - >>> print "[%0.2f, ..., %0.2f]" % (result[0], result[-1]) + >>> print("[%0.2f, ..., %0.2f]" % (result[0], result[-1])) [4.85, ..., 84.98] """ n = len(x) @@ -72,7 +75,7 @@ yest = numpy.zeros(n) delta = numpy.ones(n) for iteration in range(iter): - for i in xrange(n): + for i in range(n): weights = delta * w[:, i] weights_mul_x = weights * x b1 = numpy.dot(weights, y) @@ -95,10 +98,10 @@ def _test(): """Run the Bio.Statistics.lowess module's doctests.""" - print "Running doctests..." + print("Running doctests...") import doctest doctest.testmod() - print "Done" + print("Done") if __name__ == "__main__": _test() diff -Nru python-biopython-1.62/Bio/SubsMat/FreqTable.py python-biopython-1.63/Bio/SubsMat/FreqTable.py --- python-biopython-1.62/Bio/SubsMat/FreqTable.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SubsMat/FreqTable.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + from Bio import Alphabet COUNT = 1 FREQ = 2 @@ -52,7 +57,7 @@ def _freq_from_count(self): total = float(sum(self.count.values())) - for i, v in self.count.iteritems(): + for i, v in self.count.items(): self[i] = v / total def _alphabet_from_input(self): diff -Nru python-biopython-1.62/Bio/SubsMat/MatrixInfo.py python-biopython-1.63/Bio/SubsMat/MatrixInfo.py --- python-biopython-1.62/Bio/SubsMat/MatrixInfo.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SubsMat/MatrixInfo.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """ A whole bunch of substitution matrices for use in alignments, etc. diff -Nru python-biopython-1.62/Bio/SubsMat/__init__.py python-biopython-1.63/Bio/SubsMat/__init__.py --- python-biopython-1.62/Bio/SubsMat/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SubsMat/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -109,6 +109,8 @@ """ +from __future__ import print_function + import re import sys import copy @@ -197,8 +199,7 @@ self.relative_entropy = 0 def _correct_matrix(self): - keylist = self.keys() - for key in keylist: + for key in self: if key[0] > key[1]: self[(key[1], key[0])] = self[key] del self[key] @@ -237,7 +238,7 @@ result = {} for letter in self.alphabet.letters: result[letter] = 0.0 - for pair, value in self.iteritems(): + for pair, value in self.items(): i1, i2 = pair if i1 == i2: result[i1] += value @@ -376,7 +377,7 @@ """Calculate and return the relative entropy with respect to an observed frequency matrix""" relative_entropy = 0. - for key, value in self.iteritems(): + for key, value in self.items(): if value > EPSILON: relative_entropy += obs_freq_mat[key] * log(value) relative_entropy /= log(2) @@ -390,7 +391,7 @@ """Calculate and return the relative entropy with respect to an observed frequency matrix""" relative_entropy = 0. - for key, value in self.iteritems(): + for key, value in self.items(): relative_entropy += obs_freq_mat[key] * value / log(2) return relative_entropy @@ -464,7 +465,7 @@ minimum log-odds value of the matrix in entries containing -999 """ lo_mat = LogOddsMatrix(subs_mat) - for key, value in subs_mat.iteritems(): + for key, value in subs_mat.items(): if value < EPSILON: lo_mat[key] = -999 else: @@ -519,7 +520,7 @@ alphabet = table[0] j = 0 for rec in table[1:]: - # print j + # print(j) row = alphabet[j] # row = rec[0] if re.compile('[A-z\*]').match(rec[0]): @@ -533,7 +534,7 @@ i += 1 j += 1 # delete entries with an asterisk - for i in matrix.keys(): + for i in matrix: if '*' in i: del(matrix[i]) ret_mat = SeqMat(matrix) @@ -611,7 +612,7 @@ sum_mat.make_entropy() mat_1.make_entropy() mat_2.make_entropy() - # print mat_1.entropy, mat_2.entropy + # print(mat_1.entropy, mat_2.entropy) dJS = sum_mat.entropy - pi_1 * mat_1.entropy - pi_2 * mat_2.entropy return dJS @@ -652,10 +653,10 @@ key = (i, j) mat_2_key = [alphabet[len_alphabet-alphabet.index(key[0])-1], alphabet[len_alphabet-alphabet.index(key[1])-1]] - # print mat_2_key + # print(mat_2_key) mat_2_key.sort() mat_2_key = tuple(mat_2_key) - # print key, "||", mat_2_key + # print("%s||%s" % (key, mat_2_key) print_mat[key] = mat_2[mat_2_key] print_mat[(key[1], key[0])] = mat_1[key] for i in alphabet: diff -Nru python-biopython-1.62/Bio/SwissProt/KeyWList.py python-biopython-1.63/Bio/SwissProt/KeyWList.py --- python-biopython-1.62/Bio/SwissProt/KeyWList.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SwissProt/KeyWList.py 2013-12-05 14:10:43.000000000 +0000 @@ -19,6 +19,8 @@ """ +from __future__ import print_function + class Record(dict): """ This record stores the information of one keyword or category in the @@ -75,7 +77,7 @@ elif key in ("DE", "SY", "GO", "HI", "WW"): record[key].append(value) else: - print "Ignoring: %s" % line.strip() + print("Ignoring: %s" % line.strip()) # Read the footer and throw it away for line in handle: pass diff -Nru python-biopython-1.62/Bio/SwissProt/__init__.py python-biopython-1.63/Bio/SwissProt/__init__.py --- python-biopython-1.62/Bio/SwissProt/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/SwissProt/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -2,9 +2,8 @@ # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. -""" -This module provides code to work with the sprotXX.dat file from -SwissProt. +"""Code to work with the sprotXX.dat file from SwissProt. + http://www.expasy.ch/sprot/sprot-top.html Tested with: @@ -21,6 +20,8 @@ """ +from __future__ import print_function + from Bio._py3k import _as_string @@ -543,22 +544,21 @@ if __name__ == "__main__": - print "Quick self test..." + print("Quick self test...") example_filename = "../../Tests/SwissProt/sp008" import os if not os.path.isfile(example_filename): - print "Missing test file %s" % example_filename + print("Missing test file %s" % example_filename) else: #Try parsing it! - handle = open(example_filename) - records = parse(handle) - for record in records: - print record.entry_name - print ",".join(record.accessions) - print record.keywords - print repr(record.organism) - print record.sequence[:20] + "..." - handle.close() + with open(example_filename) as handle: + records = parse(handle) + for record in records: + print(record.entry_name) + print(",".join(record.accessions)) + print(record.keywords) + print(repr(record.organism)) + print(record.sequence[:20] + "...") diff -Nru python-biopython-1.62/Bio/TogoWS/__init__.py python-biopython-1.63/Bio/TogoWS/__init__.py --- python-biopython-1.62/Bio/TogoWS/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/TogoWS/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -30,11 +30,16 @@ http://soapy.sourceforge.net/ """ -import urllib -import urllib2 +from __future__ import print_function + import time from Bio._py3k import _binary_to_string_handle, _as_bytes +#Importing these functions with leading underscore as not intended for reuse +from Bio._py3k import urlopen as _urlopen +from Bio._py3k import urlencode as _urlencode +from Bio._py3k import quote as _quote + #Constant _BASE_URL = "http://togows.dbcls.jp" @@ -109,6 +114,11 @@ except KeyError: fields = _get_entry_fields(db) _entry_db_fields[db] = fields + if db == "pubmed" and field == "ti" and "title" in fields: + #Backwards compatibility fix for TogoWS change Nov/Dec 2013 + field = "title" + import warnings + warnings.warn("TogoWS dropped 'pubmed' field alias 'ti', please use 'title' instead.") if field not in fields: raise ValueError("TogoWS entry fetch does not explicitly support " "field '%s' for database '%s'. Only: %s" @@ -126,7 +136,7 @@ if isinstance(id, list): id = ",".join(id) - url = _BASE_URL + "/entry/%s/%s" % (db, urllib.quote(id)) + url = _BASE_URL + "/entry/%s/%s" % (db, _quote(id)) if field: url += "/" + field if format: @@ -154,7 +164,7 @@ warnings.warn("TogoWS search does not officially support database '%s'. " "See %s/search/ for options." % (db, _BASE_URL)) handle = _open(_BASE_URL + "/search/%s/%s/count" - % (db, urllib.quote(query))) + % (db, _quote(query))) count = int(handle.read().strip()) handle.close() return count @@ -172,7 +182,7 @@ You would use this function within a for loop, e.g. >>> for id in search_iter("pubmed", "lung+cancer+drug", limit=10): - ... print id #maybe fetch data with entry? + ... print(id) #maybe fetch data with entry? Internally this first calls the Bio.TogoWS.search_count() and then uses Bio.TogoWS.search() to get the results in batches. @@ -189,10 +199,10 @@ prev_ids = [] # Just cache the last batch for error checking while remain: batch = min(batch, remain) - #print "%r left, asking for %r" % (remain, batch) + #print("%r left, asking for %r" % (remain, batch)) ids = search(db, query, offset, batch).read().strip().split() assert len(ids) == batch, "Got %i, expected %i" % (len(ids), batch) - #print "offset %i, %s ... %s" % (offset, ids[0], ids[-1]) + #print("offset %i, %s ... %s" % (offset, ids[0], ids[-1])) if ids == prev_ids: raise RuntimeError("Same search results for previous offset") for identifier in ids: @@ -245,7 +255,7 @@ import warnings warnings.warn("TogoWS search does not explicitly support database '%s'. " "See %s/search/ for options." % (db, _BASE_URL)) - url = _BASE_URL + "/search/%s/%s" % (db, urllib.quote(query)) + url = _BASE_URL + "/search/%s/%s" % (db, _quote(query)) if offset is not None and limit is not None: try: offset = int(offset) @@ -264,7 +274,7 @@ raise ValueError("Expect BOTH offset AND limit to be provided (or neither)") if format: url += "." + format - #print url + #print(url) return _open(url) @@ -314,14 +324,11 @@ else: _open.previous = current - #print url - try: - if post: - handle = urllib2.urlopen(url, _as_bytes(urllib.urlencode(post))) - else: - handle = urllib2.urlopen(url) - except urllib2.HTTPError, exception: - raise exception + #print(url) + if post: + handle = _urlopen(url, _as_bytes(_urlencode(post))) + else: + handle = _urlopen(url) #We now trust TogoWS to have set an HTTP error code, that #suffices for my current unit tests. Previously we would diff -Nru python-biopython-1.62/Bio/UniGene/UniGene.py python-biopython-1.63/Bio/UniGene/UniGene.py --- python-biopython-1.62/Bio/UniGene/UniGene.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/UniGene/UniGene.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,21 +1,9 @@ +# Copyright 2001 by Katharine Lindner. All Rights Reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. -# Permission to use, copy, modify, and distribute this software and -# its documentation with or without modifications and for any purpose -# and without fee is hereby granted, provided that any copyright -# notices appear in all copies and that both those copyright notices -# and this permission notice appear in supporting documentation, and -# that the names of the contributors or copyright holders not be used -# in advertising or publicity pertaining to distribution of the software -# without specific prior permission. -# -# THE CONTRIBUTORS AND COPYRIGHT HOLDERS OF THIS SOFTWARE DISCLAIM ALL -# WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL THE -# CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT -# OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, -# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION -# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +from __future__ import print_function import warnings from Bio import BiopythonDeprecationWarning @@ -63,7 +51,7 @@ else: uhandle = Bio.File.UndoHandle(handle) text = '' - while 1: + while True: line = uhandle.readline() line = string.strip( line ) if( line == '' ): @@ -168,7 +156,7 @@ contents.append( text ) else: self.queue[ self.master_key ][ self.key_waiting ] = \ - [ contents , text ] + [ contents, text ] except: self.queue[ self.master_key ][ self.key_waiting ] = text @@ -192,26 +180,26 @@ indent = indent + ' ' if isinstance(item, str): if( item != '' ): - print '%s%s' % ( indent, item ) + print('%s%s' % ( indent, item )) elif isinstance(item, list): for subitem in item: self.print_item( subitem, level + 1 ) elif( isinstance( item, UserDict.UserDict ) ): for subitem in item: - print '%skey is %s' % ( indent, subitem ) + print('%skey is %s' % ( indent, subitem )) self.print_item( item[ subitem ], level + 1 ) else: - print item + print(item) def print_tags( self ): for key in self.queue: - print 'key %s' % key + print('key %s' % key) self.print_item( self.queue[ key ] ) if( __name__ == '__main__' ): - handle = open( 'Hs13225.htm') - undo_handle = Bio.File.UndoHandle( handle ) - unigene_parser = UniGeneParser() - unigene_parser.parse( handle ) - unigene_parser.print_tags() + with open( 'Hs13225.htm') as handle: + undo_handle = Bio.File.UndoHandle( handle ) + unigene_parser = UniGeneParser() + unigene_parser.parse( handle ) + unigene_parser.print_tags() diff -Nru python-biopython-1.62/Bio/UniGene/__init__.py python-biopython-1.63/Bio/UniGene/__init__.py --- python-biopython-1.62/Bio/UniGene/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/UniGene/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -120,7 +120,7 @@ self.text=text self._init_from_text(text) - def _init_from_text(self,text): + def _init_from_text(self, text): parts = text.split('; ') for part in parts: key, val = part.split("=") @@ -128,7 +128,7 @@ if val[:5]=='IMAGE': self.is_image=True self.image = val[6:] - setattr(self,key.lower(),val) + setattr(self, key.lower(), val) def __repr__(self): return self.text @@ -157,12 +157,12 @@ self.text=text self._init_from_text(text) - def _init_from_text(self,text): + def _init_from_text(self, text): parts = text.split('; ') for part in parts: key, val = part.split("=") - setattr(self,key.lower(),val) + setattr(self, key.lower(), val) def __repr__(self): return self.text @@ -186,12 +186,12 @@ self.text=text self._init_from_text(text) - def _init_from_text(self,text): + def _init_from_text(self, text): parts = text.split(' ') for part in parts: key, val = part.split("=") - setattr(self,key.lower(),val) + setattr(self, key.lower(), val) def __repr__(self): return self.text diff -Nru python-biopython-1.62/Bio/UniProt/GOA.py python-biopython-1.63/Bio/UniProt/GOA.py --- python-biopython-1.62/Bio/UniProt/GOA.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/UniProt/GOA.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,7 +1,9 @@ #!/usr/bin/env python -import copy -import sys - +# Copyright 2013 by Iddo Friedberg idoerg@gmail.com +# All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. """Parsers for the GAF, GPA and GPI formats from UniProt-GOA. Uniprot-GOA README + GAF format description: @@ -14,51 +16,50 @@ gp_information (GPI format) README: ftp://ftp.ebi.ac.uk/pub/databases/GO/goa/UNIPROT/gp_information_readme - -(c) 2013 Iddo Friedberg idoerg@gmail.com -http://iddo-friedberg.net -Distributed under Biopython license. - """ +import copy +import sys + +from Bio._py3k import zip # GAF: GO Annotation Format # # GAF version 2.0 -GAF20FIELDS = ['DB' , - 'DB_Object_ID' , - 'DB_Object_Symbol' , - 'Qualifier' , - 'GO_ID' , - 'DB:Reference' , - 'Evidence' , - 'With' , +GAF20FIELDS = ['DB', + 'DB_Object_ID', + 'DB_Object_Symbol', + 'Qualifier', + 'GO_ID', + 'DB:Reference', + 'Evidence', + 'With', 'Aspect', - 'DB_Object_Name' , - 'Synonym' , - 'DB_Object_Type' , - 'Taxon_ID' , - 'Date' , - 'Assigned_By' , - 'Annotation_Extension' , + 'DB_Object_Name', + 'Synonym', + 'DB_Object_Type', + 'Taxon_ID', + 'Date', + 'Assigned_By', + 'Annotation_Extension', 'Gene_Product_Form_ID'] # GAF version 1.0 -GAF10FIELDS = ['DB' , - 'DB_Object_ID' , - 'DB_Object_Symbol' , - 'Qualifier' , - 'GO_ID' , - 'DB:Reference' , - 'Evidence' , - 'With' , +GAF10FIELDS = ['DB', + 'DB_Object_ID', + 'DB_Object_Symbol', + 'Qualifier', + 'GO_ID', + 'DB:Reference', + 'Evidence', + 'With', 'Aspect', - 'DB_Object_Name' , - 'Synonym' , - 'DB_Object_Type' , - 'Taxon_ID' , - 'Date' , + 'DB_Object_Name', + 'Synonym', + 'DB_Object_Type', + 'Taxon_ID', + 'Date', 'Assigned_By'] @@ -397,7 +398,7 @@ Write only S. cerevisiae records, but remove all records with IEA evidence """ - banned = {'Evidence': set(['IEA','EXP'])} + banned = {'Evidence': set(['IEA', 'EXP'])} allowed = {'Taxon_ID': set(['taxon:4932'])} for inrec in gafiterator(open(sys.argv[1])): if record_has(inrec, allowed) and \ diff -Nru python-biopython-1.62/Bio/Wise/__init__.py python-biopython-1.63/Bio/Wise/__init__.py --- python-biopython-1.62/Bio/Wise/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Wise/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -11,7 +11,7 @@ # Bio.Wise.psw is for protein Smith-Waterman alignments # Bio.Wise.dnal is for Smith-Waterman DNA alignments -__version__ = "$Revision: 1.17 $" +from __future__ import print_function import os import sys @@ -68,18 +68,19 @@ """ Returns a filehandle """ - assert len(pair) == 2 + if not pair or len(pair) != 2: + raise ValueError("Expected pair of filename, not %s" % repr(pair)) output_file = tempfile.NamedTemporaryFile(mode='r') input_files = tempfile.NamedTemporaryFile(mode="w"), tempfile.NamedTemporaryFile(mode="w") if dry_run: - print _build_align_cmdline(cmdline, + print(_build_align_cmdline(cmdline, pair, output_file.name, kbyte, force_type, - quiet) + quiet)) return for filename, input_file in zip(pair, input_files): @@ -100,13 +101,13 @@ quiet) if debug: - print >>sys.stderr, cmdline_str + sys.stderr.write("%s\n" % cmdline_str) status = os.system(cmdline_str) >> 8 if status > 1: if kbyte != 0: # possible memory problem; could be None - print >>sys.stderr, "INFO trying again with the linear model" + sys.stderr.write("INFO trying again with the linear model\n") return align(cmdline, pair, 0, force_type, dry_run, quiet, debug) else: raise OSError("%s returned %s" % (" ".join(cmdline), status)) @@ -126,7 +127,7 @@ singles = list(singles) while singles: suitor = singles.pop(0) # if sorted, stay sorted - pairs.extend([(suitor, single) for single in singles]) + pairs.extend((suitor, single) for single in singles) return pairs diff -Nru python-biopython-1.62/Bio/Wise/dnal.py python-biopython-1.63/Bio/Wise/dnal.py --- python-biopython-1.62/Bio/Wise/dnal.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Wise/dnal.py 2013-12-05 14:10:43.000000000 +0000 @@ -11,12 +11,15 @@ # Bio.Wise.psw is for protein Smith-Waterman alignments # Bio.Wise.dnal is for Smith-Waterman DNA alignments -__version__ = "$Revision: 1.12 $" +from __future__ import print_function -import commands -import itertools import re +#Importing with leading underscore as not intended to be exposed +from Bio._py3k import getoutput as _getoutput +from Bio._py3k import zip +from Bio._py3k import map + from Bio import Wise _SCORE_MATCH = 4 @@ -40,7 +43,7 @@ def _fgrep_count(pattern, file): - return int(commands.getoutput(_CMDLINE_FGREP_COUNT % (pattern, file))) + return int(_getoutput(_CMDLINE_FGREP_COUNT % (pattern, file))) _re_alb_line2coords = re.compile(r"^\[([^:]+):[^\[]+\[([^:]+):") @@ -67,12 +70,7 @@ if end_line is None: # sequence is too short return [(0, 0), (0, 0)] - return zip(*map(_alb_line2coords, [start_line, end_line])) # returns [(start0, end0), (start1, end1)] - - -def _any(seq, pred=bool): - "Returns True if pred(x) is True at least one element in the iterable" - return True in itertools.imap(pred, seq) + return list(zip(*map(_alb_line2coords, [start_line, end_line]))) # returns [(start0, end0), (start1, end1)] class Statistics(object): @@ -94,10 +92,10 @@ gap*self.gaps + extension*self.extensions) - if _any([self.matches, self.mismatches, self.gaps, self.extensions]): + if self.matches or self.mismatches or self.gaps or self.extensions: self.coords = _get_coords(filename) else: - self.coords = [(0, 0), (0,0)] + self.coords = [(0, 0), (0, 0)] def identity_fraction(self): return self.matches/(self.matches+self.mismatches) @@ -105,7 +103,9 @@ header = "identity_fraction\tmatches\tmismatches\tgaps\textensions" def __str__(self): - return "\t".join([str(x) for x in (self.identity_fraction(), self.matches, self.mismatches, self.gaps, self.extensions)]) + return "\t".join(str(x) for x in (self.identity_fraction(), + self.matches, self.mismatches, + self.gaps, self.extensions)) def align(pair, match=_SCORE_MATCH, mismatch=_SCORE_MISMATCH, gap=_SCORE_GAP_START, extension=_SCORE_GAP_EXTENSION, **keywds): @@ -124,11 +124,10 @@ def main(): import sys stats = align(sys.argv[1:3]) - print "\n".join(["%s: %s" % (attr, getattr(stats, attr)) - for attr in - ("matches", "mismatches", "gaps", "extensions")]) - print "identity_fraction: %s" % stats.identity_fraction() - print "coords: %s" % stats.coords + print("\n".join("%s: %s" % (attr, getattr(stats, attr)) + for attr in ("matches", "mismatches", "gaps", "extensions"))) + print("identity_fraction: %s" % stats.identity_fraction()) + print("coords: %s" % stats.coords) def _test(*args, **keywds): diff -Nru python-biopython-1.62/Bio/Wise/psw.py python-biopython-1.63/Bio/Wise/psw.py --- python-biopython-1.62/Bio/Wise/psw.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/Wise/psw.py 2013-12-05 14:10:43.000000000 +0000 @@ -11,7 +11,7 @@ # Bio.Wise.psw is for protein Smith-Waterman alignments # Bio.Wise.dnal is for Smith-Waterman DNA alignments -__version__ = "$Revision: 1.5 $" +from __future__ import print_function import os import re @@ -78,7 +78,7 @@ def parse_line(line): """ - >>> print parse_line("Column 0:") + >>> print(parse_line("Column 0:")) None >>> parse_line("Unit 0- [ -1- 0] [SEQUENCE]") ColumnUnit(unit=0, column=0, SEQUENCE) @@ -108,7 +108,7 @@ for line in iterable: try: if os.environ["WISE_PY_DEBUG"]: - print line, + print(line) except KeyError: pass @@ -137,7 +137,7 @@ def main(): - print align(sys.argv[1:3]) + print(align(sys.argv[1:3])) def _test(*args, **keywds): diff -Nru python-biopython-1.62/Bio/__init__.py python-biopython-1.63/Bio/__init__.py --- python-biopython-1.62/Bio/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -12,7 +12,7 @@ __docformat__ = "epytext en" # not just plaintext -__version__ = "1.62" +__version__ = "1.63" class MissingExternalDependencyError(Exception): diff -Nru python-biopython-1.62/Bio/_py3k/__init__.py python-biopython-1.63/Bio/_py3k/__init__.py --- python-biopython-1.62/Bio/_py3k/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/_py3k/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,15 +1,54 @@ -# Copyright 2010 by Peter Cock. All rights reserved. +# Copyright 2010-2013 by Peter Cock. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. -"""Python 3 compatibility tools (PRIVATE).""" +"""Python 3 compatibility tools (PRIVATE). +We currently have lines like this under Python 2 in order +to use iterator based zip, map and filter: + + from future_builtins import zip + +There is no similar option for range yet, other than: + + range = xrange + input = raw_input + +or: + + from __builtin__ import xrange as range + from __builtin__ import raw_input as input + +Under Python 3 this imports need to be removed. Also, deliberate +importing of built in functions like open changes from Python 2: + + from __builtin__ import open + +to this under Python 3: + + from builtins import open + +Instead, we can do this under either Python 2 or 3: + + from Bio._py3k import open + from Bio._py3k import zip + +Once we drop support for Python 2, the whole of Bio._py3k will +go away. +""" import sys if sys.version_info[0] >= 3: - #Python 3 code (which will be converted using 2to3 script) + #Code for Python 3 + from builtins import open, zip, map, filter, range, input + import codecs + #Lots of our Python 2 code uses isinstance(x, basestring) + #which after 2to3 becomes isinstance(x, str) + basestring = str + unicode = str + _bytes_to_string = lambda b: b.decode() # bytes to unicode string _string_to_bytes = lambda s: s.encode() # unicode string to bytes @@ -79,8 +118,22 @@ #On Python 3, can depend on OrderedDict being present: from collections import OrderedDict + #On Python 3, this will be a unicode StringIO + from io import StringIO + + #On Python 3 urllib, urllib2, and urlparse were merged: + from urllib.request import urlopen, Request, urlretrieve, urlparse + from urllib.parse import urlencode, quote + from urllib.error import HTTPError + else: #Python 2 code + from __builtin__ import open, basestring, unicode + + #Import Python3 like iterator functions: + from future_builtins import zip, map, filter + from __builtin__ import xrange as range + from __builtin__ import raw_input as input _bytes_to_string = lambda b: b # bytes to string, i.e. do nothing _string_to_bytes = lambda s: str(s) # str (or unicode) to bytes string @@ -100,10 +153,7 @@ def _is_int_or_long(i): """Check if the value is an integer or long.""" - #If the 2to3 long fixer is enabled (which it is by default), this - #will be changed to "isinstance(i, int) or isinstance(i, int)" - #but that doesn't matter. - return isinstance(i, int) or isinstance(i, long) + return isinstance(i, (int, long)) def _binary_to_string_handle(handle): """Treat a binary handle like a text handle.""" @@ -118,4 +168,47 @@ from ordereddict import OrderedDict except ImportError: #Use our bundled copy instead - from _ordereddict import OrderedDict + from ._ordereddict import OrderedDict + + # On Python 2 this will be a (bytes) string based handle. + # Note this doesn't work as it is unicode based: + # from io import StringIO + try: + from cStringIO import StringIO + except ImportError: + from StringIO import StringIO + + #Under urllib.request on Python 3: + from urllib2 import urlopen, Request + from urllib import urlretrieve + from urlparse import urlparse + + #Under urllib.parse on Python 3: + from urllib import urlencode, quote + + #Under urllib.error on Python 3: + from urllib2 import HTTPError + + +if sys.platform == "win32": + # Can't use commands.getoutput on Python 2, Unix only/broken: + # http://bugs.python.org/issue15073 + # Can't use subprocess.getoutput on Python 3, Unix only/broken: + # http://bugs.python.org/issue10197 + def getoutput(cmd): + import subprocess + child = subprocess.Popen(cmd, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + universal_newlines=True, + shell=False) + stdout, stderr = child.communicate() + # Remove trailing \n to match the Unix function, + return stdout.rstrip("\n") +elif sys.version_info[0] >= 3: + # Use subprocess.getoutput on Python 3, + from subprocess import getoutput +else: + # Use commands.getoutput on Python 2, + from commands import getoutput diff -Nru python-biopython-1.62/Bio/_py3k/_ordereddict.py python-biopython-1.63/Bio/_py3k/_ordereddict.py --- python-biopython-1.62/Bio/_py3k/_ordereddict.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/_py3k/_ordereddict.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,128 +1,128 @@ -# Copyright (c) 2009 Raymond Hettinger -# -# Permission is hereby granted, free of charge, to any person -# obtaining a copy of this software and associated documentation files -# (the "Software"), to deal in the Software without restriction, -# including without limitation the rights to use, copy, modify, merge, -# publish, distribute, sublicense, and/or sell copies of the Software, -# and to permit persons to whom the Software is furnished to do so, -# subject to the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -# OTHER DEALINGS IN THE SOFTWARE. - -from UserDict import DictMixin - - -class OrderedDict(dict, DictMixin): - - def __init__(self, *args, **kwds): - if len(args) > 1: - raise TypeError('expected at most 1 arguments, got %d' % len(args)) - try: - self.__end - except AttributeError: - self.clear() - self.update(*args, **kwds) - - def clear(self): - self.__end = end = [] - end += [None, end, end] # sentinel node for doubly linked list - self.__map = {} # key --> [key, prev, next] - dict.clear(self) - - def __setitem__(self, key, value): - if key not in self: - end = self.__end - curr = end[1] - curr[2] = end[1] = self.__map[key] = [key, curr, end] - dict.__setitem__(self, key, value) - - def __delitem__(self, key): - dict.__delitem__(self, key) - key, prev, next = self.__map.pop(key) - prev[2] = next - next[1] = prev - - def __iter__(self): - end = self.__end - curr = end[2] - while curr is not end: - yield curr[0] - curr = curr[2] - - def __reversed__(self): - end = self.__end - curr = end[1] - while curr is not end: - yield curr[0] - curr = curr[1] - - def popitem(self, last=True): - if not self: - raise KeyError('dictionary is empty') - if last: - key = reversed(self).next() - else: - key = iter(self).next() - value = self.pop(key) - return key, value - - def __reduce__(self): - items = [[k, self[k]] for k in self] - tmp = self.__map, self.__end - del self.__map, self.__end - inst_dict = vars(self).copy() - self.__map, self.__end = tmp - if inst_dict: - return (self.__class__, (items,), inst_dict) - return self.__class__, (items,) - - def keys(self): - return list(self) - - setdefault = DictMixin.setdefault - update = DictMixin.update - pop = DictMixin.pop - values = DictMixin.values - items = DictMixin.items - iterkeys = DictMixin.iterkeys - itervalues = DictMixin.itervalues - iteritems = DictMixin.iteritems - - def __repr__(self): - if not self: - return '%s()' % (self.__class__.__name__,) - return '%s(%r)' % (self.__class__.__name__, self.items()) - - def copy(self): - return self.__class__(self) - - @classmethod - def fromkeys(cls, iterable, value=None): - d = cls() - for key in iterable: - d[key] = value - return d - - def __eq__(self, other): - if isinstance(other, OrderedDict): - if len(self) != len(other): - return False - for p, q in zip(self.items(), other.items()): - if p != q: - return False - return True - return dict.__eq__(self, other) - - def __ne__(self, other): - return not self == other +# Copyright (c) 2009 Raymond Hettinger +# +# Permission is hereby granted, free of charge, to any person +# obtaining a copy of this software and associated documentation files +# (the "Software"), to deal in the Software without restriction, +# including without limitation the rights to use, copy, modify, merge, +# publish, distribute, sublicense, and/or sell copies of the Software, +# and to permit persons to whom the Software is furnished to do so, +# subject to the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +# OTHER DEALINGS IN THE SOFTWARE. + +from UserDict import DictMixin + + +class OrderedDict(dict, DictMixin): + + def __init__(self, *args, **kwds): + if len(args) > 1: + raise TypeError('expected at most 1 arguments, got %d' % len(args)) + try: + self.__end + except AttributeError: + self.clear() + self.update(*args, **kwds) + + def clear(self): + self.__end = end = [] + end += [None, end, end] # sentinel node for doubly linked list + self.__map = {} # key --> [key, prev, next] + dict.clear(self) + + def __setitem__(self, key, value): + if key not in self: + end = self.__end + curr = end[1] + curr[2] = end[1] = self.__map[key] = [key, curr, end] + dict.__setitem__(self, key, value) + + def __delitem__(self, key): + dict.__delitem__(self, key) + key, prev, next = self.__map.pop(key) + prev[2] = next + next[1] = prev + + def __iter__(self): + end = self.__end + curr = end[2] + while curr is not end: + yield curr[0] + curr = curr[2] + + def __reversed__(self): + end = self.__end + curr = end[1] + while curr is not end: + yield curr[0] + curr = curr[1] + + def popitem(self, last=True): + if not self: + raise KeyError('dictionary is empty') + if last: + key = reversed(self).next() + else: + key = iter(self).next() + value = self.pop(key) + return key, value + + def __reduce__(self): + items = [[k, self[k]] for k in self] + tmp = self.__map, self.__end + del self.__map, self.__end + inst_dict = vars(self).copy() + self.__map, self.__end = tmp + if inst_dict: + return (self.__class__, (items,), inst_dict) + return self.__class__, (items,) + + def keys(self): + return list(self) + + setdefault = DictMixin.setdefault + update = DictMixin.update + pop = DictMixin.pop + values = DictMixin.values + items = DictMixin.items + iterkeys = DictMixin.iterkeys + itervalues = DictMixin.itervalues + iteritems = DictMixin.iteritems + + def __repr__(self): + if not self: + return '%s()' % (self.__class__.__name__,) + return '%s(%r)' % (self.__class__.__name__, self.items()) + + def copy(self): + return self.__class__(self) + + @classmethod + def fromkeys(cls, iterable, value=None): + d = cls() + for key in iterable: + d[key] = value + return d + + def __eq__(self, other): + if isinstance(other, OrderedDict): + if len(self) != len(other): + return False + for p, q in zip(self.items(), other.items()): + if p != q: + return False + return True + return dict.__eq__(self, other) + + def __ne__(self, other): + return not self == other diff -Nru python-biopython-1.62/Bio/_utils.py python-biopython-1.63/Bio/_utils.py --- python-biopython-1.62/Bio/_utils.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/_utils.py 2013-12-05 14:10:43.000000000 +0000 @@ -6,6 +6,8 @@ """Common utility functions for various Bio submodules.""" +from __future__ import print_function + import os @@ -22,8 +24,6 @@ 5 >>> iterlen(iter("abcde")) 5 - >>> iterlen(xrange(5)) - 5 """ try: @@ -39,12 +39,9 @@ """Reads through whitespaces, returns the first non-whitespace line.""" while True: line = handle.readline() - # if line has characters and stripping does not remove them, - # return the line - if line and line.strip(): - return line - # if line ends, return None - elif not line: + # if line is empty or line has characters and stripping does not remove + # them, return the line + if (not line) or (line and line.strip()): return line @@ -109,14 +106,14 @@ cur_dir = os.path.abspath(os.curdir) - print "Runing doctests..." + print("Runing doctests...") try: os.chdir(find_test_dir(target_dir)) doctest.testmod(*args, **kwargs) finally: # and revert back to initial directory os.chdir(cur_dir) - print "Done" + print("Done") if __name__ == "__main__": run_doctest() diff -Nru python-biopython-1.62/Bio/bgzf.py python-biopython-1.63/Bio/bgzf.py --- python-biopython-1.62/Bio/bgzf.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/bgzf.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,5 +1,5 @@ #!/usr/bin/env python -# Copyright 2010-2011 by Peter Cock. +# Copyright 2010-2013 by Peter Cock. # All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included @@ -93,24 +93,28 @@ i.e. Suppose you do this: >>> from Bio.bgzf import * ->>> print open.__module__ +>>> print(open.__module__) Bio.bgzf Or, >>> from gzip import * ->>> print open.__module__ +>>> print(open.__module__) gzip Notice that the open function has been replaced. You can "fix" this if you need to by importing the built-in open function: ->>> from __builtin__ import open +>>> try: +... from __builtin__ import open # Python 2 +... except ImportError: +... from builtins import open # Python 3 +... However, what we recommend instead is to use the explicit namespace, e.g. >>> from Bio import bgzf ->>> print bgzf.open.__module__ +>>> print(bgzf.open.__module__) Bio.bgzf @@ -136,20 +140,20 @@ >>> handle = BgzfReader("GenBank/NC_000932.gb.bgz", "r") >>> assert 0 == handle.tell() ->>> print handle.readline().rstrip() +>>> print(handle.readline().rstrip()) LOCUS NC_000932 154478 bp DNA circular PLN 15-APR-2009 >>> assert 80 == handle.tell() ->>> print handle.readline().rstrip() +>>> print(handle.readline().rstrip()) DEFINITION Arabidopsis thaliana chloroplast, complete genome. >>> assert 143 == handle.tell() >>> data = handle.read(70000) >>> assert 987828735 == handle.tell() ->>> print handle.readline().rstrip() +>>> print(handle.readline().rstrip()) f="GeneID:844718" ->>> print handle.readline().rstrip() +>>> print(handle.readline().rstrip()) CDS complement(join(84337..84771,85454..85843)) >>> offset = handle.seek(make_virtual_offset(55074, 126)) ->>> print handle.readline().rstrip() +>>> print(handle.readline().rstrip()) 68521 tatgtcattc gaaattgtat aaagacaact cctatttaat agagctattt gtgcaagtat >>> handle.close() @@ -158,7 +162,7 @@ >>> handle = open("GenBank/NC_000932.gb.bgz", "rb") >>> for values in BgzfBlocks(handle): -... print "Raw start %i, raw length %i; data start %i, data length %i" % values +... print("Raw start %i, raw length %i; data start %i, data length %i" % values) Raw start 0, raw length 15073; data start 0, data length 65536 Raw start 15073, raw length 17857; data start 65536, data length 65536 Raw start 32930, raw length 22144; data start 131072, data length 65536 @@ -175,7 +179,7 @@ By reading ahead 70,000 bytes we moved into the second BGZF block, and at that point the BGZF virtual offsets start to look different -a simple offset into the decompressed data as exposed by the gzip +to a simple offset into the decompressed data as exposed by the gzip library. As an example, consider seeking to the decompressed position 196734. @@ -187,9 +191,9 @@ offset of 55074 and the offset within the block of 126 to get the BGZF virtual offset. ->>> print 55074 << 16 | 126 +>>> print(55074 << 16 | 126) 3609329790 ->>> print bgzf.make_virtual_offset(55074, 126) +>>> print(bgzf.make_virtual_offset(55074, 126)) 3609329790 Thus for this BGZF file, decompressed position 196734 corresponds @@ -216,27 +220,26 @@ >>> handle = BgzfReader("GenBank/NC_000932.gb.bgz") >>> record = SeqIO.read(handle, "genbank") >>> handle.close() ->>> print record.id +>>> print(record.id) NC_000932.1 """ +from __future__ import print_function + +import sys # to detect when under Python 2 import zlib import struct -import __builtin__ # to access the usual open function from Bio._py3k import _as_bytes, _as_string +from Bio._py3k import open as _open #For Python 2 can just use: _bgzf_magic = '\x1f\x8b\x08\x04' #but need to use bytes on Python 3 -_bgzf_magic = _as_bytes("\x1f\x8b\x08\x04") -_bgzf_header = _as_bytes("\x1f\x8b\x08\x04\x00\x00\x00\x00" - "\x00\xff\x06\x00\x42\x43\x02\x00") -_bgzf_eof = _as_bytes("\x1f\x8b\x08\x04\x00\x00\x00\x00\x00\xff\x06\x00BC" + - "\x02\x00\x1b\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00") -_bytes_BC = _as_bytes("BC") -_empty_bytes_string = _as_bytes("") -_bytes_newline = _as_bytes("\n") +_bgzf_magic = b"\x1f\x8b\x08\x04" +_bgzf_header = b"\x1f\x8b\x08\x04\x00\x00\x00\x00\x00\xff\x06\x00\x42\x43\x02\x00" +_bgzf_eof = b"\x1f\x8b\x08\x04\x00\x00\x00\x00\x00\xff\x06\x00BC\x02\x00\x1b\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00" +_bytes_BC = b"BC" def open(filename, mode="rb"): @@ -262,9 +265,9 @@ within_block_offset within the (decompressed) block (unsigned 16 bit integer). - >>> make_virtual_offset(0,0) + >>> make_virtual_offset(0, 0) 0 - >>> make_virtual_offset(0,1) + >>> make_virtual_offset(0, 1) 1 >>> make_virtual_offset(0, 2**16 - 1) 65535 @@ -273,21 +276,21 @@ ... ValueError: Require 0 <= within_block_offset < 2**16, got 65536 - >>> 65536 == make_virtual_offset(1,0) + >>> 65536 == make_virtual_offset(1, 0) True - >>> 65537 == make_virtual_offset(1,1) + >>> 65537 == make_virtual_offset(1, 1) True >>> 131071 == make_virtual_offset(1, 2**16 - 1) True - >>> 6553600000 == make_virtual_offset(100000,0) + >>> 6553600000 == make_virtual_offset(100000, 0) True - >>> 6553600001 == make_virtual_offset(100000,1) + >>> 6553600001 == make_virtual_offset(100000, 1) True - >>> 6553600010 == make_virtual_offset(100000,10) + >>> 6553600010 == make_virtual_offset(100000, 10) True - >>> make_virtual_offset(2**48,0) + >>> make_virtual_offset(2**48, 0) Traceback (most recent call last): ... ValueError: Require 0 <= block_start_offset < 2**48, got 281474976710656 @@ -321,10 +324,14 @@ decompressed length of the blocks contents (limited to 65536 in BGZF). - >>> from __builtin__ import open + >>> try: + ... from __builtin__ import open # Python 2 + ... except ImportError: + ... from builtins import open # Python 3 + ... >>> handle = open("SamBam/ex1.bam", "rb") >>> for values in BgzfBlocks(handle): - ... print "Raw start %i, raw length %i; data start %i, data length %i" % values + ... print("Raw start %i, raw length %i; data start %i, data length %i" % values) Raw start 0, raw length 18239; data start 0, data length 65536 Raw start 18239, raw length 18223; data start 65536, data length 65536 Raw start 36462, raw length 18017; data start 131072, data length 65536 @@ -346,7 +353,7 @@ >>> handle = open("SamBam/ex1_refresh.bam", "rb") >>> for values in BgzfBlocks(handle): - ... print "Raw start %i, raw length %i; data start %i, data length %i" % values + ... print("Raw start %i, raw length %i; data start %i, data length %i" % values) Raw start 0, raw length 53; data start 0, data length 38 Raw start 53, raw length 18195; data start 38, data length 65434 Raw start 18248, raw length 18190; data start 65472, data length 65409 @@ -365,7 +372,7 @@ >>> handle = open("SamBam/ex1_header.bam", "rb") >>> for values in BgzfBlocks(handle): - ... print "Raw start %i, raw length %i; data start %i, data length %i" % values + ... print("Raw start %i, raw length %i; data start %i, data length %i" % values) Raw start 0, raw length 104; data start 0, data length 103 Raw start 104, raw length 18195; data start 103, data length 65434 Raw start 18299, raw length 18190; data start 65537, data length 65409 @@ -442,10 +449,14 @@ Let's use the BgzfBlocks function to have a peak at the BGZF blocks in an example BAM file, - >>> from __builtin__ import open + >>> try: + ... from __builtin__ import open # Python 2 + ... except ImportError: + ... from builtins import open # Python 3 + ... >>> handle = open("SamBam/ex1.bam", "rb") >>> for values in BgzfBlocks(handle): - ... print "Raw start %i, raw length %i; data start %i, data length %i" % values + ... print("Raw start %i, raw length %i; data start %i, data length %i" % values) Raw start 0, raw length 18239; data start 0, data length 65536 Raw start 18239, raw length 18223; data start 65536, data length 65536 Raw start 36462, raw length 18017; data start 131072, data length 65536 @@ -517,12 +528,12 @@ if "w" in mode.lower() \ or "a" in mode.lower(): raise ValueError("Must use read mode (default), not write or append mode") - handle = __builtin__.open(filename, "rb") + handle = _open(filename, "rb") self._text = "b" not in mode.lower() if self._text: self._newline = "\n" else: - self._newline = _bytes_newline + self._newline = b"\n" self._handle = handle self.max_cache = max_cache self._buffers = {} @@ -562,7 +573,7 @@ if self._text: self._buffer = "" else: - self._buffer = _empty_bytes_string + self._buffer = b"" self._within_block_offset = 0 self._block_raw_length = block_size #Finally save the block in our cache, @@ -612,7 +623,7 @@ if self._text: return "" else: - return _empty_bytes_string + return b"" elif self._within_block_offset + size <= len(self._buffer): #This may leave us right at the end of a block #(lazy loading, don't load the next block unless we have too) @@ -661,12 +672,17 @@ #assert data.endswith(self._newline) return data - def next(self): + def __next__(self): line = self.readline() if not line: raise StopIteration return line + if sys.version_info[0] < 3: + def next(self): + """Python 2 style alias for Python 3 style __next__ method.""" + return self.__next__() + def __iter__(self): return self @@ -697,16 +713,16 @@ and "a" not in mode.lower(): raise ValueError("Must use write or append mode, not %r" % mode) if "a" in mode.lower(): - handle = __builtin__.open(filename, "ab") + handle = _open(filename, "ab") else: - handle = __builtin__.open(filename, "wb") + handle = _open(filename, "wb") self._text = "b" not in mode.lower() self._handle = handle - self._buffer = _empty_bytes_string + self._buffer = b"" self.compresslevel = compresslevel def _write_block(self, block): - #print "Saving %i bytes" % len(block) + #print("Saving %i bytes" % len(block)) start_offset = self._handle.tell() assert len(block) <= 65536 #Giving a negative window bits means no gzip/zlib headers, -15 used in samtools @@ -725,7 +741,7 @@ else: crc = struct.pack("= 65536: self._write_block(self._buffer[:65536]) @@ -759,7 +775,7 @@ self._write_block(self._buffer[:65535]) self._buffer = self._buffer[65535:] self._write_block(self._buffer) - self._buffer = _empty_bytes_string + self._buffer = b"" self._handle.flush() def close(self): @@ -791,19 +807,19 @@ if __name__ == "__main__": import sys if len(sys.argv) > 1: - print "Call this with no arguments and pipe uncompressed data in on stdin" - print "and it will produce BGZF compressed data on stdout. e.g." - print - print "./bgzf.py < example.fastq > example.fastq.bgz" - print - print "The extension convention of *.bgz is to distinugish these from *.gz" - print "used for standard gzipped files without the block structure of BGZF." - print "You can use the standard gunzip command to decompress BGZF files," - print "if it complains about the extension try something like this:" - print - print "cat example.fastq.bgz | gunzip > example.fastq" - print - print "See also the tool bgzip that comes with samtools" + print("Call this with no arguments and pipe uncompressed data in on stdin") + print("and it will produce BGZF compressed data on stdout. e.g.") + print("") + print("./bgzf.py < example.fastq > example.fastq.bgz") + print("") + print("The extension convention of *.bgz is to distinugish these from *.gz") + print("used for standard gzipped files without the block structure of BGZF.") + print("You can use the standard gunzip command to decompress BGZF files,") + print("if it complains about the extension try something like this:") + print("") + print("cat example.fastq.bgz | gunzip > example.fastq") + print("") + print("See also the tool bgzip that comes with samtools") sys.exit(0) sys.stderr.write("Producing BGZF output from stdin...\n") @@ -816,3 +832,4 @@ #Doing close with write an empty BGZF block as EOF marker: w.close() sys.stderr.write("BGZF data produced\n") + diff -Nru python-biopython-1.62/Bio/motifs/__init__.py python-biopython-1.63/Bio/motifs/__init__.py --- python-biopython-1.62/Bio/motifs/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/motifs/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -13,6 +13,10 @@ Bio.motifs is replacing the older and now obsolete Bio.Motif module. """ +from __future__ import print_function + +from Bio._py3k import range + import math @@ -39,8 +43,8 @@ For example: >>> from Bio import motifs - >>> for m in motifs.parse(open("Motif/alignace.out"),"AlignAce"): - ... print m.consensus + >>> for m in motifs.parse(open("Motif/alignace.out"), "AlignAce"): + ... print(m.consensus) TCTACGATTGAG CTGCAGCTAGCTACGAGTGAG GTGCTCTAAGCATAGTAGGCG @@ -98,7 +102,7 @@ Or a single-motif MEME file, >>> from Bio import motifs - >>> m = motifs.read(open("motifs/meme.out"),"meme") + >>> m = motifs.read(open("motifs/meme.out"), "meme") >>> m.consensus Seq('CTCAATCGTA', IUPACUnambiguousDNA()) @@ -106,7 +110,7 @@ an exception is raised: >>> from Bio import motifs - >>> motif = motifs.read(open("motifs/alignace.out"),"AlignAce") + >>> motif = motifs.read(open("motifs/alignace.out"), "AlignAce") Traceback (most recent call last): ... ValueError: More than one motif found in handle @@ -116,7 +120,7 @@ shown in the example above). Instead use: >>> from Bio import motifs - >>> record = motifs.parse(open("motifs/alignace.out"),"alignace") + >>> record = motifs.parse(open("motifs/alignace.out"), "alignace") >>> motif = record[0] >>> motif.consensus Seq('TCTACGATTGAG', IUPACUnambiguousDNA()) @@ -187,10 +191,10 @@ """ a generator function, returning found positions of motif instances in a given sequence """ - for pos in xrange(0,len(sequence)-self.length+1): + for pos in range(0, len(sequence)-self.length+1): for instance in self: if str(instance) == str(sequence[pos:pos+self.length]): - yield(pos,instance) + yield(pos, instance) break # no other instance will fit (we don't want to return multiple hits) def reverse_complement(self): instances = Instances(alphabet=self.alphabet) @@ -206,7 +210,7 @@ A class representing sequence motifs. """ def __init__(self, alphabet=None, instances=None, counts=None): - import matrix + from . import matrix from Bio.Alphabet import IUPAC self.name="" if counts is not None and instances is not None: @@ -317,7 +321,7 @@ text += str(self.instances) if masked: - for i in xrange(self.length): + for i in range(self.length): if self.__mask[i]: text += "*" else: @@ -423,34 +427,34 @@ 'color4': '', """ - import urllib - import urllib2 + from Bio._py3k import urlopen, urlencode, Request + frequencies = self.format('transfac') url = 'http://weblogo.threeplusone.com/create.cgi' - values = {'sequences' : frequencies, - 'format' : format.lower(), - 'stack_width' : 'medium', - 'stack_per_line' : '40', - 'alphabet' : 'alphabet_dna', - 'ignore_lower_case' : True, - 'unit_name' : "bits", - 'first_index' : '1', - 'logo_start' : '1', + values = {'sequences': frequencies, + 'format': format.lower(), + 'stack_width': 'medium', + 'stack_per_line': '40', + 'alphabet': 'alphabet_dna', + 'ignore_lower_case': True, + 'unit_name': "bits", + 'first_index': '1', + 'logo_start': '1', 'logo_end': str(self.length), - 'composition' : "comp_auto", - 'percentCG' : '', - 'scale_width' : True, - 'show_errorbars' : True, - 'logo_title' : '', - 'logo_label' : '', + 'composition': "comp_auto", + 'percentCG': '', + 'scale_width': True, + 'show_errorbars': True, + 'logo_title': '', + 'logo_label': '', 'show_xaxis': True, 'xaxis_label': '', 'show_yaxis': True, 'yaxis_label': '', 'yaxis_scale': 'auto', - 'yaxis_tic_interval' : '1.0', - 'show_ends' : True, - 'show_fineprint' : True, + 'yaxis_tic_interval': '1.0', + 'show_ends': True, + 'show_fineprint': True, 'color_scheme': 'color_auto', 'symbols0': '', 'symbols1': '', @@ -463,20 +467,18 @@ 'color3': '', 'color4': '', } - for k,v in kwds.iteritems(): - if type(values[k])==bool: + for k, v in kwds.items(): + if isinstance(values[k], bool): if not v: v = "" values[k]=str(v) - data = urllib.urlencode(values) - req = urllib2.Request(url, data) - response = urllib2.urlopen(req) - f = open(fname,"w") - im = response.read() - - f.write(im) - f.close() + data = urlencode(values) + req = Request(url, data) + response = urlopen(req) + with open(fname,"w") as f: + im = response.read() + f.write(im) def format(self, format): """Returns a string representation of the Motif in a given format @@ -517,3 +519,5 @@ return transfac.write(motifs) else: raise ValueError("Unknown format type %s" % format) + + diff -Nru python-biopython-1.62/Bio/motifs/alignace.py python-biopython-1.63/Bio/motifs/alignace.py --- python-biopython-1.62/Bio/motifs/alignace.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/motifs/alignace.py 2013-12-05 14:10:43.000000000 +0000 @@ -19,9 +19,9 @@ def read(handle): """read(handle)""" record = Record() - line = handle.next() + line = next(handle) record.version = line.strip() - line = handle.next() + line = next(handle) record.command = line.strip() for line in handle: line = line.strip() @@ -53,7 +53,7 @@ motif.mask = mask record.append(motif) elif len(line.split("\t"))==4: - seq = Seq(line.split("\t")[0],IUPAC.unambiguous_dna) + seq = Seq(line.split("\t")[0], IUPAC.unambiguous_dna) instances.append(seq) elif "*" in line: mask = line.strip("\r\n") diff -Nru python-biopython-1.62/Bio/motifs/applications/__init__.py python-biopython-1.63/Bio/motifs/applications/__init__.py --- python-biopython-1.62/Bio/motifs/applications/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/motifs/applications/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -4,6 +4,6 @@ # license. Please see the LICENSE file that should have been included # as part of this package. """Motif command line tool wrappers.""" -from _alignace import AlignAceCommandline -from _alignace import CompareAceCommandline -from _xxmotif import XXmotifCommandline +from ._alignace import AlignAceCommandline +from ._alignace import CompareAceCommandline +from ._xxmotif import XXmotifCommandline diff -Nru python-biopython-1.62/Bio/motifs/applications/_alignace.py python-biopython-1.63/Bio/motifs/applications/_alignace.py --- python-biopython-1.62/Bio/motifs/applications/_alignace.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/motifs/applications/_alignace.py 2013-12-05 14:10:43.000000000 +0000 @@ -23,6 +23,8 @@ 1998 Oct;16(10):939-45. """ +from __future__ import print_function + from Bio.Application import AbstractCommandline, _Option, _Argument import warnings @@ -37,7 +39,7 @@ >>> from Bio.motifs.applications import AlignAceCommandline >>> in_file = "sequences.fasta" >>> alignace_cline = AlignAceCommandline(infile=in_file, gcback=0.55) - >>> print alignace_cline + >>> print(alignace_cline) AlignACE -i sequences.fasta -gcback 0.55 You would typically run the command line with alignace_cline() or via @@ -105,7 +107,7 @@ >>> m1_file = "sequences1.fasta" >>> m2_file = "sequences2.fasta" >>> compareace_cline = CompareAceCommandline(motif1=m1_file, motif2=m2_file) - >>> print compareace_cline + >>> print(compareace_cline) CompareACE sequences1.fasta sequences2.fasta You would typically run the command line with compareace_cline() or via @@ -134,10 +136,10 @@ def _test(): """Run the module's doctests (PRIVATE).""" - print "Running alignace doctests..." + print("Running alignace doctests...") import doctest doctest.testmod() - print "Done" + print("Done") if __name__ == "__main__": diff -Nru python-biopython-1.62/Bio/motifs/applications/_xxmotif.py python-biopython-1.63/Bio/motifs/applications/_xxmotif.py --- python-biopython-1.62/Bio/motifs/applications/_xxmotif.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/motifs/applications/_xxmotif.py 2013-12-05 14:10:43.000000000 +0000 @@ -6,6 +6,8 @@ # as part of this package. """Command line wrapper for the motif finding program XXmotif.""" +from __future__ import print_function + import os from Bio.Application import AbstractCommandline, _Option, _Switch, _Argument @@ -21,7 +23,7 @@ >>> out_dir = "results" >>> in_file = "sequences.fasta" >>> xxmotif_cline = XXmotifCommandline(outdir=out_dir, seqfile=in_file, revcomp=True) - >>> print xxmotif_cline + >>> print(xxmotif_cline) XXmotif results sequences.fasta --revcomp You would typically run the command line with xxmotif_cline() or via @@ -60,31 +62,32 @@ checker_function = lambda x: os.path.split(x)[0] == ""), # Options - _Option(["--negSet", "negSet", "negset", "NEGSET"], + _Option(["--negSet", "negSet", "NEGSET", "negset"], "sequence set which has to be used as a reference set", filename = True, equate = False), - _Switch(["--zoops", "zoops", "ZOOPS"], + _Switch(["--zoops", "ZOOPS", "zoops"], "use zero-or-one occurrence per sequence model (DEFAULT)"), - _Switch(["--mops", "mops", "MOPS"], + _Switch(["--mops", "MOPS", "mops"], "use multiple occurrence per sequence model"), - _Switch(["--oops", "oops", "OOPS"], + _Switch(["--oops", "OOPS", "oops"], "use one occurrence per sequence model"), - _Switch(["--revcomp", "revcomp", "REVCOMP"], + _Switch(["--revcomp", "REVCOMP", "revcomp"], "search in reverse complement of sequences as well (DEFAULT: NO)"), - _Option(["--background-model-order", "background-model-order", "BACKGROUND-MODEL-ORDER"], + _Option(["--background-model-order", "background-model-order", "BACKGROUND-MODEL-ORDER", + "background_model_order"], "order of background distribution (DEFAULT: 2, 8(--negset) )", checker_function = lambda x: isinstance(x, int), equate = False), - _Option(["--pseudo", "pseudo", "PSEUDO"], + _Option(["--pseudo", "PSEUDO", "pseudo"], "percentage of pseudocounts used (DEFAULT: 10)", checker_function = lambda x: isinstance(x, int), equate = False), - _Option(["-g", "--gaps", "gaps", "GAPS"], + _Option(["-g", "--gaps", "GAPS", "gaps"], "maximum number of gaps used for start seeds [0-3] (DEFAULT: 0)", checker_function = lambda x: x in [0-3], equate = False), - _Option(["--type", "type", "TYPE"], + _Option(["--type", "TYPE", "type"], "defines what kind of start seeds are used (DEFAULT: ALL)" "possible types: ALL, FIVEMERS, PALINDROME, TANDEM, NOPALINDROME, NOTANDEM", checker_function = lambda x: x in ["ALL", "all", @@ -94,67 +97,71 @@ "NOPALINDROME", "nopalindrome", "NOTANDEM", "notandem"], equate = False), - _Option(["--merge-motif-threshold", "merge-motif-threshold", "MERGE-MOTIF-THRESHOLD"], + _Option(["--merge-motif-threshold", "merge-motif-threshold", "MERGE-MOTIF-THRESHOLD", + "merge_motif_threshold"], "defines the similarity threshold for merging motifs (DEFAULT: HIGH)" "possible modes: LOW, MEDIUM, HIGH", checker_function = lambda x: x in ["LOW", "low", "MEDIUM", "medium", "HIGH", "high"], equate = False), - _Switch(["--no-pwm-length-optimization", "no-pwm-length-optimization", "NO-PWM-LENGTH-OPTIMIZATION"], + _Switch(["--no-pwm-length-optimization", "no-pwm-length-optimization", "NO-PWM-LENGTH-OPTIMIZATION", + "no_pwm_length_optimization"], "do not optimize length during iterations (runtime advantages)"), - _Option(["--max-match-positions", "max-match-positions", "MAX-MATCH-POSITIONS"], + _Option(["--max-match-positions", "max-match-positions", "MAX-MATCH-POSITIONS", + "max_match_positions"], "max number of positions per motif (DEFAULT: 17, higher values will lead to very long runtimes)", checker_function = lambda x: isinstance(x, int), equate = False), - _Switch(["--batch", "batch", "BATCH"], + _Switch(["--batch", "BATCH", "batch"], "suppress progress bars (reduce output size for batch jobs)"), - _Option(["--maxPosSetSize", "maxPosSetSize", "maxpossetsize", "MAXPOSSETSIZE"], + _Option(["--maxPosSetSize", "maxPosSetSize", "MAXPOSSETSIZE", "maxpossetsize"], "maximum number of sequences from the positive set used [DEFAULT: all]", checker_function = lambda x: isinstance(x, int), equate = False), # does not make sense in biopython #_Switch(["--help", "help", "HELP"], # "print this help page"), - _Option(["--trackedMotif", "trackedMotif", "trackedmotif", "TRACKEDMOTIF"], + _Option(["--trackedMotif", "trackedMotif", "TRACKEDMOTIF", "trackedmotif"], "inspect extensions and refinement of a given seed (DEFAULT: not used)", checker_function = lambda x: any((c in _valid_alphabet) for c in x), equate = False), # Using conservation information - _Option(["--format", "format", "FORMAT"], + _Option(["--format", "FORMAT", "format"], "defines what kind of format the input sequences have (DEFAULT: FASTA)", checker_function = lambda x: x in ["FASTA", "fasta", "MFASTA", "mfasta"], equate = False), - _Option(["--maxMultipleSequences", "maxMultipleSequences", "maxmultiplesequences", "MAXMULTIPLESEQUENCES"], + _Option(["--maxMultipleSequences", "maxMultipleSequences", "MAXMULTIPLESEQUENCES", + "maxmultiplesequences"], "maximum number of sequences used in an alignment [DEFAULT: all]", checker_function = lambda x: isinstance(x, int), equate = False), # Using localization information - _Switch(["--localization", "localization", "LOCALIZATION"], + _Switch(["--localization", "LOCALIZATION", "localization"], "use localization information to calculate combined P-values" "(sequences should have all the same length)"), - _Option(["--downstream", "downstream", "DOWNSTREAM"], + _Option(["--downstream", "DOWNSTREAM", "downstream"], "number of residues in positive set downstream of anchor point (DEFAULT: 0)", checker_function = lambda x: isinstance(x, int), equate = False), # Start with self defined motif - _Option(["-m", "--startMotif", "startMotif", "startmotif", "STARTMOTIF"], + _Option(["-m", "--startMotif", "startMotif", "STARTMOTIF", "startmotif"], "Start motif (IUPAC characters)", checker_function = lambda x: any((c in _valid_alphabet) for c in x), equate = False), - _Option(["-p", "--profileFile", "profileFile", "profilefile", "PROFILEFILE"], + _Option(["-p", "--profileFile", "profileFile", "PROFILEFILE", "profilefile"], "profile file", filename = True, equate = False), - _Option(["--startRegion", "startRegion", "startregion", "STARTREGION"], + _Option(["--startRegion", "startRegion", "STARTREGION", "startregion"], "expected start position for motif occurrences relative to anchor point (--localization)", checker_function = lambda x: isinstance(x, int), equate = False), - _Option(["--endRegion", "endRegion", "endregion", "ENDREGION"], + _Option(["--endRegion", "endRegion", "ENDREGION", "endregion"], "expected end position for motif occurrences relative to anchor point (--localization)", checker_function = lambda x: isinstance(x, int), equate = False), @@ -172,10 +179,10 @@ def _test(): """Run the module's doctests (PRIVATE).""" - print "Running XXmotif doctests..." + print("Running XXmotif doctests...") import doctest doctest.testmod() - print "Done" + print("Done") if __name__ == "__main__": diff -Nru python-biopython-1.62/Bio/motifs/jaspar/__init__.py python-biopython-1.63/Bio/motifs/jaspar/__init__.py --- python-biopython-1.62/Bio/motifs/jaspar/__init__.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/motifs/jaspar/__init__.py 2013-12-05 14:10:43.000000000 +0000 @@ -7,6 +7,8 @@ import re import math +from Bio._py3k import range + from Bio import motifs @@ -127,7 +129,7 @@ self.version = None def __str__(self): - return "\n".join([str(the_motif) for the_motif in self]) + return "\n".join(str(the_motif) for the_motif in self) def to_dict(self): """ @@ -204,7 +206,7 @@ #if there is a letter in the beginning, ignore it if words[0] == letter: words = words[1:] - counts[letter] = map(float, words) + counts[letter] = [float(x) for x in words] motif = Motif(matrix_id=None, name=None, alphabet=alphabet, counts=counts) motif.mask = "*" * motif.length @@ -227,7 +229,7 @@ break # line contains the header ">...." # now read the actual sequence - line = handle.next() + line = next(handle) instance = "" for c in line.strip(): if c == c.upper(): @@ -287,7 +289,7 @@ words = counts_str.split() - counts[letter] = map(float, words) + counts[letter] = [float(x) for x in words] row_count += 1 @@ -309,8 +311,8 @@ # It is possible to have unequal column sums so use the average # number of instances. total = 0 - for i in xrange(motif.length): - total += sum([float(motif.counts[letter][i]) for letter in alphabet.letters]) + for i in range(motif.length): + total += sum(float(motif.counts[letter][i]) for letter in alphabet.letters) avg_nb_instances = total / motif.length sq_nb_instances = math.sqrt(avg_nb_instances) diff -Nru python-biopython-1.62/Bio/motifs/jaspar/db.py python-biopython-1.63/Bio/motifs/jaspar/db.py --- python-biopython-1.62/Bio/motifs/jaspar/db.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/motifs/jaspar/db.py 2013-12-05 14:10:43.000000000 +0000 @@ -2,10 +2,9 @@ # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. -""" -This modules requires MySQLdb to be installed. +"""Provides read access to a JASPAR5 formatted database. -Provides read access to a JASPAR5 formatted database. +This modules requires MySQLdb to be installed. Example, substitute the your database credentials as appropriate: @@ -27,7 +26,7 @@ >>> >>> >>> ets1 = jdb.fetch_motif_by_id('MA0098') - >>> print ets1 + >>> print(ets1) TF name ETS1 Matrix ID MA0098.1 Collection CORE @@ -62,6 +61,8 @@ """ +from __future__ import print_function + from Bio import MissingPythonDependencyError try: @@ -419,7 +420,7 @@ for row in rows: base_counts.append(row[0]) - counts[base] = map(float, base_counts) + counts[base] = [float(x) for x in base_counts] return matrix.GenericPositionMatrix(dna, counts) @@ -730,3 +731,4 @@ return True return False + diff -Nru python-biopython-1.62/Bio/motifs/mast.py python-biopython-1.63/Bio/motifs/mast.py --- python-biopython-1.62/Bio/motifs/mast.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/motifs/mast.py 2013-12-05 14:10:43.000000000 +0000 @@ -4,6 +4,8 @@ # license. Please see the LICENSE file that should have been included # as part of this package. +from __future__ import print_function + from Bio.Alphabet import IUPAC from Bio.motifs import meme @@ -18,14 +20,14 @@ motifs in the record by their index. Alternatively, you can find a motif by its name: - >>> f = open("mast.output.txt") >>> from Bio import motifs - >>> record = motifs.parse(f, 'MAST') + >>> with open("mast.output.txt") as f: + ... record = motifs.parse(f, 'MAST') >>> motif = record[0] - >>> print motif.name + >>> print(motif.name) 1 >>> motif = record['1'] - >>> print motif.name + >>> print(motif.name) 1 """ @@ -72,10 +74,10 @@ for line in handle: if line.startswith('DATABASE AND MOTIFS'): break - line = handle.next() + line = next(handle) if not line.startswith('****'): raise ValueError("Line does not start with '****':\n%s" % line) - line = handle.next() + line = next(handle) if not 'DATABASE' in line: raise ValueError("Line does not contain 'DATABASE':\n%s" % line) words = line.strip().split() @@ -87,7 +89,7 @@ for line in handle: if 'MOTIF WIDTH' in line: break - line = handle.next() + line = next(handle) if not '----' in line: raise ValueError("Line does not contain '----':\n%s" % line) for line in handle: @@ -108,7 +110,7 @@ for line in handle: if line.startswith('SEQUENCE NAME'): break - line = handle.next() + line = next(handle) if not line.startswith('---'): raise ValueError("Line does not start with '---':\n%s" % line) for line in handle: @@ -117,7 +119,7 @@ else: sequence, description_evalue_length = line.split(None, 1) record.sequences.append(sequence) - line = handle.next() + line = next(handle) if not line.startswith('****'): raise ValueError("Line does not start with '****':\n%s" % line) @@ -129,7 +131,7 @@ for line in handle: if line.startswith('SEQUENCE NAME'): break - line = handle.next() + line = next(handle) if not line.startswith('---'): raise ValueError("Line does not start with '---':\n%s" % line) for line in handle: @@ -141,7 +143,7 @@ else: sequence, pvalue, diagram = line.split() record.diagrams[sequence] = diagram - line = handle.next() + line = next(handle) if not line.startswith('****'): raise ValueError("Line does not start with '****':\n%s" % line) @@ -159,3 +161,4 @@ for line in handle: if line.strip(): break + diff -Nru python-biopython-1.62/Bio/motifs/matrix.py python-biopython-1.63/Bio/motifs/matrix.py --- python-biopython-1.62/Bio/motifs/matrix.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/motifs/matrix.py 2013-12-05 14:10:43.000000000 +0000 @@ -7,6 +7,9 @@ """ import math + +from Bio._py3k import range + from Bio.Seq import Seq from Bio.Alphabet import IUPAC @@ -231,7 +234,7 @@ alphabet = self.alphabet gc_total = 0.0 total = 0.0 - for i in xrange(self.length): + for i in range(self.length): for letter in alphabet.letters: if letter in 'CG': gc_total += self[letter][i] @@ -272,7 +275,7 @@ else: for letter in self.alphabet.letters: counts[letter] = [float(pseudocounts)] * self.length - for i in xrange(self.length): + for i in range(self.length): for letter in self.alphabet.letters: counts[letter][i] += self[letter][i] # Actual normalization is done in the PositionWeightMatrix initializer @@ -283,8 +286,8 @@ def __init__(self, alphabet, counts): GenericPositionMatrix.__init__(self, alphabet, counts) - for i in xrange(self.length): - total = sum([float(self[letter][i]) for letter in alphabet.letters]) + for i in range(self.length): + total = sum(float(self[letter][i]) for letter in alphabet.letters) for letter in alphabet.letters: self[letter][i] /= total for letter in alphabet.letters: @@ -369,9 +372,9 @@ # use the slower Python code otherwise #The C code handles mixed case so Python version must too: sequence = sequence.upper() - for i in xrange(n-m+1): + for i in range(n-m+1): score = 0.0 - for position in xrange(m): + for position in range(m): letter = sequence[i+position] try: score += self[letter][position] @@ -398,7 +401,7 @@ m = self.length if both: rc = self.reverse_complement() - for position in xrange(0,n-m+1): + for position in range(0, n-m+1): s = sequence[position:position+m] score = self.calculate(s) if score > threshold: @@ -416,8 +419,8 @@ """ score = 0.0 letters = self._letters - for position in xrange(0,self.length): - score += max([self[letter][position] for letter in letters]) + for position in range(0, self.length): + score += max(self[letter][position] for letter in letters) return score @property @@ -428,8 +431,8 @@ """ score = 0.0 letters = self._letters - for position in xrange(0,self.length): - score += min([self[letter][position] for letter in letters]) + for position in range(0, self.length): + score += min(self[letter][position] for letter in letters) return score @property @@ -448,13 +451,13 @@ sx = 0.0 for i in range(self.length): for letter in self._letters: - logodds = self[letter,i] + logodds = self[letter, i] if _isnan(logodds): continue if _isinf(logodds) and logodds < 0: continue b = background[letter] - p = b * math.pow(2,logodds) + p = b * math.pow(2, logodds) sx += p * logodds return sx @@ -472,13 +475,13 @@ sx = 0.0 sxx = 0.0 for letter in self._letters: - logodds = self[letter,i] + logodds = self[letter, i] if _isnan(logodds): continue if _isinf(logodds) and logodds < 0: continue b = background[letter] - p = b * math.pow(2,logodds) + p = b * math.pow(2, logodds) sx += p*logodds sxx += p*logodds*logodds sxx -= sx*sx @@ -504,7 +507,7 @@ if max_p>> f = open("meme.output.txt") >>> from Bio.Motif import MEME - >>> record = MEME.parse(f) + >>> with open("meme.output.txt") as f: + ... record = MEME.parse(f) >>> for motif in record: ... for instance in motif.instances: - ... print instance.motif_name, instance.sequence_name, instance.strand, instance.pvalue + ... print(instance.motif_name, instance.sequence_name, instance.strand, instance.pvalue) """ record = Record() @@ -47,7 +49,7 @@ record.append(motif) __skip_unused_lines(handle) try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError('Unexpected end of stream: Expected to find new motif, or the summary of motifs') if line.startswith("SUMMARY OF MOTIFS"): @@ -94,14 +96,14 @@ motifs in the record by their index. Alternatively, you can find a motif by its name: - >>> f = open("meme.output.txt") >>> from Bio import motifs - >>> record = motifs.parse(f, 'MEME') + >>> with open("meme.output.txt") as f: + ... record = motifs.parse(f, 'MEME') >>> motif = record[0] - >>> print motif.name + >>> print(motif.name) Motif 1 >>> motif = record['Motif 1'] - >>> print motif.name + >>> print(motif.name) Motif 1 """ @@ -143,31 +145,31 @@ else: raise ValueError("Unexpected end of stream: 'TRAINING SET' not found.") try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError("Unexpected end of stream: Expected to find line starting with '****'") if not line.startswith('****'): raise ValueError("Line does not start with '****':\n%s" % line) try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError("Unexpected end of stream: Expected to find line starting with 'DATAFILE'") if not line.startswith('DATAFILE'): raise ValueError("Line does not start with 'DATAFILE':\n%s" % line) line = line.strip() - line = line.replace('DATAFILE= ','') + line = line.replace('DATAFILE= ', '') record.datafile = line def __read_alphabet(record, handle): try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError("Unexpected end of stream: Expected to find line starting with 'ALPHABET'") if not line.startswith('ALPHABET'): raise ValueError("Line does not start with 'ALPHABET':\n%s" % line) line = line.strip() - line = line.replace('ALPHABET= ','') + line = line.replace('ALPHABET= ', '') if line == 'ACGT': al = IUPAC.unambiguous_dna else: @@ -177,13 +179,13 @@ def __read_sequences(record, handle): try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError("Unexpected end of stream: Expected to find line starting with 'Sequence name'") if not line.startswith('Sequence name'): raise ValueError("Line does not start with 'Sequence name':\n%s" % line) try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError("Unexpected end of stream: Expected to find line starting with '----'") if not line.startswith('----'): @@ -207,7 +209,7 @@ else: raise ValueError("Unexpected end of stream: Expected to find line starting with 'command'") line = line.strip() - line = line.replace('command: ','') + line = line.replace('command: ', '') record.command = line @@ -234,19 +236,19 @@ def __read_motif_sequences(handle, motif_name, alphabet, length, revcomp): try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError('Unexpected end of stream: Failed to find motif sequences') if not line.startswith('---'): raise ValueError("Line does not start with '---':\n%s" % line) try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError("Unexpected end of stream: Expected to find line starting with 'Sequence name'") if not line.startswith('Sequence name'): raise ValueError("Line does not start with 'Sequence name':\n%s" % line) try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError('Unexpected end of stream: Failed to find motif sequences') if not line.startswith('---'): @@ -303,13 +305,13 @@ else: raise ValueError("Unexpected end of stream: Expected to find line starting with 'Time'") try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError('Unexpected end of stream: Expected to find blank line') if line.strip(): raise ValueError("Expected blank line, but got:\n%s" % line) try: - line = handle.next() + line = next(handle) except StopIteration: raise ValueError("Unexpected end of stream: Expected to find line starting with '***'") if not line.startswith('***'): @@ -321,3 +323,4 @@ raise ValueError("Unexpected end of stream: Expected to find line starting with '***'") if not line.startswith('***'): raise ValueError("Line does not start with '***':\n%s" % line) + diff -Nru python-biopython-1.62/Bio/motifs/thresholds.py python-biopython-1.63/Bio/motifs/thresholds.py --- python-biopython-1.62/Bio/motifs/thresholds.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/motifs/thresholds.py 2013-12-05 14:10:43.000000000 +0000 @@ -31,41 +31,41 @@ self.bg_density = [0.0]*self.n_points self.bg_density[-self._index_diff(self.min_score)] = 1.0 if pssm is None: - for lo,mo in zip(motif.log_odds(),motif.pwm()): - self.modify(lo,mo,motif.background) + for lo, mo in zip(motif.log_odds(), motif.pwm()): + self.modify(lo, mo, motif.background) else: for position in range(pssm.length): mo_new=[0.0]*self.n_points bg_new=[0.0]*self.n_points - lo = pssm[:,position] - for letter, score in lo.iteritems(): + lo = pssm[:, position] + for letter, score in lo.items(): bg = background[letter] - mo = pow(2,pssm[letter,position]) * bg + mo = pow(2, pssm[letter, position]) * bg d=self._index_diff(score) for i in range(self.n_points): - mo_new[self._add(i,d)]+=self.mo_density[i]*mo - bg_new[self._add(i,d)]+=self.bg_density[i]*bg + mo_new[self._add(i, d)]+=self.mo_density[i]*mo + bg_new[self._add(i, d)]+=self.bg_density[i]*bg self.mo_density=mo_new self.bg_density=bg_new def _index_diff(self,x,y=0.0): return int((x-y+0.5*self.step)//self.step) - def _add(self,i,j): - return max(0,min(self.n_points-1,i+j)) + def _add(self, i, j): + return max(0, min(self.n_points-1, i+j)) - def modify(self,scores,mo_probs,bg_probs): + def modify(self, scores, mo_probs, bg_probs): mo_new=[0.0]*self.n_points bg_new=[0.0]*self.n_points - for k, v in scores.iteritems(): + for k, v in scores.items(): d=self._index_diff(v) for i in range(self.n_points): - mo_new[self._add(i,d)]+=self.mo_density[i]*mo_probs[k] - bg_new[self._add(i,d)]+=self.bg_density[i]*bg_probs[k] + mo_new[self._add(i, d)]+=self.mo_density[i]*mo_probs[k] + bg_new[self._add(i, d)]+=self.bg_density[i]*bg_probs[k] self.mo_density=mo_new self.bg_density=bg_new - def threshold_fpr(self,fpr): + def threshold_fpr(self, fpr): """ Approximate the log-odds threshold which makes the type I error (false positive rate). """ @@ -76,7 +76,7 @@ prob+=self.bg_density[i] return self.min_score+i*self.step - def threshold_fnr(self,fnr): + def threshold_fnr(self, fnr): """ Approximate the log-odds threshold which makes the type II error (false negative rate). """ @@ -99,7 +99,7 @@ fpr+=self.bg_density[i] fnr-=self.mo_density[i] if return_rate: - return self.min_score+i*self.step,fpr + return self.min_score+i*self.step, fpr else: return self.min_score+i*self.step diff -Nru python-biopython-1.62/Bio/motifs/transfac.py python-biopython-1.63/Bio/motifs/transfac.py --- python-biopython-1.62/Bio/motifs/transfac.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/motifs/transfac.py 2013-12-05 14:10:43.000000000 +0000 @@ -93,7 +93,7 @@ record.version = value elif key in ('P0', 'PO'): # Old TRANSFAC files use PO instead of P0 counts = {} - assert value.split()[:4]==['A','C','G','T'] + assert value.split()[:4]==['A', 'C', 'G', 'T'] length = 0 for c in "ACGT": counts[c] = [] diff -Nru python-biopython-1.62/Bio/pairwise2.py python-biopython-1.63/Bio/pairwise2.py --- python-biopython-1.62/Bio/pairwise2.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/pairwise2.py 2013-12-05 14:10:43.000000000 +0000 @@ -55,7 +55,7 @@ # for mismatches or gaps. >>> from Bio.pairwise2 import format_alignment >>> for a in pairwise2.align.globalxx("ACCGT", "ACG"): - ... print format_alignment(*a) + ... print(format_alignment(*a)) ACCGT ||||| AC-G- @@ -69,7 +69,7 @@ # Same thing as before, but with a local alignment. >>> for a in pairwise2.align.localxx("ACCGT", "ACG"): - ... print format_alignment(*a) + ... print(format_alignment(*a)) ACCGT |||| AC-G- @@ -84,7 +84,7 @@ # Do a global alignment. Identical characters are given 2 points, # 1 point is deducted for each non-identical character. >>> for a in pairwise2.align.globalmx("ACCGT", "ACG", 2, -1): - ... print format_alignment(*a) + ... print(format_alignment(*a)) ACCGT ||||| AC-G- @@ -99,7 +99,7 @@ # Same as above, except now 0.5 points are deducted when opening a # gap, and 0.1 points are deducted when extending it. >>> for a in pairwise2.align.globalms("ACCGT", "ACG", 2, -1, -.5, -.1): - ... print format_alignment(*a) + ... print(format_alignment(*a)) ACCGT ||||| AC-G- @@ -117,7 +117,7 @@ >>> from Bio.SubsMat import MatrixInfo as matlist >>> matrix = matlist.blosum62 >>> for a in pairwise2.align.globaldx("KEVLA", "EVL", matrix): - ... print format_alignment(*a) + ... print(format_alignment(*a)) KEVLA ||||| -EVL- @@ -151,6 +151,8 @@ # - one_alignment_only: boolean # Only recover one alignment. +from __future__ import print_function + MAX_ALIGNMENTS = 1000 # maximum alignments recovered in traceback @@ -207,11 +209,11 @@ name[:-2], name[-2], name[-1] try: match_args, match_doc = self.match2args[match_type] - except KeyError, x: + except KeyError as x: raise AttributeError("unknown match type %r" % match_type) try: penalty_args, penalty_doc = self.penalty2args[penalty_type] - except KeyError, x: + except KeyError as x: raise AttributeError("unknown penalty type %r" % penalty_type) # Now get the names of the parameters to this function. @@ -337,8 +339,8 @@ score_only) score_matrix, trace_matrix = x - #print "SCORE"; print_matrix(score_matrix) - #print "TRACEBACK"; print_matrix(trace_matrix) + #print("SCORE %s" % print_matrix(score_matrix)) + #print("TRACEBACK %s" % print_matrix(trace_matrix)) # Look for the proper starting point. Get a list of all possible # starting points. @@ -852,11 +854,11 @@ for i in range(len(matrix)): for j in range(len(matrix[i])): matrixT[j].append(len(str(matrix[i][j]))) - ndigits = map(max, matrixT) + ndigits = [max(x) for x in matrixT] for i in range(len(matrix)): #Using string formatting trick to add leading spaces, - print " ".join("%*s " % (ndigits[j], matrix[i][j]) - for j in range(len(matrix[i]))) + print(" ".join("%*s " % (ndigits[j], matrix[i][j]) + for j in range(len(matrix[i])))) def format_alignment(align1, align2, score, begin, end): @@ -883,10 +885,10 @@ def _test(): """Run the module's doctests (PRIVATE).""" - print "Running doctests..." + print("Running doctests...") import doctest doctest.testmod(optionflags=doctest.IGNORE_EXCEPTION_DETAIL) - print "Done" + print("Done") if __name__ == "__main__": _test() diff -Nru python-biopython-1.62/Bio/triefind.py python-biopython-1.63/Bio/triefind.py --- python-biopython-1.62/Bio/triefind.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Bio/triefind.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """ Given a trie, find all occurrences of a word in the trie in a string. @@ -27,7 +32,7 @@ substr = string[:i+1] if not trie.has_prefix(substr): break - if trie.has_key(substr): + if substr in trie: longest = substr return longest @@ -44,7 +49,7 @@ substr = string[:i+1] if not trie.has_prefix(substr): break - if trie.has_key(substr): + if substr in trie: matches.append(substr) return matches diff -Nru python-biopython-1.62/BioSQL/BioSeq.py python-biopython-1.63/BioSQL/BioSeq.py --- python-biopython-1.62/BioSQL/BioSeq.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/BioSQL/BioSeq.py 2013-12-05 14:10:43.000000000 +0000 @@ -16,6 +16,8 @@ (like quality scores) in BioSQL. """ +from Bio._py3k import unicode + from Bio import Alphabet from Bio.Seq import Seq, UnknownSeq from Bio.SeqRecord import SeqRecord, _RestrictedDict diff -Nru python-biopython-1.62/BioSQL/BioSeqDatabase.py python-biopython-1.63/BioSQL/BioSeqDatabase.py --- python-biopython-1.62/BioSQL/BioSeqDatabase.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/BioSQL/BioSeqDatabase.py 2013-12-05 14:10:43.000000000 +0000 @@ -17,9 +17,9 @@ from Bio import BiopythonDeprecationWarning -import BioSeq -import Loader -import DBUtils +from . import BioSeq +from . import Loader +from . import DBUtils _POSTGRES_RULES_PRESENT = False # Hack for BioSQL Bug 2839 @@ -102,7 +102,7 @@ elif "db" in kw: kw["dbname"] = kw["db"] del kw["db"] - dsn = ' '.join(['='.join(i) for i in kw.items()]) + dsn = ' '.join('='.join(i) for i in kw.items()) conn = connect(dsn) if os.name == "java": @@ -175,11 +175,11 @@ def values(self): """List of BioSeqDatabase objects in the database.""" - return [self[key] for key in self.keys()] + return [self[key] for key in self] def items(self): """List of (namespace, BioSeqDatabase) for entries in the database.""" - return [(key, self[key]) for key in self.keys()] + return [(key, self[key]) for key in self] def iterkeys(self): """Iterate over namespaces (sub-databases) in the database.""" @@ -547,7 +547,7 @@ warnings.warn("Use bio_seq_database.keys() instead of " "bio_seq_database.get_all_primary_ids()", BiopythonDeprecationWarning) - return self.keys() + return list(self.keys()) def __getitem__(self, key): return BioSeq.DBSeqRecord(self.adaptor, key) @@ -593,11 +593,11 @@ def values(self): """List of DBSeqRecord objects in the namespace (sub database).""" - return [self[key] for key in self.keys()] + return [self[key] for key in self] def items(self): """List of (id, DBSeqRecord) for the namespace (sub database).""" - return [(key, self[key]) for key in self.keys()] + return [(key, self[key]) for key in self] def iterkeys(self): """Iterate over ids (which may not be meaningful outside this database).""" @@ -631,10 +631,10 @@ def lookup(self, **kwargs): if len(kwargs) != 1: raise TypeError("single key/value parameter expected") - k, v = kwargs.items()[0] + k, v = list(kwargs.items())[0] if k not in _allowed_lookups: - raise TypeError("lookup() expects one of %s, not %r" % - (repr(_allowed_lookups.keys())[1:-1], repr(k))) + raise TypeError("lookup() expects one of %r, not %r" % + (list(_allowed_lookups.keys()), k)) lookup_name = _allowed_lookups[k] lookup_func = getattr(self.adaptor, lookup_name) seqid = lookup_func(self.dbid, v) diff -Nru python-biopython-1.62/BioSQL/Loader.py python-biopython-1.63/BioSQL/Loader.py --- python-biopython-1.62/BioSQL/Loader.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/BioSQL/Loader.py 2013-12-05 14:10:43.000000000 +0000 @@ -16,6 +16,8 @@ a database object. """ # standard modules +from __future__ import print_function + from time import gmtime, strftime # biopython @@ -25,6 +27,8 @@ from Bio.Seq import UnknownSeq from Bio._py3k import _is_int_or_long +from Bio._py3k import range +from Bio._py3k import basestring class DatabaseLoader: @@ -56,7 +60,7 @@ self._load_comment(record, bioentry_id) self._load_dbxrefs(record, bioentry_id) references = record.annotations.get('references', ()) - for reference, rank in zip(references, range(len(references))): + for reference, rank in zip(references, list(range(len(references)))): self._load_reference(reference, rank, bioentry_id) self._load_annotations(record, bioentry_id) for seq_feature_num in range(len(record.features)): @@ -320,7 +324,7 @@ return " " + letter.lower() else: return letter - answer = "".join([add_space(letter) for letter in entrez_name]).strip() + answer = "".join(add_space(letter) for letter in entrez_name).strip() assert answer == answer.lower() return answer @@ -389,7 +393,7 @@ species_names = [("scientific name", taxonomic_record[0]["ScientificName"])] try: - for name_class, names in taxonomic_record[0]["OtherNames"].iteritems(): + for name_class, names in taxonomic_record[0]["OtherNames"].items(): name_class = self._fix_name_class(name_class) if not isinstance(names, list): #The Entrez parser seems to return single entry @@ -479,7 +483,7 @@ "INSERT INTO taxon(ncbi_taxon_id, parent_taxon_id, node_rank)" " VALUES (%s, %s, %s)", (ncbi_taxon_id, parent_taxon_id, rank)) taxon_id = self.adaptor.last_id("taxon") - assert isinstance(taxon_id, int) or isinstance(taxon_id, long), repr(taxon_id) + assert isinstance(taxon_id, (int, long)), repr(taxon_id) # ... and its name in taxon_name scientific_name = taxonomic_lineage[-1].get("ScientificName", None) if scientific_name: @@ -653,7 +657,7 @@ "(bioentry_id, term_id, value, rank)" \ " VALUES (%s, %s, %s, %s)" tag_ontology_id = self._get_ontology_id('Annotation Tags') - for key, value in record.annotations.iteritems(): + for key, value in record.annotations.items(): if key in ["references", "comment", "ncbi_taxid", "date"]: #Handled separately continue diff -Nru python-biopython-1.62/CONTRIB python-biopython-1.63/CONTRIB --- python-biopython-1.62/CONTRIB 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/CONTRIB 2013-12-05 14:10:43.000000000 +0000 @@ -24,17 +24,19 @@ Hye-Shik Chang Jeffrey Chang Brad Chapman -Peter Cock +Peter Cock Marc Colosimo Andres Colubri Cymon J Cox Gavin E Crooks Andrew Dalke +Wayne Decatur < https://github.com/fomightez > Michiel de Hoon Bart de Koning Sjoerd de Vries Nathan J. Edwards Kyle Ellrott +Gokcen Eraslan < https://github.com/gokceneraslan > Jeffrey Finkelstein Konrad Förstner < https://github.com/konrad > Iddo Friedberg @@ -58,12 +60,14 @@ Michal Kurowski Uri Laserson Chris Lasher +Sergei Lebedev < https://github.com/superbobry > Gaetan Lehman Katharine Lindner Bryan Lunt < https://github.com/bryan-lunt > Erick Matsen Connor McCoy Tarjei Mikkelsen +Chris Mitchell < https://github.com/chrismit > Ben Morris Konstantin Okonechnikov Cheng Soon Ong diff -Nru python-biopython-1.62/DEPRECATED python-biopython-1.63/DEPRECATED --- python-biopython-1.62/DEPRECATED 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/DEPRECATED 2013-12-05 14:10:43.000000000 +0000 @@ -14,14 +14,36 @@ Python 2.5 ========== -Biopython Release 1.62 will be the final release to support this, and -shows a warning during installation. +No longer supported as of Release 1.63, having triggered a warning with +Release 1.62, with advance notice in the release notes for Release 1.61. Python 3.0, 3.1, 3.2 ==================== Never officially supported, these trigger a warning in Release 1.62 recommending Python 3.3 or later if you wish to use Python 3. +Iterator .next() methods +======================== +The .next() method defined for any Biopython iterator is deprecated as of +Biopython 1.63 under Python 2 (and not present on Python 3). Please replace +my_iterator.next() with next(my_iterator) using the new built-in function +next() instead. + +Bio.SVDSuperimposer +=================== +As of Release 1.63, the main class (confusingly also called) SVDSuperimposer +is best imported as follows: + +>>> from Bio.SVDSuperimposer import SVDSuperimposer +>>> super_imposer = SVDSuperimposer() + +This short form also works on older releases. The longer even more +confusing historical alternatives dependent on the double module name +no longer work, e.g. you can no longer do this: + +>>> from Bio.SVDSuperimposer.SVDSuperimposer import SVDSuperimposer +>>> super_imposer = SVDSuperimposer() + Bio.PDB.mmCIF ============= This was removed in Release 1.62, when MMCIF2Dict was updated to use shlex @@ -109,8 +131,11 @@ Bio.Blast.Applications instead. The remainder of this module is a parser for the plain text BLAST output, -which was declared obsolete in Release 1.54. For some time now, both the NCBI -and Biopython have encouraged people to parse the XML output instead. +which was declared obsolete in Release 1.54, and deprecated in Release 1.63. + +For some time now, both the NCBI and Biopython have encouraged people to +parse the XML output instead, however Bio.SearchIO will initially attempt +to support plain text BLAST output. Bio.Blast.Applications ====================== @@ -551,7 +576,8 @@ Bio.ParserSupport ================= -Bio.ParserSupport was declared obsolete in Release 1.59. +Bio.ParserSupport was declared obsolete in Release 1.59, and deprecated in +Release 1.63. Bio.ParserSupport.SGMLStrippingConsumer was deprecated in Release 1.59, and removed in Release 1.61. diff -Nru python-biopython-1.62/Doc/Tutorial.html python-biopython-1.63/Doc/Tutorial.html --- python-biopython-1.62/Doc/Tutorial.html 2013-08-28 21:38:33.000000000 +0000 +++ python-biopython-1.63/Doc/Tutorial.html 2013-12-05 14:11:23.000000000 +0000 @@ -1,40 +1,45 @@ - - - -Biopython Tutorial and Cookbook - - - - - - - - -

+ +Biopython Tutorial and Cookbook + + + + +

[Biopython Logo]

-

-

Biopython Tutorial and Cookbook

Jeff Chang, Brad Chapman, Iddo Friedberg, Thomas Hamelryck,
-Michiel de Hoon, Peter Cock, Tiago Antao, Eric Talevich, Bartek Wilczyński

Last Update – 28 August 2013 (Biopython 1.62)

-

Contents

-

Chapter 1  Introduction

-

-

1.1  What is Biopython?

The Biopython Project is an international association of developers of freely available Python (http://www.python.org) tools for computational molecular biology. Python is an object oriented, interpreted, flexible language that is becoming increasingly popular for scientific computing. Python is easy to learn, has a very clear syntax and can easily be extended with modules written in C, C++ or FORTRAN.

The Biopython web site (http://www.biopython.org) provides +

+

Biopython Tutorial and Cookbook

Jeff Chang, Brad Chapman, Iddo Friedberg, Thomas Hamelryck,
+Michiel de Hoon, Peter Cock, Tiago Antao, Eric Talevich, Bartek Wilczyński

Last Update – 1 December 2013 (Biopython 1.63)

+

Contents

+ +

Chapter 1  Introduction

+

+ +

1.1  What is Biopython?

The Biopython Project is an international association of developers of freely available Python (http://www.python.org) tools for computational molecular biology. Python is an object oriented, interpreted, flexible language that is becoming increasingly popular for scientific computing. Python is easy to learn, has a very clear syntax and can easily be extended with modules written in C, C++ or FORTRAN.

The Biopython web site (http://www.biopython.org) provides an online resource for modules, scripts, and web links for developers of Python-based software for bioinformatics use and research. Basically, the goal of Biopython is to make it as easy as possible to use Python @@ -536,239 +544,260 @@ file formats (BLAST, Clustalw, FASTA, Genbank,...), access to online services (NCBI, Expasy,...), interfaces to common and not-so-common programs (Clustalw, DSSP, MSMS...), a standard sequence class, various -clustering modules, a KD tree data structure etc. and even documentation.

Basically, we just like to program in Python and want to make it as easy as possible to use Python for bioinformatics by creating high-quality, reusable modules and scripts.

-

1.2  What can I find in the Biopython package

The main Biopython releases have lots of functionality, including:

  • -The ability to parse bioinformatics files into Python utilizable data structures, including support for the following formats:
    • +clustering modules, a KD tree data structure etc. and even documentation.

      Basically, we just like to program in Python and want to make it as easy as possible to use Python for bioinformatics by creating high-quality, reusable modules and scripts.

      + +

      1.2  What can I find in the Biopython package

      The main Biopython releases have lots of functionality, including:

      • +The ability to parse bioinformatics files into Python utilizable data structures, including support for the following formats:
        • Blast output – both from standalone and WWW Blast -
        • Clustalw -
        • FASTA -
        • GenBank -
        • PubMed and Medline -
        • ExPASy files, like Enzyme and Prosite -
        • SCOP, including ‘dom’ and ‘lin’ files -
        • UniGene -
        • SwissProt -
      • Files in the supported formats can be iterated over record by record or indexed and accessed via a Dictionary interface.
      • Code to deal with popular on-line bioinformatics destinations such as:
        • +
        • Clustalw +
        • FASTA +
        • GenBank +
        • PubMed and Medline +
        • ExPASy files, like Enzyme and Prosite +
        • SCOP, including ‘dom’ and ‘lin’ files +
        • UniGene +
        • SwissProt +
      • Files in the supported formats can be iterated over record by record or indexed and accessed via a Dictionary interface.
      • Code to deal with popular on-line bioinformatics destinations such as:
        • NCBI – Blast, Entrez and PubMed services -
        • ExPASy – Swiss-Prot and Prosite entries, as well as Prosite searches -
      • Interfaces to common bioinformatics programs such as:
        • +
        • ExPASy – Swiss-Prot and Prosite entries, as well as Prosite searches +
      • Interfaces to common bioinformatics programs such as:
        • Standalone Blast from NCBI -
        • Clustalw alignment program -
        • EMBOSS command line tools -
      • A standard sequence class that deals with sequences, ids on sequences, and sequence features.
      • Tools for performing common operations on sequences, such as translation, transcription and weight calculations.
      • Code to perform classification of data using k Nearest Neighbors, Naive Bayes or Support Vector Machines.
      • Code for dealing with alignments, including a standard way to create and deal with substitution matrices.
      • Code making it easy to split up parallelizable tasks into separate processes.
      • GUI-based programs to do basic sequence manipulations, translations, BLASTing, etc.
      • Extensive documentation and help with using the modules, including this file, on-line wiki documentation, the web site, and the mailing list.
      • Integration with BioSQL, a sequence database schema also supported by the BioPerl and BioJava projects.

      We hope this gives you plenty of reasons to download and start using Biopython!

      -

      1.3  Installing Biopython

      All of the installation information for Biopython was separated from -this document to make it easier to keep updated.

      The short version is go to our downloads page (http://biopython.org/wiki/Download), +

    • Clustalw alignment program +
    • EMBOSS command line tools +
  • A standard sequence class that deals with sequences, ids on sequences, and sequence features.
  • Tools for performing common operations on sequences, such as translation, transcription and weight calculations.
  • Code to perform classification of data using k Nearest Neighbors, Naive Bayes or Support Vector Machines.
  • Code for dealing with alignments, including a standard way to create and deal with substitution matrices.
  • Code making it easy to split up parallelizable tasks into separate processes.
  • GUI-based programs to do basic sequence manipulations, translations, BLASTing, etc.
  • Extensive documentation and help with using the modules, including this file, on-line wiki documentation, the web site, and the mailing list.
  • Integration with BioSQL, a sequence database schema also supported by the BioPerl and BioJava projects.

We hope this gives you plenty of reasons to download and start using Biopython!

+ +

1.3  Installing Biopython

All of the installation information for Biopython was separated from +this document to make it easier to keep updated.

The short version is go to our downloads page (http://biopython.org/wiki/Download), download and install the listed dependencies, then download and install Biopython. Biopython runs on many platforms (Windows, Mac, and on the various flavors of Linux and Unix). For Windows we provide pre-compiled click-and-run installers, while for Unix and other operating systems you must install from source as described in the included README file. -This is usually as simple as the standard commands:

python setup.py build
+This is usually as simple as the standard commands:

python setup.py build
 python setup.py test
 sudo python setup.py install
-

(You can in fact skip the build and test, and go straight to the install – -but its better to make sure everything seems to be working.)

The longer version of our installation instructions covers +

(You can in fact skip the build and test, and go straight to the install – +but its better to make sure everything seems to be working.)

The longer version of our installation instructions covers installation of Python, Biopython dependencies and Biopython itself. It is available in PDF -(http://biopython.org/DIST/docs/install/Installation.pdf) +(http://biopython.org/DIST/docs/install/Installation.pdf) and HTML formats -(http://biopython.org/DIST/docs/install/Installation.html).

-

1.4  Frequently Asked Questions (FAQ)

  1. How do I cite Biopython in a scientific publication?
    - Please cite our application note [1, Cock et al., 2009] +(http://biopython.org/DIST/docs/install/Installation.html).

    + +

    1.4  Frequently Asked Questions (FAQ)

    1. How do I cite Biopython in a scientific publication?
      + Please cite our application note [1, Cock et al., 2009] as the main Biopython reference. In addition, please cite any publications from the following list if appropriate, in particular as a reference for specific modules within Biopython (more information can be found on our website): -
      • -For the official project announcement: [13, Chapman and Chang, 2000]; -
      • For Bio.PDB: [18, Hamelryck and Manderick, 2003]; -
      • For Bio.Cluster: [14, De Hoon et al., 2004]; -
      • For Bio.Graphics.GenomeDiagram: [2, Pritchard et al., 2006]; -
      • For Bio.Phylo and Bio.Phylo.PAML: [9, Talevich et al., 2012]; -
      • For the FASTQ file format as supported in Biopython, BioPerl, BioRuby, BioJava, and EMBOSS: [7, Cock et al., 2010]. -
    2. How should I capitalize “Biopython”? Is “BioPython” OK?
      +
      • +For the official project announcement: [13, Chapman and Chang, 2000]; +
      • For Bio.PDB: [18, Hamelryck and Manderick, 2003]; +
      • For Bio.Cluster: [14, De Hoon et al., 2004]; +
      • For Bio.Graphics.GenomeDiagram: [2, Pritchard et al., 2006]; +
      • For Bio.Phylo and Bio.Phylo.PAML: [9, Talevich et al., 2012]; +
      • For the FASTQ file format as supported in Biopython, BioPerl, BioRuby, BioJava, and EMBOSS: [7, Cock et al., 2010]. +
    3. How should I capitalize “Biopython”? Is “BioPython” OK?
      The correct capitalization is “Biopython”, not “BioPython” (even though -that would have matched BioPerl, BioJava and BioRuby).
    4. How do I find out what version of Biopython I have installed?
      +that would have matched BioPerl, BioJava and BioRuby).
    5. What is going wrong with my print commands?
      + This tutorial now uses the Python 3 style print function. +As of Biopython 1.62, we support both Python 2 and Python 3. +The most obvious language difference is the print statement +in Python 2 became a print function in Python 3.

      For example, this will only work under Python 2:

      >>> print "Hello World!"
      +Hello World!
      +

      If you try that on Python 3 you’ll get a SyntaxError. +Under Python 3 you must write:

      >>> print("Hello World!")
      +Hello World!
      +

      Surprisingly that will also work on Python 2 – but only for simple +examples printing one thing. In general you need to add this magic +line to the start of your Python scripts to use the print function +under Python 2.6 and 2.7:

      from __future__ import print_function
      +

      If you forget to add this magic import, under Python 2 you’ll see +extra brackets produced by trying to use the print function when +Python 2 is interpretting it as a print statement and a tuple.

    6. How do I find out what version of Biopython I have installed?
      Use this: -
        >>> import Bio
      -  >>> print Bio.__version__
      +
        >>> import Bio
      +  >>> print(Bio.__version__)
         ...
      -  
      If the “import Bio” line fails, Biopython is not installed. +
      If the “import Bio” line fails, Biopython is not installed. If the second line fails, your version is very out of date. If the version string ends with a plus, you don’t have an official -release, but a snapshot of the in development code.
    7. Where is the latest version of this document?
      +release, but a snapshot of the in development code.
    8. Where is the latest version of this document?
      If you download a Biopython source code archive, it will include the relevant version in both HTML and PDF formats. The latest published version of this document (updated at each release) is online: - + If you are using the very latest unreleased code from our repository you can find copies of the in-progress tutorial here: -
    9. Which “Numerical Python” do I need?
      - For Biopython 1.48 or earlier, you needed the old Numeric module. -For Biopython 1.49 onwards, you need the newer NumPy instead. -Both Numeric and NumPy can be installed on the same machine fine. -See also: http://numpy.scipy.org/
    10. Why is the Seq object missing the (back) transcription & translation methods described in this Tutorial?
      - You need Biopython 1.49 or later. Alternatively, use the Bio.Seq module functions described in Section 3.14.
    11. Why is the Seq object missing the upper & lower methods described in this Tutorial?
      - You need Biopython 1.53 or later. Alternatively, use str(my_seq).upper() to get an upper case string. -If you need a Seq object, try Seq(str(my_seq).upper()) but be careful about blindly re-using the same alphabet.
    12. Why doesn’t the Seq object translation method support the cds option described in this Tutorial?
      - You need Biopython 1.51 or later.
    13. Why doesn’t Bio.SeqIO work? It imports fine but there is no parse function etc.
      - You need Biopython 1.43 or later. Older versions did contain some related code under the Bio.SeqIO name which has since been removed - and this is why the import “works”.
    14. Why doesn’t Bio.SeqIO.read() work? The module imports fine but there is no read function!
      - You need Biopython 1.45 or later. Or, use Bio.SeqIO.parse(...).next() instead.
    15. Why isn’t Bio.AlignIO present? The module import fails!
      - You need Biopython 1.46 or later.
    16. What file formats do Bio.SeqIO and Bio.AlignIO read and write?
      - Check the built in docstrings (from Bio import SeqIO, then help(SeqIO)), or see http://biopython.org/wiki/SeqIO and http://biopython.org/wiki/AlignIO on the wiki for the latest listing.
    17. Why don’t the Bio.SeqIO and Bio.AlignIO input functions let me provide a sequence alphabet?
      - You need Biopython 1.49 or later.
    18. Why won’t the Bio.SeqIO and Bio.AlignIO functions parse, read and write take filenames? They insist on handles!
      - You need Biopython 1.54 or later, or just use handles explicitly (see Section 22.1). -It is especially important to remember to close output handles explicitly after writing your data.
    19. Why won’t the Bio.SeqIO.write() and Bio.AlignIO.write() functions accept a single record or alignment? They insist on a list or iterator!
      - You need Biopython 1.54 or later, or just wrap the item with [...] to create a list of one element.
    20. Why doesn’t str(...) give me the full sequence of a Seq object?
      - You need Biopython 1.45 or later. Alternatively, rather than str(my_seq), use my_seq.tostring() (which will also work on recent versions of Biopython).
    21. Why doesn’t Bio.Blast work with the latest plain text NCBI blast output?
      +
    22. Why is the Seq object missing the upper & lower methods described in this Tutorial?
      + You need Biopython 1.53 or later. Alternatively, use str(my_seq).upper() to get an upper case string. +If you need a Seq object, try Seq(str(my_seq).upper()) but be careful about blindly re-using the same alphabet.
    23. Why doesn’t the Seq object translation method support the cds option described in this Tutorial?
      + You need Biopython 1.51 or later.
    24. What file formats do Bio.SeqIO and Bio.AlignIO read and write?
      + Check the built in docstrings (from Bio import SeqIO, then help(SeqIO)), or see http://biopython.org/wiki/SeqIO and http://biopython.org/wiki/AlignIO on the wiki for the latest listing.
    25. Why won’t the Bio.SeqIO and Bio.AlignIO functions parse, read and write take filenames? They insist on handles!
      + You need Biopython 1.54 or later, or just use handles explicitly (see Section 22.1). +It is especially important to remember to close output handles explicitly after writing your data.
    26. Why won’t the Bio.SeqIO.write() and Bio.AlignIO.write() functions accept a single record or alignment? They insist on a list or iterator!
      + You need Biopython 1.54 or later, or just wrap the item with [...] to create a list of one element.
    27. Why doesn’t str(...) give me the full sequence of a Seq object?
      + You need Biopython 1.45 or later. Alternatively, rather than str(my_seq), use my_seq.tostring() (which will also work on recent versions of Biopython).
    28. Why doesn’t Bio.Blast work with the latest plain text NCBI blast output?
      The NCBI keep tweaking the plain text output from the BLAST tools, and keeping our parser up to date is/was an ongoing struggle. If you aren’t using the latest version of Biopython, you could try upgrading. -However, we (and the NCBI) recommend you use the XML output instead, which is designed to be read by a computer program.
    29. Why doesn’t Bio.Entrez.read() work? The module imports fine but there is no read function!
      - You need Biopython 1.46 or later.
    30. Why doesn’t Bio.Entrez.parse() work? The module imports fine but there is no parse function!
      - You need Biopython 1.52 or later.
    31. Why has my script using Bio.Entrez.efetch() stopped working?
      +However, we (and the NCBI) recommend you use the XML output instead, which is designed to be read by a computer program.
    32. Why doesn’t Bio.Entrez.parse() work? The module imports fine but there is no parse function!
      + You need Biopython 1.52 or later.
    33. Why has my script using Bio.Entrez.efetch() stopped working?
      This could be due to NCBI changes in February 2012 introducing EFetch 2.0. -First, they changed the default return modes - you probably want to add retmode="text" to +First, they changed the default return modes - you probably want to add retmode="text" to your call. Second, they are now stricter about how to provide a list of IDs – Biopython 1.59 onwards -turns a list into a comma separated string automatically.
    34. Why doesn’t Bio.Blast.NCBIWWW.qblast() give the same results as the NCBI BLAST website?
      +turns a list into a comma separated string automatically.
    35. Why doesn’t Bio.Blast.NCBIWWW.qblast() give the same results as the NCBI BLAST website?
      You need to specify the same options – the NCBI often adjust the default settings on the website, -and they do not match the QBLAST defaults anymore. Check things like the gap penalties and expectation threshold.
    36. Why doesn’t Bio.Blast.NCBIXML.read() work? The module imports but there is no read function!
      - You need Biopython 1.50 or later. Or, use Bio.Blast.NCBIXML.parse(...).next() instead.
    37. Why doesn’t my SeqRecord object have a letter_annotations attribute?
      - Per-letter-annotation support was added in Biopython 1.50.
    38. Why can’t I slice my SeqRecord to get a sub-record?
      - You need Biopython 1.50 or later.
    39. Why can’t I add SeqRecord objects together?
      - You need Biopython 1.53 or later.
    40. Why doesn’t Bio.SeqIO.convert() or Bio.AlignIO.convert() work? The modules import fine but there is no convert function!
      - You need Biopython 1.52 or later. Alternatively, combine the parse and write -functions as described in this tutorial (see Sections 5.5.2 and 6.2.1).
    41. Why doesn’t Bio.SeqIO.index() work? The module imports fine but there is no index function!
      - You need Biopython 1.52 or later.
    42. Why doesn’t Bio.SeqIO.index_db() work? The module imports fine but there is no index_db function!
      - You need Biopython 1.57 or later (and a Python with SQLite3 support).
    43. Where is the MultipleSeqAlignment object? The Bio.Align module imports fine but this class isn’t there!
      - You need Biopython 1.54 or later. Alternatively, the older Bio.Align.Generic.Alignment class supports some of its functionality, but using this is now discouraged.
    44. Why can’t I run command line tools directly from the application wrappers?
      - You need Biopython 1.55 or later. Alternatively, use the Python subprocess module directly.
    45. I looked in a directory for code, but I couldn’t find the code that does something. Where’s it hidden?
      - One thing to know is that we put code in __init__.py files. If you are not used to looking for code in this file this can be confusing. The reason we do this is to make the imports easier for users. For instance, instead of having to do a “repetitive” import like from Bio.GenBank import GenBank, you can just use from Bio import GenBank.
    46. Why does the code from CVS seem out of date?
      +and they do not match the QBLAST defaults anymore. Check things like the gap penalties and expectation threshold.
    47. Why doesn’t Bio.Blast.NCBIXML.read() work? The module imports but there is no read function!
      + You need Biopython 1.50 or later. Or, use next(Bio.Blast.NCBIXML.parse(...)) instead.
    48. Why doesn’t my SeqRecord object have a letter_annotations attribute?
      + Per-letter-annotation support was added in Biopython 1.50.
    49. Why can’t I slice my SeqRecord to get a sub-record?
      + You need Biopython 1.50 or later.
    50. Why can’t I add SeqRecord objects together?
      + You need Biopython 1.53 or later.
    51. Why doesn’t Bio.SeqIO.convert() or Bio.AlignIO.convert() work? The modules import fine but there is no convert function!
      + You need Biopython 1.52 or later. Alternatively, combine the parse and write +functions as described in this tutorial (see Sections 5.5.2 and 6.2.1).
    52. Why doesn’t Bio.SeqIO.index() work? The module imports fine but there is no index function!
      + You need Biopython 1.52 or later.
    53. Why doesn’t Bio.SeqIO.index_db() work? The module imports fine but there is no index_db function!
      + You need Biopython 1.57 or later (and a Python with SQLite3 support).
    54. Where is the MultipleSeqAlignment object? The Bio.Align module imports fine but this class isn’t there!
      + You need Biopython 1.54 or later. Alternatively, the older Bio.Align.Generic.Alignment class supports some of its functionality, but using this is now discouraged.
    55. Why can’t I run command line tools directly from the application wrappers?
      + You need Biopython 1.55 or later. Alternatively, use the Python subprocess module directly.
    56. I looked in a directory for code, but I couldn’t find the code that does something. Where’s it hidden?
      + One thing to know is that we put code in __init__.py files. If you are not used to looking for code in this file this can be confusing. The reason we do this is to make the imports easier for users. For instance, instead of having to do a “repetitive” import like from Bio.GenBank import GenBank, you can just use from Bio import GenBank.
    57. Why does the code from CVS seem out of date?
      In late September 2009, just after the release of Biopython 1.52, we switched from using CVS to git, a distributed version control system. The old CVS server will remain available as a static and read only backup, but if you want to grab the latest code, you’ll need to use git instead. See our website for more details. -

    For more general questions, the Python FAQ pages http://www.python.org/doc/faq/ may be useful.

    -

    Chapter 2  Quick Start – What can you do with Biopython?

    -

    This section is designed to get you started quickly with Biopython, and to give a general overview of what is available and how to use it. All of the examples in this section assume that you have some general working knowledge of Python, and that you have successfully installed Biopython on your system. If you think you need to brush up on your Python, the main Python web site provides quite a bit of free documentation to get started with (http://www.python.org/doc/).

    Since much biological work on the computer involves connecting with databases on the internet, some of the examples will also require a working internet connection in order to run.

    Now that that is all out of the way, let’s get into what we can do with Biopython.

    -

    2.1  General overview of what Biopython provides

    As mentioned in the introduction, Biopython is a set of libraries to provide the ability to deal with “things” of interest to biologists working on the computer. In general this means that you will need to have at least some programming experience (in Python, of course!) or at least an interest in learning to program. Biopython’s job is to make your job easier as a programmer by supplying reusable libraries so that you can focus on answering your specific question of interest, instead of focusing on the internals of parsing a particular file format (of course, if you want to help by writing a parser that doesn’t exist and contributing it to Biopython, please go ahead!). So Biopython’s job is to make you happy!

    One thing to note about Biopython is that it often provides multiple ways of “doing the same thing.” Things have improved in recent releases, but this can still be frustrating as in Python there should ideally be one right way to do something. However, this can also be a real benefit because it gives you lots of flexibility and control over the libraries. The tutorial helps to show you the common or easy ways to do things so that you can just make things work. To learn more about the alternative possibilities, look in the Cookbook (Chapter 18, this has some cools tricks and tips), the Advanced section (Chapter 20), the built in “docstrings” (via the Python help command, or the API documentation) or ultimately the code itself.

    -

    2.2  Working with sequences

    -

    Disputably (of course!), the central object in bioinformatics is the sequence. Thus, we’ll start with a quick introduction to the Biopython mechanisms for dealing with sequences, the Seq object, which we’ll discuss in more detail in Chapter 3.

    Most of the time when we think about sequences we have in my mind a string of letters like ‘AGTACACTGGT’. You can create such Seq object with this sequence as follows - the “>>>” represents the Python prompt followed by what you would type in:

    >>> from Bio.Seq import Seq
    +

For more general questions, the Python FAQ pages http://www.python.org/doc/faq/ may be useful.

+ +

Chapter 2  Quick Start – What can you do with Biopython?

+

This section is designed to get you started quickly with Biopython, and to give a general overview of what is available and how to use it. All of the examples in this section assume that you have some general working knowledge of Python, and that you have successfully installed Biopython on your system. If you think you need to brush up on your Python, the main Python web site provides quite a bit of free documentation to get started with (http://www.python.org/doc/).

Since much biological work on the computer involves connecting with databases on the internet, some of the examples will also require a working internet connection in order to run.

Now that that is all out of the way, let’s get into what we can do with Biopython.

+ +

2.1  General overview of what Biopython provides

As mentioned in the introduction, Biopython is a set of libraries to provide the ability to deal with “things” of interest to biologists working on the computer. In general this means that you will need to have at least some programming experience (in Python, of course!) or at least an interest in learning to program. Biopython’s job is to make your job easier as a programmer by supplying reusable libraries so that you can focus on answering your specific question of interest, instead of focusing on the internals of parsing a particular file format (of course, if you want to help by writing a parser that doesn’t exist and contributing it to Biopython, please go ahead!). So Biopython’s job is to make you happy!

One thing to note about Biopython is that it often provides multiple ways of “doing the same thing.” Things have improved in recent releases, but this can still be frustrating as in Python there should ideally be one right way to do something. However, this can also be a real benefit because it gives you lots of flexibility and control over the libraries. The tutorial helps to show you the common or easy ways to do things so that you can just make things work. To learn more about the alternative possibilities, look in the Cookbook (Chapter 18, this has some cools tricks and tips), the Advanced section (Chapter 20), the built in “docstrings” (via the Python help command, or the API documentation) or ultimately the code itself.

+ +

2.2  Working with sequences

+

Disputably (of course!), the central object in bioinformatics is the sequence. Thus, we’ll start with a quick introduction to the Biopython mechanisms for dealing with sequences, the Seq object, which we’ll discuss in more detail in Chapter 3.

Most of the time when we think about sequences we have in my mind a string of letters like ‘AGTACACTGGT’. You can create such Seq object with this sequence as follows - the “>>>” represents the Python prompt followed by what you would type in:

>>> from Bio.Seq import Seq
 >>> my_seq = Seq("AGTACACTGGT")
 >>> my_seq
 Seq('AGTACACTGGT', Alphabet())
->>> print my_seq
+>>> print(my_seq)
 AGTACACTGGT
 >>> my_seq.alphabet
 Alphabet()
-

What we have here is a sequence object with a generic alphabet - reflecting the fact we have not specified if this is a DNA or protein sequence (okay, a protein with a lot of Alanines, Glycines, Cysteines and Threonines!). We’ll talk more about alphabets in Chapter 3.

In addition to having an alphabet, the Seq object differs from the Python string in the methods it supports. You can’t do this with a plain string:

>>> my_seq
+

What we have here is a sequence object with a generic alphabet - reflecting the fact we have not specified if this is a DNA or protein sequence (okay, a protein with a lot of Alanines, Glycines, Cysteines and Threonines!). We’ll talk more about alphabets in Chapter 3.

In addition to having an alphabet, the Seq object differs from the Python string in the methods it supports. You can’t do this with a plain string:

>>> my_seq
 Seq('AGTACACTGGT', Alphabet())
 >>> my_seq.complement()
 Seq('TCATGTGACCA', Alphabet())
 >>> my_seq.reverse_complement()
 Seq('ACCAGTGTACT', Alphabet())
-

The next most important class is the SeqRecord or Sequence Record. This holds a sequence (as a Seq object) with additional annotation including an identifier, name and description. The Bio.SeqIO module for reading and writing sequence file formats works with SeqRecord objects, which will be introduced below and covered in more detail by Chapter 5.

This covers the basic features and uses of the Biopython sequence class. -Now that you’ve got some idea of what it is like to interact with the Biopython libraries, it’s time to delve into the fun, fun world of dealing with biological file formats!

-

2.3  A usage example

-

Before we jump right into parsers and everything else to do with Biopython, let’s set up an example to motivate everything we do and make life more interesting. After all, if there wasn’t any biology in this tutorial, why would you want you read it?

Since I love plants, I think we’re just going to have to have a plant based example (sorry to all the fans of other organisms out there!). Having just completed a recent trip to our local greenhouse, we’ve suddenly developed an incredible obsession with Lady Slipper Orchids (if you wonder why, have a look at some Lady Slipper Orchids photos on Flickr, or try a Google Image Search).

Of course, orchids are not only beautiful to look at, they are also extremely interesting for people studying evolution and systematics. So let’s suppose we’re thinking about writing a funding proposal to do a molecular study of Lady Slipper evolution, and would like to see what kind of research has already been done and how we can add to that.

After a little bit of reading up we discover that the Lady Slipper Orchids are in the Orchidaceae family and the Cypripedioideae sub-family and are made up of 5 genera: Cypripedium, Paphiopedilum, Phragmipedium, Selenipedium and Mexipedium.

That gives us enough to get started delving for more information. So, let’s look at how the Biopython tools can help us. We’ll start with sequence parsing in Section 2.4, but the orchids will be back later on as well - for example we’ll search PubMed for papers about orchids and extract sequence data from GenBank in Chapter 9, extract data from Swiss-Prot from certain orchid proteins in Chapter 10, and work with ClustalW multiple sequence alignments of orchid proteins in Section 6.4.1.

-

2.4  Parsing sequence file formats

-

A large part of much bioinformatics work involves dealing with the many types of file formats designed to hold biological data. These files are loaded with interesting biological data, and a special challenge is parsing these files into a format so that you can manipulate them with some kind of programming language. However the task of parsing these files can be frustrated by the fact that the formats can change quite regularly, and that formats may contain small subtleties which can break even the most well designed parsers.

We are now going to briefly introduce the Bio.SeqIO module – you can find out more in Chapter 5. We’ll start with an online search for our friends, the lady slipper orchids. To keep this introduction simple, we’re just using the NCBI website by hand. Let’s just take a look through the nucleotide databases at NCBI, using an Entrez online search (http://www.ncbi.nlm.nih.gov:80/entrez/query.fcgi?db=Nucleotide) for everything mentioning the text Cypripedioideae (this is the subfamily of lady slipper orchids).

When this tutorial was originally written, this search gave us only 94 hits, which we saved as a FASTA formatted text file and as a GenBank formatted text file (files ls_orchid.fasta and ls_orchid.gbk, also included with the Biopython source code under docs/tutorial/examples/).

If you run the search today, you’ll get hundreds of results! When following the tutorial, if you want to see the same list of genes, just download the two files above or copy them from docs/examples/ in the Biopython source code. In Section 2.5 we will look at how to do a search like this from within Python.

-

2.4.1  Simple FASTA parsing example

-

If you open the lady slipper orchids FASTA file ls_orchid.fasta in your favourite text editor, you’ll see that the file starts like this:

>gi|2765658|emb|Z78533.1|CIZ78533 C.irapeanum 5.8S rRNA gene and ITS1 and ITS2 DNA
+

The next most important class is the SeqRecord or Sequence Record. This holds a sequence (as a Seq object) with additional annotation including an identifier, name and description. The Bio.SeqIO module for reading and writing sequence file formats works with SeqRecord objects, which will be introduced below and covered in more detail by Chapter 5.

This covers the basic features and uses of the Biopython sequence class. +Now that you’ve got some idea of what it is like to interact with the Biopython libraries, it’s time to delve into the fun, fun world of dealing with biological file formats!

+ +

2.3  A usage example

+

Before we jump right into parsers and everything else to do with Biopython, let’s set up an example to motivate everything we do and make life more interesting. After all, if there wasn’t any biology in this tutorial, why would you want you read it?

Since I love plants, I think we’re just going to have to have a plant based example (sorry to all the fans of other organisms out there!). Having just completed a recent trip to our local greenhouse, we’ve suddenly developed an incredible obsession with Lady Slipper Orchids (if you wonder why, have a look at some Lady Slipper Orchids photos on Flickr, or try a Google Image Search).

Of course, orchids are not only beautiful to look at, they are also extremely interesting for people studying evolution and systematics. So let’s suppose we’re thinking about writing a funding proposal to do a molecular study of Lady Slipper evolution, and would like to see what kind of research has already been done and how we can add to that.

After a little bit of reading up we discover that the Lady Slipper Orchids are in the Orchidaceae family and the Cypripedioideae sub-family and are made up of 5 genera: Cypripedium, Paphiopedilum, Phragmipedium, Selenipedium and Mexipedium.

That gives us enough to get started delving for more information. So, let’s look at how the Biopython tools can help us. We’ll start with sequence parsing in Section 2.4, but the orchids will be back later on as well - for example we’ll search PubMed for papers about orchids and extract sequence data from GenBank in Chapter 9, extract data from Swiss-Prot from certain orchid proteins in Chapter 10, and work with ClustalW multiple sequence alignments of orchid proteins in Section 6.4.1.

+ +

2.4  Parsing sequence file formats

+

A large part of much bioinformatics work involves dealing with the many types of file formats designed to hold biological data. These files are loaded with interesting biological data, and a special challenge is parsing these files into a format so that you can manipulate them with some kind of programming language. However the task of parsing these files can be frustrated by the fact that the formats can change quite regularly, and that formats may contain small subtleties which can break even the most well designed parsers.

We are now going to briefly introduce the Bio.SeqIO module – you can find out more in Chapter 5. We’ll start with an online search for our friends, the lady slipper orchids. To keep this introduction simple, we’re just using the NCBI website by hand. Let’s just take a look through the nucleotide databases at NCBI, using an Entrez online search (http://www.ncbi.nlm.nih.gov:80/entrez/query.fcgi?db=Nucleotide) for everything mentioning the text Cypripedioideae (this is the subfamily of lady slipper orchids).

When this tutorial was originally written, this search gave us only 94 hits, which we saved as a FASTA formatted text file and as a GenBank formatted text file (files ls_orchid.fasta and ls_orchid.gbk, also included with the Biopython source code under docs/tutorial/examples/).

If you run the search today, you’ll get hundreds of results! When following the tutorial, if you want to see the same list of genes, just download the two files above or copy them from docs/examples/ in the Biopython source code. In Section 2.5 we will look at how to do a search like this from within Python.

+ +

2.4.1  Simple FASTA parsing example

+

If you open the lady slipper orchids FASTA file ls_orchid.fasta in your favourite text editor, you’ll see that the file starts like this:

>gi|2765658|emb|Z78533.1|CIZ78533 C.irapeanum 5.8S rRNA gene and ITS1 and ITS2 DNA
 CGTAACAAGGTTTCCGTAGGTGAACCTGCGGAAGGATCATTGATGAGACCGTGGAATAAACGATCGAGTG
 AATCCGGAGGACCGGTGTACTCAGCTCACCGGGGGCATTGCTCCCGTGGTGACCCTGATTTGTTGTTGGG
 ...
-

It contains 94 records, each has a line starting with “>” (greater-than symbol) followed by the sequence on one or more lines. Now try this in Python:

from Bio import SeqIO
+

It contains 94 records, each has a line starting with “>” (greater-than symbol) followed by the sequence on one or more lines. Now try this in Python:

from Bio import SeqIO
 for seq_record in SeqIO.parse("ls_orchid.fasta", "fasta"):
-    print seq_record.id
-    print repr(seq_record.seq)
-    print len(seq_record)
-

You should get something like this on your screen:

gi|2765658|emb|Z78533.1|CIZ78533
+    print(seq_record.id)
+    print(repr(seq_record.seq))
+    print(len(seq_record))
+

You should get something like this on your screen:

gi|2765658|emb|Z78533.1|CIZ78533
 Seq('CGTAACAAGGTTTCCGTAGGTGAACCTGCGGAAGGATCATTGATGAGACCGTGG...CGC', SingleLetterAlphabet())
 740
 ...
 gi|2765564|emb|Z78439.1|PBZ78439
 Seq('CATTGTTGAGATCACATAATAATTGATCGAGTTAATCTGGAGGATCTGTTTACT...GCC', SingleLetterAlphabet())
 592
-

Notice that the FASTA format does not specify the alphabet, so Bio.SeqIO has defaulted to the rather generic SingleLetterAlphabet() rather than something DNA specific.

-

2.4.2  Simple GenBank parsing example

Now let’s load the GenBank file ls_orchid.gbk instead - notice that the code to do this is almost identical to the snippet used above for the FASTA file - the only difference is we change the filename and the format string:

from Bio import SeqIO
+

Notice that the FASTA format does not specify the alphabet, so Bio.SeqIO has defaulted to the rather generic SingleLetterAlphabet() rather than something DNA specific.

+ +

2.4.2  Simple GenBank parsing example

Now let’s load the GenBank file ls_orchid.gbk instead - notice that the code to do this is almost identical to the snippet used above for the FASTA file - the only difference is we change the filename and the format string:

from Bio import SeqIO
 for seq_record in SeqIO.parse("ls_orchid.gbk", "genbank"):
-    print seq_record.id
-    print repr(seq_record.seq)
-    print len(seq_record)
-

This should give:

Z78533.1
+    print(seq_record.id)
+    print(repr(seq_record.seq))
+    print(len(seq_record))
+

This should give:

Z78533.1
 Seq('CGTAACAAGGTTTCCGTAGGTGAACCTGCGGAAGGATCATTGATGAGACCGTGG...CGC', IUPACAmbiguousDNA())
 740
 ...
 Z78439.1
 Seq('CATTGTTGAGATCACATAATAATTGATCGAGTTAATCTGGAGGATCTGTTTACT...GCC', IUPACAmbiguousDNA())
 592
-

This time Bio.SeqIO has been able to choose a sensible alphabet, IUPAC Ambiguous DNA. You’ll also notice that a shorter string has been used as the seq_record.id in this case.

-

2.4.3  I love parsing – please don’t stop talking about it!

Biopython has a lot of parsers, and each has its own little special niches based on the sequence format it is parsing and all of that. Chapter 5 covers Bio.SeqIO in more detail, while Chapter 6 introduces Bio.AlignIO for sequence alignments.

While the most popular file formats have parsers integrated into Bio.SeqIO and/or Bio.AlignIO, for some of the rarer and unloved file formats there is either no parser at all, or an old parser which has not been linked in yet. -Please also check the wiki pages http://biopython.org/wiki/SeqIO and http://biopython.org/wiki/AlignIO for the latest information, or ask on the mailing list. The wiki pages should include an up to date list of supported file types, and some additional examples.

The next place to look for information about specific parsers and how to do cool things with them is in the Cookbook (Chapter 18 of this Tutorial). If you don’t find the information you are looking for, please consider helping out your poor overworked documentors and submitting a cookbook entry about it! (once you figure out how to do it, that is!)

-

2.5  Connecting with biological databases

-

One of the very common things that you need to do in bioinformatics is extract information from biological databases. It can be quite tedious to access these databases manually, especially if you have a lot of repetitive work to do. Biopython attempts to save you time and energy by making some on-line databases available from Python scripts. Currently, Biopython has code to extract information from the following databases:

  • -Entrez (and PubMed) from the NCBI – See Chapter 9. -
  • ExPASy – See Chapter 10. -
  • SCOP – See the Bio.SCOP.search() function. -

The code in these modules basically makes it easy to write Python code that interact with the CGI scripts on these pages, so that you can get results in an easy to deal with format. In some cases, the results can be tightly integrated with the Biopython parsers to make it even easier to extract information.

-

2.6  What to do next

Now that you’ve made it this far, you hopefully have a good understanding of the basics of Biopython and are ready to start using it for doing useful work. The best thing to do now is finish reading this tutorial, and then if you want start snooping around in the source code, and looking at the automatically generated documentation.

Once you get a picture of what you want to do, and what libraries in Biopython will do it, you should take a peak at the Cookbook (Chapter 18), which may have example code to do something similar to what you want to do.

If you know what you want to do, but can’t figure out how to do it, please feel free to post questions to the main Biopython list (see http://biopython.org/wiki/Mailing_lists). This will not only help us answer your question, it will also allow us to improve the documentation so it can help the next person do what you want to do.

Enjoy the code!

-

Chapter 3  Sequence objects

-

Biological sequences are arguably the central object in Bioinformatics, and in this chapter we’ll introduce the Biopython mechanism for dealing with sequences, the Seq object. -Chapter 4 will introduce the related SeqRecord object, which combines the sequence information with any annotation, used again in Chapter 5 for Sequence Input/Output.

Sequences are essentially strings of letters like AGTACACTGGT, which seems very natural since this is the most common way that sequences are seen in biological file formats.

There are two important differences between Seq objects and standard Python strings. -First of all, they have different methods. Although the Seq object supports many of the same methods as a plain string, its translate() method differs by doing biological translation, and there are also additional biologically relevant methods like reverse_complement(). -Secondly, the Seq object has an important attribute, alphabet, which is an object describing what the individual characters making up the sequence string “mean”, and how they should be interpreted. For example, is AGTACACTGGT a DNA sequence, or just a protein sequence that happens to be rich in Alanines, Glycines, Cysteines -and Threonines?

-

3.1  Sequences and Alphabets

The alphabet object is perhaps the important thing that makes the Seq object more than just a string. The currently available alphabets for Biopython are defined in the Bio.Alphabet module. We’ll use the IUPAC alphabets (http://www.chem.qmw.ac.uk/iupac/) here to deal with some of our favorite objects: DNA, RNA and Proteins.

Bio.Alphabet.IUPAC provides basic definitions for proteins, DNA and RNA, but additionally provides the ability to extend and customize the basic definitions. For instance, for proteins, there is a basic IUPACProtein class, but there is an additional ExtendedIUPACProtein class providing for the additional elements “U” (or “Sec” for selenocysteine) and “O” (or “Pyl” for pyrrolysine), plus the ambiguous symbols “B” (or “Asx” for asparagine or aspartic acid), “Z” (or “Glx” for glutamine or glutamic acid), “J” (or “Xle” for leucine isoleucine) and “X” (or “Xxx” for an unknown amino acid). For DNA you’ve got choices of IUPACUnambiguousDNA, which provides for just the basic letters, IUPACAmbiguousDNA (which provides for ambiguity letters for every possible situation) and ExtendedIUPACDNA, which allows letters for modified bases. Similarly, RNA can be represented by IUPACAmbiguousRNA or IUPACUnambiguousRNA.

The advantages of having an alphabet class are two fold. First, this gives an idea of the type of information the Seq object contains. Secondly, this provides a means of constraining the information, as a means of type checking.

Now that we know what we are dealing with, let’s look at how to utilize this class to do interesting work. -You can create an ambiguous sequence with the default generic alphabet like this:

>>> from Bio.Seq import Seq
+

This time Bio.SeqIO has been able to choose a sensible alphabet, IUPAC Ambiguous DNA. You’ll also notice that a shorter string has been used as the seq_record.id in this case.

+ +

2.4.3  I love parsing – please don’t stop talking about it!

Biopython has a lot of parsers, and each has its own little special niches based on the sequence format it is parsing and all of that. Chapter 5 covers Bio.SeqIO in more detail, while Chapter 6 introduces Bio.AlignIO for sequence alignments.

While the most popular file formats have parsers integrated into Bio.SeqIO and/or Bio.AlignIO, for some of the rarer and unloved file formats there is either no parser at all, or an old parser which has not been linked in yet. +Please also check the wiki pages http://biopython.org/wiki/SeqIO and http://biopython.org/wiki/AlignIO for the latest information, or ask on the mailing list. The wiki pages should include an up to date list of supported file types, and some additional examples.

The next place to look for information about specific parsers and how to do cool things with them is in the Cookbook (Chapter 18 of this Tutorial). If you don’t find the information you are looking for, please consider helping out your poor overworked documentors and submitting a cookbook entry about it! (once you figure out how to do it, that is!)

+ +

2.5  Connecting with biological databases

+

One of the very common things that you need to do in bioinformatics is extract information from biological databases. It can be quite tedious to access these databases manually, especially if you have a lot of repetitive work to do. Biopython attempts to save you time and energy by making some on-line databases available from Python scripts. Currently, Biopython has code to extract information from the following databases:

  • +Entrez (and PubMed) from the NCBI – See Chapter 9. +
  • ExPASy – See Chapter 10. +
  • SCOP – See the Bio.SCOP.search() function. +

The code in these modules basically makes it easy to write Python code that interact with the CGI scripts on these pages, so that you can get results in an easy to deal with format. In some cases, the results can be tightly integrated with the Biopython parsers to make it even easier to extract information.

+ +

2.6  What to do next

Now that you’ve made it this far, you hopefully have a good understanding of the basics of Biopython and are ready to start using it for doing useful work. The best thing to do now is finish reading this tutorial, and then if you want start snooping around in the source code, and looking at the automatically generated documentation.

Once you get a picture of what you want to do, and what libraries in Biopython will do it, you should take a peak at the Cookbook (Chapter 18), which may have example code to do something similar to what you want to do.

If you know what you want to do, but can’t figure out how to do it, please feel free to post questions to the main Biopython list (see http://biopython.org/wiki/Mailing_lists). This will not only help us answer your question, it will also allow us to improve the documentation so it can help the next person do what you want to do.

Enjoy the code!

+ +

Chapter 3  Sequence objects

+

Biological sequences are arguably the central object in Bioinformatics, and in this chapter we’ll introduce the Biopython mechanism for dealing with sequences, the Seq object. +Chapter 4 will introduce the related SeqRecord object, which combines the sequence information with any annotation, used again in Chapter 5 for Sequence Input/Output.

Sequences are essentially strings of letters like AGTACACTGGT, which seems very natural since this is the most common way that sequences are seen in biological file formats.

There are two important differences between Seq objects and standard Python strings. +First of all, they have different methods. Although the Seq object supports many of the same methods as a plain string, its translate() method differs by doing biological translation, and there are also additional biologically relevant methods like reverse_complement(). +Secondly, the Seq object has an important attribute, alphabet, which is an object describing what the individual characters making up the sequence string “mean”, and how they should be interpreted. For example, is AGTACACTGGT a DNA sequence, or just a protein sequence that happens to be rich in Alanines, Glycines, Cysteines +and Threonines?

+ +

3.1  Sequences and Alphabets

The alphabet object is perhaps the important thing that makes the Seq object more than just a string. The currently available alphabets for Biopython are defined in the Bio.Alphabet module. We’ll use the IUPAC alphabets (http://www.chem.qmw.ac.uk/iupac/) here to deal with some of our favorite objects: DNA, RNA and Proteins.

Bio.Alphabet.IUPAC provides basic definitions for proteins, DNA and RNA, but additionally provides the ability to extend and customize the basic definitions. For instance, for proteins, there is a basic IUPACProtein class, but there is an additional ExtendedIUPACProtein class providing for the additional elements “U” (or “Sec” for selenocysteine) and “O” (or “Pyl” for pyrrolysine), plus the ambiguous symbols “B” (or “Asx” for asparagine or aspartic acid), “Z” (or “Glx” for glutamine or glutamic acid), “J” (or “Xle” for leucine isoleucine) and “X” (or “Xxx” for an unknown amino acid). For DNA you’ve got choices of IUPACUnambiguousDNA, which provides for just the basic letters, IUPACAmbiguousDNA (which provides for ambiguity letters for every possible situation) and ExtendedIUPACDNA, which allows letters for modified bases. Similarly, RNA can be represented by IUPACAmbiguousRNA or IUPACUnambiguousRNA.

The advantages of having an alphabet class are two fold. First, this gives an idea of the type of information the Seq object contains. Secondly, this provides a means of constraining the information, as a means of type checking.

Now that we know what we are dealing with, let’s look at how to utilize this class to do interesting work. +You can create an ambiguous sequence with the default generic alphabet like this:

>>> from Bio.Seq import Seq
 >>> my_seq = Seq("AGTACACTGGT")
 >>> my_seq
 Seq('AGTACACTGGT', Alphabet())
 >>> my_seq.alphabet
 Alphabet()
-

However, where possible you should specify the alphabet explicitly when creating your sequence objects - in this case an unambiguous DNA alphabet object:

>>> from Bio.Seq import Seq
+

However, where possible you should specify the alphabet explicitly when creating your sequence objects - in this case an unambiguous DNA alphabet object:

>>> from Bio.Seq import Seq
 >>> from Bio.Alphabet import IUPAC
 >>> my_seq = Seq("AGTACACTGGT", IUPAC.unambiguous_dna)
 >>> my_seq
 Seq('AGTACACTGGT', IUPACUnambiguousDNA())
 >>> my_seq.alphabet
 IUPACUnambiguousDNA()
-

Unless of course, this really is an amino acid sequence:

>>> from Bio.Seq import Seq
+

Unless of course, this really is an amino acid sequence:

>>> from Bio.Seq import Seq
 >>> from Bio.Alphabet import IUPAC
 >>> my_prot = Seq("AGTACACTGGT", IUPAC.protein)
 >>> my_prot
 Seq('AGTACACTGGT', IUPACProtein())
 >>> my_prot.alphabet
 IUPACProtein()
-
-

3.2  Sequences act like strings

In many ways, we can deal with Seq objects as if they were normal Python strings, for example getting the length, or iterating over the elements:

>>> from Bio.Seq import Seq
+
+ +

3.2  Sequences act like strings

In many ways, we can deal with Seq objects as if they were normal Python strings, for example getting the length, or iterating over the elements:

>>> from Bio.Seq import Seq
 >>> from Bio.Alphabet import IUPAC
 >>> my_seq = Seq("GATCG", IUPAC.unambiguous_dna)
 >>> for index, letter in enumerate(my_seq):
-...     print index, letter
+...     print("%i %s" % (index, letter))
 0 G
 1 A
 2 T
 3 C
 4 G
->>> print len(my_seq)
+>>> print(len(my_seq))
 5
-

You can access elements of the sequence in the same way as for strings (but remember, Python counts from zero!):

>>> print my_seq[0] #first letter
+

You can access elements of the sequence in the same way as for strings (but remember, Python counts from zero!):

>>> print(my_seq[0]) #first letter
 G
->>> print my_seq[2] #third letter
+>>> print(my_seq[2]) #third letter
 T
->>> print my_seq[-1] #last letter
+>>> print(my_seq[-1]) #last letter
 G
-

The Seq object has a .count() method, just like a string. +

The Seq object has a .count() method, just like a string. Note that this means that like a Python string, this gives a -non-overlapping count:

>>> from Bio.Seq import Seq
+non-overlapping count:

>>> from Bio.Seq import Seq
 >>> "AAAA".count("AA")
 2
 >>> Seq("AAAA").count("AA")
 2
-

For some biological uses, you may actually want an overlapping count +

For some biological uses, you may actually want an overlapping count (i.e. 3 in this trivial example). When searching for single letters, this -makes no difference:

>>> from Bio.Seq import Seq
+makes no difference:

>>> from Bio.Seq import Seq
 >>> from Bio.Alphabet import IUPAC
 >>> my_seq = Seq('GATCGATGGGCCTATATAGGATCGAAAATCGC', IUPAC.unambiguous_dna)
 >>> len(my_seq)
@@ -777,51 +806,55 @@
 9
 >>> 100 * float(my_seq.count("G") + my_seq.count("C")) / len(my_seq)
 46.875
-

While you could use the above snippet of code to calculate a GC%, note that the Bio.SeqUtils module has several GC functions already built. For example:

>>> from Bio.Seq import Seq
+

While you could use the above snippet of code to calculate a GC%, note that the Bio.SeqUtils module has several GC functions already built. For example:

>>> from Bio.Seq import Seq
 >>> from Bio.Alphabet import IUPAC
 >>> from Bio.SeqUtils import GC
 >>> my_seq = Seq('GATCGATGGGCCTATATAGGATCGAAAATCGC', IUPAC.unambiguous_dna)
 >>> GC(my_seq)
 46.875
-

Note that using the Bio.SeqUtils.GC() function should automatically cope with mixed case sequences and the ambiguous nucleotide S which means G or C.

Also note that just like a normal Python string, the Seq object is in some ways “read-only”. If you need to edit your sequence, for example simulating a point mutation, look at the Section 3.12 below which talks about the MutableSeq object.

-

3.3  Slicing a sequence

A more complicated example, let’s get a slice of the sequence:

>>> from Bio.Seq import Seq
+

Note that using the Bio.SeqUtils.GC() function should automatically cope with mixed case sequences and the ambiguous nucleotide S which means G or C.

Also note that just like a normal Python string, the Seq object is in some ways “read-only”. If you need to edit your sequence, for example simulating a point mutation, look at the Section 3.12 below which talks about the MutableSeq object.

+ +

3.3  Slicing a sequence

A more complicated example, let’s get a slice of the sequence:

>>> from Bio.Seq import Seq
 >>> from Bio.Alphabet import IUPAC
 >>> my_seq = Seq("GATCGATGGGCCTATATAGGATCGAAAATCGC", IUPAC.unambiguous_dna)
 >>> my_seq[4:12]
 Seq('GATGGGCC', IUPACUnambiguousDNA())
-

Two things are interesting to note. First, this follows the normal conventions for Python strings. So the first element of the sequence is 0 (which is normal for computer science, but not so normal for biology). When you do a slice the first item is included (i.e. 4 in this case) and the last is excluded (12 in this case), which is the way things work in Python, but of course not necessarily the way everyone in the world would expect. The main goal is to stay consistent with what Python does.

The second thing to notice is that the slice is performed on the sequence data string, but the new object produced is another Seq object which retains the alphabet information from the original Seq object.

Also like a Python string, you can do slices with a start, stop and stride (the step size, which defaults to one). For example, we can get the first, second and third codon positions of this DNA sequence:

>>> my_seq[0::3]
+

Two things are interesting to note. First, this follows the normal conventions for Python strings. So the first element of the sequence is 0 (which is normal for computer science, but not so normal for biology). When you do a slice the first item is included (i.e. 4 in this case) and the last is excluded (12 in this case), which is the way things work in Python, but of course not necessarily the way everyone in the world would expect. The main goal is to stay consistent with what Python does.

The second thing to notice is that the slice is performed on the sequence data string, but the new object produced is another Seq object which retains the alphabet information from the original Seq object.

Also like a Python string, you can do slices with a start, stop and stride (the step size, which defaults to one). For example, we can get the first, second and third codon positions of this DNA sequence:

>>> my_seq[0::3]
 Seq('GCTGTAGTAAG', IUPACUnambiguousDNA())
 >>> my_seq[1::3]
 Seq('AGGCATGCATC', IUPACUnambiguousDNA())
 >>> my_seq[2::3]
 Seq('TAGCTAAGAC', IUPACUnambiguousDNA())
-

Another stride trick you might have seen with a Python string is the use of a -1 stride to reverse the string. You can do this with a Seq object too:

>>> my_seq[::-1]
+

Another stride trick you might have seen with a Python string is the use of a -1 stride to reverse the string. You can do this with a Seq object too:

>>> my_seq[::-1]
 Seq('CGCTAAAAGCTAGGATATATCCGGGTAGCTAG', IUPACUnambiguousDNA())
-
-

3.4  Turning Seq objects into strings

-

If you really do just need a plain string, for example to write to a file, or insert into a database, then this is very easy to get: -

>>> str(my_seq)
+
+ +

3.4  Turning Seq objects into strings

+

If you really do just need a plain string, for example to write to a file, or insert into a database, then this is very easy to get: +

>>> str(my_seq)
 'GATCGATGGGCCTATATAGGATCGAAAATCGC'
-

Since calling str() on a Seq object returns the full sequence as a string, +

Since calling str() on a Seq object returns the full sequence as a string, you often don’t actually have to do this conversion explicitly. -Python does this automatically with a print statement: -

>>> print my_seq
+Python does this automatically in the print function
+(and the print statement under Python 2):
+

>>> print(my_seq)
 GATCGATGGGCCTATATAGGATCGAAAATCGC
-

You can also use the Seq object directly with a %s placeholder when using the Python string formatting or interpolation operator (%): -

>>> fasta_format_string = ">Name\n%s\n" % my_seq
->>> print fasta_format_string
+

You can also use the Seq object directly with a %s placeholder when using the Python string formatting or interpolation operator (%): +

>>> fasta_format_string = ">Name\n%s\n" % my_seq
+>>> print(fasta_format_string)
 >Name
 GATCGATGGGCCTATATAGGATCGAAAATCGC
 <BLANKLINE>
-

This line of code constructs a simple FASTA format record (without worrying about line wrapping). -Section 4.5 describes a neat way to get a FASTA formatted -string from a SeqRecord object, while the more general topic of reading and -writing FASTA format sequence files is covered in Chapter 5.

NOTE: If you are using Biopython 1.44 or older, using str(my_seq) -will give just a truncated representation. Instead use my_seq.tostring() -(which is still available in the current Biopython releases for backwards compatibility):

>>> my_seq.tostring()
+

This line of code constructs a simple FASTA format record (without worrying about line wrapping). +Section 4.5 describes a neat way to get a FASTA formatted +string from a SeqRecord object, while the more general topic of reading and +writing FASTA format sequence files is covered in Chapter 5.

NOTE: If you are using Biopython 1.44 or older, using str(my_seq) +will give just a truncated representation. Instead use my_seq.tostring() +(which is still available in the current Biopython releases for backwards compatibility):

>>> my_seq.tostring()
 'GATCGATGGGCCTATATAGGATCGAAAATCGC'
-
-

3.5  Concatenating or adding sequences

Naturally, you can in principle add any two Seq objects together - just like you can with Python strings to concatenate them. However, you can’t add sequences with incompatible alphabets, such as a protein sequence and a DNA sequence:

>>> from Bio.Alphabet import IUPAC
+
+ +

3.5  Concatenating or adding sequences

Naturally, you can in principle add any two Seq objects together - just like you can with Python strings to concatenate them. However, you can’t add sequences with incompatible alphabets, such as a protein sequence and a DNA sequence:

>>> from Bio.Alphabet import IUPAC
 >>> from Bio.Seq import Seq
 >>> protein_seq = Seq("EVRNAK", IUPAC.protein)
 >>> dna_seq = Seq("ACGT", IUPAC.unambiguous_dna)
@@ -829,12 +862,12 @@
 Traceback (most recent call last):
 ...
 TypeError: Incompatible alphabets IUPACProtein() and IUPACUnambiguousDNA()
-

If you really wanted to do this, you’d have to first give both sequences generic alphabets:

>>> from Bio.Alphabet import generic_alphabet
+

If you really wanted to do this, you’d have to first give both sequences generic alphabets:

>>> from Bio.Alphabet import generic_alphabet
 >>> protein_seq.alphabet = generic_alphabet
 >>> dna_seq.alphabet = generic_alphabet
 >>> protein_seq + dna_seq
 Seq('EVRNAKACGT', Alphabet())
-

Here is an example of adding a generic nucleotide sequence to an unambiguous IUPAC DNA sequence, resulting in an ambiguous nucleotide sequence:

>>> from Bio.Seq import Seq
+

Here is an example of adding a generic nucleotide sequence to an unambiguous IUPAC DNA sequence, resulting in an ambiguous nucleotide sequence:

>>> from Bio.Seq import Seq
 >>> from Bio.Alphabet import generic_nucleotide
 >>> from Bio.Alphabet import IUPAC
 >>> nuc_seq = Seq("GATCGATGC", generic_nucleotide)
@@ -845,10 +878,11 @@
 Seq('ACGT', IUPACUnambiguousDNA())
 >>> nuc_seq + dna_seq
 Seq('GATCGATGCACGT', NucleotideAlphabet())
-
-

3.6  Changing case

Python strings have very useful upper and lower methods for changing the case. -As of Biopython 1.53, the Seq object gained similar methods which are alphabet aware. -For example,

>>> from Bio.Seq import Seq
+
+ +

3.6  Changing case

Python strings have very useful upper and lower methods for changing the case. +As of Biopython 1.53, the Seq object gained similar methods which are alphabet aware. +For example,

>>> from Bio.Seq import Seq
 >>> from Bio.Alphabet import generic_dna
 >>> dna_seq = Seq("acgtACGT", generic_dna)
 >>> dna_seq
@@ -857,22 +891,23 @@
 Seq('ACGTACGT', DNAAlphabet())
 >>> dna_seq.lower()
 Seq('acgtacgt', DNAAlphabet())
-

These are useful for doing case insensitive matching:

>>> "GTAC" in dna_seq
+

These are useful for doing case insensitive matching:

>>> "GTAC" in dna_seq
 False
 >>> "GTAC" in dna_seq.upper()
 True
-

Note that strictly speaking the IUPAC alphabets are for upper case -sequences only, thus:

>>> from Bio.Seq import Seq
+

Note that strictly speaking the IUPAC alphabets are for upper case +sequences only, thus:

>>> from Bio.Seq import Seq
 >>> from Bio.Alphabet import IUPAC
 >>> dna_seq = Seq("ACGT", IUPAC.unambiguous_dna)
 >>> dna_seq
 Seq('ACGT', IUPACUnambiguousDNA())
 >>> dna_seq.lower()
 Seq('acgt', DNAAlphabet())
-
-

3.7  Nucleotide sequences and (reverse) complements

-

For nucleotide sequences, you can easily obtain the complement or reverse -complement of a Seq object using its built-in methods:

>>> from Bio.Seq import Seq
+
+ +

3.7  Nucleotide sequences and (reverse) complements

+

For nucleotide sequences, you can easily obtain the complement or reverse +complement of a Seq object using its built-in methods:

>>> from Bio.Seq import Seq
 >>> from Bio.Alphabet import IUPAC
 >>> my_seq = Seq("GATCGATGGGCCTATATAGGATCGAAAATCGC", IUPAC.unambiguous_dna)
 >>> my_seq
@@ -881,39 +916,40 @@
 Seq('CTAGCTACCCGGATATATCCTAGCTTTTAGCG', IUPACUnambiguousDNA())
 >>> my_seq.reverse_complement()
 Seq('GCGATTTTCGATCCTATATAGGCCCATCGATC', IUPACUnambiguousDNA())
-

As mentioned earlier, an easy way to just reverse a Seq object (or a -Python string) is slice it with -1 step:

>>> my_seq[::-1]
+

As mentioned earlier, an easy way to just reverse a Seq object (or a +Python string) is slice it with -1 step:

>>> my_seq[::-1]
 Seq('CGCTAAAAGCTAGGATATATCCGGGTAGCTAG', IUPACUnambiguousDNA())
-

In all of these operations, the alphabet property is maintained. This is very +

In all of these operations, the alphabet property is maintained. This is very useful in case you accidentally end up trying to do something weird like take -the (reverse)complement of a protein sequence:

>>> from Bio.Seq import Seq
+the (reverse)complement of a protein sequence:

>>> from Bio.Seq import Seq
 >>> from Bio.Alphabet import IUPAC
 >>> protein_seq = Seq("EVRNAK", IUPAC.protein)
 >>> protein_seq.complement()
 Traceback (most recent call last):
 ...
 ValueError: Proteins do not have complements!
-

The example in Section 5.5.3 combines the Seq -object’s reverse complement method with Bio.SeqIO for sequence input/output.

-

3.8  Transcription

+

The example in Section 5.5.3 combines the Seq +object’s reverse complement method with Bio.SeqIO for sequence input/output.

+ +

3.8  Transcription

Before talking about transcription, I want to try and clarify the strand issue. Consider the following (made up) stretch of double stranded DNA which -encodes a short peptide:

- - - - - - - - - - - - - -
 
 DNA coding strand (aka Crick strand, strand +1) 
5’ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG3’
 ||||||||||||||||||||||||||||||||||||||| 
3’TACCGGTAACATTACCCGGCGACTTTCCCACGGGCTATC5’
 DNA template strand (aka Watson strand, strand −1) 
 
 | 
 Transcription 
  
 
5’AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG3’
 Single stranded messenger RNA 
 

The actual biological transcription process works from the template strand, doing a reverse complement (TCAG → CUGA) to give the mRNA. However, in Biopython and bioinformatics in general, we typically work directly with the coding strand because this means we can get the mRNA sequence just by switching T → U.

Now let’s actually get down to doing a transcription in Biopython. First, let’s create Seq objects for the coding and template DNA strands: -

>>> from Bio.Seq import Seq
+encodes a short peptide:

+ + + + + + + + + + + + + +
 
 DNA coding strand (aka Crick strand, strand +1) 
5’ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG3’
 ||||||||||||||||||||||||||||||||||||||| 
3’TACCGGTAACATTACCCGGCGACTTTCCCACGGGCTATC5’
 DNA template strand (aka Watson strand, strand −1) 
 
 | 
 Transcription 
  
 
5’AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG3’
 Single stranded messenger RNA 
 

The actual biological transcription process works from the template strand, doing a reverse complement (TCAG → CUGA) to give the mRNA. However, in Biopython and bioinformatics in general, we typically work directly with the coding strand because this means we can get the mRNA sequence just by switching T → U.

Now let’s actually get down to doing a transcription in Biopython. First, let’s create Seq objects for the coding and template DNA strands: +

>>> from Bio.Seq import Seq
 >>> from Bio.Alphabet import IUPAC
 >>> coding_dna = Seq("ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG", IUPAC.unambiguous_dna)
 >>> coding_dna
@@ -921,55 +957,56 @@
 >>> template_dna = coding_dna.reverse_complement()
 >>> template_dna
 Seq('CTATCGGGCACCCTTTCAGCGGCCCATTACAATGGCCAT', IUPACUnambiguousDNA())
-

These should match the figure above - remember by convention nucleotide sequences are normally read from the 5’ to 3’ direction, while in the figure the template strand is shown reversed.

Now let’s transcribe the coding strand into the corresponding mRNA, using the Seq object’s built in transcribe method: -

>>> coding_dna
+

These should match the figure above - remember by convention nucleotide sequences are normally read from the 5’ to 3’ direction, while in the figure the template strand is shown reversed.

Now let’s transcribe the coding strand into the corresponding mRNA, using the Seq object’s built in transcribe method: +

>>> coding_dna
 Seq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG', IUPACUnambiguousDNA())
 >>> messenger_rna = coding_dna.transcribe()
 >>> messenger_rna
 Seq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG', IUPACUnambiguousRNA())
-

As you can see, all this does is switch T → U, and adjust the alphabet.

If you do want to do a true biological transcription starting with the template strand, then this becomes a two-step process: -

>>> template_dna.reverse_complement().transcribe()
+

As you can see, all this does is switch T → U, and adjust the alphabet.

If you do want to do a true biological transcription starting with the template strand, then this becomes a two-step process: +

>>> template_dna.reverse_complement().transcribe()
 Seq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG', IUPACUnambiguousRNA())
-

The Seq object also includes a back-transcription method for going from the mRNA to the coding strand of the DNA. Again, this is a simple U → T substitution and associated change of alphabet: -

>>> from Bio.Seq import Seq
+

The Seq object also includes a back-transcription method for going from the mRNA to the coding strand of the DNA. Again, this is a simple U → T substitution and associated change of alphabet: +

>>> from Bio.Seq import Seq
 >>> from Bio.Alphabet import IUPAC
 >>> messenger_rna = Seq("AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG", IUPAC.unambiguous_rna)
 >>> messenger_rna
 Seq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG', IUPACUnambiguousRNA())
 >>> messenger_rna.back_transcribe()
 Seq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG', IUPACUnambiguousDNA())
-

Note: The Seq object’s transcribe and back_transcribe methods -were added in Biopython 1.49. For older releases you would have to use the Bio.Seq -module’s functions instead, see Section 3.14.

-

3.9  Translation

- +

Note: The Seq object’s transcribe and back_transcribe methods +were added in Biopython 1.49. For older releases you would have to use the Bio.Seq +module’s functions instead, see Section 3.14.

+ +

3.9  Translation

+ Sticking with the same example discussed in the transcription section above, now let’s translate this mRNA into the corresponding protein sequence - again taking -advantage of one of the Seq object’s biological methods:

>>> from Bio.Seq import Seq
+advantage of one of the Seq object’s biological methods:

>>> from Bio.Seq import Seq
 >>> from Bio.Alphabet import IUPAC
 >>> messenger_rna = Seq("AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG", IUPAC.unambiguous_rna)
 >>> messenger_rna
 Seq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG', IUPACUnambiguousRNA())
 >>> messenger_rna.translate()
 Seq('MAIVMGR*KGAR*', HasStopCodon(IUPACProtein(), '*'))
-

You can also translate directly from the coding strand DNA sequence: -

>>> from Bio.Seq import Seq
+

You can also translate directly from the coding strand DNA sequence: +

>>> from Bio.Seq import Seq
 >>> from Bio.Alphabet import IUPAC
 >>> coding_dna = Seq("ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG", IUPAC.unambiguous_dna)
 >>> coding_dna
 Seq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG', IUPACUnambiguousDNA())
 >>> coding_dna.translate()
 Seq('MAIVMGR*KGAR*', HasStopCodon(IUPACProtein(), '*'))
-

You should notice in the above protein sequences that in addition to the end stop character, there is an internal stop as well. This was a deliberate choice of example, as it gives an excuse to talk about some optional arguments, including different translation tables (Genetic Codes).

The translation tables available in Biopython are based on those from the NCBI (see the next section of this tutorial). By default, translation will use the standard genetic code (NCBI table id 1). +

You should notice in the above protein sequences that in addition to the end stop character, there is an internal stop as well. This was a deliberate choice of example, as it gives an excuse to talk about some optional arguments, including different translation tables (Genetic Codes).

The translation tables available in Biopython are based on those from the NCBI (see the next section of this tutorial). By default, translation will use the standard genetic code (NCBI table id 1). Suppose we are dealing with a mitochondrial sequence. We need to tell the translation function to use the relevant genetic code instead: -

>>> coding_dna.translate(table="Vertebrate Mitochondrial")
+

>>> coding_dna.translate(table="Vertebrate Mitochondrial")
 Seq('MAIVMGRWKGAR*', HasStopCodon(IUPACProtein(), '*'))
-

You can also specify the table using the NCBI table number which is shorter, and often included in the feature annotation of GenBank files: -

>>> coding_dna.translate(table=2)
+

You can also specify the table using the NCBI table number which is shorter, and often included in the feature annotation of GenBank files: +

>>> coding_dna.translate(table=2)
 Seq('MAIVMGRWKGAR*', HasStopCodon(IUPACProtein(), '*'))
-

Now, you may want to translate the nucleotides up to the first in frame stop codon, +

Now, you may want to translate the nucleotides up to the first in frame stop codon, and then stop (as happens in nature): -

>>> coding_dna.translate()
+

>>> coding_dna.translate()
 Seq('MAIVMGR*KGAR*', HasStopCodon(IUPACProtein(), '*'))
 >>> coding_dna.translate(to_stop=True)
 Seq('MAIVMGR', IUPACProtein())
@@ -977,19 +1014,19 @@
 Seq('MAIVMGRWKGAR*', HasStopCodon(IUPACProtein(), '*'))
 >>> coding_dna.translate(table=2, to_stop=True)
 Seq('MAIVMGRWKGAR', IUPACProtein())
-

Notice that when you use the to_stop argument, the stop codon itself +

Notice that when you use the to_stop argument, the stop codon itself is not translated - and the stop symbol is not included at the end of your protein -sequence.

You can even specify the stop symbol if you don’t like the default asterisk: -

>>> coding_dna.translate(table=2, stop_symbol="@")
+sequence.

You can even specify the stop symbol if you don’t like the default asterisk: +

>>> coding_dna.translate(table=2, stop_symbol="@")
 Seq('MAIVMGRWKGAR@', HasStopCodon(IUPACProtein(), '@'))
-

Now, suppose you have a complete coding sequence CDS, which is to say a +

Now, suppose you have a complete coding sequence CDS, which is to say a nucleotide sequence (e.g. mRNA – after any splicing) which is a whole number of codons (i.e. the length is a multiple of three), commences with a start codon, ends with a stop codon, and has no internal in-frame stop codons. In general, given a complete CDS, the default translate method will do what -you want (perhaps with the to_stop option). However, what if your +you want (perhaps with the to_stop option). However, what if your sequence uses a non-standard start codon? This happens a lot in bacteria – -for example the gene yaaX in E. coli K12:

>>> from Bio.Seq import Seq
+for example the gene yaaX in E. coli K12:

>>> from Bio.Seq import Seq
 >>> from Bio.Alphabet import generic_dna
 >>> gene = Seq("GTGAAAAAGATGCAATCTATCGTACTCGCACTTTCCCTGGTTCTGGTCGCTCCCATGGCA" + \
 ...            "GCACAGGCTGCGGAAATTACGTTAGTCCCGTCAGTAAAATTACAGATAGGCGATCGTGAT" + \
@@ -1003,30 +1040,31 @@
 >>> gene.translate(table="Bacterial", to_stop=True)
 Seq('VKKMQSIVLALSLVLVAPMAAQAAEITLVPSVKLQIGDRDNRGYYWDGGHWRDH...HHR',
 ExtendedIUPACProtein())
-

In the bacterial genetic code GTG is a valid start codon, -and while it does normally encode Valine, if used as a start codon it +

In the bacterial genetic code GTG is a valid start codon, +and while it does normally encode Valine, if used as a start codon it should be translated as methionine. This happens if you tell Biopython your -sequence is a complete CDS:

>>> gene.translate(table="Bacterial", cds=True)
+sequence is a complete CDS:

>>> gene.translate(table="Bacterial", cds=True)
 Seq('MKKMQSIVLALSLVLVAPMAAQAAEITLVPSVKLQIGDRDNRGYYWDGGHWRDH...HHR',
 ExtendedIUPACProtein())
-

In addition to telling Biopython to translate an alternative start codon as +

In addition to telling Biopython to translate an alternative start codon as methionine, using this option also makes sure your sequence really is a valid -CDS (you’ll get an exception if not).

The example in Section 18.1.3 combines the Seq object’s -translate method with Bio.SeqIO for sequence input/output.

-

3.10  Translation Tables

In the previous sections we talked about the Seq object translation method (and mentioned the equivalent function in the Bio.Seq module – see -Section 3.14). +CDS (you’ll get an exception if not).

The example in Section 18.1.3 combines the Seq object’s +translate method with Bio.SeqIO for sequence input/output.

+ +

3.10  Translation Tables

In the previous sections we talked about the Seq object translation method (and mentioned the equivalent function in the Bio.Seq module – see +Section 3.14). Internally these use codon table objects derived from the NCBI information at -ftp://ftp.ncbi.nlm.nih.gov/entrez/misc/data/gc.prt, also shown on -http://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi in a much more readable layout.

As before, let’s just focus on two choices: the Standard translation table, and the -translation table for Vertebrate Mitochondrial DNA.

>>> from Bio.Data import CodonTable
+ftp://ftp.ncbi.nlm.nih.gov/entrez/misc/data/gc.prt, also shown on
+http://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi in a much more readable layout.

As before, let’s just focus on two choices: the Standard translation table, and the +translation table for Vertebrate Mitochondrial DNA.

>>> from Bio.Data import CodonTable
 >>> standard_table = CodonTable.unambiguous_dna_by_name["Standard"]
 >>> mito_table = CodonTable.unambiguous_dna_by_name["Vertebrate Mitochondrial"]
-

Alternatively, these tables are labeled with ID numbers 1 and 2, respectively: -

>>> from Bio.Data import CodonTable
+

Alternatively, these tables are labeled with ID numbers 1 and 2, respectively: +

>>> from Bio.Data import CodonTable
 >>> standard_table = CodonTable.unambiguous_dna_by_id[1]
 >>> mito_table = CodonTable.unambiguous_dna_by_id[2]
-

You can compare the actual tables visually by printing them: -

>>> print standard_table
+

You can compare the actual tables visually by printing them: +

>>> print(standard_table)
 Table 1 Standard, SGC0
 
   |  T      |  C      |  A      |  G      |
@@ -1051,8 +1089,8 @@
 G | GTA V   | GCA A   | GAA E   | GGA G   | A
 G | GTG V   | GCG A   | GAG E   | GGG G   | G
 --+---------+---------+---------+---------+--
-

and: -

>>> print mito_table
+

and: +

>>> print(mito_table)
 Table 2 Vertebrate Mitochondrial, SGC1
 
   |  T      |  C      |  A      |  G      |
@@ -1077,80 +1115,82 @@
 G | GTA V   | GCA A   | GAA E   | GGA G   | A
 G | GTG V(s)| GCG A   | GAG E   | GGG G   | G
 --+---------+---------+---------+---------+--
-

You may find these following properties useful – for example if you are trying +

You may find these following properties useful – for example if you are trying to do your own gene finding: -

>>> mito_table.stop_codons
+

>>> mito_table.stop_codons
 ['TAA', 'TAG', 'AGA', 'AGG']
 >>> mito_table.start_codons
 ['ATT', 'ATC', 'ATA', 'ATG', 'GTG']
 >>> mito_table.forward_table["ACG"]
 'T'
-
-

3.11  Comparing Seq objects

-

Sequence comparison is actually a very complicated topic, and there is no easy +

+ +

3.11  Comparing Seq objects

+

Sequence comparison is actually a very complicated topic, and there is no easy way to decide if two sequences are equal. The basic problem is the meaning of the letters in a sequence are context dependent - the letter “A” could be part of a DNA, RNA or protein sequence. Biopython uses alphabet objects as part of -each Seq object to try and capture this information - so comparing two -Seq objects means considering both the sequence strings and the -alphabets.

For example, you might argue that the two DNA Seq objects -Seq("ACGT", IUPAC.unambiguous_dna) and -Seq("ACGT", IUPAC.ambiguous_dna) should be equal, even though +each Seq object to try and capture this information - so comparing two +Seq objects means considering both the sequence strings and the +alphabets.

For example, you might argue that the two DNA Seq objects +Seq("ACGT", IUPAC.unambiguous_dna) and +Seq("ACGT", IUPAC.ambiguous_dna) should be equal, even though they do have different alphabets. Depending on the context this could be -important.

This gets worse – suppose you think Seq("ACGT", -IUPAC.unambiguous_dna) and Seq("ACGT") (i.e. the default generic -alphabet) should be equal. Then, logically, Seq("ACGT", IUPAC.protein) -and Seq("ACGT") should also be equal. Now, in logic if A=B and -B=C, by transitivity we expect A=C. So for logical consistency we’d -require Seq("ACGT", IUPAC.unambiguous_dna) and Seq("ACGT", -IUPAC.protein) to be equal – which most people would agree is just not right. -This transitivity problem would also have implications for using Seq -objects as Python dictionary keys.

>>> from Bio.Seq import Seq
+important.

This gets worse – suppose you think Seq("ACGT", +IUPAC.unambiguous_dna) and Seq("ACGT") (i.e. the default generic +alphabet) should be equal. Then, logically, Seq("ACGT", IUPAC.protein) +and Seq("ACGT") should also be equal. Now, in logic if A=B and +B=C, by transitivity we expect A=C. So for logical consistency we’d +require Seq("ACGT", IUPAC.unambiguous_dna) and Seq("ACGT", +IUPAC.protein) to be equal – which most people would agree is just not right. +This transitivity problem would also have implications for using Seq +objects as Python dictionary keys.

>>> from Bio.Seq import Seq
 >>> from Bio.Alphabet import IUPAC
 >>> seq1 = Seq("ACGT", IUPAC.unambiguous_dna)
 >>> seq2 = Seq("ACGT", IUPAC.unambiguous_dna)
-

So, what does Biopython do? Well, the equality test is the default for Python +

So, what does Biopython do? Well, the equality test is the default for Python objects – it tests to see if they are the same object in memory. This is a very strict test: -

>>> seq1 == seq2
+

>>> seq1 == seq2
 False
 >>> seq1 == seq1
 True
-

If you actually want to do this, you can be more explicit by using the Python -id function, -

>>> id(seq1) == id(seq2)
+

If you actually want to do this, you can be more explicit by using the Python +id function, +

>>> id(seq1) == id(seq2)
 False
 >>> id(seq1) == id(seq1)
 True
-

Now, in every day use, your sequences will probably all have the same +

Now, in every day use, your sequences will probably all have the same alphabet, or at least all be the same type of sequence (all DNA, all RNA, or all protein). What you probably want is to just compare the sequences as strings – so do this explicitly: -

>>> str(seq1) == str(seq2)
+

>>> str(seq1) == str(seq2)
 True
 >>> str(seq1) == str(seq1)
 True
-

As an extension to this, while you can use a Python dictionary with -Seq objects as keys, it is generally more useful to use the sequence a -string for the key. See also Section 3.4.

-

3.12  MutableSeq objects

-

Just like the normal Python string, the Seq object is “read only”, or in Python terminology, immutable. Apart from wanting the Seq object to act like a string, this is also a useful default since in many biological applications you want to ensure you are not changing your sequence data:

>>> from Bio.Seq import Seq
+

As an extension to this, while you can use a Python dictionary with +Seq objects as keys, it is generally more useful to use the sequence a +string for the key. See also Section 3.4.

+ +

3.12  MutableSeq objects

+

Just like the normal Python string, the Seq object is “read only”, or in Python terminology, immutable. Apart from wanting the Seq object to act like a string, this is also a useful default since in many biological applications you want to ensure you are not changing your sequence data:

>>> from Bio.Seq import Seq
 >>> from Bio.Alphabet import IUPAC
 >>> my_seq = Seq("GCCATTGTAATGGGCCGCTGAAAGGGTGCCCGA", IUPAC.unambiguous_dna)
-

Observe what happens if you try to edit the sequence: -

>>> my_seq[5] = "G"
+

Observe what happens if you try to edit the sequence: +

>>> my_seq[5] = "G"
 Traceback (most recent call last):
 ...
 TypeError: 'Seq' object does not support item assignment
-

However, you can convert it into a mutable sequence (a MutableSeq object) and do pretty much anything you want with it:

>>> mutable_seq = my_seq.tomutable()
+

However, you can convert it into a mutable sequence (a MutableSeq object) and do pretty much anything you want with it:

>>> mutable_seq = my_seq.tomutable()
 >>> mutable_seq
 MutableSeq('GCCATTGTAATGGGCCGCTGAAAGGGTGCCCGA', IUPACUnambiguousDNA())
-

Alternatively, you can create a MutableSeq object directly from a string: -

>>> from Bio.Seq import MutableSeq
+

Alternatively, you can create a MutableSeq object directly from a string: +

>>> from Bio.Seq import MutableSeq
 >>> from Bio.Alphabet import IUPAC
 >>> mutable_seq = MutableSeq("GCCATTGTAATGGGCCGCTGAAAGGGTGCCCGA", IUPAC.unambiguous_dna)
-

Either way will give you a sequence object which can be changed: -

>>> mutable_seq
+

Either way will give you a sequence object which can be changed: +

>>> mutable_seq
 MutableSeq('GCCATTGTAATGGGCCGCTGAAAGGGTGCCCGA', IUPACUnambiguousDNA())
 >>> mutable_seq[5] = "C"
 >>> mutable_seq
@@ -1161,34 +1201,35 @@
 >>> mutable_seq.reverse()
 >>> mutable_seq
 MutableSeq('AGCCCGTGGGAAAGTCGCCGGGTAATGCACCG', IUPACUnambiguousDNA())
-

Do note that unlike the Seq object, the MutableSeq object’s methods like reverse_complement() and reverse() act in-situ!

An important technical difference between mutable and immutable objects in Python means that you can’t use a MutableSeq object as a dictionary key, but you can use a Python string or a Seq object in this way.

Once you have finished editing your a MutableSeq object, it’s easy to get back to a read-only Seq object should you need to:

>>> new_seq = mutable_seq.toseq()
+

Do note that unlike the Seq object, the MutableSeq object’s methods like reverse_complement() and reverse() act in-situ!

An important technical difference between mutable and immutable objects in Python means that you can’t use a MutableSeq object as a dictionary key, but you can use a Python string or a Seq object in this way.

Once you have finished editing your a MutableSeq object, it’s easy to get back to a read-only Seq object should you need to:

>>> new_seq = mutable_seq.toseq()
 >>> new_seq
 Seq('AGCCCGTGGGAAAGTCGCCGGGTAATGCACCG', IUPACUnambiguousDNA())
-

You can also get a string from a MutableSeq object just like from a Seq object (Section 3.4).

-

3.13  UnknownSeq objects

-The UnknownSeq object is a subclass of the basic Seq object +

You can also get a string from a MutableSeq object just like from a Seq object (Section 3.4).

+ +

3.13  UnknownSeq objects

+The UnknownSeq object is a subclass of the basic Seq object and its purpose is to represent a sequence where we know the length, but not the actual letters making it up. -You could of course use a normal Seq object in this situation, but it wastes +You could of course use a normal Seq object in this situation, but it wastes rather a lot of memory to hold a string of a million “N” characters when you could -just store a single letter “N” and the desired length as an integer.

>>> from Bio.Seq import UnknownSeq
+just store a single letter “N” and the desired length as an integer.

>>> from Bio.Seq import UnknownSeq
 >>> unk = UnknownSeq(20)
 >>> unk
 UnknownSeq(20, alphabet = Alphabet(), character = '?')
->>> print unk
+>>> print(unk)
 ????????????????????
 >>> len(unk)
 20
-

You can of course specify an alphabet, meaning for nucleotide sequences -the letter defaults to “N” and for proteins “X”, rather than just “?”.

>>> from Bio.Seq import UnknownSeq
+

You can of course specify an alphabet, meaning for nucleotide sequences +the letter defaults to “N” and for proteins “X”, rather than just “?”.

>>> from Bio.Seq import UnknownSeq
 >>> from Bio.Alphabet import IUPAC
 >>> unk_dna = UnknownSeq(20, alphabet=IUPAC.ambiguous_dna)
 >>> unk_dna
 UnknownSeq(20, alphabet = IUPACAmbiguousDNA(), character = 'N')
->>> print unk_dna
+>>> print(unk_dna)
 NNNNNNNNNNNNNNNNNNNN
-

You can use all the usual Seq object methods too, note these give back -memory saving UnknownSeq objects where appropriate as you might expect:

>>> unk_dna
+

You can use all the usual Seq object methods too, note these give back +memory saving UnknownSeq objects where appropriate as you might expect:

>>> unk_dna
 UnknownSeq(20, alphabet = IUPACAmbiguousDNA(), character = 'N')
 >>> unk_dna.complement()
 UnknownSeq(20, alphabet = IUPACAmbiguousDNA(), character = 'N')
@@ -1199,26 +1240,27 @@
 >>> unk_protein = unk_dna.translate()
 >>> unk_protein
 UnknownSeq(6, alphabet = ProteinAlphabet(), character = 'X')
->>> print unk_protein
+>>> print(unk_protein)
 XXXXXX
 >>> len(unk_protein)
 6
-

You may be able to find a use for the UnknownSeq object in your own +

You may be able to find a use for the UnknownSeq object in your own code, but it is more likely that you will first come across them in a -SeqRecord object created by Bio.SeqIO -(see Chapter 5). +SeqRecord object created by Bio.SeqIO +(see Chapter 5). Some sequence file formats don’t always include the actual sequence, for example GenBank and EMBL files may include a list of features but for the sequence just present the contig information. Alternatively, the QUAL files -used in sequencing work hold quality scores but they never contain a -sequence – instead there is a partner FASTA file which does have the -sequence.

-

3.14  Working with directly strings

- -To close this chapter, for those you who really don’t want to use the sequence +used in sequencing work hold quality scores but they never contain a +sequence – instead there is a partner FASTA file which does have the +sequence.

+ +

3.14  Working with strings directly

+ +To close this chapter, for those you who really don’t want to use the sequence objects (or who prefer a functional programming style to an object orientated one), -there are module level functions in Bio.Seq will accept plain Python strings, -Seq objects (including UnknownSeq objects) or MutableSeq objects:

>>> from Bio.Seq import reverse_complement, transcribe, back_transcribe, translate
+there are module level functions in Bio.Seq will accept plain Python strings,
+Seq objects (including UnknownSeq objects) or MutableSeq objects:

>>> from Bio.Seq import reverse_complement, transcribe, back_transcribe, translate
 >>> my_string = "GCTGTTATGGGTCGTTGGAAGGGTGGTCGTGCTGCTGGTTAG"
 >>> reverse_complement(my_string)
 'CTAACCAGCAGCACGACCACCCTTCCAACGACCCATAACAGC'
@@ -1228,91 +1270,96 @@
 'GCTGTTATGGGTCGTTGGAAGGGTGGTCGTGCTGCTGGTTAG'
 >>> translate(my_string)
 'AVMGRWKGGRAAG*'
-

You are, however, encouraged to work with Seq objects by default.

-

Chapter 4  Sequence annotation objects

-

Chapter 3 introduced the sequence classes. Immediately “above” the Seq class is the Sequence Record or SeqRecord class, defined in the Bio.SeqRecord module. This class allows higher level features such as identifiers and features (as SeqFeature objects) to be associated with the sequence, and is used throughout the sequence input/output interface Bio.SeqIO described fully in Chapter 5.

If you are only going to be working with simple data like FASTA files, you can probably skip this chapter +

You are, however, encouraged to work with Seq objects by default.

+ +

Chapter 4  Sequence annotation objects

+

Chapter 3 introduced the sequence classes. Immediately “above” the Seq class is the Sequence Record or SeqRecord class, defined in the Bio.SeqRecord module. This class allows higher level features such as identifiers and features (as SeqFeature objects) to be associated with the sequence, and is used throughout the sequence input/output interface Bio.SeqIO described fully in Chapter 5.

If you are only going to be working with simple data like FASTA files, you can probably skip this chapter for now. If on the other hand you are going to be using richly annotated sequence data, say from GenBank -or EMBL files, this information is quite important.

While this chapter should cover most things to do with the SeqRecord and SeqFeature objects in this chapter, you may also want to read the SeqRecord wiki page (http://biopython.org/wiki/SeqRecord), and the built in documentation (also online – SeqRecord and SeqFeature):

>>> from Bio.SeqRecord import SeqRecord
+or EMBL files, this information is quite important.

While this chapter should cover most things to do with the SeqRecord and SeqFeature objects in this chapter, you may also want to read the SeqRecord wiki page (http://biopython.org/wiki/SeqRecord), and the built in documentation (also online – SeqRecord and SeqFeature):

>>> from Bio.SeqRecord import SeqRecord
 >>> help(SeqRecord)
 ...
-
-

4.1  The SeqRecord object

-

The SeqRecord (Sequence Record) class is defined in the Bio.SeqRecord module. This class allows higher level features such as identifiers and features to be associated with a sequence (see Chapter 3), and is the basic data type for the Bio.SeqIO sequence input/output interface (see Chapter 5).

The SeqRecord class itself is quite simple, and offers the following information as attributes:

-.seq
– The sequence itself, typically a Seq object.
.id
– The primary ID used to identify the sequence – a string. In most cases this is something like an accession number.
.name
– A “common” name/id for the sequence – a string. In some cases this will be the same as the accession number, but it could also be a clone name. I think of this as being analogous to the LOCUS id in a GenBank record.
.description
– A human readable description or expressive name for the sequence – a string.
.letter_annotations
– Holds per-letter-annotations using a (restricted) dictionary of additional information about the letters in the sequence. The keys are the name of the information, and the information is contained in the value as a Python sequence (i.e. a list, tuple or string) with the same length as the sequence itself. This is often used for quality scores (e.g. Section 18.1.6) or secondary structure information (e.g. from Stockholm/PFAM alignment files).
.annotations
– A dictionary of additional information about the sequence. The keys are the name of the information, and the information is contained in the value. This allows the addition of more “unstructured” information to the sequence.
.features
– A list of SeqFeature objects with more structured information about the features on a sequence (e.g. position of genes on a genome, or domains on a protein sequence). The structure of sequence features is described below in Section 4.3.
.dbxrefs
- A list of database cross-references as strings. -
-

4.2  Creating a SeqRecord

Using a SeqRecord object is not very complicated, since all of the +

+ +

4.1  The SeqRecord object

+

The SeqRecord (Sequence Record) class is defined in the Bio.SeqRecord module. This class allows higher level features such as identifiers and features to be associated with a sequence (see Chapter 3), and is the basic data type for the Bio.SeqIO sequence input/output interface (see Chapter 5).

The SeqRecord class itself is quite simple, and offers the following information as attributes:

+.seq
– The sequence itself, typically a Seq object.
.id
– The primary ID used to identify the sequence – a string. In most cases this is something like an accession number.
.name
– A “common” name/id for the sequence – a string. In some cases this will be the same as the accession number, but it could also be a clone name. I think of this as being analogous to the LOCUS id in a GenBank record.
.description
– A human readable description or expressive name for the sequence – a string.
.letter_annotations
– Holds per-letter-annotations using a (restricted) dictionary of additional information about the letters in the sequence. The keys are the name of the information, and the information is contained in the value as a Python sequence (i.e. a list, tuple or string) with the same length as the sequence itself. This is often used for quality scores (e.g. Section 18.1.6) or secondary structure information (e.g. from Stockholm/PFAM alignment files).
.annotations
– A dictionary of additional information about the sequence. The keys are the name of the information, and the information is contained in the value. This allows the addition of more “unstructured” information to the sequence.
.features
– A list of SeqFeature objects with more structured information about the features on a sequence (e.g. position of genes on a genome, or domains on a protein sequence). The structure of sequence features is described below in Section 4.3.
.dbxrefs
- A list of database cross-references as strings. +
+ +

4.2  Creating a SeqRecord

Using a SeqRecord object is not very complicated, since all of the information is presented as attributes of the class. Usually you won’t create -a SeqRecord “by hand”, but instead use Bio.SeqIO to read in a -sequence file for you (see Chapter 5 and the examples -below). However, creating SeqRecord can be quite simple.

-

4.2.1  SeqRecord objects from scratch

To create a SeqRecord at a minimum you just need a Seq object:

>>> from Bio.Seq import Seq
+a SeqRecord “by hand”, but instead use Bio.SeqIO to read in a
+sequence file for you (see Chapter 5 and the examples
+below). However, creating SeqRecord can be quite simple.

+ +

4.2.1  SeqRecord objects from scratch

To create a SeqRecord at a minimum you just need a Seq object:

>>> from Bio.Seq import Seq
 >>> simple_seq = Seq("GATC")
 >>> from Bio.SeqRecord import SeqRecord
 >>> simple_seq_r = SeqRecord(simple_seq)
-

Additionally, you can also pass the id, name and description to the initialization function, but if not they will be set as strings indicating they are unknown, and can be modified subsequently:

>>> simple_seq_r.id
+

Additionally, you can also pass the id, name and description to the initialization function, but if not they will be set as strings indicating they are unknown, and can be modified subsequently:

>>> simple_seq_r.id
 '<unknown id>'
 >>> simple_seq_r.id = "AC12345"
 >>> simple_seq_r.description = "Made up sequence I wish I could write a paper about"
->>> print simple_seq_r.description
+>>> print(simple_seq_r.description)
 Made up sequence I wish I could write a paper about
 >>> simple_seq_r.seq
 Seq('GATC', Alphabet())
-

Including an identifier is very important if you want to output your SeqRecord to a file. You would normally include this when creating the object:

>>> from Bio.Seq import Seq
+

Including an identifier is very important if you want to output your SeqRecord to a file. You would normally include this when creating the object:

>>> from Bio.Seq import Seq
 >>> simple_seq = Seq("GATC")
 >>> from Bio.SeqRecord import SeqRecord
 >>> simple_seq_r = SeqRecord(simple_seq, id="AC12345")
-

As mentioned above, the SeqRecord has an dictionary attribute annotations. This is used +

As mentioned above, the SeqRecord has an dictionary attribute annotations. This is used for any miscellaneous annotations that doesn’t fit under one of the other more specific attributes. -Adding annotations is easy, and just involves dealing directly with the annotation dictionary:

>>> simple_seq_r.annotations["evidence"] = "None. I just made it up."
->>> print simple_seq_r.annotations
+Adding annotations is easy, and just involves dealing directly with the annotation dictionary:

>>> simple_seq_r.annotations["evidence"] = "None. I just made it up."
+>>> print(simple_seq_r.annotations)
 {'evidence': 'None. I just made it up.'}
->>> print simple_seq_r.annotations["evidence"]
+>>> print(simple_seq_r.annotations["evidence"])
 None. I just made it up.
-

Working with per-letter-annotations is similar, letter_annotations is a +

Working with per-letter-annotations is similar, letter_annotations is a dictionary like attribute which will let you assign any Python sequence (i.e. -a string, list or tuple) which has the same length as the sequence:

>>> simple_seq_r.letter_annotations["phred_quality"] = [40,40,38,30]
->>> print simple_seq_r.letter_annotations
+a string, list or tuple) which has the same length as the sequence:

>>> simple_seq_r.letter_annotations["phred_quality"] = [40, 40, 38, 30]
+>>> print(simple_seq_r.letter_annotations)
 {'phred_quality': [40, 40, 38, 30]}
->>> print simple_seq_r.letter_annotations["phred_quality"]
+>>> print(simple_seq_r.letter_annotations["phred_quality"])
 [40, 40, 38, 30]
-

The dbxrefs and features attributes are just Python lists, and -should be used to store strings and SeqFeature objects (discussed later -in this chapter) respectively.

-

4.2.2  SeqRecord objects from FASTA files

This example uses a fairly large FASTA file containing the whole sequence for Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, originally downloaded from the NCBI. This file is included with the Biopython unit tests under the GenBank folder, or online NC_005816.fna from our website.

The file starts like this - and you can check there is only one record present (i.e. only one line starting with a greater than symbol):

>gi|45478711|ref|NC_005816.1| Yersinia pestis biovar Microtus ... pPCP1, complete sequence
+

The dbxrefs and features attributes are just Python lists, and +should be used to store strings and SeqFeature objects (discussed later +in this chapter) respectively.

+ +

4.2.2  SeqRecord objects from FASTA files

This example uses a fairly large FASTA file containing the whole sequence for Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, originally downloaded from the NCBI. This file is included with the Biopython unit tests under the GenBank folder, or online NC_005816.fna from our website.

The file starts like this - and you can check there is only one record present (i.e. only one line starting with a greater than symbol):

>gi|45478711|ref|NC_005816.1| Yersinia pestis biovar Microtus ... pPCP1, complete sequence
 TGTAACGAACGGTGCAATAGTGATCCACACCCAACGCCTGAAATCAGATCCAGGGGGTAATCTGCTCTCC
 ...
-

Back in Chapter 2 you will have seen the function Bio.SeqIO.parse(...) -used to loop over all the records in a file as SeqRecord objects. The Bio.SeqIO module -has a sister function for use on files which contain just one record which we’ll use here (see Chapter 5 for details):

>>> from Bio import SeqIO
+

Back in Chapter 2 you will have seen the function Bio.SeqIO.parse(...) +used to loop over all the records in a file as SeqRecord objects. The Bio.SeqIO module +has a sister function for use on files which contain just one record which we’ll use here (see Chapter 5 for details):

>>> from Bio import SeqIO
 >>> record = SeqIO.read("NC_005816.fna", "fasta")
 >>> record
 SeqRecord(seq=Seq('TGTAACGAACGGTGCAATAGTGATCCACACCCAACGCCTGAAATCAGATCCAGG...CTG',
 SingleLetterAlphabet()), id='gi|45478711|ref|NC_005816.1|', name='gi|45478711|ref|NC_005816.1|',
 description='gi|45478711|ref|NC_005816.1| Yersinia pestis biovar Microtus ... sequence',
 dbxrefs=[])
-

Now, let’s have a look at the key attributes of this SeqRecord -individually – starting with the seq attribute which gives you a -Seq object:

>>> record.seq
+

Now, let’s have a look at the key attributes of this SeqRecord +individually – starting with the seq attribute which gives you a +Seq object:

>>> record.seq
 Seq('TGTAACGAACGGTGCAATAGTGATCCACACCCAACGCCTGAAATCAGATCCAGG...CTG', SingleLetterAlphabet())
-

Here Bio.SeqIO has defaulted to a generic alphabet, rather +

Here Bio.SeqIO has defaulted to a generic alphabet, rather than guessing that this is DNA. If you know in advance what kind of sequence -your FASTA file contains, you can tell Bio.SeqIO which alphabet to use -(see Chapter 5).

Next, the identifiers and description:

>>> record.id
+your FASTA file contains, you can tell Bio.SeqIO which alphabet to use
+(see Chapter 5).

Next, the identifiers and description:

>>> record.id
 'gi|45478711|ref|NC_005816.1|'
 >>> record.name
 'gi|45478711|ref|NC_005816.1|'
 >>> record.description
 'gi|45478711|ref|NC_005816.1| Yersinia pestis biovar Microtus ... pPCP1, complete sequence'
-

As you can see above, the first word of the FASTA record’s title line (after -removing the greater than symbol) is used for both the id and -name attributes. The whole title line (after removing the greater than +

As you can see above, the first word of the FASTA record’s title line (after +removing the greater than symbol) is used for both the id and +name attributes. The whole title line (after removing the greater than symbol) is used for the record description. This is deliberate, partly for backwards compatibility reasons, but it also makes sense if you have a FASTA -file like this:

>Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1
+file like this:

>Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1
 TGTAACGAACGGTGCAATAGTGATCCACACCCAACGCCTGAAATCAGATCCAGGGGGTAATCTGCTCTCC
 ...
-

Note that none of the other annotation attributes get populated when reading a -FASTA file:

>>> record.dbxrefs
+

Note that none of the other annotation attributes get populated when reading a +FASTA file:

>>> record.dbxrefs
 []
 >>> record.annotations
 {}
@@ -1320,81 +1367,88 @@
 {}
 >>> record.features
 []
-

In this case our example FASTA file was from the NCBI, and they have a fairly well defined set of conventions for formatting their FASTA lines. This means it would be possible to parse this information and extract the GI number and accession for example. However, FASTA files from other sources vary, so this isn’t possible in general.

-

4.2.3  SeqRecord objects from GenBank files

As in the previous example, we’re going to look at the whole sequence for Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, originally downloaded from the NCBI, but this time as a GenBank file. -Again, this file is included with the Biopython unit tests under the GenBank folder, or online NC_005816.gb from our website.

This file contains a single record (i.e. only one LOCUS line) and starts: -

LOCUS       NC_005816               9609 bp    DNA     circular BCT 21-JUL-2008
+

In this case our example FASTA file was from the NCBI, and they have a fairly well defined set of conventions for formatting their FASTA lines. This means it would be possible to parse this information and extract the GI number and accession for example. However, FASTA files from other sources vary, so this isn’t possible in general.

+ +

4.2.3  SeqRecord objects from GenBank files

As in the previous example, we’re going to look at the whole sequence for Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, originally downloaded from the NCBI, but this time as a GenBank file. +Again, this file is included with the Biopython unit tests under the GenBank folder, or online NC_005816.gb from our website.

This file contains a single record (i.e. only one LOCUS line) and starts: +

LOCUS       NC_005816               9609 bp    DNA     circular BCT 21-JUL-2008
 DEFINITION  Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete
             sequence.
 ACCESSION   NC_005816
 VERSION     NC_005816.1  GI:45478711
 PROJECT     GenomeProject:10638
 ...
-

Again, we’ll use Bio.SeqIO to read this file in, and the code is almost identical to that for used above for the FASTA file (see Chapter 5 for details):

>>> from Bio import SeqIO
+

Again, we’ll use Bio.SeqIO to read this file in, and the code is almost identical to that for used above for the FASTA file (see Chapter 5 for details):

>>> from Bio import SeqIO
 >>> record = SeqIO.read("NC_005816.gb", "genbank")
 >>> record
 SeqRecord(seq=Seq('TGTAACGAACGGTGCAATAGTGATCCACACCCAACGCCTGAAATCAGATCCAGG...CTG',
 IUPACAmbiguousDNA()), id='NC_005816.1', name='NC_005816',
 description='Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete sequence.',
 dbxrefs=['Project:10638'])
-

You should be able to spot some differences already! But taking the attributes individually, -the sequence string is the same as before, but this time Bio.SeqIO has been able to automatically assign a more specific alphabet (see Chapter 5 for details):

>>> record.seq
+

You should be able to spot some differences already! But taking the attributes individually, +the sequence string is the same as before, but this time Bio.SeqIO has been able to automatically assign a more specific alphabet (see Chapter 5 for details):

>>> record.seq
 Seq('TGTAACGAACGGTGCAATAGTGATCCACACCCAACGCCTGAAATCAGATCCAGG...CTG', IUPACAmbiguousDNA())
-

The name comes from the LOCUS line, while the id includes the version suffix. -The description comes from the DEFINITION line:

>>> record.id
+

The name comes from the LOCUS line, while the id includes the version suffix. +The description comes from the DEFINITION line:

>>> record.id
 'NC_005816.1'
 >>> record.name
 'NC_005816'
 >>> record.description
 'Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete sequence.'
-

GenBank files don’t have any per-letter annotations:

>>> record.letter_annotations
+

GenBank files don’t have any per-letter annotations:

>>> record.letter_annotations
 {}
-

Most of the annotations information gets recorded in the annotations dictionary, for example:

>>> len(record.annotations)
+

Most of the annotations information gets recorded in the annotations dictionary, for example:

>>> len(record.annotations)
 11
 >>> record.annotations["source"]
 'Yersinia pestis biovar Microtus str. 91001'
-

The dbxrefs list gets populated from any PROJECT or DBLINK lines:

>>> record.dbxrefs
+

The dbxrefs list gets populated from any PROJECT or DBLINK lines:

>>> record.dbxrefs
 ['Project:10638']
-

Finally, and perhaps most interestingly, all the entries in the features table (e.g. the genes or CDS features) get recorded as SeqFeature objects in the features list.

>>> len(record.features)
+

Finally, and perhaps most interestingly, all the entries in the features table (e.g. the genes or CDS features) get recorded as SeqFeature objects in the features list.

>>> len(record.features)
 29
-

We’ll talk about SeqFeature objects next, in -Section 4.3.

-

4.3  Feature, location and position objects

-

-

4.3.1  SeqFeature objects

Sequence features are an essential part of describing a sequence. Once you get beyond the sequence itself, you need some way to organize and easily get at the more “abstract” information that is known about the sequence. While it is probably impossible to develop a general sequence feature class that will cover everything, the Biopython SeqFeature class attempts to encapsulate as much of the information about the sequence as possible. The design is heavily based on the GenBank/EMBL feature tables, so if you understand how they look, you’ll probably have an easier time grasping the structure of the Biopython classes.

The key idea about each SeqFeature object is to describe a region on a parent sequence, typically a SeqRecord object. That region is described with a location object, typically a range between two positions (see Section 4.3.2 below).

The SeqFeature class has a number of attributes, so first we’ll list them and their general features, and then later in the chapter work through examples to show how this applies to a real life example. The attributes of a SeqFeature are:

-.type
– This is a textual description of the type of feature (for instance, this will be something like ‘CDS’ or ‘gene’).
.location
– The location of the SeqFeature on the sequence -that you are dealing with, see Section 4.3.2 below. The -SeqFeature delegates much of its functionality to the location +

We’ll talk about SeqFeature objects next, in +Section 4.3.

+ +

4.3  Feature, location and position objects

+

+ +

4.3.1  SeqFeature objects

Sequence features are an essential part of describing a sequence. Once you get beyond the sequence itself, you need some way to organize and easily get at the more “abstract” information that is known about the sequence. While it is probably impossible to develop a general sequence feature class that will cover everything, the Biopython SeqFeature class attempts to encapsulate as much of the information about the sequence as possible. The design is heavily based on the GenBank/EMBL feature tables, so if you understand how they look, you’ll probably have an easier time grasping the structure of the Biopython classes.

The key idea about each SeqFeature object is to describe a region on a parent sequence, typically a SeqRecord object. That region is described with a location object, typically a range between two positions (see Section 4.3.2 below).

The SeqFeature class has a number of attributes, so first we’ll list them and their general features, and then later in the chapter work through examples to show how this applies to a real life example. The attributes of a SeqFeature are:

+.type
– This is a textual description of the type of feature (for instance, this will be something like ‘CDS’ or ‘gene’).
.location
– The location of the SeqFeature on the sequence +that you are dealing with, see Section 4.3.2 below. The +SeqFeature delegates much of its functionality to the location object, and includes a number of shortcut attributes for properties -of the location:
-.ref
– shorthand for .location.ref – any (different) -reference sequence the location is referring to. Usually just None.
.ref_db
– shorthand for .location.ref_db – specifies -the database any identifier in .ref refers to. Usually just None.
.strand
– shorthand for .location.strand – the strand on +of the location:
+.ref
– shorthand for .location.ref – any (different) +reference sequence the location is referring to. Usually just None.
.ref_db
– shorthand for .location.ref_db – specifies +the database any identifier in .ref refers to. Usually just None.
.strand
– shorthand for .location.strand – the strand on the sequence that the feature is located on. For double stranded nucleotide sequence this may either be 1 for the top strand, −1 for the bottom -strand, 0 if the strand is important but is unknown, or None +strand, 0 if the strand is important but is unknown, or None if it doesn’t matter. This is None for proteins, or single stranded sequences. -
.qualifiers
– This is a Python dictionary of additional information about the feature. The key is some kind of terse one-word description of what the information contained in the value is about, and the value is the actual information. For example, a common key for a qualifier might be “evidence” and the value might be “computational (non-experimental).” This is just a way to let the person who is looking at the feature know that it has not be experimentally (i. e. in a wet lab) confirmed. Note that other the value will be a list of strings (even when there is only one string). This is a reflection of the feature tables in GenBank/EMBL files.
.sub_features
– This used to be used to represent features with complicated locations like ‘joins’ in GenBank/EMBL files. This has been deprecated with the introduction of the CompoundLocation object, and should now be ignored.
-

4.3.2  Positions and locations

-

The key idea about each SeqFeature object is to describe a +

.qualifiers
– This is a Python dictionary of additional information about the feature. The key is some kind of terse one-word description of what the information contained in the value is about, and the value is the actual information. For example, a common key for a qualifier might be “evidence” and the value might be “computational (non-experimental).” This is just a way to let the person who is looking at the feature know that it has not be experimentally (i. e. in a wet lab) confirmed. Note that other the value will be a list of strings (even when there is only one string). This is a reflection of the feature tables in GenBank/EMBL files.
.sub_features
– This used to be used to represent features with complicated locations like ‘joins’ in GenBank/EMBL files. This has been deprecated with the introduction of the CompoundLocation object, and should now be ignored.
+ +

4.3.2  Positions and locations

+

The key idea about each SeqFeature object is to describe a region on a parent sequence, for which we use a location object, typically describing a range between two positions. Two try to -clarify the terminology we’re using:

-position
– This refers to a single position on a sequence, -which may be fuzzy or not. For instance, 5, 20, <100 and ->200 are all positions.
location
– A location is region of sequence bounded by +clarify the terminology we’re using:

+position
– This refers to a single position on a sequence, +which may be fuzzy or not. For instance, 5, 20, <100 and +>200 are all positions.
location
– A location is region of sequence bounded by some positions. For instance 5..20 (i. e. 5 to 20) is a location. -

I just mention this because sometimes I get confused between the two.

-

4.3.2.1  FeatureLocation object

Unless you work with eukaryotic genes, most SeqFeature locations are +

I just mention this because sometimes I get confused between the two.

+ +

4.3.2.1  FeatureLocation object

Unless you work with eukaryotic genes, most SeqFeature locations are extremely simple - you just need start and end coordinates and a strand. -That’s essentially all the basic FeatureLocation object does.

In practise of course, things can be more complicated. First of all +That’s essentially all the basic FeatureLocation object does.

In practise of course, things can be more complicated. First of all we have to handle compound locations made up of several regions. -Secondly, the positions themselves may be fuzzy (inexact).

-

4.3.2.2  CompoundLocation object

Biopython 1.62 introduced the CompoundLocation as part of +Secondly, the positions themselves may be fuzzy (inexact).

+ +

4.3.2.2  CompoundLocation object

Biopython 1.62 introduced the CompoundLocation as part of a restructuring of how complex locations made up of multiple regions are represented. -The main usage is for handling ‘join’ locations in EMBL/GenBank files.

-

4.3.2.3  Fuzzy Positions

So far we’ve only used simple positions. One complication in dealing +The main usage is for handling ‘join’ locations in EMBL/GenBank files.

+ +

4.3.2.3  Fuzzy Positions

So far we’ve only used simple positions. One complication in dealing with feature locations comes in the positions themselves. In biology many times things aren’t entirely certain (as much as us wet lab biologists try to make them certain!). For @@ -1403,63 +1457,63 @@ is very useful information, but the complication comes in how to represent this as a position. To help us deal with this, we have the concept of fuzzy positions. Basically there are several types -of fuzzy positions, so we have five classes do deal with them:

-ExactPosition
– As its name suggests, this class represents a position which is specified as exact along the sequence. This is represented as just a number, and you can get the position by looking at the position attribute of the object.
BeforePosition
– This class represents a fuzzy position +of fuzzy positions, so we have five classes do deal with them:

+ExactPosition
– As its name suggests, this class represents a position which is specified as exact along the sequence. This is represented as just a number, and you can get the position by looking at the position attribute of the object.
BeforePosition
– This class represents a fuzzy position that occurs prior to some specified site. In GenBank/EMBL notation, -this is represented as something like `<13', signifying that +this is represented as something like `<13', signifying that the real position is located somewhere less than 13. To get -the specified upper boundary, look at the position -attribute of the object.
AfterPosition
– Contrary to BeforePosition, this +the specified upper boundary, look at the position +attribute of the object.
AfterPosition
– Contrary to BeforePosition, this class represents a position that occurs after some specified site. -This is represented in GenBank as `>13', and like -BeforePosition, you get the boundary number by looking -at the position attribute of the object.
WithinPosition
– Occasionally used for GenBank/EMBL locations, +This is represented in GenBank as `>13', and like +BeforePosition, you get the boundary number by looking +at the position attribute of the object.
WithinPosition
– Occasionally used for GenBank/EMBL locations, this class models a position which occurs somewhere between two specified nucleotides. In GenBank/EMBL notation, this would be represented as ‘(1.5)’, to represent that the position is somewhere within the range 1 to 5. To get the information in this class you -have to look at two attributes. The position attribute +have to look at two attributes. The position attribute specifies the lower boundary of the range we are looking at, so in -our example case this would be one. The extension attribute +our example case this would be one. The extension attribute specifies the range to the higher boundary, so in this case it -would be 4. So object.position is the lower boundary and -object.position + object.extension is the upper boundary.
OneOfPosition
– Occasionally used for GenBank/EMBL locations, +would be 4. So object.position is the lower boundary and +object.position + object.extension is the upper boundary.
OneOfPosition
– Occasionally used for GenBank/EMBL locations, this class deals with a position where several possible values exist, for instance you could use this if the start codon was unclear and there where two candidates for the start of the gene. Alternatively, -that might be handled explicitly as two related gene features.
UnknownPosition
– This class deals with a position of unknown +that might be handled explicitly as two related gene features.
UnknownPosition
– This class deals with a position of unknown location. This is not used in GenBank/EMBL, but corresponds to the ‘?’ -feature coordinate used in UniProt.

Here’s an example where we create a location with fuzzy end points:

>>> from Bio import SeqFeature
+feature coordinate used in UniProt.

Here’s an example where we create a location with fuzzy end points:

>>> from Bio import SeqFeature
 >>> start_pos = SeqFeature.AfterPosition(5)
 >>> end_pos = SeqFeature.BetweenPosition(9, left=8, right=9)
 >>> my_location = SeqFeature.FeatureLocation(start_pos, end_pos)
-

Note that the details of some of the fuzzy-locations changed in Biopython 1.59, +

Note that the details of some of the fuzzy-locations changed in Biopython 1.59, in particular for BetweenPosition and WithinPosition you must now make it explicit which integer position should be used for slicing etc. For a start position this is generally the lower (left) value, while for an end position this would generally -be the higher (right) value.

If you print out a FeatureLocation object, you can get a nice representation of the information:

>>> print my_location
+be the higher (right) value.

If you print out a FeatureLocation object, you can get a nice representation of the information:

>>> print(my_location)
 [>5:(8^9)]
-

We can access the fuzzy start and end positions using the start and end attributes of the location:

>>> my_location.start
+

We can access the fuzzy start and end positions using the start and end attributes of the location:

>>> my_location.start
 AfterPosition(5)
->>> print my_location.start
+>>> print(my_location.start)
 >5
 >>> my_location.end
 BetweenPosition(9, left=8, right=9)
->>> print my_location.end
+>>> print(my_location.end)
 (8^9)
-

If you don’t want to deal with fuzzy positions and just want numbers, -they are actually subclasses of integers so should work like integers:

>>> int(my_location.start)
+

If you don’t want to deal with fuzzy positions and just want numbers, +they are actually subclasses of integers so should work like integers:

>>> int(my_location.start)
 5
 >>> int(my_location.end)
 9
-

For compatibility with older versions of Biopython you can ask for the -nofuzzy_start and nofuzzy_end attributes of the location -which are plain integers:

>>> my_location.nofuzzy_start
+

For compatibility with older versions of Biopython you can ask for the +nofuzzy_start and nofuzzy_end attributes of the location +which are plain integers:

>>> my_location.nofuzzy_start
 5
 >>> my_location.nofuzzy_end
 9
-

Notice that this just gives you back the position attributes of the fuzzy locations.

Similarly, to make it easy to create a position without worrying about fuzzy positions, you can just pass in numbers to the FeaturePosition constructors, and you’ll get back out ExactPosition objects:

>>> exact_location = SeqFeature.FeatureLocation(5, 9)
->>> print exact_location
+

Notice that this just gives you back the position attributes of the fuzzy locations.

Similarly, to make it easy to create a position without worrying about fuzzy positions, you can just pass in numbers to the FeaturePosition constructors, and you’ll get back out ExactPosition objects:

>>> exact_location = SeqFeature.FeatureLocation(5, 9)
+>>> print(exact_location)
 [5:9]
 >>> exact_location.start
 ExactPosition(5)
@@ -1467,56 +1521,60 @@
 5
 >>> exact_location.nofuzzy_start
 5
-

That is most of the nitty gritty about dealing with fuzzy positions in Biopython. +

That is most of the nitty gritty about dealing with fuzzy positions in Biopython. It has been designed so that dealing with fuzziness is not that much more -complicated than dealing with exact positions, and hopefully you find that true!

-

4.3.2.4  Location testing

You can use the Python keyword in with a SeqFeature or location +complicated than dealing with exact positions, and hopefully you find that true!

+ +

4.3.2.4  Location testing

You can use the Python keyword in with a SeqFeature or location object to see if the base/residue for a parent coordinate is within the -feature/location or not.

For example, suppose you have a SNP of interest and you want to know which +feature/location or not.

For example, suppose you have a SNP of interest and you want to know which features this SNP is within, and lets suppose this SNP is at index 4350 (Python counting!). Here is a simple brute force solution where we just -check all the features one by one in a loop:

>>> from Bio import SeqIO
+check all the features one by one in a loop:

>>> from Bio import SeqIO
 >>> my_snp = 4350
 >>> record = SeqIO.read("NC_005816.gb", "genbank")
 >>> for feature in record.features:
 ...     if my_snp in feature:
-...         print feature.type, feature.qualifiers.get('db_xref')
-...
+...         print("%s %s" % (feature.type, feature.qualifiers.get('db_xref')))
+... 
 source ['taxon:229193']
 gene ['GeneID:2767712']
 CDS ['GI:45478716', 'GeneID:2767712']
-

Note that gene and CDS features from GenBank or EMBL files defined with joins -are the union of the exons – they do not cover any introns.

-

4.3.3  Sequence described by a feature or location

A SeqFeature or location object doesn’t directly contain a sequence, instead the location (see Section 4.3.2) describes how to get this from the parent sequence. For example consider a (short) gene sequence with location 5:18 on the reverse strand, which in GenBank/EMBL notation using 1-based counting would be complement(6..18), like this:

>>> from Bio.Seq import Seq
+

Note that gene and CDS features from GenBank or EMBL files defined with joins +are the union of the exons – they do not cover any introns.

+ +

4.3.3  Sequence described by a feature or location

A SeqFeature or location object doesn’t directly contain a sequence, instead the location (see Section 4.3.2) describes how to get this from the parent sequence. For example consider a (short) gene sequence with location 5:18 on the reverse strand, which in GenBank/EMBL notation using 1-based counting would be complement(6..18), like this:

>>> from Bio.Seq import Seq
 >>> from Bio.SeqFeature import SeqFeature, FeatureLocation
 >>> example_parent = Seq("ACCGAGACGGCAAAGGCTAGCATAGGTATGAGACTTCCTTCCTGCCAGTGCTGAGGAACTGGGAGCCTAC")
 >>> example_feature = SeqFeature(FeatureLocation(5, 18), type="gene", strand=-1)
-

You could take the parent sequence, slice it to extract 5:18, and then take the reverse complement. -If you are using Biopython 1.59 or later, the feature location’s start and end are integer like so this works:

>>> feature_seq = example_parent[example_feature.location.start:example_feature.location.end].reverse_complement()
->>> print feature_seq
+

You could take the parent sequence, slice it to extract 5:18, and then take the reverse complement. +If you are using Biopython 1.59 or later, the feature location’s start and end are integer like so this works:

>>> feature_seq = example_parent[example_feature.location.start:example_feature.location.end].reverse_complement()
+>>> print(feature_seq)
 AGCCTTTGCCGTC
-

This is a simple example so this isn’t too bad – however once you have to deal with compound features (joins) this is rather messy. Instead, the SeqFeature object has an extract method to take care of all this:

>>> feature_seq = example_feature.extract(example_parent)
->>> print feature_seq
+

This is a simple example so this isn’t too bad – however once you have to deal with compound features (joins) this is rather messy. Instead, the SeqFeature object has an extract method to take care of all this:

>>> feature_seq = example_feature.extract(example_parent)
+>>> print(feature_seq)
 AGCCTTTGCCGTC
-

The length of a SeqFeature or location matches -that of the region of sequence it describes.

>>> print example_feature.extract(example_parent)
+

The length of a SeqFeature or location matches +that of the region of sequence it describes.

>>> print(example_feature.extract(example_parent))
 AGCCTTTGCCGTC
->>> print len(example_feature.extract(example_parent))
+>>> print(len(example_feature.extract(example_parent)))
 13
->>> print len(example_feature)
+>>> print(len(example_feature))
 13
->>> print len(example_feature.location)
+>>> print(len(example_feature.location))
 13
-

For simple FeatureLocation objects the length is just +

For simple FeatureLocation objects the length is just the difference between the start and end positions. However, -for a CompoundLocation the length is the sum of the -constituent regions.

-

4.4  References

Another common annotation related to a sequence is a reference to a journal or other published work dealing with the sequence. We have a fairly simple way of representing a Reference in Biopython – we have a Bio.SeqFeature.Reference class that stores the relevant information about a reference as attributes of an object.

The attributes include things that you would expect to see in a reference like journal, title and authors. Additionally, it also can hold the medline_id and pubmed_id and a comment about the reference. These are all accessed simply as attributes of the object.

A reference also has a location object so that it can specify a particular location on the sequence that the reference refers to. For instance, you might have a journal that is dealing with a particular gene located on a BAC, and want to specify that it only refers to this position exactly. The location is a potentially fuzzy location, as described in section 4.3.2.

Any reference objects are stored as a list in the SeqRecord object’s annotations dictionary under the key “references”. -That’s all there is too it. References are meant to be easy to deal with, and hopefully general enough to cover lots of usage cases.

-

4.5  The format method

-

The format() method of the SeqRecord class gives a string +for a CompoundLocation the length is the sum of the +constituent regions.

+ +

4.4  References

Another common annotation related to a sequence is a reference to a journal or other published work dealing with the sequence. We have a fairly simple way of representing a Reference in Biopython – we have a Bio.SeqFeature.Reference class that stores the relevant information about a reference as attributes of an object.

The attributes include things that you would expect to see in a reference like journal, title and authors. Additionally, it also can hold the medline_id and pubmed_id and a comment about the reference. These are all accessed simply as attributes of the object.

A reference also has a location object so that it can specify a particular location on the sequence that the reference refers to. For instance, you might have a journal that is dealing with a particular gene located on a BAC, and want to specify that it only refers to this position exactly. The location is a potentially fuzzy location, as described in section 4.3.2.

Any reference objects are stored as a list in the SeqRecord object’s annotations dictionary under the key “references”. +That’s all there is too it. References are meant to be easy to deal with, and hopefully general enough to cover lots of usage cases.

+ +

4.5  The format method

+

The format() method of the SeqRecord class gives a string containing your record formatted using one of the output file formats -supported by Bio.SeqIO, such as FASTA:

from Bio.Seq import Seq
+supported by Bio.SeqIO, such as FASTA:

from Bio.Seq import Seq
 from Bio.SeqRecord import SeqRecord
 from Bio.Alphabet import generic_protein
 
@@ -1527,39 +1585,40 @@
                    id="gi|14150838|gb|AAK54648.1|AF376133_1",
                    description="chalcone synthase [Cucumis sativus]")
                    
-print record.format("fasta")
-

which should give: -

>gi|14150838|gb|AAK54648.1|AF376133_1 chalcone synthase [Cucumis sativus]
+print(record.format("fasta"))
+

which should give: +

>gi|14150838|gb|AAK54648.1|AF376133_1 chalcone synthase [Cucumis sativus]
 MMYQQGCFAGGTVLRLAKDLAENNRGARVLVVCSEITAVTFRGPSETHLDSMVGQALFGD
 GAGAVIVGSDPDLSVERPLYELVWTGATLLPDSEGAIDGHLREVGLTFHLLKDVPGLISK
 NIEKSLKEAFTPLGISDWNSTFWIAHPGGPAILDQVEAKLGLKEEKMRATREVLSEYGNM
 SSAC
-

This format method takes a single mandatory argument, a lower case string which is -supported by Bio.SeqIO as an output format (see Chapter 5). -However, some of the file formats Bio.SeqIO can write to require more than +

This format method takes a single mandatory argument, a lower case string which is +supported by Bio.SeqIO as an output format (see Chapter 5). +However, some of the file formats Bio.SeqIO can write to require more than one record (typically the case for multiple sequence alignment formats), and thus won’t -work via this format() method. See also Section 5.5.4.

-

4.6  Slicing a SeqRecord

-

You can slice a SeqRecord, to give you a new SeqRecord covering just +work via this format() method. See also Section 5.5.4.

+ +

4.6  Slicing a SeqRecord

+

You can slice a SeqRecord, to give you a new SeqRecord covering just part of the sequence. What is important here is that any per-letter annotations are also sliced, and any features which fall -completely within the new sequence are preserved (with their locations adjusted).

For example, taking the same GenBank file used earlier:

>>> from Bio import SeqIO
+completely within the new sequence are preserved (with their locations adjusted).

For example, taking the same GenBank file used earlier:

>>> from Bio import SeqIO
 >>> record = SeqIO.read("NC_005816.gb", "genbank")
-
>>> record
+
>>> record
 SeqRecord(seq=Seq('TGTAACGAACGGTGCAATAGTGATCCACACCCAACGCCTGAAATCAGATCCAGG...CTG',
 IUPACAmbiguousDNA()), id='NC_005816.1', name='NC_005816',
 description='Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete sequence.',
 dbxrefs=['Project:10638'])
-
>>> len(record)
+
>>> len(record)
 9609
 >>> len(record.features)
 41
-

For this example we’re going to focus in on the pim gene, YP_pPCP05. +

For this example we’re going to focus in on the pim gene, YP_pPCP05. If you have a look at the GenBank file directly you’ll find this gene/CDS has -location string 4343..4780, or in Python counting 4342:4780. +location string 4343..4780, or in Python counting 4342:4780. From looking at the file you can work out that these are the twelfth and thirteenth entries in the file, so in Python zero-based counting they are -entries 11 and 12 in the features list:

>>> print record.features[20]
+entries 11 and 12 in the features list:

>>> print(record.features[20])
 type: gene
 location: [4342:4780](+)
 qualifiers: 
@@ -1567,7 +1626,7 @@
     Key: gene, Value: ['pim']
     Key: locus_tag, Value: ['YP_pPCP05']
 <BLANKLINE>
-
>>> print record.features[21]
+
>>> print(record.features[21])
 type: CDS
 location: [4342:4780](+)
 qualifiers: 
@@ -1580,18 +1639,18 @@
     Key: protein_id, Value: ['NP_995571.1']
     Key: transl_table, Value: ['11']
     Key: translation, Value: ['MGGGMISKLFCLALIFLSSSGLAEKNTYTAKDILQNLELNTFGNSLSH...']
-

Let’s slice this parent record from 4300 to 4800 (enough to include the pim -gene/CDS), and see how many features we get:

>>> sub_record = record[4300:4800]
-
>>> sub_record
+

Let’s slice this parent record from 4300 to 4800 (enough to include the pim +gene/CDS), and see how many features we get:

>>> sub_record = record[4300:4800]
+
>>> sub_record
 SeqRecord(seq=Seq('ATAAATAGATTATTCCAAATAATTTATTTATGTAAGAACAGGATGGGAGGGGGA...TTA',
 IUPACAmbiguousDNA()), id='NC_005816.1', name='NC_005816',
 description='Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete sequence.',
 dbxrefs=[])
-
>>> len(sub_record)
+
>>> len(sub_record)
 500
 >>> len(sub_record.features)
 2
-

Our sub-record just has two features, the gene and CDS entries for YP_pPCP05:

>>> print sub_record.features[0]
+

Our sub-record just has two features, the gene and CDS entries for YP_pPCP05:

>>> print(sub_record.features[0])
 type: gene
 location: [42:480](+)
 qualifiers: 
@@ -1599,7 +1658,7 @@
     Key: gene, Value: ['pim']
     Key: locus_tag, Value: ['YP_pPCP05']
 <BLANKLINE>
-
>>> print sub_record.features[20]
+
>>> print(sub_record.features[20])
 type: CDS
 location: [42:480](+)
 qualifiers: 
@@ -1612,198 +1671,205 @@
     Key: protein_id, Value: ['NP_995571.1']
     Key: transl_table, Value: ['11']
     Key: translation, Value: ['MGGGMISKLFCLALIFLSSSGLAEKNTYTAKDILQNLELNTFGNSLSH...']
-

Notice that their locations have been adjusted to reflect the new parent sequence!

While Biopython has done something sensible and hopefully intuitive with the features +

Notice that their locations have been adjusted to reflect the new parent sequence!

While Biopython has done something sensible and hopefully intuitive with the features (and any per-letter annotation), for the other annotation it is impossible to know if -this still applies to the sub-sequence or not. To avoid guessing, the annotations -and dbxrefs are omitted from the sub-record, and it is up to you to transfer -any relevant information as appropriate.

>>> sub_record.annotations
+this still applies to the sub-sequence or not. To avoid guessing, the annotations
+and dbxrefs are omitted from the sub-record, and it is up to you to transfer
+any relevant information as appropriate.

>>> sub_record.annotations
 {}
 >>> sub_record.dbxrefs
 []
-

The same point could be made about the record id, name -and description, but for practicality these are preserved:

>>> sub_record.id
+

The same point could be made about the record id, name +and description, but for practicality these are preserved:

>>> sub_record.id
 'NC_005816.1'
 >>> sub_record.name
 'NC_005816'
 >>> sub_record.description
 'Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete sequence.'
-

This illustrates the problem nicely though, our new sub-record is -not the complete sequence of the plasmid, so the description is wrong! +

This illustrates the problem nicely though, our new sub-record is +not the complete sequence of the plasmid, so the description is wrong! Let’s fix this and then view the sub-record as a reduced GenBank file using -the format method described above in Section 4.5:

>>> sub_record.description = "Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, partial."
->>> print sub_record.format("genbank")
+the format method described above in Section 4.5:

>>> sub_record.description = "Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, partial."
+>>> print(sub_record.format("genbank"))
 ...
-

See Sections 18.1.7 -and 18.1.8 for some FASTQ examples where the -per-letter annotations (the read quality scores) are also sliced.

-

4.7  Adding SeqRecord objects

-

You can add SeqRecord objects together, giving a new SeqRecord. +

See Sections 18.1.7 +and 18.1.8 for some FASTQ examples where the +per-letter annotations (the read quality scores) are also sliced.

+ +

4.7  Adding SeqRecord objects

+

You can add SeqRecord objects together, giving a new SeqRecord. What is important here is that any common per-letter annotations are also added, all the features are preserved (with their locations adjusted), and any other common annotation is also kept (like the id, name -and description).

For an example with per-letter annotation, we’ll use the first record in a -FASTQ file. Chapter 5 will explain the SeqIO functions:

>>> from Bio import SeqIO
->>> record = SeqIO.parse("example.fastq", "fastq").next()
+and description).

For an example with per-letter annotation, we’ll use the first record in a +FASTQ file. Chapter 5 will explain the SeqIO functions:

>>> from Bio import SeqIO
+>>> record = next(SeqIO.parse("example.fastq", "fastq"))
 >>> len(record)
 25
->>> print record.seq
+>>> print(record.seq)
 CCCTTCTTGTCTTCAGCGTTTCTCC
-
>>> print record.letter_annotations["phred_quality"]
+
>>> print(record.letter_annotations["phred_quality"])
 [26, 26, 18, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 22, 26, 26, 26, 26,
 26, 26, 26, 23, 23]
-

Let’s suppose this was Roche 454 data, and that from other information -you think the TTT should be only TT. We can make a new edited -record by first slicing the SeqRecord before and after the “extra” -third T:

>>> left = record[:20]
->>> print left.seq
+

Let’s suppose this was Roche 454 data, and that from other information +you think the TTT should be only TT. We can make a new edited +record by first slicing the SeqRecord before and after the “extra” +third T:

>>> left = record[:20]
+>>> print(left.seq)
 CCCTTCTTGTCTTCAGCGTT
->>> print left.letter_annotations["phred_quality"]
+>>> print(left.letter_annotations["phred_quality"])
 [26, 26, 18, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 22, 26, 26, 26, 26]
 >>> right = record[21:]
->>> print right.seq
+>>> print(right.seq)
 CTCC
->>> print right.letter_annotations["phred_quality"]
+>>> print(right.letter_annotations["phred_quality"])
 [26, 26, 23, 23]
-

Now add the two parts together:

>>> edited = left + right
+

Now add the two parts together:

>>> edited = left + right
 >>> len(edited)
 24
->>> print edited.seq
+>>> print(edited.seq)
 CCCTTCTTGTCTTCAGCGTTCTCC
-
>>> print edited.letter_annotations["phred_quality"]
+
>>> print(edited.letter_annotations["phred_quality"])
 [26, 26, 18, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 22, 26, 26, 26, 26,
 26, 26, 23, 23]
-

Easy and intuitive? We hope so! You can make this shorter with just:

>>> edited = record[:20] + record[21:]
-

Now, for an example with features, we’ll use a GenBank file. -Suppose you have a circular genome:

>>> from Bio import SeqIO
+

Easy and intuitive? We hope so! You can make this shorter with just:

>>> edited = record[:20] + record[21:]
+

Now, for an example with features, we’ll use a GenBank file. +Suppose you have a circular genome:

>>> from Bio import SeqIO
 >>> record = SeqIO.read("NC_005816.gb", "genbank")
-
>>> record
+
>>> record
 SeqRecord(seq=Seq('TGTAACGAACGGTGCAATAGTGATCCACACCCAACGCCTGAAATCAGATCCAGG...CTG',
 IUPACAmbiguousDNA()), id='NC_005816.1', name='NC_005816',
 description='Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete sequence.',
 dbxrefs=['Project:10638'])
-
>>> len(record)
+
>>> len(record)
 9609
 >>> len(record.features)
 41
 >>> record.dbxrefs
 ['Project:58037']
-
>>> record.annotations.keys()
+
>>> record.annotations.keys()
 ['comment', 'sequence_version', 'source', 'taxonomy', 'keywords', 'references',
 'accessions', 'data_file_division', 'date', 'organism', 'gi']
-

You can shift the origin like this:

>>> shifted = record[2000:] + record[:2000]
-
>>> shifted
+

You can shift the origin like this:

>>> shifted = record[2000:] + record[:2000]
+
>>> shifted
 SeqRecord(seq=Seq('GATACGCAGTCATATTTTTTACACAATTCTCTAATCCCGACAAGGTCGTAGGTC...GGA',
 IUPACAmbiguousDNA()), id='NC_005816.1', name='NC_005816',
 description='Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete sequence.',
 dbxrefs=[])
-
>>> len(shifted)
+
>>> len(shifted)
 9609
-

Note that this isn’t perfect in that some annotation like the database cross references -and one of the features (the source feature) have been lost:

>>> len(shifted.features)
+

Note that this isn’t perfect in that some annotation like the database cross references +and one of the features (the source feature) have been lost:

>>> len(shifted.features)
 40
 >>> shifted.dbxrefs
 []
 >>> shifted.annotations.keys()
 []
-

This is because the SeqRecord slicing step is cautious in what annotation +

This is because the SeqRecord slicing step is cautious in what annotation it preserves (erroneously propagating annotation can cause major problems). If you want to keep the database cross references or the annotations dictionary, -this must be done explicitly:

>>> shifted.dbxrefs = record.dbxrefs[:]
+this must be done explicitly:

>>> shifted.dbxrefs = record.dbxrefs[:]
 >>> shifted.annotations = record.annotations.copy()
 >>> shifted.dbxrefs
 ['Project:10638']
 >>> shifted.annotations.keys()
 ['comment', 'sequence_version', 'source', 'taxonomy', 'keywords', 'references',
 'accessions', 'data_file_division', 'date', 'organism', 'gi']
-

Also note that in an example like this, you should probably change the record -identifiers since the NCBI references refer to the original unmodified -sequence.

-

4.8  Reverse-complementing SeqRecord objects

-

One of the new features in Biopython 1.57 was the SeqRecord object’s -reverse_complement method. This tries to balance easy of use with worries -about what to do with the annotation in the reverse complemented record.

For the sequence, this uses the Seq object’s reverse complement method. Any +

Also note that in an example like this, you should probably change the record +identifiers since the NCBI references refer to the original unmodified +sequence.

+ +

4.8  Reverse-complementing SeqRecord objects

+

One of the new features in Biopython 1.57 was the SeqRecord object’s +reverse_complement method. This tries to balance easy of use with worries +about what to do with the annotation in the reverse complemented record.

For the sequence, this uses the Seq object’s reverse complement method. Any features are transferred with the location and strand recalculated. Likewise any per-letter-annotation is also copied but reversed (which makes sense for typical examples like quality scores). However, transfer of most annotation -is problematical.

For instance, if the record ID was an accession, that accession should not really +is problematical.

For instance, if the record ID was an accession, that accession should not really apply to the reverse complemented sequence, and transferring the identifier by default could easily cause subtle data corruption in downstream analysis. -Therefore by default, the SeqRecord’s id, name, description, annotations -and database cross references are all not transferred by default.

The SeqRecord object’s reverse_complement method takes a number +Therefore by default, the SeqRecord’s id, name, description, annotations +and database cross references are all not transferred by default.

The SeqRecord object’s reverse_complement method takes a number of optional arguments corresponding to properties of the record. Setting these -arguments to True means copy the old values, while False means +arguments to True means copy the old values, while False means drop the old values and use the default value. You can alternatively provide -the new desired value instead.

Consider this example record:

>>> from Bio import SeqIO
+the new desired value instead.

Consider this example record:

>>> from Bio import SeqIO
 >>> record = SeqIO.read("NC_005816.gb", "genbank")
->>> print record.id, len(record), len(record.features), len(record.dbxrefs), len(record.annotations)
+>>> print("%s %i %i %i %i" % (record.id, len(record), len(record.features), len(record.dbxrefs), len(record.annotations)))
 NC_005816.1 9609 41 1 11
-

Here we take the reverse complement and specify a new identifier – but notice -how most of the annotation is dropped (but not the features):

>>> rc = record.reverse_complement(id="TESTING")
->>> print rc.id, len(rc), len(rc.features), len(rc.dbxrefs), len(rc.annotations)
+

Here we take the reverse complement and specify a new identifier – but notice +how most of the annotation is dropped (but not the features):

>>> rc = record.reverse_complement(id="TESTING")
+>>> print("%s %i %i %i %i" % (rc.id, len(rc), len(rc.features), len(rc.dbxrefs), len(rc.annotations)))
 TESTING 9609 41 0 0
-
-

Chapter 5  Sequence Input/Output

-

In this chapter we’ll discuss in more detail the Bio.SeqIO module, which was briefly introduced in Chapter 2 and also used in Chapter 4. This aims to provide a simple interface for working with assorted sequence file formats in a uniform way. -See also the Bio.SeqIO wiki page (http://biopython.org/wiki/SeqIO), and the built in documentation (also online):

>>> from Bio import SeqIO
+
+ +

Chapter 5  Sequence Input/Output

+

In this chapter we’ll discuss in more detail the Bio.SeqIO module, which was briefly introduced in Chapter 2 and also used in Chapter 4. This aims to provide a simple interface for working with assorted sequence file formats in a uniform way. +See also the Bio.SeqIO wiki page (http://biopython.org/wiki/SeqIO), and the built in documentation (also online):

>>> from Bio import SeqIO
 >>> help(SeqIO)
 ...
-

The “catch” is that you have to work with SeqRecord objects (see Chapter 4), which contain a Seq object (see Chapter 3) plus annotation like an identifier and description.

-

5.1  Parsing or Reading Sequences

-

The workhorse function Bio.SeqIO.parse() is used to read in sequence data as SeqRecord objects. This function expects two arguments:

  1. -The first argument is a handle to read the data from, or a filename. A handle is typically a file opened for reading, but could be the output from a command line program, or data downloaded from the internet (see Section 5.3). See Section 22.1 for more about handles. -
  2. The second argument is a lower case string specifying sequence format – we don’t try and guess the file format for you! See http://biopython.org/wiki/SeqIO for a full listing of supported formats. -

There is an optional argument alphabet to specify the alphabet to be used. This is useful for file formats like FASTA where otherwise Bio.SeqIO will default to a generic alphabet.

The Bio.SeqIO.parse() function returns an iterator which gives SeqRecord objects. Iterators are typically used in a for loop as shown below.

Sometimes you’ll find yourself dealing with files which contain only a single record. For this situation use the function Bio.SeqIO.read() which takes the same arguments. Provided there is one and only one record in the file, this is returned as a SeqRecord object. Otherwise an exception is raised.

-

5.1.1  Reading Sequence Files

In general Bio.SeqIO.parse() is used to read in sequence files as SeqRecord objects, and is typically used with a for loop like this:

from Bio import SeqIO
+

The “catch” is that you have to work with SeqRecord objects (see Chapter 4), which contain a Seq object (see Chapter 3) plus annotation like an identifier and description.

+ +

5.1  Parsing or Reading Sequences

+

The workhorse function Bio.SeqIO.parse() is used to read in sequence data as SeqRecord objects. This function expects two arguments:

  1. +The first argument is a handle to read the data from, or a filename. A handle is typically a file opened for reading, but could be the output from a command line program, or data downloaded from the internet (see Section 5.3). See Section 22.1 for more about handles. +
  2. The second argument is a lower case string specifying sequence format – we don’t try and guess the file format for you! See http://biopython.org/wiki/SeqIO for a full listing of supported formats. +

There is an optional argument alphabet to specify the alphabet to be used. This is useful for file formats like FASTA where otherwise Bio.SeqIO will default to a generic alphabet.

The Bio.SeqIO.parse() function returns an iterator which gives SeqRecord objects. Iterators are typically used in a for loop as shown below.

Sometimes you’ll find yourself dealing with files which contain only a single record. For this situation use the function Bio.SeqIO.read() which takes the same arguments. Provided there is one and only one record in the file, this is returned as a SeqRecord object. Otherwise an exception is raised.

+ +

5.1.1  Reading Sequence Files

In general Bio.SeqIO.parse() is used to read in sequence files as SeqRecord objects, and is typically used with a for loop like this:

from Bio import SeqIO
 for seq_record in SeqIO.parse("ls_orchid.fasta", "fasta"):
-    print seq_record.id
-    print repr(seq_record.seq)
-    print len(seq_record)
-

The above example is repeated from the introduction in Section 2.4, and will load the orchid DNA sequences in the FASTA format file ls_orchid.fasta. If instead you wanted to load a GenBank format file like ls_orchid.gbk then all you need to do is change the filename and the format string:

from Bio import SeqIO
+    print(seq_record.id)
+    print(repr(seq_record.seq))
+    print(len(seq_record))
+

The above example is repeated from the introduction in Section 2.4, and will load the orchid DNA sequences in the FASTA format file ls_orchid.fasta. If instead you wanted to load a GenBank format file like ls_orchid.gbk then all you need to do is change the filename and the format string:

from Bio import SeqIO
 for seq_record in SeqIO.parse("ls_orchid.gbk", "genbank"):
-    print seq_record.id
-    print seq_record.seq
-    print len(seq_record)
-

Similarly, if you wanted to read in a file in another file format, then assuming Bio.SeqIO.parse() supports it you would just need to change the format string as appropriate, for example “swiss” for SwissProt files or “embl” for EMBL text files. There is a full listing on the wiki page (http://biopython.org/wiki/SeqIO) and in the built in documentation (also online).

Another very common way to use a Python iterator is within a list comprehension (or + print(seq_record.id) + print(seq_record.seq) + print(len(seq_record)) +

Similarly, if you wanted to read in a file in another file format, then assuming Bio.SeqIO.parse() supports it you would just need to change the format string as appropriate, for example “swiss” for SwissProt files or “embl” for EMBL text files. There is a full listing on the wiki page (http://biopython.org/wiki/SeqIO) and in the built in documentation (also online).

Another very common way to use a Python iterator is within a list comprehension (or a generator expression). For example, if all you wanted to extract from the file was -a list of the record identifiers we can easily do this with the following list comprehension:

>>> from Bio import SeqIO
+a list of the record identifiers we can easily do this with the following list comprehension:

>>> from Bio import SeqIO
 >>> identifiers = [seq_record.id for seq_record in SeqIO.parse("ls_orchid.gbk", "genbank")]
 >>> identifiers
 ['Z78533.1', 'Z78532.1', 'Z78531.1', 'Z78530.1', 'Z78529.1', 'Z78527.1', ..., 'Z78439.1']
-

There are more examples using SeqIO.parse() in a list -comprehension like this in Section 18.2 -(e.g. for plotting sequence lengths or GC%).

-

5.1.2  Iterating over the records in a sequence file

In the above examples, we have usually used a for loop to iterate over all the records one by one. You can use the for loop with all sorts of Python objects (including lists, tuples and strings) which support the iteration interface.

The object returned by Bio.SeqIO is actually an iterator which returns SeqRecord objects. You get to see each record in turn, but once and only once. The plus point is that an iterator can save you memory when dealing with large files.

Instead of using a for loop, can also use the .next() method of an iterator to step through the entries, like this:

from Bio import SeqIO
+

There are more examples using SeqIO.parse() in a list +comprehension like this in Section 18.2 +(e.g. for plotting sequence lengths or GC%).

+ +

5.1.2  Iterating over the records in a sequence file

In the above examples, we have usually used a for loop to iterate over all the records one by one. You can use the for loop with all sorts of Python objects (including lists, tuples and strings) which support the iteration interface.

The object returned by Bio.SeqIO is actually an iterator which returns SeqRecord objects. You get to see each record in turn, but once and only once. The plus point is that an iterator can save you memory when dealing with large files.

Instead of using a for loop, can also use the next() function on an iterator to step through the entries, like this:

from Bio import SeqIO
 record_iterator = SeqIO.parse("ls_orchid.fasta", "fasta")
 
-first_record = record_iterator.next()
-print first_record.id
-print first_record.description
-
-second_record = record_iterator.next()
-print second_record.id
-print second_record.description
-

Note that if you try and use .next() and there are no more results, you’ll get the special StopIteration exception.

One special case to consider is when your sequence files have multiple records, but you only want the first one. In this situation the following code is very concise:

from Bio import SeqIO
-first_record  = SeqIO.parse("ls_orchid.gbk", "genbank").next()
-

A word of warning here – using the .next() method like this will silently ignore any additional records in the file. -If your files have one and only one record, like some of the online examples later in this chapter, or a GenBank file for a single chromosome, then use the new Bio.SeqIO.read() function instead. -This will check there are no extra unexpected records present.

-

5.1.3  Getting a list of the records in a sequence file

In the previous section we talked about the fact that Bio.SeqIO.parse() gives you a SeqRecord iterator, and that you get the records one by one. Very often you need to be able to access the records in any order. The Python list data type is perfect for this, and we can turn the record iterator into a list of SeqRecord objects using the built-in Python function list() like so:

from Bio import SeqIO
+first_record = next(record_iterator)
+print(first_record.id)
+print(first_record.description)
+
+second_record = next(record_iterator)
+print(second_record.id)
+print(second_record.description)
+

Note that if you try to use next() and there are no more results, you’ll get the special StopIteration exception.

One special case to consider is when your sequence files have multiple records, but you only want the first one. In this situation the following code is very concise:

from Bio import SeqIO
+first_record = next(SeqIO.parse("ls_orchid.gbk", "genbank"))
+

A word of warning here – using the next() function like this will silently ignore any additional records in the file. +If your files have one and only one record, like some of the online examples later in this chapter, or a GenBank file for a single chromosome, then use the new Bio.SeqIO.read() function instead. +This will check there are no extra unexpected records present.

+ +

5.1.3  Getting a list of the records in a sequence file

In the previous section we talked about the fact that Bio.SeqIO.parse() gives you a SeqRecord iterator, and that you get the records one by one. Very often you need to be able to access the records in any order. The Python list data type is perfect for this, and we can turn the record iterator into a list of SeqRecord objects using the built-in Python function list() like so:

from Bio import SeqIO
 records = list(SeqIO.parse("ls_orchid.gbk", "genbank"))
 
-print "Found %i records" % len(records)
+print("Found %i records" % len(records))
 
-print "The last record"
+print("The last record")
 last_record = records[-1] #using Python's list tricks
-print last_record.id
-print repr(last_record.seq)
-print len(last_record)
+print(last_record.id)
+print(repr(last_record.seq))
+print(len(last_record))
 
-print "The first record"
+print("The first record")
 first_record = records[0] #remember, Python counts from zero
-print first_record.id
-print repr(first_record.seq)
-print len(first_record)
-

Giving:

Found 94 records
+print(first_record.id)
+print(repr(first_record.seq))
+print(len(first_record))
+

Giving:

Found 94 records
 The last record
 Z78439.1
 Seq('CATTGTTGAGATCACATAATAATTGATCGAGTTAATCTGGAGGATCTGTTTACT...GCC', IUPACAmbiguousDNA())
@@ -1812,13 +1878,14 @@
 Z78533.1
 Seq('CGTAACAAGGTTTCCGTAGGTGAACCTGCGGAAGGATCATTGATGAGACCGTGG...CGC', IUPACAmbiguousDNA())
 740
-

You can of course still use a for loop with a list of SeqRecord objects. Using a list is much more flexible than an iterator (for example, you can determine the number of records from the length of the list), but does need more memory because it will hold all the records in memory at once.

-

5.1.4  Extracting data

The SeqRecord object and its annotation structures are described more fully in -Chapter 4. As an example of how annotations are stored, we’ll look at the output from parsing the first record in the GenBank file ls_orchid.gbk.

from Bio import SeqIO
+

You can of course still use a for loop with a list of SeqRecord objects. Using a list is much more flexible than an iterator (for example, you can determine the number of records from the length of the list), but does need more memory because it will hold all the records in memory at once.

+ +

5.1.4  Extracting data

The SeqRecord object and its annotation structures are described more fully in +Chapter 4. As an example of how annotations are stored, we’ll look at the output from parsing the first record in the GenBank file ls_orchid.gbk.

from Bio import SeqIO
 record_iterator = SeqIO.parse("ls_orchid.gbk", "genbank")
-first_record = record_iterator.next()
-print first_record
-

That should give something like this:

ID: Z78533.1
+first_record = next(record_iterator)
+print(first_record)
+

That should give something like this:

ID: Z78533.1
 Name: Z78533
 Description: C.irapeanum 5.8S rRNA gene and ITS1 and ITS2 DNA.
 Number of features: 5
@@ -1833,132 +1900,134 @@
 /organism=Cypripedium irapeanum
 /gi=2765658
 Seq('CGTAACAAGGTTTCCGTAGGTGAACCTGCGGAAGGATCATTGATGAGACCGTGG...CGC', IUPACAmbiguousDNA())
-

This gives a human readable summary of most of the annotation data for the SeqRecord. -For this example we’re going to use the .annotations attribute which is just a Python dictionary. +

This gives a human readable summary of most of the annotation data for the SeqRecord. +For this example we’re going to use the .annotations attribute which is just a Python dictionary. The contents of this annotations dictionary were shown when we printed the record above. You can also print them out directly: -

print first_record.annotations
-

Like any Python dictionary, you can easily get a list of the keys: -

print first_record.annotations.keys()
-

or values: -

print first_record.annotations.values()
-

In general, the annotation values are strings, or lists of strings. One special case is any references in the file get stored as reference objects.

Suppose you wanted to extract a list of the species from the ls_orchid.gbk GenBank file. The information we want, Cypripedium irapeanum, is held in the annotations dictionary under ‘source’ and ‘organism’, which we can access like this:

>>> print first_record.annotations["source"]
+

print(first_record.annotations)
+

Like any Python dictionary, you can easily get a list of the keys: +

print(first_record.annotations.keys())
+

or values: +

print(first_record.annotations.values())
+

In general, the annotation values are strings, or lists of strings. One special case is any references in the file get stored as reference objects.

Suppose you wanted to extract a list of the species from the ls_orchid.gbk GenBank file. The information we want, Cypripedium irapeanum, is held in the annotations dictionary under ‘source’ and ‘organism’, which we can access like this:

>>> print(first_record.annotations["source"])
 Cypripedium irapeanum
-

or:

>>> print first_record.annotations["organism"]
+

or:

>>> print(first_record.annotations["organism"])
 Cypripedium irapeanum
-

In general, ‘organism’ is used for the scientific name (in Latin, e.g. Arabidopsis thaliana), +

In general, ‘organism’ is used for the scientific name (in Latin, e.g. Arabidopsis thaliana), while ‘source’ will often be the common name (e.g. thale cress). In this example, as is often the case, -the two fields are identical.

Now let’s go through all the records, building up a list of the species each orchid sequence is from:

from Bio import SeqIO
+the two fields are identical. 

Now let’s go through all the records, building up a list of the species each orchid sequence is from:

from Bio import SeqIO
 all_species = []
 for seq_record in SeqIO.parse("ls_orchid.gbk", "genbank"):
     all_species.append(seq_record.annotations["organism"])
-print all_species
-

Another way of writing this code is to use a list comprehension:

from Bio import SeqIO
+print(all_species)
+

Another way of writing this code is to use a list comprehension:

from Bio import SeqIO
 all_species = [seq_record.annotations["organism"] for seq_record in \
                SeqIO.parse("ls_orchid.gbk", "genbank")]
-print all_species
-

In either case, the result is:

['Cypripedium irapeanum', 'Cypripedium californicum', ..., 'Paphiopedilum barbatum']
-

Great. That was pretty easy because GenBank files are annotated in a standardised way.

Now, let’s suppose you wanted to extract a list of the species from a FASTA file, rather than the GenBank file. The bad news is you will have to write some code to extract the data you want from the record’s description line - if the information is in the file in the first place! Our example FASTA format file ls_orchid.fasta starts like this:

>gi|2765658|emb|Z78533.1|CIZ78533 C.irapeanum 5.8S rRNA gene and ITS1 and ITS2 DNA
+print(all_species)
+

In either case, the result is:

['Cypripedium irapeanum', 'Cypripedium californicum', ..., 'Paphiopedilum barbatum']
+

Great. That was pretty easy because GenBank files are annotated in a standardised way.

Now, let’s suppose you wanted to extract a list of the species from a FASTA file, rather than the GenBank file. The bad news is you will have to write some code to extract the data you want from the record’s description line - if the information is in the file in the first place! Our example FASTA format file ls_orchid.fasta starts like this:

>gi|2765658|emb|Z78533.1|CIZ78533 C.irapeanum 5.8S rRNA gene and ITS1 and ITS2 DNA
 CGTAACAAGGTTTCCGTAGGTGAACCTGCGGAAGGATCATTGATGAGACCGTGGAATAAACGATCGAGTG
 AATCCGGAGGACCGGTGTACTCAGCTCACCGGGGGCATTGCTCCCGTGGTGACCCTGATTTGTTGTTGGG
 ...
-

You can check by hand, but for every record the species name is in the description line as the second word. This means if we break up each record’s .description at the spaces, then the species is there as field number one (field zero is the record identifier). That means we can do this:

from Bio import SeqIO
+

You can check by hand, but for every record the species name is in the description line as the second word. This means if we break up each record’s .description at the spaces, then the species is there as field number one (field zero is the record identifier). That means we can do this:

from Bio import SeqIO
 all_species = []
 for seq_record in SeqIO.parse("ls_orchid.fasta", "fasta"):
     all_species.append(seq_record.description.split()[1])
-print all_species
-

This gives:

['C.irapeanum', 'C.californicum', 'C.fasciculatum', 'C.margaritaceum', ..., 'P.barbatum']
-

The concise alternative using list comprehensions would be:

from Bio import SeqIO
+print(all_species)
+

This gives:

['C.irapeanum', 'C.californicum', 'C.fasciculatum', 'C.margaritaceum', ..., 'P.barbatum']
+

The concise alternative using list comprehensions would be:

from Bio import SeqIO
 all_species == [seq_record.description.split()[1] for seq_record in \
                 SeqIO.parse("ls_orchid.fasta", "fasta")]
-print all_species
-

In general, extracting information from the FASTA description line is not very nice. +print(all_species) +

In general, extracting information from the FASTA description line is not very nice. If you can get your sequences in a well annotated file format like GenBank or EMBL, -then this sort of annotation information is much easier to deal with.

-

5.2  Parsing sequences from compressed files

- +then this sort of annotation information is much easier to deal with.

+ +

5.2  Parsing sequences from compressed files

+ In the previous section, we looked at parsing sequence data from a file. -Instead of using a filename, you can give Bio.SeqIO a handle -(see Section 22.1), and in this section -we’ll use handles to parse sequence from compressed files.

As you’ll have seen above, we can use Bio.SeqIO.read() or -Bio.SeqIO.parse() with a filename - for instance this quick +Instead of using a filename, you can give Bio.SeqIO a handle +(see Section 22.1), and in this section +we’ll use handles to parse sequence from compressed files.

As you’ll have seen above, we can use Bio.SeqIO.read() or +Bio.SeqIO.parse() with a filename - for instance this quick example calculates the total length of the sequences in a multiple -record GenBank file using a generator expression:

>>> from Bio import SeqIO
->>> print sum(len(r) for r in SeqIO.parse("ls_orchid.gbk", "gb"))
+record GenBank file using a generator expression:

>>> from Bio import SeqIO
+>>> print(sum(len(r) for r in SeqIO.parse("ls_orchid.gbk", "gb")))
 67518
-

Here we use a file handle instead, using the with statement -(Python 2.5 or later) to close the handle automatically:

>>> from __future__ import with_statement #Needed on Python 2.5
->>> from Bio import SeqIO
+

Here we use a file handle instead, using the with statement +to close the handle automatically:

>>> from Bio import SeqIO
 >>> with open("ls_orchid.gbk") as handle:
-...     print sum(len(r) for r in SeqIO.parse(handle, "gb"))
+...     print(sum(len(r) for r in SeqIO.parse(handle, "gb")))
 67518
-

Or, the old fashioned way where you manually close the handle:

>>> from Bio import SeqIO
+

Or, the old fashioned way where you manually close the handle:

>>> from Bio import SeqIO
 >>> handle = open("ls_orchid.gbk")
->>> print sum(len(r) for r in SeqIO.parse(handle, "gb"))
+>>> print(sum(len(r) for r in SeqIO.parse(handle, "gb")))
 67518
 >>> handle.close()
-

Now, suppose we have a gzip compressed file instead? These are very -commonly used on Linux. We can use Python’s gzip module to open -the compressed file for reading - which gives us a handle object:

>>> import gzip
+

Now, suppose we have a gzip compressed file instead? These are very +commonly used on Linux. We can use Python’s gzip module to open +the compressed file for reading - which gives us a handle object:

>>> import gzip
 >>> from Bio import SeqIO
 >>> handle = gzip.open("ls_orchid.gbk.gz", "r")
->>> print sum(len(r) for r in SeqIO.parse(handle, "gb"))
+>>> print(sum(len(r) for r in SeqIO.parse(handle, "gb")))
 67518
 >>> handle.close()
-

Similarly if we had a bzip2 compressed file (sadly the function name isn’t -quite as consistent):

>>> import bz2
+

Similarly if we had a bzip2 compressed file (sadly the function name isn’t +quite as consistent):

>>> import bz2
 >>> from Bio import SeqIO
 >>> handle = bz2.BZ2File("ls_orchid.gbk.bz2", "r")
->>> print sum(len(r) for r in SeqIO.parse(handle, "gb"))
+>>> print(sum(len(r) for r in SeqIO.parse(handle, "gb")))
 67518
 >>> handle.close()
-

If you are using Python 2.7 or later, the with-version works for +

If you are using Python 2.7 or later, the with-version works for gzip and bz2 as well. Unfortunately this is broken on older versions of -Python (Issue 3860) and you’d -get an AttributeError about __exit__ being missing.

There is a gzip (GNU Zip) variant called BGZF (Blocked GNU Zip Format), +Python (Issue 3860) and you’d +get an AttributeError about __exit__ being missing.

There is a gzip (GNU Zip) variant called BGZF (Blocked GNU Zip Format), which can be treated like an ordinary gzip file for reading, but has advantages for random access later which we’ll talk about later in -Section 5.4.4.

-

5.3  Parsing sequences from the net

- +Section 5.4.4.

+ +

5.3  Parsing sequences from the net

+ In the previous sections, we looked at parsing sequence data from a file (using a filename or handle), and from compressed files (using a handle). -Here we’ll use Bio.SeqIO with another type of handle, a network -connection, to download and parse sequences from the internet.

Note that just because you can download sequence data and parse it into -a SeqRecord object in one go doesn’t mean this is a good idea. -In general, you should probably download sequences once and save them to -a file for reuse.

-

5.3.1  Parsing GenBank records from the net

- -Section 9.6 talks about the Entrez EFetch interface in more detail, -but for now let’s just connect to the NCBI and get a few Opuntia (prickly-pear) -sequences from GenBank using their GI numbers.

First of all, let’s fetch just one record. If you don’t care about the +Here we’ll use Bio.SeqIO with another type of handle, a network +connection, to download and parse sequences from the internet.

Note that just because you can download sequence data and parse it into +a SeqRecord object in one go doesn’t mean this is a good idea. +In general, you should probably download sequences once and save them to +a file for reuse.

+ +

5.3.1  Parsing GenBank records from the net

+ +Section 9.6 talks about the Entrez EFetch interface in more detail, +but for now let’s just connect to the NCBI and get a few Opuntia (prickly-pear) +sequences from GenBank using their GI numbers.

First of all, let’s fetch just one record. If you don’t care about the annotations and features downloading a FASTA file is a good choice as these are compact. Now remember, when you expect the handle to contain one and -only one record, use the Bio.SeqIO.read() function:

from Bio import Entrez
+only one record, use the Bio.SeqIO.read() function:

from Bio import Entrez
 from Bio import SeqIO
 Entrez.email = "A.N.Other@example.com"
 handle = Entrez.efetch(db="nucleotide", rettype="fasta", retmode="text", id="6273291")
 seq_record = SeqIO.read(handle, "fasta")
 handle.close()
-print "%s with %i features" % (seq_record.id, len(seq_record.features))
-

Expected output:

gi|6273291|gb|AF191665.1|AF191665 with 0 features
-

The NCBI will also let you ask for the file in other formats, in particular as +print("%s with %i features" % (seq_record.id, len(seq_record.features))) +

Expected output:

gi|6273291|gb|AF191665.1|AF191665 with 0 features
+

The NCBI will also let you ask for the file in other formats, in particular as a GenBank file. Until Easter 2009, the Entrez EFetch API let you use “genbank” as the return type, however the NCBI now insist on using the official return types of “gb” (or “gp” for proteins) as described on -EFetch for Sequence and other Molecular Biology Databases. +EFetch for Sequence and other Molecular Biology Databases. As a result, in Biopython 1.50 onwards, we support “gb” as an -alias for “genbank” in Bio.SeqIO.

from Bio import Entrez
+alias for “genbank” in Bio.SeqIO.

from Bio import Entrez
 from Bio import SeqIO
 Entrez.email = "A.N.Other@example.com"
 handle = Entrez.efetch(db="nucleotide", rettype="gb", retmode="text", id="6273291")
 seq_record = SeqIO.read(handle, "gb") #using "gb" as an alias for "genbank"
 handle.close()
-print "%s with %i features" % (seq_record.id, len(seq_record.features))
-

The expected output of this example is:

AF191665.1 with 3 features
-

Notice this time we have three features.

Now let’s fetch several records. This time the handle contains multiple records, -so we must use the Bio.SeqIO.parse() function:

from Bio import Entrez
+print("%s with %i features" % (seq_record.id, len(seq_record.features)))
+

The expected output of this example is:

AF191665.1 with 3 features
+

Notice this time we have three features.

Now let’s fetch several records. This time the handle contains multiple records, +so we must use the Bio.SeqIO.parse() function:

from Bio import Entrez
 from Bio import SeqIO
 Entrez.email = "A.N.Other@example.com"
 handle = Entrez.efetch(db="nucleotide", rettype="gb", retmode="text", \
@@ -1969,88 +2038,92 @@
     print "%i features," % len(seq_record.features),
     print "from: %s" % seq_record.annotations["source"]
 handle.close()
-

That should give the following output:

AF191665.1 Opuntia marenae rpl16 gene; chloroplast gene for c...
+

That should give the following output:

AF191665.1 Opuntia marenae rpl16 gene; chloroplast gene for c...
 Sequence length 902, 3 features, from: chloroplast Opuntia marenae
 AF191664.1 Opuntia clavata rpl16 gene; chloroplast gene for c...
 Sequence length 899, 3 features, from: chloroplast Grusonia clavata
 AF191663.1 Opuntia bradtiana rpl16 gene; chloroplast gene for...
 Sequence length 899, 3 features, from: chloroplast Opuntia bradtianaa
-

See Chapter 9 for more about the Bio.Entrez module, and make sure to read about the NCBI guidelines for using Entrez (Section 9.1).

-

5.3.2  Parsing SwissProt sequences from the net

- +

See Chapter 9 for more about the Bio.Entrez module, and make sure to read about the NCBI guidelines for using Entrez (Section 9.1).

+ +

5.3.2  Parsing SwissProt sequences from the net

+ Now let’s use a handle to download a SwissProt file from ExPASy, -something covered in more depth in Chapter 10. +something covered in more depth in Chapter 10. As mentioned above, when you expect the handle to contain one and only one record, -use the Bio.SeqIO.read() function:

from Bio import ExPASy
+use the Bio.SeqIO.read() function:

from Bio import ExPASy
 from Bio import SeqIO
 handle = ExPASy.get_sprot_raw("O23729")
 seq_record = SeqIO.read(handle, "swiss")
 handle.close()
-print seq_record.id
-print seq_record.name
-print seq_record.description
-print repr(seq_record.seq)
-print "Length %i" % len(seq_record)
-print seq_record.annotations["keywords"]
-

Assuming your network connection is OK, you should get back:

O23729
+print(seq_record.id)
+print(seq_record.name)
+print(seq_record.description)
+print(repr(seq_record.seq))
+print("Length %i" % len(seq_record))
+print(seq_record.annotations["keywords"])
+

Assuming your network connection is OK, you should get back:

O23729
 CHS3_BROFI
 RecName: Full=Chalcone synthase 3; EC=2.3.1.74; AltName: Full=Naringenin-chalcone synthase 3;
 Seq('MAPAMEEIRQAQRAEGPAAVLAIGTSTPPNALYQADYPDYYFRITKSEHLTELK...GAE', ProteinAlphabet())
 Length 394
 ['Acyltransferase', 'Flavonoid biosynthesis', 'Transferase']
-
-

5.4  Sequence files as Dictionaries

We’re now going to introduce three related functions in the Bio.SeqIO +

+ +

5.4  Sequence files as Dictionaries

We’re now going to introduce three related functions in the Bio.SeqIO module which allow dictionary like random access to a multi-sequence file. There is a trade off here between flexibility and memory usage. In summary: -

  • -Bio.SeqIO.to_dict() is the most flexible but also the most -memory demanding option (see Section 5.4.1). This is basically -a helper function to build a normal Python dictionary with each entry -held as a SeqRecord object in memory, allowing you to modify the +

    • +Bio.SeqIO.to_dict() is the most flexible but also the most +memory demanding option (see Section 5.4.1). This is basically +a helper function to build a normal Python dictionary with each entry +held as a SeqRecord object in memory, allowing you to modify the records. -
    • Bio.SeqIO.index() is a useful middle ground, acting like a -read only dictionary and parsing sequences into SeqRecord objects -on demand (see Section 5.4.2). -
    • Bio.SeqIO.index_db() also acts like a read only dictionary +
    • Bio.SeqIO.index() is a useful middle ground, acting like a +read only dictionary and parsing sequences into SeqRecord objects +on demand (see Section 5.4.2). +
    • Bio.SeqIO.index_db() also acts like a read only dictionary but stores the identifiers and file offsets in a file on disk (as an SQLite3 database), meaning it has very low memory requirements (see -Section 5.4.3), but will be a little bit slower. -

    +Section 5.4.3), but will be a little bit slower. +

See the discussion for an broad overview -(Section 5.4.5).

-

5.4.1  Sequence files as Dictionaries – In memory

-

The next thing that we’ll do with our ubiquitous orchid files is to show how -to index them and access them like a database using the Python dictionary +(Section 5.4.5).

+ +

5.4.1  Sequence files as Dictionaries – In memory

+

The next thing that we’ll do with our ubiquitous orchid files is to show how +to index them and access them like a database using the Python dictionary data type (like a hash in Perl). This is very useful for moderately large files where you only need to access certain elements of the file, and makes for a nice quick ’n dirty database. For dealing with larger files where memory becomes a -problem, see Section 5.4.2 below.

You can use the function Bio.SeqIO.to_dict() to make a SeqRecord dictionary -(in memory). By default this will use each record’s identifier (i.e. the .id -attribute) as the key. Let’s try this using our GenBank file:

>>> from Bio import SeqIO
+problem, see Section 5.4.2 below.

You can use the function Bio.SeqIO.to_dict() to make a SeqRecord dictionary +(in memory). By default this will use each record’s identifier (i.e. the .id +attribute) as the key. Let’s try this using our GenBank file:

>>> from Bio import SeqIO
 >>> orchid_dict = SeqIO.to_dict(SeqIO.parse("ls_orchid.gbk", "genbank"))
-

There is just one required argument for Bio.SeqIO.to_dict(), a list or -generator giving SeqRecord objects. Here we have just used the output -from the SeqIO.parse function. As the name suggests, this returns a -Python dictionary.

Since this variable orchid_dict is an ordinary Python dictionary, we can look at all of the keys we have available:

>>> len(orchid_dict)
+

There is just one required argument for Bio.SeqIO.to_dict(), a list or +generator giving SeqRecord objects. Here we have just used the output +from the SeqIO.parse function. As the name suggests, this returns a +Python dictionary.

Since this variable orchid_dict is an ordinary Python dictionary, we can look at all of the keys we have available:

>>> len(orchid_dict)
 94
-
>>> print orchid_dict.keys()
+
>>> orchid_dict.keys()
 ['Z78484.1', 'Z78464.1', 'Z78455.1', 'Z78442.1', 'Z78532.1', 'Z78453.1', ..., 'Z78471.1']
-

If you really want to, you can even look at all the records at once: -

>>> orchid_dict.values() #lots of output!
+

If you really want to, you can even look at all the records at once: +

>>> orchid_dict.values() #lots of output!
 ...
-

We can access a single SeqRecord object via the keys and manipulate the object as normal:

>>> seq_record = orchid_dict["Z78475.1"]
->>> print seq_record.description
+

We can access a single SeqRecord object via the keys and manipulate the object as normal:

>>> seq_record = orchid_dict["Z78475.1"]
+>>> print(seq_record.description)
 P.supardii 5.8S rRNA gene and ITS1 and ITS2 DNA.
->>> print repr(seq_record.seq)
+>>> print(repr(seq_record.seq))
 Seq('CGTAACAAGGTTTCCGTAGGTGAACCTGCGGAAGGATCATTGTTGAGATCACAT...GGT', IUPACAmbiguousDNA())
-

So, it is very easy to create an in memory “database” of our GenBank records. Next we’ll try this for the FASTA file instead.

Note that those of you with prior Python experience should all be able to construct a dictionary like this “by hand”. However, typical dictionary construction methods will not deal with the case of repeated keys very nicely. Using the Bio.SeqIO.to_dict() will explicitly check for duplicate keys, and raise an exception if any are found.

-

5.4.1.1  Specifying the dictionary keys

-

Using the same code as above, but for the FASTA file instead:

from Bio import SeqIO
+

So, it is very easy to create an in memory “database” of our GenBank records. Next we’ll try this for the FASTA file instead.

Note that those of you with prior Python experience should all be able to construct a dictionary like this “by hand”. However, typical dictionary construction methods will not deal with the case of repeated keys very nicely. Using the Bio.SeqIO.to_dict() will explicitly check for duplicate keys, and raise an exception if any are found.

+ +

5.4.1.1  Specifying the dictionary keys

+

Using the same code as above, but for the FASTA file instead:

from Bio import SeqIO
 orchid_dict = SeqIO.to_dict(SeqIO.parse("ls_orchid.fasta", "fasta"))
-print orchid_dict.keys()
-

This time the keys are:

['gi|2765596|emb|Z78471.1|PDZ78471', 'gi|2765646|emb|Z78521.1|CCZ78521', ...
+print(orchid_dict.keys())
+

This time the keys are:

['gi|2765596|emb|Z78471.1|PDZ78471', 'gi|2765646|emb|Z78521.1|CCZ78521', ...
  ..., 'gi|2765613|emb|Z78488.1|PTZ78488', 'gi|2765583|emb|Z78458.1|PHZ78458']
-

You should recognise these strings from when we parsed the FASTA file earlier in Section 2.4.1. Suppose you would rather have something else as the keys - like the accession numbers. This brings us nicely to SeqIO.to_dict()’s optional argument key_function, which lets you define what to use as the dictionary key for your records.

First you must write your own function to return the key you want (as a string) when given a SeqRecord object. In general, the details of function will depend on the sort of input records you are dealing with. But for our orchids, we can just split up the record’s identifier using the “pipe” character (the vertical line) and return the fourth entry (field three):

def get_accession(record):
+

You should recognise these strings from when we parsed the FASTA file earlier in Section 2.4.1. Suppose you would rather have something else as the keys - like the accession numbers. This brings us nicely to SeqIO.to_dict()’s optional argument key_function, which lets you define what to use as the dictionary key for your records.

First you must write your own function to return the key you want (as a string) when given a SeqRecord object. In general, the details of function will depend on the sort of input records you are dealing with. But for our orchids, we can just split up the record’s identifier using the “pipe” character (the vertical line) and return the fourth entry (field three):

def get_accession(record):
     """"Given a SeqRecord, return the accession number as a string.
   
     e.g. "gi|2765613|emb|Z78488.1|PTZ78488" -> "Z78488.1"
@@ -2058,71 +2131,74 @@
     parts = record.id.split("|")
     assert len(parts) == 5 and parts[0] == "gi" and parts[2] == "emb"
     return parts[3]
-

Then we can give this function to the SeqIO.to_dict() function to use in building the dictionary:

from Bio import SeqIO
+

Then we can give this function to the SeqIO.to_dict() function to use in building the dictionary:

from Bio import SeqIO
 orchid_dict = SeqIO.to_dict(SeqIO.parse("ls_orchid.fasta", "fasta"), key_function=get_accession)
-print orchid_dict.keys()
-

Finally, as desired, the new dictionary keys:

>>> print orchid_dict.keys()
+print(orchid_dict.keys())
+

Finally, as desired, the new dictionary keys:

>>> print(orchid_dict.keys())
 ['Z78484.1', 'Z78464.1', 'Z78455.1', 'Z78442.1', 'Z78532.1', 'Z78453.1', ..., 'Z78471.1']
-

Not too complicated, I hope!

-

5.4.1.2  Indexing a dictionary using the SEGUID checksum

To give another example of working with dictionaries of SeqRecord objects, we’ll use the SEGUID checksum function. This is a relatively recent checksum, and collisions should be very rare (i.e. two different sequences with the same checksum), an improvement on the CRC64 checksum.

Once again, working with the orchids GenBank file:

from Bio import SeqIO
+

Not too complicated, I hope!

+ +

5.4.1.2  Indexing a dictionary using the SEGUID checksum

To give another example of working with dictionaries of SeqRecord objects, we’ll use the SEGUID checksum function. This is a relatively recent checksum, and collisions should be very rare (i.e. two different sequences with the same checksum), an improvement on the CRC64 checksum.

Once again, working with the orchids GenBank file:

from Bio import SeqIO
 from Bio.SeqUtils.CheckSum import seguid
 for record in SeqIO.parse("ls_orchid.gbk", "genbank"):
-    print record.id, seguid(record.seq)
-

This should give:

Z78533.1 JUEoWn6DPhgZ9nAyowsgtoD9TTo
+    print(record.id, seguid(record.seq))
+

This should give:

Z78533.1 JUEoWn6DPhgZ9nAyowsgtoD9TTo
 Z78532.1 MN/s0q9zDoCVEEc+k/IFwCNF2pY
 ...
 Z78439.1 H+JfaShya/4yyAj7IbMqgNkxdxQ
-

Now, recall the Bio.SeqIO.to_dict() function’s key_function argument expects a function which turns a SeqRecord into a string. We can’t use the seguid() function directly because it expects to be given a Seq object (or a string). However, we can use Python’s lambda feature to create a “one off” function to give to Bio.SeqIO.to_dict() instead:

>>> from Bio import SeqIO
+

Now, recall the Bio.SeqIO.to_dict() function’s key_function argument expects a function which turns a SeqRecord into a string. We can’t use the seguid() function directly because it expects to be given a Seq object (or a string). However, we can use Python’s lambda feature to create a “one off” function to give to Bio.SeqIO.to_dict() instead:

>>> from Bio import SeqIO
 >>> from Bio.SeqUtils.CheckSum import seguid
 >>> seguid_dict = SeqIO.to_dict(SeqIO.parse("ls_orchid.gbk", "genbank"),
 ...                             lambda rec : seguid(rec.seq))
 >>> record = seguid_dict["MN/s0q9zDoCVEEc+k/IFwCNF2pY"]
->>> print record.id
+>>> print(record.id)
 Z78532.1
->>> print record.description
+>>> print(record.description)
 C.californicum 5.8S rRNA gene and ITS1 and ITS2 DNA.
-

That should have retrieved the record Z78532.1, the second entry in the file.

-

5.4.2  Sequence files as Dictionaries – Indexed files

-

As the previous couple of examples tried to illustrate, using -Bio.SeqIO.to_dict() is very flexible. However, because it holds +

That should have retrieved the record Z78532.1, the second entry in the file.

+ +

5.4.2  Sequence files as Dictionaries – Indexed files

+

As the previous couple of examples tried to illustrate, using +Bio.SeqIO.to_dict() is very flexible. However, because it holds everything in memory, the size of file you can work with is limited by your -computer’s RAM. In general, this will only work on small to medium files.

For larger files you should consider -Bio.SeqIO.index(), which works a little differently. Although -it still returns a dictionary like object, this does not keep -everything in memory. Instead, it just records where each record +computer’s RAM. In general, this will only work on small to medium files.

For larger files you should consider +Bio.SeqIO.index(), which works a little differently. Although +it still returns a dictionary like object, this does not keep +everything in memory. Instead, it just records where each record is within the file – when you ask for a particular record, it then parses -it on demand.

As an example, let’s use the same GenBank file as before:

>>> from Bio import SeqIO
+it on demand.

As an example, let’s use the same GenBank file as before:

>>> from Bio import SeqIO
 >>> orchid_dict = SeqIO.index("ls_orchid.gbk", "genbank")
 >>> len(orchid_dict)
 94
-
>>> orchid_dict.keys()
+
>>> orchid_dict.keys()
 ['Z78484.1', 'Z78464.1', 'Z78455.1', 'Z78442.1', 'Z78532.1', 'Z78453.1', ..., 'Z78471.1']
-
>>> seq_record = orchid_dict["Z78475.1"]
->>> print seq_record.description
+
>>> seq_record = orchid_dict["Z78475.1"]
+>>> print(seq_record.description)
 P.supardii 5.8S rRNA gene and ITS1 and ITS2 DNA.
 >>> seq_record.seq
 Seq('CGTAACAAGGTTTCCGTAGGTGAACCTGCGGAAGGATCATTGTTGAGATCACAT...GGT', IUPACAmbiguousDNA())
-

Note that Bio.SeqIO.index() won’t take a handle, +

Note that Bio.SeqIO.index() won’t take a handle, but only a filename. There are good reasons for this, but it is a little technical. The second argument is the file format (a lower case string as -used in the other Bio.SeqIO functions). You can use many other +used in the other Bio.SeqIO functions). You can use many other simple file formats, including FASTA and FASTQ files (see the example in -Section 18.1.11). However, alignment +Section 18.1.11). However, alignment formats like PHYLIP or Clustal are not supported. Finally as an optional -argument you can supply an alphabet, or a key function.

Here is the same example using the FASTA file - all we change is the -filename and the format name:

>>> from Bio import SeqIO
+argument you can supply an alphabet, or a key function.

Here is the same example using the FASTA file - all we change is the +filename and the format name:

>>> from Bio import SeqIO
 >>> orchid_dict = SeqIO.index("ls_orchid.fasta", "fasta")
 >>> len(orchid_dict)
 94
 >>> orchid_dict.keys()
 ['gi|2765596|emb|Z78471.1|PDZ78471', 'gi|2765646|emb|Z78521.1|CCZ78521', ...
  ..., 'gi|2765613|emb|Z78488.1|PTZ78488', 'gi|2765583|emb|Z78458.1|PHZ78458']
-
-

5.4.2.1  Specifying the dictionary keys

-

Suppose you want to use the same keys as before? Much like with the -Bio.SeqIO.to_dict() example in Section 5.4.1.1, +

+ +

5.4.2.1  Specifying the dictionary keys

+

Suppose you want to use the same keys as before? Much like with the +Bio.SeqIO.to_dict() example in Section 5.4.1.1, you’ll need to write a tiny function to map from the FASTA identifier -(as a string) to the key you want:

def get_acc(identifier):
+(as a string) to the key you want:

def get_acc(identifier):
     """"Given a SeqRecord identifier string, return the accession number as a string.
   
     e.g. "gi|2765613|emb|Z78488.1|PTZ78488" -> "Z78488.1"
@@ -2130,141 +2206,147 @@
     parts = identifier.split("|")
     assert len(parts) == 5 and parts[0] == "gi" and parts[2] == "emb"
     return parts[3]
-

Then we can give this function to the Bio.SeqIO.index() -function to use in building the dictionary:

>>> from Bio import SeqIO
+

Then we can give this function to the Bio.SeqIO.index() +function to use in building the dictionary:

>>> from Bio import SeqIO
 >>> orchid_dict = SeqIO.index("ls_orchid.fasta", "fasta", key_function=get_acc)
->>> print orchid_dict.keys()
+>>> print(orchid_dict.keys())
 ['Z78484.1', 'Z78464.1', 'Z78455.1', 'Z78442.1', 'Z78532.1', 'Z78453.1', ..., 'Z78471.1']
-

Easy when you know how?

-

5.4.2.2  Getting the raw data for a record

-

The dictionary-like object from Bio.SeqIO.index() gives you each -entry as a SeqRecord object. However, it is sometimes useful to +

Easy when you know how?

+ +

5.4.2.2  Getting the raw data for a record

+

The dictionary-like object from Bio.SeqIO.index() gives you each +entry as a SeqRecord object. However, it is sometimes useful to be able to get the original raw data straight from the file. For this -use the get_raw() method which takes a +use the get_raw() method which takes a single argument (the record identifier) and returns a string (extracted -from the file without modification).

A motivating example is extracting a subset of a records from a large -file where either Bio.SeqIO.write() does not (yet) support the +from the file without modification).

A motivating example is extracting a subset of a records from a large +file where either Bio.SeqIO.write() does not (yet) support the output file format (e.g. the plain text SwissProt file format) or where you need to preserve the text exactly (e.g. GenBank or EMBL output from Biopython does not yet preserve every last bit of -annotation).

Let’s suppose you have download the whole of UniProt in the plain +annotation).

Let’s suppose you have download the whole of UniProt in the plain text SwissPort file format from their FTP site -(ftp://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/complete/uniprot_sprot.dat.gz) -and uncompressed it as the file uniprot_sprot.dat, and you -want to extract just a few records from it:

>>> from Bio import SeqIO
+(ftp://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/complete/uniprot_sprot.dat.gz)
+and uncompressed it as the file uniprot_sprot.dat, and you
+want to extract just a few records from it:

>>> from Bio import SeqIO
 >>> uniprot = SeqIO.index("uniprot_sprot.dat", "swiss")
 >>> handle = open("selected.dat", "w")
 >>> for acc in ["P33487", "P19801", "P13689", "Q8JZQ5", "Q9TRC7"]:
 ...     handle.write(uniprot.get_raw(acc))
 >>> handle.close()
-

There is a longer example in Section 18.1.5 using the -SeqIO.index() function to sort a large sequence file (without -loading everything into memory at once).

-

5.4.3  Sequence files as Dictionaries – Database indexed files

-

Biopython 1.57 introduced an alternative, Bio.SeqIO.index_db(), which +

There is a longer example in Section 18.1.5 using the +SeqIO.index() function to sort a large sequence file (without +loading everything into memory at once).

+ +

5.4.3  Sequence files as Dictionaries – Database indexed files

+

Biopython 1.57 introduced an alternative, Bio.SeqIO.index_db(), which can work on even extremely large files since it stores the record information as a file on disk (using an SQLite3 database) rather than in memory. Also, you can index multiple files together (providing all the record identifiers -are unique).

The Bio.SeqIO.index() function takes three required arguments: -

  • -Index filename, we suggest using something ending .idx. +are unique).

    The Bio.SeqIO.index() function takes three required arguments: +

    • +Index filename, we suggest using something ending .idx. This index file is actually an SQLite3 database. -
    • List of sequence filenames to index (or a single filename) -
    • File format (lower case string as used in the rest of the -SeqIO module). -

    As an example, consider the GenBank flat file releases from the NCBI FTP site, -ftp://ftp.ncbi.nih.gov/genbank/, which are gzip compressed GenBank files. +

  • List of sequence filenames to index (or a single filename) +
  • File format (lower case string as used in the rest of the +SeqIO module). +

As an example, consider the GenBank flat file releases from the NCBI FTP site, +ftp://ftp.ncbi.nih.gov/genbank/, which are gzip compressed GenBank files. As of GenBank release 182, there are 16 files making up the viral sequences, -gbvrl1.seq, …, gbvrl16.seq, containing in total almost -one million records. You can index them like this:

>>> from Bio import SeqIO
+gbvrl1.seq, …, gbvrl16.seq, containing in total almost
+one million records. You can index them like this:

>>> from Bio import SeqIO
 >>> files = ["gbvrl%i.seq" % (i+1) for i in range(16)]
 >>> gb_vrl = SeqIO.index_db("gbvrl.idx", files, "genbank")
->>> print "%i sequences indexed" % len(gb_vrl)
+>>> print("%i sequences indexed" % len(gb_vrl))
 958086 sequences indexed
-

That takes about two minutes to run on my machine. If you rerun it then the -index file (here gbvrl.idx) is reloaded in under a second. You can +

That takes about two minutes to run on my machine. If you rerun it then the +index file (here gbvrl.idx) is reloaded in under a second. You can use the index as a read only Python dictionary - without having to worry -about which file the sequence comes from, e.g.

>>> print gb_vrl["GQ333173.1"].description
+about which file the sequence comes from, e.g.

>>> print(gb_vrl["GQ333173.1"].description)
 HIV-1 isolate F12279A1 from Uganda gag protein (gag) gene, partial cds.
-
-

5.4.3.1  Getting the raw data for a record

Just as with the Bio.SeqIO.index() function discussed above in -Section 5.4.2.2, the dictionary like object also lets you -get at the raw text of each record:

>>> print gb_vrl.get_raw("GQ333173.1")
+
+ +

5.4.3.1  Getting the raw data for a record

Just as with the Bio.SeqIO.index() function discussed above in +Section 5.4.2.2, the dictionary like object also lets you +get at the raw text of each record:

>>> print(gb_vrl.get_raw("GQ333173.1"))
 LOCUS       GQ333173                 459 bp    DNA     linear   VRL 21-OCT-2009
 DEFINITION  HIV-1 isolate F12279A1 from Uganda gag protein (gag) gene, partial
             cds.
 ACCESSION   GQ333173
 ...
 //
-
-

5.4.4  Indexing compressed files

-

Very often when you are indexing a sequence file it can be quite large – so +

+ +

5.4.4  Indexing compressed files

+

Very often when you are indexing a sequence file it can be quite large – so you may want to compress it on disk. Unfortunately efficient random access is difficult with the more common file formats like gzip and bzip2. In this setting, BGZF (Blocked GNU Zip Format) can be very helpful. This is a variant of gzip (and can be decompressed using standard gzip tools) popularised by -the BAM file format, samtools, and -tabix.

To create a BGZF compressed file you can use the command line tool bgzip +the BAM file format, samtools, and +tabix.

To create a BGZF compressed file you can use the command line tool bgzip which comes with samtools. In our examples we use a filename extension -*.bgz, so they can be distinguished from normal gzipped files (named -*.gz). You can also use the Bio.bgzf module to read and write -BGZF files from within Python.

The Bio.SeqIO.index() and Bio.SeqIO.index_db() can both be +*.bgz, so they can be distinguished from normal gzipped files (named +*.gz). You can also use the Bio.bgzf module to read and write +BGZF files from within Python.

The Bio.SeqIO.index() and Bio.SeqIO.index_db() can both be used with BGZF compressed files. For example, if you started with an -uncompressed GenBank file:

>>> from Bio import SeqIO
+uncompressed GenBank file:

>>> from Bio import SeqIO
 >>> orchid_dict = SeqIO.index("ls_orchid.gbk", "genbank")
 >>> len(orchid_dict)
 94
-

You could compress this (while keeping the original file) at the command +

You could compress this (while keeping the original file) at the command line using the following command – but don’t worry, the compressed file -is already included with the other example files:

$ bgzip -c ls_orchid.gbk > ls_orchid.gbk.bgz
-

You can use the compressed file in exactly the same way:

>>> from Bio import SeqIO
+is already included with the other example files:

$ bgzip -c ls_orchid.gbk > ls_orchid.gbk.bgz
+

You can use the compressed file in exactly the same way:

>>> from Bio import SeqIO
 >>> orchid_dict = SeqIO.index("ls_orchid.gbk.bgz", "genbank")
 >>> len(orchid_dict)
 94
-

or:

>>> from Bio import SeqIO
+

or:

>>> from Bio import SeqIO
 >>> orchid_dict = SeqIO.index_db("ls_orchid.gbk.bgz.idx", "ls_orchid.gbk.bgz", "genbank")
 >>> len(orchid_dict)
 94
-

The SeqIO indexing automatically detects the BGZF compression. Note -that you can’t use the same index file for the uncompressed and compressed files.

-

5.4.5  Discussion

-

So, which of these methods should you use and why? It depends on what you are +

The SeqIO indexing automatically detects the BGZF compression. Note +that you can’t use the same index file for the uncompressed and compressed files.

+ +

5.4.5  Discussion

+

So, which of these methods should you use and why? It depends on what you are trying to do (and how much data you are dealing with). However, in general -picking Bio.SeqIO.index() is a good starting point. If you are dealing +picking Bio.SeqIO.index() is a good starting point. If you are dealing with millions of records, multiple files, or repeated analyses, then look at -Bio.SeqIO.index_db().

Reasons to choose Bio.SeqIO.to_dict() over either -Bio.SeqIO.index() or Bio.SeqIO.index_db() boil down to a need +Bio.SeqIO.index_db().

Reasons to choose Bio.SeqIO.to_dict() over either +Bio.SeqIO.index() or Bio.SeqIO.index_db() boil down to a need for flexibility despite its high memory needs. The advantage of storing the -SeqRecord objects in memory is they can be changed, added to, or +SeqRecord objects in memory is they can be changed, added to, or removed at will. In addition to the downside of high memory consumption, -indexing can also take longer because all the records must be fully parsed.

Both Bio.SeqIO.index() and Bio.SeqIO.index_db() only parse +indexing can also take longer because all the records must be fully parsed.

Both Bio.SeqIO.index() and Bio.SeqIO.index_db() only parse records on demand. When indexing, they scan the file once looking for the start of each record and do as little work as possible to extract the -identifier.

Reasons to choose Bio.SeqIO.index() over Bio.SeqIO.index_db() +identifier.

Reasons to choose Bio.SeqIO.index() over Bio.SeqIO.index_db() include: -

  • +

    • Faster to build the index (more noticeable in simple file formats) -
    • Slightly faster access as SeqRecord objects (but the difference is only +
    • Slightly faster access as SeqRecord objects (but the difference is only really noticeable for simple to parse file formats). -
    • Can use any immutable Python object as the dictionary keys (e.g. a +
    • Can use any immutable Python object as the dictionary keys (e.g. a tuple of strings, or a frozen set) not just strings. -
    • Don’t need to worry about the index database being out of date if the +
    • Don’t need to worry about the index database being out of date if the sequence file being indexed has changed. -

    Reasons to choose Bio.SeqIO.index_db() over Bio.SeqIO.index() +

Reasons to choose Bio.SeqIO.index_db() over Bio.SeqIO.index() include: -

  • +

    • Not memory limited – this is already important with files from second generation sequencing where 10s of millions of sequences are common, and -using Bio.SeqIO.index() can require more than 4GB of RAM and therefore +using Bio.SeqIO.index() can require more than 4GB of RAM and therefore a 64bit version of Python. -
    • Because the index is kept on disk, it can be reused. Although building +
    • Because the index is kept on disk, it can be reused. Although building the index database file takes longer, if you have a script which will be rerun on the same datafiles in future, this could save time in the long run. -
    • Indexing multiple files together -
    • The get_raw() method can be much faster, since for most file +
    • Indexing multiple files together +
    • The get_raw() method can be much faster, since for most file formats the length of each record is stored as well as its offset. -
    -

    5.5  Writing Sequence Files

    We’ve talked about using Bio.SeqIO.parse() for sequence input (reading files), and now we’ll look at Bio.SeqIO.write() which is for sequence output (writing files). This is a function taking three arguments: some SeqRecord objects, a handle or filename to write to, and a sequence format.

    Here is an example, where we start by creating a few SeqRecord objects the hard way (by hand, rather than by loading them from a file):

    from Bio.Seq import Seq
    +
+ +

5.5  Writing Sequence Files

We’ve talked about using Bio.SeqIO.parse() for sequence input (reading files), and now we’ll look at Bio.SeqIO.write() which is for sequence output (writing files). This is a function taking three arguments: some SeqRecord objects, a handle or filename to write to, and a sequence format.

Here is an example, where we start by creating a few SeqRecord objects the hard way (by hand, rather than by loading them from a file):

from Bio.Seq import Seq
 from Bio.SeqRecord import SeqRecord
 from Bio.Alphabet import generic_protein
 
@@ -2291,9 +2373,9 @@
                  description="chalcone synthase [Nicotiana tabacum]")
                
 my_records = [rec1, rec2, rec3]
-

Now we have a list of SeqRecord objects, we’ll write them to a FASTA format file:

from Bio import SeqIO
+

Now we have a list of SeqRecord objects, we’ll write them to a FASTA format file:

from Bio import SeqIO
 SeqIO.write(my_records, "my_example.faa", "fasta")
-

And if you open this file in your favourite text editor it should look like this:

>gi|14150838|gb|AAK54648.1|AF376133_1 chalcone synthase [Cucumis sativus]
+

And if you open this file in your favourite text editor it should look like this:

>gi|14150838|gb|AAK54648.1|AF376133_1 chalcone synthase [Cucumis sativus]
 MMYQQGCFAGGTVLRLAKDLAENNRGARVLVVCSEITAVTFRGPSETHLDSMVGQALFGD
 GAGAVIVGSDPDLSVERPLYELVWTGATLLPDSEGAIDGHLREVGLTFHLLKDVPGLISK
 NIEKSLKEAFTPLGISDWNSTFWIAHPGGPAILDQVEAKLGLKEEKMRATREVLSEYGNM
@@ -2309,14 +2391,15 @@
 SAAQTLLPDSEGAIDGHLREVGLTFHLLKDVPGLISKNIEKSLVEAFQPLGISDWNSLFW
 IAHPGGPAILDQVELKLGLKQEKLKATRKVLSNYGNMSSACVLFILDEMRKASAKEGLGT
 TGEGLEWGVLFGFGPGLTVETVVLHSVAT
-

Suppose you wanted to know how many records the Bio.SeqIO.write() function wrote to the handle? -If your records were in a list you could just use len(my_records), however you can’t do that when your records come from a generator/iterator. The Bio.SeqIO.write() function returns the number of SeqRecord objects written to the file.

Note - If you tell the Bio.SeqIO.write() function to write to a file that already exists, the old file will be overwritten without any warning.

-

5.5.1  Round trips

Some people like their parsers to be “round-tripable”, meaning if you read in +

Suppose you wanted to know how many records the Bio.SeqIO.write() function wrote to the handle? +If your records were in a list you could just use len(my_records), however you can’t do that when your records come from a generator/iterator. The Bio.SeqIO.write() function returns the number of SeqRecord objects written to the file.

Note - If you tell the Bio.SeqIO.write() function to write to a file that already exists, the old file will be overwritten without any warning.

+ +

5.5.1  Round trips

Some people like their parsers to be “round-tripable”, meaning if you read in a file and write it back out again it is unchanged. This requires that the parser -must extract enough information to reproduce the original file exactly. -Bio.SeqIO does not aim to do this.

As a trivial example, any line wrapping of the sequence data in FASTA files is -allowed. An identical SeqRecord would be given from parsing the following -two examples which differ only in their line breaks:

>YAL068C-7235.2170 Putative promoter sequence
+must extract enough information to reproduce the original file exactly.
+Bio.SeqIO does not aim to do this.

As a trivial example, any line wrapping of the sequence data in FASTA files is +allowed. An identical SeqRecord would be given from parsing the following +two examples which differ only in their line breaks:

>YAL068C-7235.2170 Putative promoter sequence
 TACGAGAATAATTTCTCATCATCCAGCTTTAACACAAAATTCGCACAGTTTTCGTTAAGA
 GAACTTAACATTTTCTTATGACGTAAATGAAGTTTATATATAAATTTCCTTTTTATTGGA
 
@@ -2324,106 +2407,112 @@
 TACGAGAATAATTTCTCATCATCCAGCTTTAACACAAAATTCGCA
 CAGTTTTCGTTAAGAGAACTTAACATTTTCTTATGACGTAAATGA
 AGTTTATATATAAATTTCCTTTTTATTGGA
-

To make a round-tripable FASTA parser you would need to keep track of where the +

To make a round-tripable FASTA parser you would need to keep track of where the sequence line breaks occurred, and this extra information is usually pointless. Instead Biopython uses a default line wrapping of 60 characters on output. The same problem with white space applies in many other file formats too. Another issue in some cases is that Biopython does not (yet) preserve every -last bit of annotation (e.g. GenBank and EMBL).

Occasionally preserving the original layout (with any quirks it may have) is -important. See Section 5.4.2.2 about the get_raw() -method of the Bio.SeqIO.index() dictionary-like object for one potential -solution.

-

5.5.2  Converting between sequence file formats

-

In previous example we used a list of SeqRecord objects as input to the Bio.SeqIO.write() function, but it will also accept a SeqRecord iterator like we get from Bio.SeqIO.parse() – this lets us do file conversion by combining these two functions.

For this example we’ll read in the GenBank format file ls_orchid.gbk and write it out in FASTA format:

from Bio import SeqIO
+last bit of annotation (e.g. GenBank and EMBL).

Occasionally preserving the original layout (with any quirks it may have) is +important. See Section 5.4.2.2 about the get_raw() +method of the Bio.SeqIO.index() dictionary-like object for one potential +solution.

+ +

5.5.2  Converting between sequence file formats

+

In previous example we used a list of SeqRecord objects as input to the Bio.SeqIO.write() function, but it will also accept a SeqRecord iterator like we get from Bio.SeqIO.parse() – this lets us do file conversion by combining these two functions.

For this example we’ll read in the GenBank format file ls_orchid.gbk and write it out in FASTA format:

from Bio import SeqIO
 records = SeqIO.parse("ls_orchid.gbk", "genbank")
 count = SeqIO.write(records, "my_example.fasta", "fasta")
-print "Converted %i records" % count
-

Still, that is a little bit complicated. So, because file conversion is such a -common task, there is a helper function letting you replace that with just:

from Bio import SeqIO
+print("Converted %i records" % count)
+

Still, that is a little bit complicated. So, because file conversion is such a +common task, there is a helper function letting you replace that with just:

from Bio import SeqIO
 count = SeqIO.convert("ls_orchid.gbk", "genbank", "my_example.fasta", "fasta")
-print "Converted %i records" % count
-

The Bio.SeqIO.convert() function will take handles or filenames. +print("Converted %i records" % count) +

The Bio.SeqIO.convert() function will take handles or filenames. Watch out though – if the output file already exists, it will overwrite it! -To find out more, see the built in help:

>>> from Bio import SeqIO
+To find out more, see the built in help:

>>> from Bio import SeqIO
 >>> help(SeqIO.convert)
 ...
-

In principle, just by changing the filenames and the format names, this code +

In principle, just by changing the filenames and the format names, this code could be used to convert between any file formats available in Biopython. However, writing some formats requires information (e.g. quality scores) which other files formats don’t contain. For example, while you can turn a FASTQ file into a FASTA file, you can’t do the reverse. See also -Sections 18.1.9 and 18.1.10 -in the cookbook chapter which looks at inter-converting between different FASTQ formats.

Finally, as an added incentive for using the Bio.SeqIO.convert() function +Sections 18.1.9 and 18.1.10 +in the cookbook chapter which looks at inter-converting between different FASTQ formats.

Finally, as an added incentive for using the Bio.SeqIO.convert() function (on top of the fact your code will be shorter), doing it this way may also be faster! The reason for this is the convert function can take advantage of -several file format specific optimisations and tricks.

-

5.5.3  Converting a file of sequences to their reverse complements

-

Suppose you had a file of nucleotide sequences, and you wanted to turn it into a file containing their reverse complement sequences. This time a little bit of work is required to transform the SeqRecord objects we get from our input file into something suitable for saving to our output file.

To start with, we’ll use Bio.SeqIO.parse() to load some nucleotide +several file format specific optimisations and tricks.

+ +

5.5.3  Converting a file of sequences to their reverse complements

+

Suppose you had a file of nucleotide sequences, and you wanted to turn it into a file containing their reverse complement sequences. This time a little bit of work is required to transform the SeqRecord objects we get from our input file into something suitable for saving to our output file.

To start with, we’ll use Bio.SeqIO.parse() to load some nucleotide sequences from a file, then print out their reverse complements using -the Seq object’s built in .reverse_complement() method (see Section 3.7):

>>> from Bio import SeqIO
+the Seq object’s built in .reverse_complement() method (see Section 3.7):

>>> from Bio import SeqIO
 >>> for record in SeqIO.parse("ls_orchid.gbk", "genbank"):
-...     print record.id
-...     print record.seq.reverse_complement()
-

Now, if we want to save these reverse complements to a file, we’ll need to make SeqRecord objects. -We can use the SeqRecord object’s built in .reverse_complement() method (see Section 4.8) but we must decide how to name our new records.

This is an excellent place to demonstrate the power of list comprehensions which make a list in memory: -

>>> from Bio import SeqIO
+...     print(record.id)
+...     print(record.seq.reverse_complement())
+

Now, if we want to save these reverse complements to a file, we’ll need to make SeqRecord objects. +We can use the SeqRecord object’s built in .reverse_complement() method (see Section 4.8) but we must decide how to name our new records.

This is an excellent place to demonstrate the power of list comprehensions which make a list in memory: +

>>> from Bio import SeqIO
 >>> records = [rec.reverse_complement(id="rc_"+rec.id, description = "reverse complement") \
 ...            for rec in SeqIO.parse("ls_orchid.fasta", "fasta")]
 >>> len(records)
 94
-

Now list comprehensions have a nice trick up their sleeves, you can add a conditional statement:

>>> records = [rec.reverse_complement(id="rc_"+rec.id, description = "reverse complement") \
+

Now list comprehensions have a nice trick up their sleeves, you can add a conditional statement:

>>> records = [rec.reverse_complement(id="rc_"+rec.id, description = "reverse complement") \
 ...            for rec in SeqIO.parse("ls_orchid.fasta", "fasta") if len(rec)<700]
 >>> len(records)
 18
-

That would create an in memory list of reverse complement records where the sequence length was under 700 base pairs. However, we can do exactly the same with a generator expression - but with the advantage that this does not create a list of all the records in memory at once:

>>> records = (rec.reverse_complement(id="rc_"+rec.id, description = "reverse complement") \
+

That would create an in memory list of reverse complement records where the sequence length was under 700 base pairs. However, we can do exactly the same with a generator expression - but with the advantage that this does not create a list of all the records in memory at once:

>>> records = (rec.reverse_complement(id="rc_"+rec.id, description = "reverse complement") \
 ...           for rec in SeqIO.parse("ls_orchid.fasta", "fasta") if len(rec)<700)
-

As a complete example:

>>> from Bio import SeqIO
+

As a complete example:

>>> from Bio import SeqIO
 >>> records = (rec.reverse_complement(id="rc_"+rec.id, description = "reverse complement") \
 ...            for rec in SeqIO.parse("ls_orchid.fasta", "fasta") if len(rec)<700)
 >>> SeqIO.write(records, "rev_comp.fasta", "fasta")
 18
-

There is a related example in Section 18.1.3, translating each -record in a FASTA file from nucleotides to amino acids.

-

5.5.4  Getting your SeqRecord objects as formatted strings

- -Suppose that you don’t really want to write your records to a file or handle – instead you want a string containing the records in a particular file format. The Bio.SeqIO interface is based on handles, but Python has a useful built in module which provides a string based handle.

For an example of how you might use this, let’s load in a bunch of SeqRecord objects from our orchids GenBank file, and create a string containing the records in FASTA format:

from Bio import SeqIO
+

There is a related example in Section 18.1.3, translating each +record in a FASTA file from nucleotides to amino acids.

+ +

5.5.4  Getting your SeqRecord objects as formatted strings

+ +Suppose that you don’t really want to write your records to a file or handle – instead you want a string containing the records in a particular file format. The Bio.SeqIO interface is based on handles, but Python has a useful built in module which provides a string based handle.

For an example of how you might use this, let’s load in a bunch of SeqRecord objects from our orchids GenBank file, and create a string containing the records in FASTA format:

from Bio import SeqIO
 from StringIO import StringIO
 records = SeqIO.parse("ls_orchid.gbk", "genbank")
 out_handle = StringIO()
 SeqIO.write(records, out_handle, "fasta")
 fasta_data = out_handle.getvalue()
-print fasta_data
-

This isn’t entirely straightforward the first time you see it! On the bright side, for the special case where you would like a string containing a single record in a particular file format, use the the SeqRecord class’ format() method (see Section 4.5).

Note that although we don’t encourage it, you can use the format() method to write to a file, for example something like this: -

from Bio import SeqIO
+print(fasta_data)
+

This isn’t entirely straightforward the first time you see it! On the bright side, for the special case where you would like a string containing a single record in a particular file format, use the the SeqRecord class’ format() method (see Section 4.5).

Note that although we don’t encourage it, you can use the format() method to write to a file, for example something like this: +

from Bio import SeqIO
 out_handle = open("ls_orchid_long.tab", "w")
 for record in SeqIO.parse("ls_orchid.gbk", "genbank"):
     if len(record) > 100:
         out_handle.write(record.format("tab"))
 out_handle.close()
-

While this style of code will work for a simple sequential file format like FASTA or the simple tab separated format used here, it will not work for more complex or interlaced file formats. This is why we still recommend using Bio.SeqIO.write(), as in the following example: -

from Bio import SeqIO
+

While this style of code will work for a simple sequential file format like FASTA or the simple tab separated format used here, it will not work for more complex or interlaced file formats. This is why we still recommend using Bio.SeqIO.write(), as in the following example: +

from Bio import SeqIO
 records = (rec for rec in SeqIO.parse("ls_orchid.gbk", "genbank") if len(rec) > 100)
 SeqIO.write(records, "ls_orchid.tab", "tab")
-

Making a single call to SeqIO.write(...) is also much quicker than -multiple calls to the SeqRecord.format(...) method.

-

Chapter 6  Multiple Sequence Alignment objects

-

This chapter is about Multiple Sequence Alignments, by which we mean a collection of +

Making a single call to SeqIO.write(...) is also much quicker than +multiple calls to the SeqRecord.format(...) method.

+ +

Chapter 6  Multiple Sequence Alignment objects

+

This chapter is about Multiple Sequence Alignments, by which we mean a collection of multiple sequences which have been aligned together – usually with the insertion of gap characters, and addition of leading or trailing gaps – such that all the sequence strings are the same length. Such an alignment can be regarded as a matrix of letters, -where each row is held as a SeqRecord object internally.

We will introduce the MultipleSeqAlignment object which holds this kind of data, -and the Bio.AlignIO module for reading and writing them as various file formats -(following the design of the Bio.SeqIO module from the previous chapter). -Note that both Bio.SeqIO and Bio.AlignIO can read and write sequence +where each row is held as a SeqRecord object internally.

We will introduce the MultipleSeqAlignment object which holds this kind of data, +and the Bio.AlignIO module for reading and writing them as various file formats +(following the design of the Bio.SeqIO module from the previous chapter). +Note that both Bio.SeqIO and Bio.AlignIO can read and write sequence alignment files. The appropriate choice will depend largely on what you want to do -with the data.

The final part of this chapter is about our command line wrappers for common multiple -sequence alignment tools like ClustalW and MUSCLE.

-

6.1  Parsing or Reading Sequence Alignments

We have two functions for reading in sequence alignments, Bio.AlignIO.read() and Bio.AlignIO.parse() which following the convention introduced in Bio.SeqIO are for files containing one or multiple alignments respectively.

Using Bio.AlignIO.parse() will return an iterator which gives MultipleSeqAlignment objects. Iterators are typically used in a for loop. Examples of situations where you will have multiple different alignments include resampled alignments from the PHYLIP tool seqboot, or multiple pairwise alignments from the EMBOSS tools water or needle, or Bill Pearson’s FASTA tools.

However, in many situations you will be dealing with files which contain only a single alignment. In this case, you should use the Bio.AlignIO.read() function which returns a single MultipleSeqAlignment object.

Both functions expect two mandatory arguments:

  1. -The first argument is a handle to read the data from, typically an open file (see Section 22.1), or a filename. -
  2. The second argument is a lower case string specifying the alignment format. As in Bio.SeqIO we don’t try and guess the file format for you! See http://biopython.org/wiki/AlignIO for a full listing of supported formats. -

There is also an optional seq_count argument which is discussed in Section 6.1.3 below for dealing with ambiguous file formats which may contain more than one alignment.

A further optional alphabet argument allowing you to specify the expected alphabet. This can be useful as many alignment file formats do not explicitly label the sequences as RNA, DNA or protein – which means Bio.AlignIO will default to using a generic alphabet.

-

6.1.1  Single Alignments

-As an example, consider the following annotation rich protein alignment in the PFAM or Stockholm file format:

# STOCKHOLM 1.0
+with the data.

The final part of this chapter is about our command line wrappers for common multiple +sequence alignment tools like ClustalW and MUSCLE.

+ +

6.1  Parsing or Reading Sequence Alignments

We have two functions for reading in sequence alignments, Bio.AlignIO.read() and Bio.AlignIO.parse() which following the convention introduced in Bio.SeqIO are for files containing one or multiple alignments respectively.

Using Bio.AlignIO.parse() will return an iterator which gives MultipleSeqAlignment objects. Iterators are typically used in a for loop. Examples of situations where you will have multiple different alignments include resampled alignments from the PHYLIP tool seqboot, or multiple pairwise alignments from the EMBOSS tools water or needle, or Bill Pearson’s FASTA tools.

However, in many situations you will be dealing with files which contain only a single alignment. In this case, you should use the Bio.AlignIO.read() function which returns a single MultipleSeqAlignment object.

Both functions expect two mandatory arguments:

  1. +The first argument is a handle to read the data from, typically an open file (see Section 22.1), or a filename. +
  2. The second argument is a lower case string specifying the alignment format. As in Bio.SeqIO we don’t try and guess the file format for you! See http://biopython.org/wiki/AlignIO for a full listing of supported formats. +

There is also an optional seq_count argument which is discussed in Section 6.1.3 below for dealing with ambiguous file formats which may contain more than one alignment.

A further optional alphabet argument allowing you to specify the expected alphabet. This can be useful as many alignment file formats do not explicitly label the sequences as RNA, DNA or protein – which means Bio.AlignIO will default to using a generic alphabet.

+ +

6.1.1  Single Alignments

+As an example, consider the following annotation rich protein alignment in the PFAM or Stockholm file format:

# STOCKHOLM 1.0
 #=GS COATB_BPIKE/30-81  AC P03620.1
 #=GS COATB_BPIKE/30-81  DR PDB; 1ifl ; 1-52;
 #=GS Q9T0Q8_BPIKE/1-52  AC Q9T0Q8.1
@@ -2450,9 +2539,9 @@
 #=GC SS_cons                  XHHHHHHHHHHHHHHHCHHHHHHHHCHHHHHHHHHHHHHHHHHHHHHHHC--
 #=GC seq_cons                 AEssss...AptAhDSLpspAT-hIu.sWshVsslVsAsluIKLFKKFsSKA
 //
-

This is the seed alignment for the Phage_Coat_Gp8 (PF05371) PFAM entry, downloaded from a now out of date release of PFAM from http://pfam.sanger.ac.uk/. We can load this file as follows (assuming it has been saved to disk as “PF05371_seed.sth” in the current working directory):

>>> from Bio import AlignIO
+

This is the seed alignment for the Phage_Coat_Gp8 (PF05371) PFAM entry, downloaded from a now out of date release of PFAM from http://pfam.sanger.ac.uk/. We can load this file as follows (assuming it has been saved to disk as “PF05371_seed.sth” in the current working directory):

>>> from Bio import AlignIO
 >>> alignment = AlignIO.read("PF05371_seed.sth", "stockholm")
-

This code will print out a summary of the alignment:

>>> print alignment
+

This code will print out a summary of the alignment:

>>> print(alignment)
 SingleLetterAlphabet() alignment with 7 rows and 52 columns
 AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRL...SKA COATB_BPIKE/30-81
 AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKL...SRA Q9T0Q8_BPIKE/1-52
@@ -2461,12 +2550,12 @@
 AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPZJ2/1-49
 AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA Q9T0Q9_BPFD/1-49
 FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKL...SRA COATB_BPIF1/22-73
-

You’ll notice in the above output the sequences have been truncated. We could instead write our own code to format this as we please by iterating over the rows as SeqRecord objects:

>>> from Bio import AlignIO
+

You’ll notice in the above output the sequences have been truncated. We could instead write our own code to format this as we please by iterating over the rows as SeqRecord objects:

>>> from Bio import AlignIO
 >>> alignment = AlignIO.read("PF05371_seed.sth", "stockholm")
->>> print "Alignment length %i" % alignment.get_alignment_length()
+>>> print("Alignment length %i" % alignment.get_alignment_length())
 Alignment length 52
 >>> for record in alignment:
-...     print "%s - %s" % (record.seq, record.id)
+...     print("%s - %s" % (record.seq, record.id))
 AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA - COATB_BPIKE/30-81
 AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA - Q9T0Q8_BPIKE/1-52
 DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA - COATB_BPI22/32-83
@@ -2474,16 +2563,16 @@
 AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA - COATB_BPZJ2/1-49
 AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA - Q9T0Q9_BPFD/1-49
 FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA - COATB_BPIF1/22-73
-

You could also use the alignment object’s format method to show it in a particular file format – see Section 6.2.2 for details.

Did you notice in the raw file above that several of the sequences include database cross-references to the PDB and the associated known secondary structure? Try this:

>>> for record in alignment:
+

You could also use the alignment object’s format method to show it in a particular file format – see Section 6.2.2 for details.

Did you notice in the raw file above that several of the sequences include database cross-references to the PDB and the associated known secondary structure? Try this:

>>> for record in alignment:
 ...     if record.dbxrefs:
-...         print record.id, record.dbxrefs
+...         print("%s %s" % (record.id, record.dbxrefs))
 COATB_BPIKE/30-81 ['PDB; 1ifl ; 1-52;']
 COATB_BPM13/24-72 ['PDB; 2cpb ; 1-49;', 'PDB; 2cps ; 1-49;']
 Q9T0Q9_BPFD/1-49 ['PDB; 1nh4 A; 1-49;']
 COATB_BPIF1/22-73 ['PDB; 1ifk ; 1-50;']
-

To have a look at all the sequence annotation, try this:

>>> for record in alignment:
-...     print record
-

Sanger provide a nice web interface at http://pfam.sanger.ac.uk/family?acc=PF05371 which will actually let you download this alignment in several other formats. This is what the file looks like in the FASTA file format:

>COATB_BPIKE/30-81
+

To have a look at all the sequence annotation, try this:

>>> for record in alignment:
+...     print(record)
+

Sanger provide a nice web interface at http://pfam.sanger.ac.uk/family?acc=PF05371 which will actually let you download this alignment in several other formats. This is what the file looks like in the FASTA file format:

>COATB_BPIKE/30-81
 AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA
 >Q9T0Q8_BPIKE/1-52
 AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA
@@ -2497,21 +2586,22 @@
 AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA
 >COATB_BPIF1/22-73
 FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA
-

Note the website should have an option about showing gaps as periods (dots) or dashes, we’ve shown dashes above. Assuming you download and save this as file “PF05371_seed.faa” then you can load it with almost exactly the same code:

from Bio import AlignIO
+

Note the website should have an option about showing gaps as periods (dots) or dashes, we’ve shown dashes above. Assuming you download and save this as file “PF05371_seed.faa” then you can load it with almost exactly the same code:

from Bio import AlignIO
 alignment = AlignIO.read("PF05371_seed.faa", "fasta")
-print alignment
-

All that has changed in this code is the filename and the format string. You’ll get the same output as before, the sequences and record identifiers are the same. -However, as you should expect, if you check each SeqRecord there is no annotation nor database cross-references because these are not included in the FASTA file format.

Note that rather than using the Sanger website, you could have used Bio.AlignIO to convert the original Stockholm format file into a FASTA file yourself (see below).

With any supported file format, you can load an alignment in exactly the same way just by changing the format string. For example, use “phylip” for PHYLIP files, “nexus” for NEXUS files or “emboss” for the alignments output by the EMBOSS tools. There is a full listing on the wiki page (http://biopython.org/wiki/AlignIO) and in the built in documentation (also online):

>>> from Bio import AlignIO
+print(alignment)
+

All that has changed in this code is the filename and the format string. You’ll get the same output as before, the sequences and record identifiers are the same. +However, as you should expect, if you check each SeqRecord there is no annotation nor database cross-references because these are not included in the FASTA file format.

Note that rather than using the Sanger website, you could have used Bio.AlignIO to convert the original Stockholm format file into a FASTA file yourself (see below).

With any supported file format, you can load an alignment in exactly the same way just by changing the format string. For example, use “phylip” for PHYLIP files, “nexus” for NEXUS files or “emboss” for the alignments output by the EMBOSS tools. There is a full listing on the wiki page (http://biopython.org/wiki/AlignIO) and in the built in documentation (also online):

>>> from Bio import AlignIO
 >>> help(AlignIO)
 ...
-
-

6.1.2  Multiple Alignments

The previous section focused on reading files containing a single alignment. In general however, files can contain more than one alignment, and to read these files we must use the Bio.AlignIO.parse() function.

Suppose you have a small alignment in PHYLIP format:

    5    6
+
+ +

6.1.2  Multiple Alignments

The previous section focused on reading files containing a single alignment. In general however, files can contain more than one alignment, and to read these files we must use the Bio.AlignIO.parse() function.

Suppose you have a small alignment in PHYLIP format:

    5    6
 Alpha     AACAAC
 Beta      AACCCC
 Gamma     ACCAAC
 Delta     CCACCA
 Epsilon   CCAAAC
-

If you wanted to bootstrap a phylogenetic tree using the PHYLIP tools, one of the steps would be to create a set of many resampled alignments using the tool bootseq. This would give output something like this, which has been abbreviated for conciseness:

    5     6
+

If you wanted to bootstrap a phylogenetic tree using the PHYLIP tools, one of the steps would be to create a set of many resampled alignments using the tool bootseq. This would give output something like this, which has been abbreviated for conciseness:

    5     6
 Alpha     AAACCA
 Beta      AAACCC
 Gamma     ACCCCA
@@ -2536,12 +2626,12 @@
 Gamma     AAAACC
 Delta     CCCCAA
 Epsilon   CAAACC
-

If you wanted to read this in using Bio.AlignIO you could use:

from Bio import AlignIO
+

If you wanted to read this in using Bio.AlignIO you could use:

from Bio import AlignIO
 alignments = AlignIO.parse("resampled.phy", "phylip")
 for alignment in alignments:
-    print alignment
-    print
-

This would give the following output, again abbreviated for display:

SingleLetterAlphabet() alignment with 5 rows and 6 columns
+    print(alignment)
+    print("")
+

This would give the following output, again abbreviated for display:

SingleLetterAlphabet() alignment with 5 rows and 6 columns
 AAACCA Alpha
 AAACCC Beta
 ACCCCA Gamma
@@ -2570,15 +2660,16 @@
 AAAACC Gamma
 CCCCAA Delta
 CAAACC Epsilon
-

As with the function Bio.SeqIO.parse(), using Bio.AlignIO.parse() returns an iterator. -If you want to keep all the alignments in memory at once, which will allow you to access them in any order, then turn the iterator into a list:

from Bio import AlignIO
+

As with the function Bio.SeqIO.parse(), using Bio.AlignIO.parse() returns an iterator. +If you want to keep all the alignments in memory at once, which will allow you to access them in any order, then turn the iterator into a list:

from Bio import AlignIO
 alignments = list(AlignIO.parse("resampled.phy", "phylip"))
 last_align = alignments[-1]
 first_align = alignments[0]
-
-

6.1.3  Ambiguous Alignments

- -Many alignment file formats can explicitly store more than one alignment, and the division between each alignment is clear. However, when a general sequence file format has been used there is no such block structure. The most common such situation is when alignments have been saved in the FASTA file format. For example consider the following:

>Alpha
+
+ +

6.1.3  Ambiguous Alignments

+ +Many alignment file formats can explicitly store more than one alignment, and the division between each alignment is clear. However, when a general sequence file format has been used there is no such block structure. The most common such situation is when alignments have been saved in the FASTA file format. For example consider the following:

>Alpha
 ACTACGACTAGCTCAG--G
 >Beta
 ACTACCGCTAGCTCAGAAG
@@ -2590,7 +2681,7 @@
 ACTACCGCTAGCTCAGAAG
 >Gamma
 ACTACGGCTAGCACAGAAG
-

This could be a single alignment containing six sequences (with repeated identifiers). Or, judging from the identifiers, this is probably two different alignments each with three sequences, which happen to all have the same length.

What about this next example?

>Alpha
+

This could be a single alignment containing six sequences (with repeated identifiers). Or, judging from the identifiers, this is probably two different alignments each with three sequences, which happen to all have the same length.

What about this next example?

>Alpha
 ACTACGACTAGCTCAG--G
 >Beta
 ACTACCGCTAGCTCAGAAG
@@ -2602,7 +2693,7 @@
 ACTACGACTAGCTCAGG--
 >Delta
 ACTACGGCTAGCACAGAAG
-

Again, this could be a single alignment with six sequences. However this time based on the identifiers we might guess this is three pairwise alignments which by chance have all got the same lengths.

This final example is similar:

>Alpha
+

Again, this could be a single alignment with six sequences. However this time based on the identifiers we might guess this is three pairwise alignments which by chance have all got the same lengths.

This final example is similar:

>Alpha
 ACTACGACTAGCTCAG--G
 >XXX
 ACTACCGCTAGCTCAGAAG
@@ -2614,14 +2705,14 @@
 --ACTACGAC--TAGCTCAGG
 >ZZZ
 GGACTACGACAATAGCTCAGG
-

In this third example, because of the differing lengths, this cannot be treated as a single alignment containing all six records. However, it could be three pairwise alignments.

Clearly trying to store more than one alignment in a FASTA file is not ideal. However, if you are forced to deal with these as input files Bio.AlignIO can cope with the most common situation where all the alignments have the same number of records. -One example of this is a collection of pairwise alignments, which can be produced by the EMBOSS tools needle and water – although in this situation, Bio.AlignIO should be able to understand their native output using “emboss” as the format string.

To interpret these FASTA examples as several separate alignments, we can use Bio.AlignIO.parse() with the optional seq_count argument which specifies how many sequences are expected in each alignment (in these examples, 3, 2 and 2 respectively). -For example, using the third example as the input data:

for alignment in AlignIO.parse(handle, "fasta", seq_count=2):
-    print "Alignment length %i" % alignment.get_alignment_length()
+

In this third example, because of the differing lengths, this cannot be treated as a single alignment containing all six records. However, it could be three pairwise alignments.

Clearly trying to store more than one alignment in a FASTA file is not ideal. However, if you are forced to deal with these as input files Bio.AlignIO can cope with the most common situation where all the alignments have the same number of records. +One example of this is a collection of pairwise alignments, which can be produced by the EMBOSS tools needle and water – although in this situation, Bio.AlignIO should be able to understand their native output using “emboss” as the format string.

To interpret these FASTA examples as several separate alignments, we can use Bio.AlignIO.parse() with the optional seq_count argument which specifies how many sequences are expected in each alignment (in these examples, 3, 2 and 2 respectively). +For example, using the third example as the input data:

for alignment in AlignIO.parse(handle, "fasta", seq_count=2):
+    print("Alignment length %i" % alignment.get_alignment_length())
     for record in alignment:
-        print "%s - %s" % (record.seq, record.id)
-    print
-

giving:

Alignment length 19
+        print("%s - %s" % (record.seq, record.id))
+    print("")
+

giving:

Alignment length 19
 ACTACGACTAGCTCAG--G - Alpha
 ACTACCGCTAGCTCAGAAG - XXX
 
@@ -2632,9 +2723,10 @@
 Alignment length 21
 --ACTACGAC--TAGCTCAGG - Alpha
 GGACTACGACAATAGCTCAGG - ZZZ
-

Using Bio.AlignIO.read() or Bio.AlignIO.parse() without the seq_count argument would give a single alignment containing all six records for the first two examples. For the third example, an exception would be raised because the lengths differ preventing them being turned into a single alignment.

If the file format itself has a block structure allowing Bio.AlignIO to determine the number of sequences in each alignment directly, then the seq_count argument is not needed. If it is supplied, and doesn’t agree with the file contents, an error is raised.

Note that this optional seq_count argument assumes each alignment in the file has the same number of sequences. Hypothetically you may come across stranger situations, for example a FASTA file containing several alignments each with a different number of sequences – although I would love to hear of a real world example of this. Assuming you cannot get the data in a nicer file format, there is no straight forward way to deal with this using Bio.AlignIO. In this case, you could consider reading in the sequences themselves using Bio.SeqIO and batching them together to create the alignments as appropriate.

-

6.2  Writing Alignments

We’ve talked about using Bio.AlignIO.read() and Bio.AlignIO.parse() for alignment input (reading files), and now we’ll look at Bio.AlignIO.write() which is for alignment output (writing files). This is a function taking three arguments: some MultipleSeqAlignment objects (or for backwards compatibility the obsolete Alignment objects), a handle or filename to write to, and a sequence format.

Here is an example, where we start by creating a few MultipleSeqAlignment objects the hard way (by hand, rather than by loading them from a file). -Note we create some SeqRecord objects to construct the alignment from.

from Bio.Alphabet import generic_dna
+

Using Bio.AlignIO.read() or Bio.AlignIO.parse() without the seq_count argument would give a single alignment containing all six records for the first two examples. For the third example, an exception would be raised because the lengths differ preventing them being turned into a single alignment.

If the file format itself has a block structure allowing Bio.AlignIO to determine the number of sequences in each alignment directly, then the seq_count argument is not needed. If it is supplied, and doesn’t agree with the file contents, an error is raised.

Note that this optional seq_count argument assumes each alignment in the file has the same number of sequences. Hypothetically you may come across stranger situations, for example a FASTA file containing several alignments each with a different number of sequences – although I would love to hear of a real world example of this. Assuming you cannot get the data in a nicer file format, there is no straight forward way to deal with this using Bio.AlignIO. In this case, you could consider reading in the sequences themselves using Bio.SeqIO and batching them together to create the alignments as appropriate.

+ +

6.2  Writing Alignments

We’ve talked about using Bio.AlignIO.read() and Bio.AlignIO.parse() for alignment input (reading files), and now we’ll look at Bio.AlignIO.write() which is for alignment output (writing files). This is a function taking three arguments: some MultipleSeqAlignment objects (or for backwards compatibility the obsolete Alignment objects), a handle or filename to write to, and a sequence format.

Here is an example, where we start by creating a few MultipleSeqAlignment objects the hard way (by hand, rather than by loading them from a file). +Note we create some SeqRecord objects to construct the alignment from.

from Bio.Alphabet import generic_dna
 from Bio.Seq import Seq
 from Bio.SeqRecord import SeqRecord
 from Bio.Align import MultipleSeqAlignment
@@ -2658,9 +2750,9 @@
          ])
 
 my_alignments = [align1, align2, align3]
-

Now we have a list of Alignment objects, we’ll write them to a PHYLIP format file:

from Bio import AlignIO
+

Now we have a list of Alignment objects, we’ll write them to a PHYLIP format file:

from Bio import AlignIO
 AlignIO.write(my_alignments, "my_example.phy", "phylip")
-

And if you open this file in your favourite text editor it should look like this:

 3 12
+

And if you open this file in your favourite text editor it should look like this:

 3 12
 Alpha      ACTGCTAGCT AG
 Beta       ACT-CTAGCT AG
 Gamma      ACTGCTAGDT AG
@@ -2672,23 +2764,24 @@
 Eta        ACTAGTACAG CTG
 Theta      ACTAGTACAG CT-
 Iota       -CTACTACAG GTG
-

Its more common to want to load an existing alignment, and save that, perhaps after some simple manipulation like removing certain rows or columns.

Suppose you wanted to know how many alignments the Bio.AlignIO.write() function wrote to the handle? If your alignments were in a list like the example above, you could just use len(my_alignments), however you can’t do that when your records come from a generator/iterator. Therefore the Bio.AlignIO.write() function returns the number of alignments written to the file.

Note - If you tell the Bio.AlignIO.write() function to write to a file that already exists, the old file will be overwritten without any warning.

-

6.2.1  Converting between sequence alignment file formats

-

Converting between sequence alignment file formats with Bio.AlignIO works -in the same way as converting between sequence file formats with Bio.SeqIO -(Section 5.5.2). We load generally the alignment(s) using -Bio.AlignIO.parse() and then save them using the Bio.AlignIO.write() -– or just use the Bio.AlignIO.convert() helper function.

For this example, we’ll load the PFAM/Stockholm format file used earlier and save it as a Clustal W format file:

from Bio import AlignIO
+

Its more common to want to load an existing alignment, and save that, perhaps after some simple manipulation like removing certain rows or columns.

Suppose you wanted to know how many alignments the Bio.AlignIO.write() function wrote to the handle? If your alignments were in a list like the example above, you could just use len(my_alignments), however you can’t do that when your records come from a generator/iterator. Therefore the Bio.AlignIO.write() function returns the number of alignments written to the file.

Note - If you tell the Bio.AlignIO.write() function to write to a file that already exists, the old file will be overwritten without any warning.

+ +

6.2.1  Converting between sequence alignment file formats

+

Converting between sequence alignment file formats with Bio.AlignIO works +in the same way as converting between sequence file formats with Bio.SeqIO +(Section 5.5.2). We load generally the alignment(s) using +Bio.AlignIO.parse() and then save them using the Bio.AlignIO.write() +– or just use the Bio.AlignIO.convert() helper function.

For this example, we’ll load the PFAM/Stockholm format file used earlier and save it as a Clustal W format file:

from Bio import AlignIO
 count = AlignIO.convert("PF05371_seed.sth", "stockholm", "PF05371_seed.aln", "clustal")
-print "Converted %i alignments" % count
-

Or, using Bio.AlignIO.parse() and Bio.AlignIO.write():

from Bio import AlignIO
+print("Converted %i alignments" % count)
+

Or, using Bio.AlignIO.parse() and Bio.AlignIO.write():

from Bio import AlignIO
 alignments = AlignIO.parse("PF05371_seed.sth", "stockholm")
 count = AlignIO.write(alignments, "PF05371_seed.aln", "clustal")
-print "Converted %i alignments" % count
-

The Bio.AlignIO.write() function expects to be given multiple alignment objects. In the example above we gave it the alignment iterator returned by Bio.AlignIO.parse().

In this case, we know there is only one alignment in the file so we could have used Bio.AlignIO.read() instead, but notice we have to pass this alignment to Bio.AlignIO.write() as a single element list:

from Bio import AlignIO
+print("Converted %i alignments" % count)
+

The Bio.AlignIO.write() function expects to be given multiple alignment objects. In the example above we gave it the alignment iterator returned by Bio.AlignIO.parse().

In this case, we know there is only one alignment in the file so we could have used Bio.AlignIO.read() instead, but notice we have to pass this alignment to Bio.AlignIO.write() as a single element list:

from Bio import AlignIO
 alignment = AlignIO.read("PF05371_seed.sth", "stockholm")
 AlignIO.write([alignment], "PF05371_seed.aln", "clustal")
-

Either way, you should end up with the same new Clustal W format file “PF05371_seed.aln” with the following content:

CLUSTAL X (1.81) multiple sequence alignment
+

Either way, you should end up with the same new Clustal W format file “PF05371_seed.aln” with the following content:

CLUSTAL X (1.81) multiple sequence alignment
 
 
 COATB_BPIKE/30-81                   AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSS
@@ -2706,9 +2799,9 @@
 COATB_BPZJ2/1-49                    KA
 Q9T0Q9_BPFD/1-49                    KA
 COATB_BPIF1/22-73                   RA
-

Alternatively, you could make a PHYLIP format file which we’ll name “PF05371_seed.phy”:

from Bio import AlignIO
+

Alternatively, you could make a PHYLIP format file which we’ll name “PF05371_seed.phy”:

from Bio import AlignIO
 AlignIO.convert("PF05371_seed.sth", "stockholm", "PF05371_seed.phy", "phylip")
-

This time the output looks like this:

 7 52
+

This time the output looks like this:

 7 52
 COATB_BPIK AEPNAATNYA TEAMDSLKTQ AIDLISQTWP VVTTVVVAGL VIRLFKKFSS
 Q9T0Q8_BPI AEPNAATNYA TEAMDSLKTQ AIDLISQTWP VVTTVVVAGL VIKLFKKFVS
 COATB_BPI2 DGTSTATSYA TEAMNSLKTQ ATDLIDQTWP VVTSVAVAGL AIRLFKKFSS
@@ -2724,19 +2817,19 @@
            KA
            KA
            RA
-

One of the big handicaps of the PHYLIP alignment file format is that the sequence identifiers are strictly truncated at ten characters. In this example, as you can see the resulting names are still unique - but they are not very readable. In this particular case, there is no clear way to compress the identifiers, but for the sake of argument you may want to assign your own names or numbering system. This following bit of code manipulates the record identifiers before saving the output:

from Bio import AlignIO
+

One of the big handicaps of the PHYLIP alignment file format is that the sequence identifiers are strictly truncated at ten characters. In this example, as you can see the resulting names are still unique - but they are not very readable. In this particular case, there is no clear way to compress the identifiers, but for the sake of argument you may want to assign your own names or numbering system. This following bit of code manipulates the record identifiers before saving the output:

from Bio import AlignIO
 alignment = AlignIO.read("PF05371_seed.sth", "stockholm")
 name_mapping = {}
 for i, record in enumerate(alignment):
     name_mapping[i] = record.id
     record.id = "seq%i" % i
-print name_mapping
+print(name_mapping)
 
 AlignIO.write([alignment], "PF05371_seed.phy", "phylip")
-

This code used a Python dictionary to record a simple mapping from the new sequence system to the original identifier: -

{0: 'COATB_BPIKE/30-81', 1: 'Q9T0Q8_BPIKE/1-52', 2: 'COATB_BPI22/32-83', ...}
-

Here is the new PHYLIP format output: -

 7 52
+

This code used a Python dictionary to record a simple mapping from the new sequence system to the original identifier: +

{0: 'COATB_BPIKE/30-81', 1: 'Q9T0Q8_BPIKE/1-52', 2: 'COATB_BPI22/32-83', ...}
+

Here is the new PHYLIP format output: +

 7 52
 seq0       AEPNAATNYA TEAMDSLKTQ AIDLISQTWP VVTTVVVAGL VIRLFKKFSS
 seq1       AEPNAATNYA TEAMDSLKTQ AIDLISQTWP VVTTVVVAGL VIKLFKKFVS
 seq2       DGTSTATSYA TEAMNSLKTQ ATDLIDQTWP VVTSVAVAGL AIRLFKKFSS
@@ -2752,17 +2845,18 @@
            KA
            KA
            RA
-

In general, because of the identifier limitation, working with PHYLIP file formats shouldn’t be your first choice. Using the PFAM/Stockholm format on the other hand allows you to record a lot of additional annotation too.

-

6.2.2  Getting your alignment objects as formatted strings

- -The Bio.AlignIO interface is based on handles, which means if you want to get your alignment(s) into a string in a particular file format you need to do a little bit more work (see below). -However, you will probably prefer to take advantage of the alignment object’s format() method. -This takes a single mandatory argument, a lower case string which is supported by Bio.AlignIO as an output format. For example:

from Bio import AlignIO
+

In general, because of the identifier limitation, working with PHYLIP file formats shouldn’t be your first choice. Using the PFAM/Stockholm format on the other hand allows you to record a lot of additional annotation too.

+ +

6.2.2  Getting your alignment objects as formatted strings

+ +The Bio.AlignIO interface is based on handles, which means if you want to get your alignment(s) into a string in a particular file format you need to do a little bit more work (see below). +However, you will probably prefer to take advantage of the alignment object’s format() method. +This takes a single mandatory argument, a lower case string which is supported by Bio.AlignIO as an output format. For example:

from Bio import AlignIO
 alignment = AlignIO.read("PF05371_seed.sth", "stockholm")
-print alignment.format("clustal")
-

As described in Section 4.5), the SeqRecord object has a similar method using output formats supported by Bio.SeqIO.

Internally the format() method is using the StringIO string based handle and calling -Bio.AlignIO.write(). You can do this in your own code if for example you are using an -older version of Biopython:

from Bio import AlignIO
+print(alignment.format("clustal"))
+

As described in Section 4.5), the SeqRecord object has a similar method using output formats supported by Bio.SeqIO.

Internally the format() method is using the StringIO string based handle and calling +Bio.AlignIO.write(). You can do this in your own code if for example you are using an +older version of Biopython:

from Bio import AlignIO
 from StringIO import StringIO
 
 alignments = AlignIO.parse("PF05371_seed.sth", "stockholm")
@@ -2771,21 +2865,23 @@
 AlignIO.write(alignments, out_handle, "clustal")
 clustal_data = out_handle.getvalue()
 
-print clustal_data
-
-

6.3  Manipulating Alignments

-

Now that we’ve covered loading and saving alignments, we’ll look at what else you can do -with them.

-

6.3.1  Slicing alignments

-First of all, in some senses the alignment objects act like a Python list of -SeqRecord objects (the rows). With this model in mind hopefully the actions -of len() (the number of rows) and iteration (each row as a SeqRecord) -make sense:

>>> from Bio import AlignIO
+print(clustal_data)
+
+ +

6.3  Manipulating Alignments

+

Now that we’ve covered loading and saving alignments, we’ll look at what else you can do +with them.

+ +

6.3.1  Slicing alignments

+First of all, in some senses the alignment objects act like a Python list of +SeqRecord objects (the rows). With this model in mind hopefully the actions +of len() (the number of rows) and iteration (each row as a SeqRecord) +make sense:

>>> from Bio import AlignIO
 >>> alignment = AlignIO.read("PF05371_seed.sth", "stockholm")
->>> print "Number of rows: %i" % len(alignment)
+>>> print("Number of rows: %i" % len(alignment))
 Number of rows: 7
 >>> for record in alignment:
-...     print "%s - %s" % (record.seq, record.id)
+...     print("%s - %s" % (record.seq, record.id))
 AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA - COATB_BPIKE/30-81
 AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA - Q9T0Q8_BPIKE/1-52
 DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA - COATB_BPI22/32-83
@@ -2793,10 +2889,10 @@
 AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA - COATB_BPZJ2/1-49
 AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA - Q9T0Q9_BPFD/1-49
 FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA - COATB_BPIF1/22-73
-

You can also use the list-like append and extend methods to add -more rows to the alignment (as SeqRecord objects). Keeping the list +

You can also use the list-like append and extend methods to add +more rows to the alignment (as SeqRecord objects). Keeping the list metaphor in mind, simple slicing of the alignment should also make sense - -it selects some of the rows giving back another alignment object:

>>> print alignment
+it selects some of the rows giving back another alignment object:

>>> print(alignment)
 SingleLetterAlphabet() alignment with 7 rows and 52 columns
 AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRL...SKA COATB_BPIKE/30-81
 AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKL...SRA Q9T0Q8_BPIKE/1-52
@@ -2805,26 +2901,26 @@
 AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPZJ2/1-49
 AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA Q9T0Q9_BPFD/1-49
 FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKL...SRA COATB_BPIF1/22-73
->>> print alignment[3:7]
+>>> print(alignment[3:7])
 SingleLetterAlphabet() alignment with 4 rows and 52 columns
 AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPM13/24-72
 AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPZJ2/1-49
 AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA Q9T0Q9_BPFD/1-49
 FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKL...SRA COATB_BPIF1/22-73
-

What if you wanted to select by column? Those of you who have used the NumPy -matrix or array objects won’t be surprised at this - you use a double index.

>>> print alignment[2,6]
+

What if you wanted to select by column? Those of you who have used the NumPy +matrix or array objects won’t be surprised at this - you use a double index.

>>> print(alignment[2, 6])
 T
-

Using two integer indices pulls out a single letter, short hand for this:

>>> print alignment[2].seq[6]
+

Using two integer indices pulls out a single letter, short hand for this:

>>> print(alignment[2].seq[6])
 T
-

You can pull out a single column as a string like this:

>>> print alignment[:,6]
+

You can pull out a single column as a string like this:

>>> print(alignment[:, 6])
 TTT---T
-

You can also select a range of columns. For example, to pick out those same -three rows we extracted earlier, but take just their first six columns:

>>> print alignment[3:6,:6]
+

You can also select a range of columns. For example, to pick out those same +three rows we extracted earlier, but take just their first six columns:

>>> print(alignment[3:6, :6])
 SingleLetterAlphabet() alignment with 3 rows and 6 columns
 AEGDDP COATB_BPM13/24-72
 AEGDDP COATB_BPZJ2/1-49
 AEGDDP Q9T0Q9_BPFD/1-49
-

Leaving the first index as : means take all the rows:

>>> print alignment[:,:6]
+

Leaving the first index as : means take all the rows:

>>> print(alignment[:, :6])
 SingleLetterAlphabet() alignment with 7 rows and 6 columns
 AEPNAA COATB_BPIKE/30-81
 AEPNAA Q9T0Q8_BPIKE/1-52
@@ -2833,8 +2929,8 @@
 AEGDDP COATB_BPZJ2/1-49
 AEGDDP Q9T0Q9_BPFD/1-49
 FAADDA COATB_BPIF1/22-73
-

This brings us to a neat way to remove a section. Notice columns -7, 8 and 9 which are gaps in three of the seven sequences:

>>> print alignment[:,6:9]
+

This brings us to a neat way to remove a section. Notice columns +7, 8 and 9 which are gaps in three of the seven sequences:

>>> print(alignment[:, 6:9])
 SingleLetterAlphabet() alignment with 7 rows and 3 columns
 TNY COATB_BPIKE/30-81
 TNY Q9T0Q8_BPIKE/1-52
@@ -2843,7 +2939,7 @@
 --- COATB_BPZJ2/1-49
 --- Q9T0Q9_BPFD/1-49
 TSQ COATB_BPIF1/22-73
-

Again, you can slice to get everything after the ninth column:

>>> print alignment[:,9:]
+

Again, you can slice to get everything after the ninth column:

>>> print(alignment[:, 9:])
 SingleLetterAlphabet() alignment with 7 rows and 43 columns
 ATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA COATB_BPIKE/30-81
 ATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA Q9T0Q8_BPIKE/1-52
@@ -2852,9 +2948,9 @@
 AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA COATB_BPZJ2/1-49
 AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA Q9T0Q9_BPFD/1-49
 AKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA COATB_BPIF1/22-73
-

Now, the interesting thing is that addition of alignment objects works -by column. This lets you do this as a way to remove a block of columns:

>>> edited = alignment[:,:6] + alignment[:,9:]
->>> print edited
+

Now, the interesting thing is that addition of alignment objects works +by column. This lets you do this as a way to remove a block of columns:

>>> edited = alignment[:, :6] + alignment[:, 9:]
+>>> print(edited)
 SingleLetterAlphabet() alignment with 7 rows and 49 columns
 AEPNAAATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA COATB_BPIKE/30-81
 AEPNAAATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA Q9T0Q8_BPIKE/1-52
@@ -2863,12 +2959,12 @@
 AEGDDPAKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA COATB_BPZJ2/1-49
 AEGDDPAKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA Q9T0Q9_BPFD/1-49
 FAADDAAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA COATB_BPIF1/22-73
-

Another common use of alignment addition would be to combine alignments for +

Another common use of alignment addition would be to combine alignments for several different genes into a meta-alignment. Watch out though - the identifiers -need to match up (see Section 4.7 for how adding -SeqRecord objects works). You may find it helpful to first sort the -alignment rows alphabetically by id:

>>> edited.sort()
->>> print edited
+need to match up (see Section 4.7 for how adding
+SeqRecord objects works). You may find it helpful to first sort the
+alignment rows alphabetically by id:

>>> edited.sort()
+>>> print(edited)
 SingleLetterAlphabet() alignment with 7 rows and 49 columns
 DGTSTAATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA COATB_BPI22/32-83
 FAADDAAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA COATB_BPIF1/22-73
@@ -2877,115 +2973,118 @@
 AEGDDPAKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA COATB_BPZJ2/1-49
 AEPNAAATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA Q9T0Q8_BPIKE/1-52
 AEGDDPAKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA Q9T0Q9_BPFD/1-49
-

Note that you can only add two alignments together if they -have the same number of rows.

-

6.3.2  Alignments as arrays

+

Note that you can only add two alignments together if they +have the same number of rows.

+ +

6.3.2  Alignments as arrays

Depending on what you are doing, it can be more useful to turn the alignment -object into an array of letters – and you can do this with NumPy:

>>> import numpy as np
+object into an array of letters – and you can do this with NumPy:

>>> import numpy as np
 >>> from Bio import AlignIO
 >>> alignment = AlignIO.read("PF05371_seed.sth", "stockholm")
 >>> align_array = np.array([list(rec) for rec in alignment], np.character)
 >>> align_array.shape
 (7, 52)
-

If you will be working heavily with the columns, you can tell NumPy to store -the array by column (as in Fortran) rather then its default of by row (as in C):

>>> align_array = np.array([list(rec) for rec in alignment], np.character, order="F")
-

Note that this leaves the original Biopython alignment object and the NumPy array -in memory as separate objects - editing one will not update the other!

-

6.4  Alignment Tools

-

There are lots of algorithms out there for aligning sequences, both pairwise alignments +

If you will be working heavily with the columns, you can tell NumPy to store +the array by column (as in Fortran) rather then its default of by row (as in C):

>>> align_array = np.array([list(rec) for rec in alignment], np.character, order="F")
+

Note that this leaves the original Biopython alignment object and the NumPy array +in memory as separate objects - editing one will not update the other!

+ +

6.4  Alignment Tools

+

There are lots of algorithms out there for aligning sequences, both pairwise alignments and multiple sequence alignments. These calculations are relatively slow, and you generally wouldn’t want to write such an algorithm in Python. Instead, you can use Biopython to invoke a command line tool on your behalf. Normally you would: -

  1. +

    1. Prepare an input file of your unaligned sequences, typically this will be a FASTA file -which you might create using Bio.SeqIO (see Chapter 5). -
    2. Call the command line tool to process this input file, typically via one of Biopython’s +which you might create using Bio.SeqIO (see Chapter 5). +
    3. Call the command line tool to process this input file, typically via one of Biopython’s command line wrappers (which we’ll discuss here). -
    4. Read the output from the tool, i.e. your aligned sequences, typically using -Bio.AlignIO (see earlier in this chapter). -

    All the command line wrappers we’re going to talk about in this chapter follow the same style. +

  2. Read the output from the tool, i.e. your aligned sequences, typically using +Bio.AlignIO (see earlier in this chapter). +

All the command line wrappers we’re going to talk about in this chapter follow the same style. You create a command line object specifying the options (e.g. the input filename and the output filename), then invoke this command line via a Python operating system call (e.g. -using the subprocess module).

Most of these wrappers are defined in the Bio.Align.Applications module:

>>> import Bio.Align.Applications
+using the subprocess module).

Most of these wrappers are defined in the Bio.Align.Applications module:

>>> import Bio.Align.Applications
 >>> dir(Bio.Align.Applications)
 ...
 ['ClustalwCommandline', 'DialignCommandline', 'MafftCommandline', 'MuscleCommandline',
 'PrankCommandline', 'ProbconsCommandline', 'TCoffeeCommandline' ...]
-

(Ignore the entries starting with an underscore – these have +

(Ignore the entries starting with an underscore – these have special meaning in Python.) -The module Bio.Emboss.Applications has wrappers for some of the -EMBOSS suite, including -needle and water, which are described below in -Section 6.4.5, and wrappers for the EMBOSS +The module Bio.Emboss.Applications has wrappers for some of the +EMBOSS suite, including +needle and water, which are described below in +Section 6.4.5, and wrappers for the EMBOSS packaged versions of the PHYLIP tools (which EMBOSS refer to as one of their EMBASSY packages - third party tools with an EMBOSS style interface). We won’t explore all these alignment tools here in the section, just a -sample, but the same principles apply.

-

6.4.1  ClustalW

- +sample, but the same principles apply.

+ +

6.4.1  ClustalW

+ ClustalW is a popular command line tool for multiple sequence alignment (there is also a graphical interface called ClustalX). Biopython’s -Bio.Align.Applications module has a wrapper for this alignment tool -(and several others).

Before trying to use ClustalW from within Python, you should first try running +Bio.Align.Applications module has a wrapper for this alignment tool +(and several others).

Before trying to use ClustalW from within Python, you should first try running the ClustalW tool yourself by hand at the command line, to familiarise yourself the other options. You’ll find the Biopython wrapper is very -faithful to the actual command line API:

>>> from Bio.Align.Applications import ClustalwCommandline
+faithful to the actual command line API:

>>> from Bio.Align.Applications import ClustalwCommandline
 >>> help(ClustalwCommandline)
 ...
-

For the most basic usage, all you need is to have a FASTA input file, such as -opuntia.fasta +

For the most basic usage, all you need is to have a FASTA input file, such as +opuntia.fasta (available online or in the Doc/examples subdirectory of the Biopython source code). This is a small FASTA file containing seven prickly-pear DNA sequences -(from the cactus family Opuntia).

By default ClustalW will generate an alignment and guide tree file with names -based on the input FASTA file, in this case opuntia.aln and -opuntia.dnd, but you can override this or make it explicit:

>>> from Bio.Align.Applications import ClustalwCommandline
+(from the cactus family Opuntia).

By default ClustalW will generate an alignment and guide tree file with names +based on the input FASTA file, in this case opuntia.aln and +opuntia.dnd, but you can override this or make it explicit:

>>> from Bio.Align.Applications import ClustalwCommandline
 >>> cline = ClustalwCommandline("clustalw2", infile="opuntia.fasta")
->>> print cline
+>>> print(cline)
 clustalw2 -infile=opuntia.fasta
-

Notice here we have given the executable name as clustalw2, +

Notice here we have given the executable name as clustalw2, indicating we have version two installed, which has a different filename to -version one (clustalw, the default). Fortunately both versions +version one (clustalw, the default). Fortunately both versions support the same set of arguments at the command line (and indeed, should be -functionally identical).

You may find that even though you have ClustalW installed, the above command +functionally identical).

You may find that even though you have ClustalW installed, the above command doesn’t work – you may get a message about “command not found” (especially on Windows). This indicated that the ClustalW executable is not on your PATH (an environment variable, a list of directories to be searched). You can either update your PATH setting to include the location of your copy of ClustalW tools (how you do this will depend on your OS), or simply type in -the full path of the tool. For example:

>>> import os
+the full path of the tool. For example:

>>> import os
 >>> from Bio.Align.Applications import ClustalwCommandline
 >>> clustalw_exe = r"C:\Program Files\new clustal\clustalw2.exe"
 >>> clustalw_cline = ClustalwCommandline(clustalw_exe, infile="opuntia.fasta")
-
>>> assert os.path.isfile(clustalw_exe), "Clustal W executable missing"
+
>>> assert os.path.isfile(clustalw_exe), "Clustal W executable missing"
 >>> stdout, stderr = clustalw_cline()
-

Remember, in Python strings \n and \t are by default +

Remember, in Python strings \n and \t are by default interpreted as a new line and a tab – which is why we’re put a letter “r” at the start for a raw string that isn’t translated in this way. -This is generally good practice when specifying a Windows style file name.

Internally this uses the -subprocess module which is now the recommended way to run another -program in Python. This replaces older options like the os.system() -and the os.popen* functions.

Now, at this point it helps to know about how command line tools “work”. +This is generally good practice when specifying a Windows style file name.

Internally this uses the +subprocess module which is now the recommended way to run another +program in Python. This replaces older options like the os.system() +and the os.popen* functions.

Now, at this point it helps to know about how command line tools “work”. When you run a tool at the command line, it will often print text output directly to screen. This text can be captured or redirected, via two “pipes”, called standard output (the normal results) and standard error (for error messages and debug messages). There is also standard input, which is any text fed into the tool. These names get shortened to stdin, stdout and stderr. When the tool finishes, it has a return -code (an integer), which by convention is zero for success.

When you run the command line tool like this via the Biopython wrapper, +code (an integer), which by convention is zero for success.

When you run the command line tool like this via the Biopython wrapper, it will wait for it to finish, and check the return code. If this is non zero (indicating an error), an exception is raised. The wrapper -then returns two strings, stdout and stderr.

In the case of ClustalW, when run at the command line all the important +then returns two strings, stdout and stderr.

In the case of ClustalW, when run at the command line all the important output is written directly to the output files. Everything normally printed to screen while you wait (via stdout or stderr) is boring and can be -ignored (assuming it worked).

What we care about are the two output files, the alignment and the guide +ignored (assuming it worked).

What we care about are the two output files, the alignment and the guide tree. We didn’t tell ClustalW what filenames to use, but it defaults to picking names based on the input file. In this case the output should be -in the file opuntia.aln. +in the file opuntia.aln. You should be able to work out how to read in the alignment using -Bio.AlignIO by now:

>>> from Bio import AlignIO
+Bio.AlignIO by now:

>>> from Bio import AlignIO
 >>> align = AlignIO.read("opuntia.aln", "clustal")
->>> print align
+>>> print(align)
 SingleLetterAlphabet() alignment with 7 rows and 906 columns
 TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF191
 TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF191
@@ -2994,9 +3093,9 @@
 TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF191
 TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF191
 TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273291|gb|AF191665.1|AF191
-

In case you are interested (and this is an aside from the main thrust of this -chapter), the opuntia.dnd file ClustalW creates is just a standard -Newick tree file, and Bio.Phylo can parse these:

>>> from Bio import Phylo
+

In case you are interested (and this is an aside from the main thrust of this +chapter), the opuntia.dnd file ClustalW creates is just a standard +Newick tree file, and Bio.Phylo can parse these:

>>> from Bio import Phylo
 >>> tree = Phylo.read("opuntia.dnd", "newick")
 >>> Phylo.draw_ascii(tree)
                              _______________ gi|6273291|gb|AF191665.1|AF191665
@@ -3013,62 +3112,64 @@
  |___|
      | gi|6273284|gb|AF191658.1|AF191658
 
-

Chapter 13 covers Biopython’s support for phylogenetic trees in more -depth.

-

6.4.2  MUSCLE

+

Chapter 13 covers Biopython’s support for phylogenetic trees in more +depth.

+ +

6.4.2  MUSCLE

MUSCLE is a more recent multiple sequence alignment tool than ClustalW, and -Biopython also has a wrapper for it under the Bio.Align.Applications +Biopython also has a wrapper for it under the Bio.Align.Applications module. As before, we recommend you try using MUSCLE from the command line before trying it from within Python, as the Biopython wrapper is very faithful to the -actual command line API:

>>> from Bio.Align.Applications import MuscleCommandline
+actual command line API:

>>> from Bio.Align.Applications import MuscleCommandline
 >>> help(MuscleCommandline)
 ...
-

For the most basic usage, all you need is to have a FASTA input file, such as -opuntia.fasta +

For the most basic usage, all you need is to have a FASTA input file, such as +opuntia.fasta (available online or in the Doc/examples subdirectory of the Biopython source code). You can then tell MUSCLE to read in this FASTA file, and write the -alignment to an output file:

>>> from Bio.Align.Applications import MuscleCommandline
+alignment to an output file:

>>> from Bio.Align.Applications import MuscleCommandline
 >>> cline = MuscleCommandline(input="opuntia.fasta", out="opuntia.txt")
->>> print cline
+>>> print(cline)
 muscle -in opuntia.fasta -out opuntia.txt
-

Note that MUSCLE uses “-in” and “-out” but in Biopython we have to use +

Note that MUSCLE uses “-in” and “-out” but in Biopython we have to use “input” and “out” as the keyword arguments or property names. This is -because “in” is a reserved word in Python.

By default MUSCLE will output the alignment as a FASTA file (using gapped -sequences). The Bio.AlignIO module should be able to read this -alignment using format="fasta". -You can also ask for ClustalW-like output:

>>> from Bio.Align.Applications import MuscleCommandline
+because “in” is a reserved word in Python.

By default MUSCLE will output the alignment as a FASTA file (using gapped +sequences). The Bio.AlignIO module should be able to read this +alignment using format="fasta". +You can also ask for ClustalW-like output:

>>> from Bio.Align.Applications import MuscleCommandline
 >>> cline = MuscleCommandline(input="opuntia.fasta", out="opuntia.aln", clw=True)
->>> print cline
+>>> print(cline)
 muscle -in opuntia.fasta -out opuntia.aln -clw
-

Or, strict ClustalW output where the original ClustalW header line is -used for maximum compatibility:

>>> from Bio.Align.Applications import MuscleCommandline
+

Or, strict ClustalW output where the original ClustalW header line is +used for maximum compatibility:

>>> from Bio.Align.Applications import MuscleCommandline
 >>> cline = MuscleCommandline(input="opuntia.fasta", out="opuntia.aln", clwstrict=True)
->>> print cline
+>>> print(cline)
 muscle -in opuntia.fasta -out opuntia.aln -clwstrict
-

The Bio.AlignIO module should be able to read these alignments -using format="clustal".

MUSCLE can also output in GCG MSF format (using the msf argument), but +

The Bio.AlignIO module should be able to read these alignments +using format="clustal".

MUSCLE can also output in GCG MSF format (using the msf argument), but Biopython can’t currently parse that, or using HTML which would give a human -readable web page (not suitable for parsing).

You can also set the other optional parameters, for example the maximum number -of iterations. See the built in help for details.

You would then run MUSCLE command line string as described above for -ClustalW, and parse the output using Bio.AlignIO to get an -alignment object.

-

6.4.3  MUSCLE using stdout

Using a MUSCLE command line as in the examples above will write the alignment +readable web page (not suitable for parsing).

You can also set the other optional parameters, for example the maximum number +of iterations. See the built in help for details.

You would then run MUSCLE command line string as described above for +ClustalW, and parse the output using Bio.AlignIO to get an +alignment object.

+ +

6.4.3  MUSCLE using stdout

Using a MUSCLE command line as in the examples above will write the alignment to a file. This means there will be no important information written to the standard out (stdout) or standard error (stderr) handles. However, by default MUSCLE will write the alignment to standard output (stdout). We can take -advantage of this to avoid having a temporary output file! For example:

>>> from Bio.Align.Applications import MuscleCommandline
+advantage of this to avoid having a temporary output file! For example:

>>> from Bio.Align.Applications import MuscleCommandline
 >>> muscle_cline = MuscleCommandline(input="opuntia.fasta")
->>> print muscle_cline
+>>> print(muscle_cline)
 muscle -in opuntia.fasta
-

If we run this via the wrapper, we get back the output as a string. In order -to parse this we can use StringIO to turn it into a handle. -Remember that MUSCLE defaults to using FASTA as the output format:

>>> from Bio.Align.Applications import MuscleCommandline
+

If we run this via the wrapper, we get back the output as a string. In order +to parse this we can use StringIO to turn it into a handle. +Remember that MUSCLE defaults to using FASTA as the output format:

>>> from Bio.Align.Applications import MuscleCommandline
 >>> muscle_cline = MuscleCommandline(input="opuntia.fasta")
 >>> stdout, stderr = muscle_cline()
 >>> from StringIO import StringIO
 >>> from Bio import AlignIO
 >>> align = AlignIO.read(StringIO(stdout), "fasta")
->>> print align
+>>> print(align)
 SingleLetterAlphabet() alignment with 7 rows and 906 columns
 TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF191663
 TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273291|gb|AF191665.1|AF191665
@@ -3077,10 +3178,10 @@
 TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273286|gb|AF191660.1|AF191660
 TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF191659
 TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF191658
-

The above approach is fairly simple, but if you are dealing with very large output +

The above approach is fairly simple, but if you are dealing with very large output text the fact that all of stdout and stderr is loaded into memory as a string can -be a potential drawback. Using the subprocess module we can work directly -with handles instead:

>>> import subprocess
+be a potential drawback. Using the subprocess module we can work directly
+with handles instead:

>>> import subprocess
 >>> from Bio.Align.Applications import MuscleCommandline
 >>> muscle_cline = MuscleCommandline(input="opuntia.fasta")
 >>> child = subprocess.Popen(str(muscle_cline),
@@ -3089,7 +3190,7 @@
 ...                          shell=(sys.platform!="win32"))
 >>> from Bio import AlignIO
 >>> align = AlignIO.read(child.stdout, "fasta")
->>> print align
+>>> print(align)
 SingleLetterAlphabet() alignment with 7 rows and 906 columns
 TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF191663
 TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273291|gb|AF191665.1|AF191665
@@ -3098,37 +3199,38 @@
 TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273286|gb|AF191660.1|AF191660
 TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF191659
 TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF191658
-
-

6.4.4  MUSCLE using stdin and stdout

We don’t actually need to have our FASTA input sequences prepared in a file, +

+ +

6.4.4  MUSCLE using stdin and stdout

We don’t actually need to have our FASTA input sequences prepared in a file, because by default MUSCLE will read in the input sequence from standard input! Note this is a bit more advanced and fiddly, so don’t bother with this technique -unless you need to.

First, we’ll need some unaligned sequences in memory as SeqRecord objects. +unless you need to.

First, we’ll need some unaligned sequences in memory as SeqRecord objects. For this demonstration I’m going to use a filtered version of the original FASTA -file (using a generator expression), taking just six of the seven sequences:

>>> from Bio import SeqIO
+file (using a generator expression), taking just six of the seven sequences:

>>> from Bio import SeqIO
 >>> records = (r for r in SeqIO.parse("opuntia.fasta", "fasta") if len(r) < 900)
-

Then we create the MUSCLE command line, leaving the input and output to their +

Then we create the MUSCLE command line, leaving the input and output to their defaults (stdin and stdout). I’m also going to ask for strict ClustalW format -as for the output.

>>> from Bio.Align.Applications import MuscleCommandline
+as for the output.

>>> from Bio.Align.Applications import MuscleCommandline
 >>> muscle_cline = MuscleCommandline(clwstrict=True)
->>> print muscle_cline
+>>> print(muscle_cline)
 muscle -clwstrict
-

Now for the fiddly bits using the subprocess module, stdin and stdout:

>>> import subprocess
+

Now for the fiddly bits using the subprocess module, stdin and stdout:

>>> import subprocess
 >>> import sys
 >>> child = subprocess.Popen(str(cline),
 ...                          stdin=subprocess.PIPE,
 ...                          stdout=subprocess.PIPE,
 ...                          stderr=subprocess.PIPE,
 ...                          shell=(sys.platform!="win32"))                     
-

That should start MUSCLE, but it will be sitting waiting for its FASTA input -sequences, which we must supply via its stdin handle:

>>> SeqIO.write(records, child.stdin, "fasta")
+

That should start MUSCLE, but it will be sitting waiting for its FASTA input +sequences, which we must supply via its stdin handle:

>>> SeqIO.write(records, child.stdin, "fasta")
 6
 >>> child.stdin.close()
-

After writing the six sequences to the handle, MUSCLE will still be waiting +

After writing the six sequences to the handle, MUSCLE will still be waiting to see if that is all the FASTA sequences or not – so we must signal that this is all the input data by closing the handle. At that point MUSCLE should -start to run, and we can ask for the output:

>>> from Bio import AlignIO
+start to run, and we can ask for the output:

>>> from Bio import AlignIO
 >>> align = AlignIO.read(child.stdout, "clustal")
->>> print align
+>>> print(align)
 SingleLetterAlphabet() alignment with 6 rows and 900 columns
 TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF19166
 TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF19166
@@ -3136,7 +3238,7 @@
 TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273286|gb|AF191660.1|AF19166
 TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF19165
 TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF19165
-

Wow! There we are with a new alignment of just the six records, without having created +

Wow! There we are with a new alignment of just the six records, without having created a temporary FASTA input file, or a temporary alignment output file. However, a word of caution: Dealing with errors with this style of calling external programs is much more complicated. @@ -3145,21 +3247,21 @@ There can also be subtle cross platform issues (e.g. Windows versus Linux), and how you run your script can have an impact (e.g. at the command line, from IDLE or an IDE, or as a GUI script). These are all generic Python issues though, and not -specific to Biopython.

If you find working directly with subprocess like this scary, there is an -alternative. If you execute the tool with muscle_cline() you can supply -any standard input as a big string, muscle_cline(stdin=...). So, +specific to Biopython.

If you find working directly with subprocess like this scary, there is an +alternative. If you execute the tool with muscle_cline() you can supply +any standard input as a big string, muscle_cline(stdin=...). So, provided your data isn’t very big, you can prepare the FASTA input in memory as -a string using StringIO (see Section 22.1):

>>> from Bio import SeqIO
+a string using StringIO (see Section 22.1):

>>> from Bio import SeqIO
 >>> records = (r for r in SeqIO.parse("opuntia.fasta", "fasta") if len(r) < 900)
 >>> from StringIO import StringIO
 >>> handle = StringIO()
 >>> SeqIO.write(records, handle, "fasta")
 6
 >>> data = handle.getvalue()
-

You can then run the tool and parse the alignment as follows:

>>> stdout, stderr = muscle_cline(stdin=data)
+

You can then run the tool and parse the alignment as follows:

>>> stdout, stderr = muscle_cline(stdin=data)
 >>> from Bio import AlignIO
 >>> align = AlignIO.read(StringIO(stdout), "clustal")
->>> print align
+>>> print(align)
 SingleLetterAlphabet() alignment with 6 rows and 900 columns
 TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF19166
 TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF19166
@@ -3167,220 +3269,210 @@
 TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273286|gb|AF191660.1|AF19166
 TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF19165
 TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF19165
-

You might find this easier, but it does require more memory (RAM) for the strings -used for the input FASTA and output Clustal formatted data.

-

6.4.5  EMBOSS needle and water

- -The EMBOSS suite includes the water and -needle tools for Smith-Waterman algorithm local alignment, and Needleman-Wunsch +

You might find this easier, but it does require more memory (RAM) for the strings +used for the input FASTA and output Clustal formatted data.

+ +

6.4.5  EMBOSS needle and water

+ +The EMBOSS suite includes the water and +needle tools for Smith-Waterman algorithm local alignment, and Needleman-Wunsch global alignment. The tools share the same style interface, so switching between the two -is trivial – we’ll just use needle here.

Suppose you want to do a global pairwise alignment between two sequences, prepared in -FASTA format as follows:

>HBA_HUMAN
+is trivial – we’ll just use needle here.

Suppose you want to do a global pairwise alignment between two sequences, prepared in +FASTA format as follows:

>HBA_HUMAN
 MVLSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTYFPHFDLSHGSAQVKGHG
 KKVADALTNAVAHVDDMPNALSALSDLHAHKLRVDPVNFKLLSHCLLVTLAAHLPAEFTP
 AVHASLDKFLASVSTVLTSKYR
-

in a file alpha.fasta, and secondly in a file beta.fasta:

>HBB_HUMAN
+

in a file alpha.fasta, and secondly in a file beta.fasta:

>HBB_HUMAN
 MVHLTPEEKSAVTALWGKVNVDEVGGEALGRLLVVYPWTQRFFESFGDLSTPDAVMGNPK
 VKAHGKKVLGAFSDGLAHLDNLKGTFATLSELHCDKLHVDPENFRLLGNVLVCVLAHHFG
 KEFTPPVQAAYQKVVAGVANALAHKYH
-

Let’s start by creating a complete needle command line object in one go:

>>> from Bio.Emboss.Applications import NeedleCommandline
+

Let’s start by creating a complete needle command line object in one go:

>>> from Bio.Emboss.Applications import NeedleCommandline
 >>> needle_cline = NeedleCommandline(asequence="alpha.faa", bsequence="beta.faa",
 ...                                  gapopen=10, gapextend=0.5, outfile="needle.txt")
->>> print needle_cline
+>>> print(needle_cline)
 needle -outfile=needle.txt -asequence=alpha.faa -bsequence=beta.faa -gapopen=10 -gapextend=0.5
-

Why not try running this by hand at the command prompt? You should see it does a -pairwise comparison and records the output in the file needle.txt (in the -default EMBOSS alignment file format).

Even if you have EMBOSS installed, running this command may not work – you +

Why not try running this by hand at the command prompt? You should see it does a +pairwise comparison and records the output in the file needle.txt (in the +default EMBOSS alignment file format).

Even if you have EMBOSS installed, running this command may not work – you might get a message about “command not found” (especially on Windows). This probably means that the EMBOSS tools are not on your PATH environment variable. You can either update your PATH setting, or simply tell Biopython -the full path to the tool, for example:

>>> from Bio.Emboss.Applications import NeedleCommandline
+the full path to the tool, for example:

>>> from Bio.Emboss.Applications import NeedleCommandline
 >>> needle_cline = NeedleCommandline(r"C:\EMBOSS\needle.exe",
 ...                                  asequence="alpha.faa", bsequence="beta.faa",
 ...                                  gapopen=10, gapextend=0.5, outfile="needle.txt")
-

Remember in Python that for a default string \n or \t means a -new line or a tab – which is why we’re put a letter “r” at the start for a raw string.

At this point it might help to try running the EMBOSS tools yourself by hand at the +

Remember in Python that for a default string \n or \t means a +new line or a tab – which is why we’re put a letter “r” at the start for a raw string.

At this point it might help to try running the EMBOSS tools yourself by hand at the command line, to familiarise yourself the other options and compare them to the -Biopython help text:

>>> from Bio.Emboss.Applications import NeedleCommandline
+Biopython help text:

>>> from Bio.Emboss.Applications import NeedleCommandline
 >>> help(NeedleCommandline)
 ...
-

Note that you can also specify (or change or look at) the settings like this:

>>> from Bio.Emboss.Applications import NeedleCommandline
+

Note that you can also specify (or change or look at) the settings like this:

>>> from Bio.Emboss.Applications import NeedleCommandline
 >>> needle_cline = NeedleCommandline()
 >>> needle_cline.asequence="alpha.faa"
 >>> needle_cline.bsequence="beta.faa"
 >>> needle_cline.gapopen=10
 >>> needle_cline.gapextend=0.5
 >>> needle_cline.outfile="needle.txt"
->>> print needle_cline
+>>> print(needle_cline)
 needle -outfile=needle.txt -asequence=alpha.faa -bsequence=beta.faa -gapopen=10 -gapextend=0.5
->>> print needle_cline.outfile
+>>> print(needle_cline.outfile)
 needle.txt
-

Next we want to use Python to run this command for us. As explained above, -for full control, we recommend you use the built in Python subprocess -module, but for simple usage the wrapper object usually suffices:

>>> stdout, stderr = needle_cline()
->>> print stdout + stderr
+

Next we want to use Python to run this command for us. As explained above, +for full control, we recommend you use the built in Python subprocess +module, but for simple usage the wrapper object usually suffices:

>>> stdout, stderr = needle_cline()
+>>> print(stdout + stderr)
 Needleman-Wunsch global alignment of two sequences
-

Next we can load the output file with Bio.AlignIO as -discussed earlier in this chapter, as the emboss format:

>>> from Bio import AlignIO
+

Next we can load the output file with Bio.AlignIO as +discussed earlier in this chapter, as the emboss format:

>>> from Bio import AlignIO
 >>> align = AlignIO.read("needle.txt", "emboss")
->>> print align
+>>> print(align)
 SingleLetterAlphabet() alignment with 2 rows and 149 columns
 MV-LSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTY...KYR HBA_HUMAN
 MVHLTPEEKSAVTALWGKV--NVDEVGGEALGRLLVVYPWTQRF...KYH HBB_HUMAN
-

In this example, we told EMBOSS to write the output to a file, but you -can tell it to write the output to stdout instead (useful if you +

In this example, we told EMBOSS to write the output to a file, but you +can tell it to write the output to stdout instead (useful if you don’t want a temporary output file to get rid of – use -stdout=True rather than the outfile argument), and -also to read one of the one of the inputs from stdin (e.g. -asequence="stdin", much like in the MUSCLE example in the -section above).

This has only scratched the surface of what you can do with needle -and water. One useful trick is that the second file can contain +stdout=True rather than the outfile argument), and +also to read one of the one of the inputs from stdin (e.g. +asequence="stdin", much like in the MUSCLE example in the +section above).

This has only scratched the surface of what you can do with needle +and water. One useful trick is that the second file can contain multiple sequences (say five), and then EMBOSS will do five pairwise -alignments.

Note - Biopython includes its own pairwise alignment code in the Bio.pairwise2 +alignments.

Note - Biopython includes its own pairwise alignment code in the Bio.pairwise2 module (written in C for speed, but with a pure Python fallback available too). This doesn’t work with alignment objects, so we have not covered it within this chapter. -See the module’s docstring (built in help) for details.

-

Chapter 7  BLAST

- -Hey, everybody loves BLAST right? I mean, geez, how can get it get any easier to do comparisons between one of your sequences and every other sequence in the known world? But, of course, this section isn’t about how cool BLAST is, since we already know that. It is about the problem with BLAST – it can be really difficult to deal with the volume of data generated by large runs, and to automate BLAST runs in general.

Fortunately, the Biopython folks know this only too well, so they’ve developed lots of tools for dealing with BLAST and making things much easier. This section details how to use these tools and do useful things with them.

Dealing with BLAST can be split up into two steps, both of which can be done from within Biopython. +See the module’s docstring (built in help) for details.

+ +

Chapter 7  BLAST

+ +Hey, everybody loves BLAST right? I mean, geez, how can get it get any easier to do comparisons between one of your sequences and every other sequence in the known world? But, of course, this section isn’t about how cool BLAST is, since we already know that. It is about the problem with BLAST – it can be really difficult to deal with the volume of data generated by large runs, and to automate BLAST runs in general.

Fortunately, the Biopython folks know this only too well, so they’ve developed lots of tools for dealing with BLAST and making things much easier. This section details how to use these tools and do useful things with them.

Dealing with BLAST can be split up into two steps, both of which can be done from within Biopython. Firstly, running BLAST for your query sequence(s), and getting some output. -Secondly, parsing the BLAST output in Python for further analysis.

Your first introduction to running BLAST was probably via the NCBI web-service. +Secondly, parsing the BLAST output in Python for further analysis.

Your first introduction to running BLAST was probably via the NCBI web-service. In fact, there are lots of ways you can run BLAST, which can be categorised several ways. The most important distinction is running BLAST locally (on your own machine), and running BLAST remotely (on another machine, typically the NCBI servers). We’re going to start this chapter by invoking the NCBI online BLAST service -from within a Python script.

NOTE: The following Chapter 8 describes -Bio.SearchIO, an experimental module in Biopython. We -intend this to ultimately replace the older Bio.Blast module, as it +from within a Python script.

NOTE: The following Chapter 8 describes +Bio.SearchIO, an experimental module in Biopython. We +intend this to ultimately replace the older Bio.Blast module, as it provides a more general framework handling other related sequence searching tools as well. However, until that is declared stable, for -production code please continue to use the Bio.Blast module -for dealing with NCBI BLAST.

-

7.1  Running BLAST over the Internet

-

We use the function qblast() in the Bio.Blast.NCBIWWW module +production code please continue to use the Bio.Blast module +for dealing with NCBI BLAST.

+ +

7.1  Running BLAST over the Internet

+

We use the function qblast() in the Bio.Blast.NCBIWWW module call the online version of BLAST. This has three non-optional arguments: -

The qblast function also take a number of other option arguments which are basically analogous to the different parameters you can set -on the BLAST web page. We’ll just highlight a few of them here:

  • -The qblast function can return the BLAST results in various -formats, which you can choose with the optional format_type keyword: -"HTML", "Text", "ASN.1", or "XML". -The default is "XML", as that is the format expected by the parser, -described in section 7.3 below. -
  • The argument expect sets the expectation or e-value threshold. -

For more about the optional BLAST arguments, we refer you to the NCBI’s own -documentation, or that built into Biopython:

>>> from Bio.Blast import NCBIWWW
+on the BLAST web page. We’ll just highlight a few of them here:

  • +The qblast function can return the BLAST results in various +formats, which you can choose with the optional format_type keyword: +"HTML", "Text", "ASN.1", or "XML". +The default is "XML", as that is the format expected by the parser, +described in section 7.3 below. +
  • The argument expect sets the expectation or e-value threshold. +

For more about the optional BLAST arguments, we refer you to the NCBI’s own +documentation, or that built into Biopython:

>>> from Bio.Blast import NCBIWWW
 >>> help(NCBIWWW.qblast)
 ...
-

Note that the default settings on the NCBI BLAST website are not quite +

Note that the default settings on the NCBI BLAST website are not quite the same as the defaults on QBLAST. If you get different results, you’ll need to check the parameters (e.g. the expectation value threshold and -the gap values).

For example, if you have a nucleotide sequence you want to search against +the gap values).

For example, if you have a nucleotide sequence you want to search against the nucleotide database (nt) using BLASTN, and you know the GI number of your -query sequence, you can use:

>>> from Bio.Blast import NCBIWWW
+query sequence, you can use:

>>> from Bio.Blast import NCBIWWW
 >>> result_handle = NCBIWWW.qblast("blastn", "nt", "8332116")
-

Alternatively, if we have our query sequence already in a FASTA formatted +

Alternatively, if we have our query sequence already in a FASTA formatted file, we just need to open the file and read in this record as a string, -and use that as the query argument:

>>> from Bio.Blast import NCBIWWW
+and use that as the query argument:

>>> from Bio.Blast import NCBIWWW
 >>> fasta_string = open("m_cold.fasta").read()
 >>> result_handle = NCBIWWW.qblast("blastn", "nt", fasta_string)
-

We could also have read in the FASTA file as a SeqRecord and then -supplied just the sequence itself:

>>> from Bio.Blast import NCBIWWW
+

We could also have read in the FASTA file as a SeqRecord and then +supplied just the sequence itself:

>>> from Bio.Blast import NCBIWWW
 >>> from Bio import SeqIO
 >>> record = SeqIO.read("m_cold.fasta", format="fasta")
 >>> result_handle = NCBIWWW.qblast("blastn", "nt", record.seq)
-

Supplying just the sequence means that BLAST will assign an identifier +

Supplying just the sequence means that BLAST will assign an identifier for your sequence automatically. You might prefer to use the -SeqRecord object’s format method to make a fasta string -(which will include the existing identifier):

>>> from Bio.Blast import NCBIWWW
+SeqRecord object’s format method to make a fasta string
+(which will include the existing identifier):

>>> from Bio.Blast import NCBIWWW
 >>> from Bio import SeqIO
 >>> record = SeqIO.read("m_cold.fasta", format="fasta")
 >>> result_handle = NCBIWWW.qblast("blastn", "nt", record.format("fasta"))
-

This approach makes more sense if you have your sequence(s) in a -non-FASTA file format which you can extract using Bio.SeqIO -(see Chapter 5).

Whatever arguments you give the qblast() function, you should +

This approach makes more sense if you have your sequence(s) in a +non-FASTA file format which you can extract using Bio.SeqIO +(see Chapter 5).

Whatever arguments you give the qblast() function, you should get back your results in a handle object (by default in XML format). The next step would be to parse the XML output into Python objects -representing the search results (Section 7.3), +representing the search results (Section 7.3), but you might want to save a local copy of the output file first. I find this especially useful when debugging my code that extracts info from the BLAST results (because re-running the online search -is slow and wastes the NCBI computer time).

We need to be a bit careful since we can use result_handle.read() to -read the BLAST output only once – calling result_handle.read() again -returns an empty string.

>>> save_file = open("my_blast.xml", "w")
+is slow and wastes the NCBI computer time).

We need to be a bit careful since we can use result_handle.read() to +read the BLAST output only once – calling result_handle.read() again +returns an empty string.

>>> save_file = open("my_blast.xml", "w")
 >>> save_file.write(result_handle.read())
 >>> save_file.close()
 >>> result_handle.close()
-

After doing this, the results are in the file my_blast.xml and the +

After doing this, the results are in the file my_blast.xml and the original handle has had all its data extracted (so we closed it). However, -the parse function of the BLAST parser (described -in 7.3) takes a file-handle-like object, so -we can just open the saved file for input:

>>> result_handle = open("my_blast.xml")
-

Now that we’ve got the BLAST results back into a handle again, we are ready +the parse function of the BLAST parser (described +in 7.3) takes a file-handle-like object, so +we can just open the saved file for input:

>>> result_handle = open("my_blast.xml")
+

Now that we’ve got the BLAST results back into a handle again, we are ready to do something with them, so this leads us right into the parsing section -(see Section 7.3 below). You may want to jump ahead to -that now ….

-

7.2  Running BLAST locally

-

-

7.2.1  Introduction

Running BLAST locally (as opposed to over the internet, see -Section 7.1) has at least major two advantages: -

  • +(see Section 7.3 below). You may want to jump ahead to +that now ….

    + +

    7.2  Running BLAST locally

    +

    + +

    7.2.1  Introduction

    Running BLAST locally (as opposed to over the internet, see +Section 7.1) has at least major two advantages: +

    • Local BLAST may be faster than BLAST over the internet; -
    • Local BLAST allows you to make your own database to search for sequences against. -

    +

  • Local BLAST allows you to make your own database to search for sequences against. +

Dealing with proprietary or unpublished sequence data can be another reason to run BLAST locally. You may not be allowed to redistribute the sequences, so submitting them to the -NCBI as a BLAST query would not be an option.

Unfortunately, there are some major drawbacks too – installing all the bits and getting +NCBI as a BLAST query would not be an option.

Unfortunately, there are some major drawbacks too – installing all the bits and getting it setup right takes some effort: -

  • +

    • Local BLAST requires command line tools to be installed. -
    • Local BLAST requires (large) BLAST databases to be setup (and potentially kept up to date). -

    To further confuse matters there are at least four different standalone BLAST packages, -and there are also other tools which can produce imitation BLAST output files, such as BLAT.

    -

    7.2.2  Standalone NCBI “legacy” BLAST

    NCBI “legacy” BLAST included command line tools blastall, blastpgp and -rpsblast. This was the most widely used standalone BLAST tool up until its replacement -BLAST+ was released by the NCBI.

    The Bio.Blast.Applications module has wrappers for the “legacy” NCBI BLAST tools -like blastall, blastpgp and rpsblast, and there are also helper -functions in Bio.Blast.NCBIStandalone. These are now considered obsolete, and will -be deprecated and eventually removed from Biopython as people move over to the replacement -BLAST+ suite.

    To try and avoid confusion, we will not cover calling these old tools from Biopython -in this tutorial. Have a look at the older edition of this tutorial included with -Biopython 1.52 if you are curious (look at the Tutorial PDF or HTML file in the Doc -directory within biopython-1.52.tar.gz or biopython-1.52.zip).

    -

    7.2.3  Standalone NCBI BLAST+

    NCBI “new” BLAST+ was released in 2009. This replaces the old NCBI “legacy” BLAST -package. The Bio.Blast.Applications module has wrappers for these “new” tools -like blastn, blastp, blastx, tblastn, tblastx -(which all used to be handled by blastall), psiblast -(replacing blastpgp) and rpsblast and rpstblastn -(which replace the old rpsblast). -We don’t include a wrapper for the makeblastdb used in BLAST+ to build a -local BLAST database from FASTA file, nor the equivalent tool formatdb in -“legacy” BLAST.

    This section will show briefly how to use these tools from within Python. If you have -already read or tried the alignment tool examples in Section 6.4 +

  • Local BLAST requires (large) BLAST databases to be setup (and potentially kept up to date). +

To further confuse matters there are several different BLAST packages available, +and there are also other tools which can produce imitation BLAST output files, such as BLAT.

+ +

7.2.2  Standalone NCBI BLAST+

The “new” +NCBI BLAST+ suite was released in 2009. This replaces the old NCBI “legacy” BLAST +package (see below).

This section will show briefly how to use these tools from within Python. If you have +already read or tried the alignment tool examples in Section 6.4 this should all seem quite straightforward. First, we construct a command line string (as you would type in at the command line prompt if running standalone BLAST by hand). -Then we can execute this command from within Python.

For example, taking a FASTA file of gene nucleotide sequences, you might want to +Then we can execute this command from within Python.

For example, taking a FASTA file of gene nucleotide sequences, you might want to run a BLASTX (translation) search against the non-redundant (NR) protein database. Assuming you (or your systems administrator) has downloaded and installed the NR -database, you might run:

blastx -query opuntia.fasta -db nr -out opuntia.xml -evalue 0.001 -outfmt 5
-

This should run BLASTX against the NR database, using an expectation cut-off value +database, you might run:

blastx -query opuntia.fasta -db nr -out opuntia.xml -evalue 0.001 -outfmt 5
+

This should run BLASTX against the NR database, using an expectation cut-off value of 0.001 and produce XML output to the specified file (which we can then parse). On my computer this takes about six minutes - a good reason to save the output -to a file so you and repeat any analysis as needed.

From within Biopython we can use the NCBI BLASTX wrapper from the -Bio.Blast.Applications module to build the command line string, -and run it:

>>> from Bio.Blast.Applications import NcbiblastxCommandline
+to a file so you and repeat any analysis as needed.

From within Biopython we can use the NCBI BLASTX wrapper from the +Bio.Blast.Applications module to build the command line string, +and run it:

>>> from Bio.Blast.Applications import NcbiblastxCommandline
 >>> help(NcbiblastxCommandline)
 ...
 >>> blastx_cline = NcbiblastxCommandline(query="opuntia.fasta", db="nr", evalue=0.001,
@@ -3388,130 +3480,144 @@
 >>> blastx_cline
 NcbiblastxCommandline(cmd='blastx', out='opuntia.xml', outfmt=5, query='opuntia.fasta',
 db='nr', evalue=0.001)
->>> print blastx_cline
+>>> print(blastx_cline)
 blastx -out opuntia.xml -outfmt 5 -query opuntia.fasta -db nr -evalue 0.001
 >>> stdout, stderr = blastx_cline()
-

In this example there shouldn’t be any output from BLASTX to the terminal, +

In this example there shouldn’t be any output from BLASTX to the terminal, so stdout and stderr should be empty. You may want to check the output file -opuntia.xml has been created.

As you may recall from earlier examples in the tutorial, the opuntia.fasta +opuntia.xml has been created.

As you may recall from earlier examples in the tutorial, the opuntia.fasta contains seven sequences, so the BLAST XML output should contain multiple results. -Therefore use Bio.Blast.NCBIXML.parse() to parse it as described below in -Section 7.3.

-

7.2.4  WU-BLAST and AB-BLAST

You may also come across Washington University BLAST -(WU-BLAST), and its successor, Advanced Biocomputing -BLAST (AB-BLAST, released in 2009, not free/open source). These packages include -the command line tools wu-blastall and ab-blastall.

Biopython does not currently provide wrappers for calling these tools, but should be able -to parse any NCBI compatible output from them.

-

7.3  Parsing BLAST output

-

As mentioned above, BLAST can generate output in various formats, such as +Therefore use Bio.Blast.NCBIXML.parse() to parse it as described below in +Section 7.3.

+ +

7.2.3  Other versions of BLAST

NCBI BLAST+ (written in C++) was first released in 2009 as a replacement for +the original NCBI “legacy” BLAST (written in C) which is no longer being updated. +There were a lot of changes – the old version had a single core command line +tool blastall which covered multiple different BLAST search types (which +are now separate commands in BLAST+), and all the command line options +were renamed. +Biopython’s wrappers for the NCBI “legacy” BLAST tools have been deprecated +and will be removed in a future release. +To try to avoid confusion, we do not cover calling these old tools from Biopython +in this tutorial.

You may also come across Washington University BLAST +(WU-BLAST), and its successor, Advanced Biocomputing +BLAST (AB-BLAST, released in 2009, not free/open source). These packages include +the command line tools wu-blastall and ab-blastall, which mimicked +blastall from the NCBI “legacy” BLAST stuie. +Biopython does not currently provide wrappers for calling these tools, but should be able +to parse any NCBI compatible output from them.

+ +

7.3  Parsing BLAST output

+

As mentioned above, BLAST can generate output in various formats, such as XML, HTML, and plain text. Originally, Biopython had parsers for BLAST plain text and HTML output, as these were the only output formats offered at the time. Unfortunately, the BLAST output in these formats kept changing, each time breaking the Biopython parsers. Our HTML BLAST parser has been removed, but the plain text BLAST parser is still available (see -Section 7.5). Use it at your own risk, -it may or may not work, depending on which BLAST version you’re using.

As keeping up with changes in BLAST +Section 7.5). Use it at your own risk, +it may or may not work, depending on which BLAST version you’re using.

As keeping up with changes in BLAST became a hopeless endeavor, especially with users running different BLAST versions, we now recommend to parse the output in XML format, which can be generated by recent versions of BLAST. Not only is the XML output more stable than the plain text and HTML output, it is also much easier to parse -automatically, making Biopython a whole lot more stable.

You can get BLAST output in XML format in various ways. For the parser, it +automatically, making Biopython a whole lot more stable.

You can get BLAST output in XML format in various ways. For the parser, it doesn’t matter how the output was generated, as long as it is in the XML format. -

  • +

    • You can use Biopython to run BLAST over the internet, as described in -section 7.1. -
    • You can use Biopython to run BLAST locally, as described in -section 7.2. -
    • You can do the BLAST search yourself on the NCBI site through your +section 7.1. +
    • You can use Biopython to run BLAST locally, as described in +section 7.2. +
    • You can do the BLAST search yourself on the NCBI site through your web browser, and then save the results. You need to choose XML as the format in which to receive the results, and save the final BLAST page you get (you know, the one with all of the interesting results!) to a file. -
    • You can also run BLAST locally without using Biopython, and save +
    • You can also run BLAST locally without using Biopython, and save the output in a file. Again, you need to choose XML as the format in which to receive the results. -

    +

The important point is that you do not have to use Biopython scripts to fetch the data in order to be able to parse it. Doing things in one of these ways, you then need to get a handle to the results. In Python, a handle is just a nice general way of describing input to any info source so that the info can be retrieved -using read() and readline() functions -(see Section sec:appendix-handles).

If you followed the code above for interacting with BLAST through a -script, then you already have result_handle, the handle to the -BLAST results. For example, using a GI number to do an online search:

>>> from Bio.Blast import NCBIWWW
+using read() and readline() functions
+(see Section sec:appendix-handles).

If you followed the code above for interacting with BLAST through a +script, then you already have result_handle, the handle to the +BLAST results. For example, using a GI number to do an online search:

>>> from Bio.Blast import NCBIWWW
 >>> result_handle = NCBIWWW.qblast("blastn", "nt", "8332116")
-

If instead you ran BLAST some other way, and have the -BLAST output (in XML format) in the file my_blast.xml, all you -need to do is to open the file for reading:

>>> result_handle = open("my_blast.xml")
-

Now that we’ve got a handle, we are ready to parse the output. The +

If instead you ran BLAST some other way, and have the +BLAST output (in XML format) in the file my_blast.xml, all you +need to do is to open the file for reading:

>>> result_handle = open("my_blast.xml")
+

Now that we’ve got a handle, we are ready to parse the output. The code to parse it is really quite small. If you expect a single -BLAST result (i.e. you used a single query):

>>> from Bio.Blast import NCBIXML
+BLAST result (i.e. you used a single query):

>>> from Bio.Blast import NCBIXML
 >>> blast_record = NCBIXML.read(result_handle)
-

or, if you have lots of results (i.e. multiple query sequences):

>>> from Bio.Blast import NCBIXML
+

or, if you have lots of results (i.e. multiple query sequences):

>>> from Bio.Blast import NCBIXML
 >>> blast_records = NCBIXML.parse(result_handle)
-

Just like Bio.SeqIO and Bio.AlignIO -(see Chapters 5 and 6), -we have a pair of input functions, read and parse, where -read is for when you have exactly one object, and parse +

Just like Bio.SeqIO and Bio.AlignIO +(see Chapters 5 and 6), +we have a pair of input functions, read and parse, where +read is for when you have exactly one object, and parse is an iterator for when you can have lots of objects – but instead of -getting SeqRecord or MultipleSeqAlignment objects, we -get BLAST record objects.

To be able to handle the situation where the BLAST file may be huge, -containing thousands of results, NCBIXML.parse() returns an +getting SeqRecord or MultipleSeqAlignment objects, we +get BLAST record objects.

To be able to handle the situation where the BLAST file may be huge, +containing thousands of results, NCBIXML.parse() returns an iterator. In plain English, an iterator allows you to step through the BLAST output, retrieving BLAST records one by one for each BLAST -search result:

>>> from Bio.Blast import NCBIXML
+search result:

>>> from Bio.Blast import NCBIXML
 >>> blast_records = NCBIXML.parse(result_handle)
->>> blast_record = blast_records.next()
+>>> blast_record = next(blast_records)
 # ... do something with blast_record
->>> blast_record = blast_records.next()
+>>> blast_record = next(blast_records)
 # ... do something with blast_record
->>> blast_record = blast_records.next()
+>>> blast_record = next(blast_records)
 # ... do something with blast_record
->>> blast_record = blast_records.next()
+>>> blast_record = next(blast_records)
 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
 StopIteration
 # No further records
-

Or, you can use a for-loop: -

>>> for blast_record in blast_records:
+

Or, you can use a for-loop: +

>>> for blast_record in blast_records:
 ...     # Do something with blast_record
-

Note though that you can step through the BLAST records only once. +

Note though that you can step through the BLAST records only once. Usually, from each BLAST record you would save the information that you are interested in. If you want to save all returned BLAST records, you can convert the iterator into a list: -

>>> blast_records = list(blast_records)
-

Now you can access each BLAST record in the list with an index as usual. +

>>> blast_records = list(blast_records)
+

Now you can access each BLAST record in the list with an index as usual. If your BLAST file is huge though, you may run into memory problems trying to -save them all in a list.

Usually, you’ll be running one BLAST search at a time. Then, all you need -to do is to pick up the first (and only) BLAST record in blast_records: -

>>> from Bio.Blast import NCBIXML
+save them all in a list.

Usually, you’ll be running one BLAST search at a time. Then, all you need +to do is to pick up the first (and only) BLAST record in blast_records: +

>>> from Bio.Blast import NCBIXML
 >>> blast_records = NCBIXML.parse(result_handle)
->>> blast_record = blast_records.next()
-

or more elegantly: -

>>> from Bio.Blast import NCBIXML
+>>> blast_record = next(blast_records)
+

or more elegantly: +

>>> from Bio.Blast import NCBIXML
 >>> blast_record = NCBIXML.read(result_handle)
-

I guess by now you’re wondering what is in a BLAST record.

-

7.4  The BLAST record class

A BLAST Record contains everything you might ever want to extract from the +

I guess by now you’re wondering what is in a BLAST record.

+ +

7.4  The BLAST record class

A BLAST Record contains everything you might ever want to extract from the BLAST output. Right now we’ll just show an example of how to get some info out of the BLAST report, but if you want something in particular that is not described here, look at the info on the record class in detail, and take a gander into the code or automatically generated documentation – the docstrings have lots of -good info about what is stored in each piece of information.

To continue with our example, let’s just print out some summary info +good info about what is stored in each piece of information.

To continue with our example, let’s just print out some summary info about all hits in our blast report greater than a particular -threshold. The following code does this:

>>> E_VALUE_THRESH = 0.04
+threshold. The following code does this:

>>> E_VALUE_THRESH = 0.04
 
 >>> for alignment in blast_record.alignments:
 ...     for hsp in alignment.hsps:
 ...         if hsp.expect < E_VALUE_THRESH:
-...             print '****Alignment****'
-...             print 'sequence:', alignment.title
-...             print 'length:', alignment.length
-...             print 'e value:', hsp.expect
-...             print hsp.query[0:75] + '...'
-...             print hsp.match[0:75] + '...'
-...             print hsp.sbjct[0:75] + '...'
-

This will print out summary reports like the following:

****Alignment****
+...             print('****Alignment****')
+...             print('sequence:', alignment.title)
+...             print('length:', alignment.length)
+...             print('e value:', hsp.expect)
+...             print(hsp.query[0:75] + '...')
+...             print(hsp.match[0:75] + '...')
+...             print(hsp.sbjct[0:75] + '...')
+

This will print out summary reports like the following:

****Alignment****
 sequence: >gb|AF283004.1|AF283004 Arabidopsis thaliana cold acclimation protein WCOR413-like protein
 alpha form mRNA, complete cds
 length: 783
@@ -3519,103 +3625,110 @@
 tacttgttgatattggatcgaacaaactggagaaccaacatgctcacgtcacttttagtcccttacatattcctc...
 ||||||||| | ||||||||||| || ||||  || || |||||||| |||||| |  | |||||||| ||| ||...
 tacttgttggtgttggatcgaaccaattggaagacgaatatgctcacatcacttctcattccttacatcttcttc...
-

Basically, you can do anything you want to with the info in the BLAST +

Basically, you can do anything you want to with the info in the BLAST report once you have parsed it. This will, of course, depend on what you want to use it for, but hopefully this helps you get started on -doing what you need to do!

An important consideration for extracting information from a BLAST report is the type of objects that the information is stored in. In Biopython, the parsers return Record objects, either Blast or PSIBlast depending on what you are parsing. These objects are defined in Bio.Blast.Record and are quite complete.

Here are my attempts at UML class diagrams for the Blast and PSIBlast record classes. If you are good at UML and see mistakes/improvements that can be made, please let me know. The Blast class diagram is shown in Figure 7.4.

- - -

The PSIBlast record object is similar, but has support for the rounds that are used in the iteration steps of PSIBlast. The class diagram for PSIBlast is shown in Figure 7.4.

- - -

-

7.5  Deprecated BLAST parsers

-

Older versions of Biopython had parsers for BLAST output in plain text or HTML +doing what you need to do!

An important consideration for extracting information from a BLAST report is the type of objects that the information is stored in. In Biopython, the parsers return Record objects, either Blast or PSIBlast depending on what you are parsing. These objects are defined in Bio.Blast.Record and are quite complete.

Here are my attempts at UML class diagrams for the Blast and PSIBlast record classes. If you are good at UML and see mistakes/improvements that can be made, please let me know. The Blast class diagram is shown in Figure 7.4.

+ + +

The PSIBlast record object is similar, but has support for the rounds that are used in the iteration steps of PSIBlast. The class diagram for PSIBlast is shown in Figure 7.4.

+ + +

+ +

7.5  Deprecated BLAST parsers

+

Older versions of Biopython had parsers for BLAST output in plain text or HTML format. Over the years, we discovered that it is very hard to maintain these parsers in working order. Basically, any small change to the BLAST output in newly released BLAST versions tends to cause the plain text and HTML parsers to break. We therefore recommend parsing BLAST output in XML format, as -described in section 7.3.

Depending on which BLAST versions or programs you’re using, our plain text BLAST parser may or may not work. Use it at your own risk!

-

7.5.1  Parsing plain-text BLAST output

The plain text BLAST parser is located in Bio.Blast.NCBIStandalone.

As with the XML parser, we need to have a handle object that we can pass to the parser. The handle must implement the readline() method and do this properly. The common ways to get such a handle are to either use the provided blastall or blastpgp functions to run the local blast, or to run a local blast via the command line, and then do something like the following:

>>> result_handle = open("my_file_of_blast_output.txt")
-

Well, now that we’ve got a handle (which we’ll call result_handle), -we are ready to parse it. This can be done with the following code:

>>> from Bio.Blast import NCBIStandalone
+described in section 7.3.

Depending on which BLAST versions or programs you’re using, our plain text BLAST parser may or may not work. Use it at your own risk!

+ +

7.5.1  Parsing plain-text BLAST output

The plain text BLAST parser is located in Bio.Blast.NCBIStandalone.

As with the XML parser, we need to have a handle object that we can pass to the parser. The handle must implement the readline() method and do this properly. The common ways to get such a handle are to either use the provided blastall or blastpgp functions to run the local blast, or to run a local blast via the command line, and then do something like the following:

>>> result_handle = open("my_file_of_blast_output.txt")
+

Well, now that we’ve got a handle (which we’ll call result_handle), +we are ready to parse it. This can be done with the following code:

>>> from Bio.Blast import NCBIStandalone
 >>> blast_parser = NCBIStandalone.BlastParser()
 >>> blast_record = blast_parser.parse(result_handle)
-

This will parse the BLAST report into a Blast Record class (either a Blast or a PSIBlast record, depending on what you are parsing) so that you can extract the information from it. In our case, let’s just use print out a quick summary of all of the alignments greater than some threshold value.

>>> E_VALUE_THRESH = 0.04
+

This will parse the BLAST report into a Blast Record class (either a Blast or a PSIBlast record, depending on what you are parsing) so that you can extract the information from it. In our case, let’s just use print out a quick summary of all of the alignments greater than some threshold value.

>>> E_VALUE_THRESH = 0.04
 >>> for alignment in blast_record.alignments:
 ...     for hsp in alignment.hsps:
 ...         if hsp.expect < E_VALUE_THRESH:
-...             print '****Alignment****'
-...             print 'sequence:', alignment.title
-...             print 'length:', alignment.length
-...             print 'e value:', hsp.expect
-...             print hsp.query[0:75] + '...'
-...             print hsp.match[0:75] + '...'
-...             print hsp.sbjct[0:75] + '...'
-

If you also read the section 7.3 on parsing BLAST XML output, you’ll notice that the above code is identical to what is found in that section. Once you parse something into a record class you can deal with it independent of the format of the original BLAST info you were parsing. Pretty snazzy!

Sure, parsing one record is great, but I’ve got a BLAST file with tons of records – how can I parse them all? Well, fear not, the answer lies in the very next section.

-

7.5.2  Parsing a plain-text BLAST file full of BLAST runs

We can do this using the blast iterator. To set up an iterator, we first set up a parser, to parse our blast reports in Blast Record objects:

>>> from Bio.Blast import NCBIStandalone
+...             print('****Alignment****')
+...             print('sequence:', alignment.title)
+...             print('length:', alignment.length)
+...             print('e value:', hsp.expect)
+...             print(hsp.query[0:75] + '...')
+...             print(hsp.match[0:75] + '...')
+...             print(hsp.sbjct[0:75] + '...')
+

If you also read the section 7.3 on parsing BLAST XML output, you’ll notice that the above code is identical to what is found in that section. Once you parse something into a record class you can deal with it independent of the format of the original BLAST info you were parsing. Pretty snazzy!

Sure, parsing one record is great, but I’ve got a BLAST file with tons of records – how can I parse them all? Well, fear not, the answer lies in the very next section.

+ +

7.5.2  Parsing a plain-text BLAST file full of BLAST runs

We can do this using the blast iterator. To set up an iterator, we first set up a parser, to parse our blast reports in Blast Record objects:

>>> from Bio.Blast import NCBIStandalone
 >>> blast_parser = NCBIStandalone.BlastParser()
-

Then we will assume we have a handle to a bunch of blast records, which we’ll call result_handle. Getting a handle is described in full detail above in the blast parsing sections.

Now that we’ve got a parser and a handle, we are ready to set up the iterator with the following command:

>>> blast_iterator = NCBIStandalone.Iterator(result_handle, blast_parser)
-

The second option, the parser, is optional. If we don’t supply a parser, then the iterator will just return the raw BLAST reports one at a time.

Now that we’ve got an iterator, we start retrieving blast records (generated by our parser) using next():

>>> blast_record = blast_iterator.next()
-

Each call to next will return a new record that we can deal with. Now we can iterate through this records and generate our old favorite, a nice little blast report:

>>> for blast_record in blast_iterator:
+

Then we will assume we have a handle to a bunch of blast records, which we’ll call result_handle. Getting a handle is described in full detail above in the blast parsing sections.

Now that we’ve got a parser and a handle, we are ready to set up the iterator with the following command:

>>> blast_iterator = NCBIStandalone.Iterator(result_handle, blast_parser)
+

The second option, the parser, is optional. If we don’t supply a parser, then the iterator will just return the raw BLAST reports one at a time.

Now that we’ve got an iterator, we start retrieving blast records (generated by our parser) using next():

>>> blast_record = next(blast_iterator)
+

Each call to next will return a new record that we can deal with. Now we can iterate through this records and generate our old favorite, a nice little blast report:

>>> for blast_record in blast_iterator:
 ...     E_VALUE_THRESH = 0.04
 ...     for alignment in blast_record.alignments:
 ...         for hsp in alignment.hsps:
 ...             if hsp.expect < E_VALUE_THRESH:
-...                 print '****Alignment****'
-...                 print 'sequence:', alignment.title
-...                 print 'length:', alignment.length
-...                 print 'e value:', hsp.expect
+...                 print('****Alignment****')
+...                 print('sequence:', alignment.title)
+...                 print('length:', alignment.length)
+...                 print('e value:', hsp.expect)
 ...                 if len(hsp.query) > 75:
 ...                     dots = '...'
 ...                 else:
 ...                     dots = ''
-...                 print hsp.query[0:75] + dots
-...                 print hsp.match[0:75] + dots
-...                 print hsp.sbjct[0:75] + dots
-

The iterator allows you to deal with huge blast records without any memory problems, since things are read in one at a time. I have parsed tremendously huge files without any problems using this.

-

7.5.3  Finding a bad record somewhere in a huge plain-text BLAST file

One really ugly problem that happens to me is that I’ll be parsing a huge blast file for a while, and the parser will bomb out with a ValueError. This is a serious problem, since you can’t tell if the ValueError is due to a parser problem, or a problem with the BLAST. To make it even worse, you have no idea where the parse failed, so you can’t just ignore the error, since this could be ignoring an important data point.

We used to have to make a little script to get around this problem, but the Bio.Blast module now includes a BlastErrorParser which really helps make this easier. The BlastErrorParser works very similar to the regular BlastParser, but it adds an extra layer of work by catching ValueErrors that are generated by the parser, and attempting to diagnose the errors.

Let’s take a look at using this parser – first we define the file we are going to parse and the file to write the problem reports to:

>>> import os
+...                 print(hsp.query[0:75] + dots)
+...                 print(hsp.match[0:75] + dots)
+...                 print(hsp.sbjct[0:75] + dots)
+

The iterator allows you to deal with huge blast records without any memory problems, since things are read in one at a time. I have parsed tremendously huge files without any problems using this.

+ +

7.5.3  Finding a bad record somewhere in a huge plain-text BLAST file

One really ugly problem that happens to me is that I’ll be parsing a huge blast file for a while, and the parser will bomb out with a ValueError. This is a serious problem, since you can’t tell if the ValueError is due to a parser problem, or a problem with the BLAST. To make it even worse, you have no idea where the parse failed, so you can’t just ignore the error, since this could be ignoring an important data point.

We used to have to make a little script to get around this problem, but the Bio.Blast module now includes a BlastErrorParser which really helps make this easier. The BlastErrorParser works very similar to the regular BlastParser, but it adds an extra layer of work by catching ValueErrors that are generated by the parser, and attempting to diagnose the errors.

Let’s take a look at using this parser – first we define the file we are going to parse and the file to write the problem reports to:

>>> import os
 >>> blast_file = os.path.join(os.getcwd(), "blast_out", "big_blast.out")
 >>> error_file = os.path.join(os.getcwd(), "blast_out", "big_blast.problems")
-

Now we want to get a BlastErrorParser:

>>> from Bio.Blast import NCBIStandalone
+

Now we want to get a BlastErrorParser:

>>> from Bio.Blast import NCBIStandalone
 >>> error_handle = open(error_file, "w")
 >>> blast_error_parser = NCBIStandalone.BlastErrorParser(error_handle)
-

Notice that the parser take an optional argument of a handle. If a handle is passed, then the parser will write any blast records which generate a ValueError to this handle. Otherwise, these records will not be recorded.

Now we can use the BlastErrorParser just like a regular blast parser. Specifically, we might want to make an iterator that goes through our blast records one at a time and parses them with the error parser:

>>> result_handle = open(blast_file)
+

Notice that the parser take an optional argument of a handle. If a handle is passed, then the parser will write any blast records which generate a ValueError to this handle. Otherwise, these records will not be recorded.

Now we can use the BlastErrorParser just like a regular blast parser. Specifically, we might want to make an iterator that goes through our blast records one at a time and parses them with the error parser:

>>> result_handle = open(blast_file)
 >>> iterator = NCBIStandalone.Iterator(result_handle, blast_error_parser)
-

We can read these records one a time, but now we can catch and deal with errors that are due to problems with Blast (and not with the parser itself):

>>> try:
-...     next_record = iterator.next()
-... except NCBIStandalone.LowQualityBlastError, info:
-...     print "LowQualityBlastError detected in id %s" % info[1]
-

The .next() method is normally called indirectly via a for-loop. -Right now the BlastErrorParser can generate the following errors:

  • -ValueError – This is the same error generated by the regular BlastParser, and is due to the parser not being able to parse a specific file. This is normally either due to a bug in the parser, or some kind of discrepancy between the version of BLAST you are using and the versions the parser is able to handle.
  • LowQualityBlastError – When BLASTing a sequence that is of really bad quality (for example, a short sequence that is basically a stretch of one nucleotide), it seems that Blast ends up masking out the entire sequence and ending up with nothing to parse. In this case it will produce a truncated report that causes the parser to generate a ValueError. LowQualityBlastError is reported in these cases. This error returns an info item with the following information: -
    • -item[0] – The error message -
    • item[1] – The id of the input record that caused the error. This is really useful if you want to record all of the records that are causing problems. -
    -

As mentioned, with each error generated, the BlastErrorParser will write the offending record to the specified error_handle. You can then go ahead and look and these and deal with them as you see fit. Either you will be able to debug the parser with a single blast report, or will find out problems in your blast runs. Either way, it will definitely be a useful experience!

Hopefully the BlastErrorParser will make it much easier to debug and deal with large Blast files.

-

7.6  Dealing with PSI-BLAST

You can run the standalone version of PSI-BLAST (the legacy NCBI command line -tool blastpgp, or its replacement psiblast) using the wrappers -in Bio.Blast.Applications module.

At the time of writing, the NCBI do not appear to support tools running a -PSI-BLAST search via the internet.

Note that the Bio.Blast.NCBIXML parser can read the XML output from +

We can read these records one a time, but now we can catch and deal with errors that are due to problems with Blast (and not with the parser itself):

>>> try:
+...     next_record = next(iterator)
+... except NCBIStandalone.LowQualityBlastError as info:
+...     print("LowQualityBlastError detected in id %s" % info[1])
+

The next() functionality is normally called indirectly via a for-loop. +Right now the BlastErrorParser can generate the following errors:

  • +ValueError – This is the same error generated by the regular BlastParser, and is due to the parser not being able to parse a specific file. This is normally either due to a bug in the parser, or some kind of discrepancy between the version of BLAST you are using and the versions the parser is able to handle.
  • LowQualityBlastError – When BLASTing a sequence that is of really bad quality (for example, a short sequence that is basically a stretch of one nucleotide), it seems that Blast ends up masking out the entire sequence and ending up with nothing to parse. In this case it will produce a truncated report that causes the parser to generate a ValueError. LowQualityBlastError is reported in these cases. This error returns an info item with the following information: +
    • +item[0] – The error message +
    • item[1] – The id of the input record that caused the error. This is really useful if you want to record all of the records that are causing problems. +
    +

As mentioned, with each error generated, the BlastErrorParser will write the offending record to the specified error_handle. You can then go ahead and look and these and deal with them as you see fit. Either you will be able to debug the parser with a single blast report, or will find out problems in your blast runs. Either way, it will definitely be a useful experience!

Hopefully the BlastErrorParser will make it much easier to debug and deal with large Blast files.

+ +

7.6  Dealing with PSI-BLAST

You can run the standalone version of PSI-BLAST (the legacy NCBI command line +tool blastpgp, or its replacement psiblast) using the wrappers +in Bio.Blast.Applications module.

At the time of writing, the NCBI do not appear to support tools running a +PSI-BLAST search via the internet.

Note that the Bio.Blast.NCBIXML parser can read the XML output from current versions of PSI-BLAST, but information like which sequences in each iteration is new or reused isn’t present in the XML file. If you care about this information you may have more joy with the plain text -output and the PSIBlastParser in Bio.Blast.NCBIStandalone.

-

7.7  Dealing with RPS-BLAST

You can run the standalone version of RPS-BLAST (either the legacy NCBI -command line tool rpsblast, or its replacement with the same name) -using the wrappers in Bio.Blast.Applications module.

At the time of writing, the NCBI do not appear to support tools running an -RPS-BLAST search via the internet.

You can use the Bio.Blast.NCBIXML parser to read the XML output from -current versions of RPS-BLAST.

-

Chapter 8  BLAST and other sequence search tools (experimental code)

-

WARNING: This chapter of the Tutorial describes an experimental +output and the PSIBlastParser in Bio.Blast.NCBIStandalone.

+ +

7.7  Dealing with RPS-BLAST

You can run the standalone version of RPS-BLAST (either the legacy NCBI +command line tool rpsblast, or its replacement with the same name) +using the wrappers in Bio.Blast.Applications module.

At the time of writing, the NCBI do not appear to support tools running an +RPS-BLAST search via the internet.

You can use the Bio.Blast.NCBIXML parser to read the XML output from +current versions of RPS-BLAST.

+ +

Chapter 8  BLAST and other sequence search tools (experimental code)

+

WARNING: This chapter of the Tutorial describes an experimental module in Biopython. It is being included in Biopython and documented here in the tutorial in a pre-final state to allow a period of feedback and refinement before we declare it stable. Until then the details will -probably change, and any scripts using the current Bio.SearchIO +probably change, and any scripts using the current Bio.SearchIO would need to be updated. Please keep this in mind! For stable code working with NCBI BLAST, please continue to use Bio.Blast described -in the preceding Chapter 7.

Biological sequence identification is an integral part of bioinformatics. +in the preceding Chapter 7.

Biological sequence identification is an integral part of bioinformatics. Several tools are available for this, each with their own algorithms and approaches, such as BLAST (arguably the most popular), FASTA, HMMER, and many more. In general, these tools usually use your sequence to search a database of @@ -3626,78 +3739,80 @@ the question. Moreover, you often need to work with several sequence search tools, each with its own statistics, conventions, and output format. Imagine how daunting it would be when you need to work with multiple sequences using -multiple search tools.

We know this too well ourselves, which is why we created the Bio.SearchIO -submodule in Biopython. Bio.SearchIO allows you to extract information +multiple search tools.

We know this too well ourselves, which is why we created the Bio.SearchIO +submodule in Biopython. Bio.SearchIO allows you to extract information from your search results in a convenient way, while also dealing with the different standards and conventions used by different search tools. -The name SearchIO is a homage to BioPerl’s module of the same name.

In this chapter, we’ll go through the main features of Bio.SearchIO to +The name SearchIO is a homage to BioPerl’s module of the same name.

In this chapter, we’ll go through the main features of Bio.SearchIO to show what it can do for you. We’ll use two popular search tools along the way: BLAST and BLAT. They are used merely for illustrative purposes, and you should be able to adapt the workflow to any other search tools supported by -Bio.SearchIO in a breeze. You’re very welcome to follow along with the +Bio.SearchIO in a breeze. You’re very welcome to follow along with the search output files we’ll be using. The BLAST output file can be downloaded -here, +here, and the BLAT output file -here. -Both output files were generated using this sequence:

>mystery_seq
+here.
+Both output files were generated using this sequence:

>mystery_seq
 CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG
-

The BLAST result is an XML file generated using blastn against the NCBI -refseq_rna database. For BLAT, the sequence database was the February 2009 -hg19 human genome draft and the output format is PSL.

We’ll start from an introduction to the Bio.SearchIO object model. The +

The BLAST result is an XML file generated using blastn against the NCBI +refseq_rna database. For BLAT, the sequence database was the February 2009 +hg19 human genome draft and the output format is PSL.

We’ll start from an introduction to the Bio.SearchIO object model. The model is the representation of your search results, thus it is core to -Bio.SearchIO itself. After that, we’ll check out the main functions in -Bio.SearchIO that you may often use.

Now that we’re all set, let’s go to the first step: introducing the core -object model.

-

8.1  The SearchIO object model

-

Despite the wildly differing output styles among many sequence search tools, -it turns out that their underlying concept is similar:

  • +Bio.SearchIO itself. After that, we’ll check out the main functions in +Bio.SearchIO that you may often use.

    Now that we’re all set, let’s go to the first step: introducing the core +object model.

    + +

    8.1  The SearchIO object model

    +

    Despite the wildly differing output styles among many sequence search tools, +it turns out that their underlying concept is similar:

    • The output file may contain results from one or more search queries. -
    • In each search query, you will see one or more hits from the given +
    • In each search query, you will see one or more hits from the given search database. -
    • In each database hit, you will see one or more regions containing the +
    • In each database hit, you will see one or more regions containing the actual sequence alignment between your query sequence and the database sequence. -
    • Some programs like BLAT or Exonerate may further split these regions into +
    • Some programs like BLAT or Exonerate may further split these regions into several alignment fragments (or blocks in BLAT and possibly exons in exonerate). This is not something you always see, as programs like BLAST and HMMER do not do this. -

    Realizing this generality, we decided use it as base for creating the -Bio.SearchIO object model. The object model consists of a nested +

Realizing this generality, we decided use it as base for creating the +Bio.SearchIO object model. The object model consists of a nested hierarchy of Python objects, each one representing one concept outlined above. -These objects are:

  • -QueryResult, to represent a single search query. -
  • Hit, to represent a single database hit. Hit objects are -contained within QueryResult and in each QueryResult there is -zero or more Hit objects. -
  • HSP (short for high-scoring pair), to represent region(s) of -significant alignments between query and hit sequences. HSP objects -are contained within Hit objects and each Hit has one or more -HSP objects. -
  • HSPFragment, to represent a single contiguous alignment between -query and hit sequences. HSPFragment objects are contained within -HSP objects. Most sequence search tools like BLAST and HMMER unify -HSP and HSPFragment objects as each HSP will only have -a single HSPFragment. However there are tools like BLAT and Exonerate -that produce HSP containing multiple HSPFragment. Don’t worry +These objects are:

    • +QueryResult, to represent a single search query. +
    • Hit, to represent a single database hit. Hit objects are +contained within QueryResult and in each QueryResult there is +zero or more Hit objects. +
    • HSP (short for high-scoring pair), to represent region(s) of +significant alignments between query and hit sequences. HSP objects +are contained within Hit objects and each Hit has one or more +HSP objects. +
    • HSPFragment, to represent a single contiguous alignment between +query and hit sequences. HSPFragment objects are contained within +HSP objects. Most sequence search tools like BLAST and HMMER unify +HSP and HSPFragment objects as each HSP will only have +a single HSPFragment. However there are tools like BLAT and Exonerate +that produce HSP containing multiple HSPFragment. Don’t worry if this seems a tad confusing now, we’ll elaborate more on these two objects later on. -

    These four objects are the ones you will interact with when you use -Bio.SearchIO. They are created using one of the main Bio.SearchIO -methods: read, parse, index, or index_db. The +

These four objects are the ones you will interact with when you use +Bio.SearchIO. They are created using one of the main Bio.SearchIO +methods: read, parse, index, or index_db. The details of these methods are provided in later sections. For this section, we’ll only be using read and parse. These functions behave similarly to their -Bio.SeqIO and Bio.AlignIO counterparts:

  • -read is used for search output files with a single query and -returns a QueryResult object -
  • parse is used for search output files with multiple queries and -returns a generator that yields QueryResult objects -

With that settled, let’s start probing each Bio.SearchIO object, -beginning with QueryResult.

-

8.1.1  QueryResult

-

The QueryResult object represents a single search query and contains zero or -more Hit objects. Let’s see what it looks like using the BLAST file we have:

>>> from Bio import SearchIO
+Bio.SeqIO and Bio.AlignIO counterparts:

  • +read is used for search output files with a single query and +returns a QueryResult object +
  • parse is used for search output files with multiple queries and +returns a generator that yields QueryResult objects +

With that settled, let’s start probing each Bio.SearchIO object, +beginning with QueryResult.

+ +

8.1.1  QueryResult

+

The QueryResult object represents a single search query and contains zero or +more Hit objects. Let’s see what it looks like using the BLAST file we have:

>>> from Bio import SearchIO
 >>> blast_qresult = SearchIO.read('my_blast.xml', 'blast-xml')
->>> print blast_qresult
+>>> print(blast_qresult)
 Program: blastn (2.2.27+)
   Query: 42291 (61)
          mystery_seq
@@ -3739,20 +3854,20 @@
            97      1  gi|356517317|ref|XM_003527287.1|  PREDICTED: Glycine ma...
            98      1  gi|297814701|ref|XM_002875188.1|  Arabidopsis lyrata su...
            99      1  gi|397513516|ref|XM_003827011.1|  PREDICTED: Pan panisc...
-

We’ve just begun to scratch the surface of the object model, but you can see that -there’s already some useful information. By invoking print on the -QueryResult object, you can see:

  • +

We’ve just begun to scratch the surface of the object model, but you can see that +there’s already some useful information. By invoking print on the +QueryResult object, you can see:

  • The program name and version (blastn version 2.2.27+) -
  • The query ID, description, and its sequence length (ID is 42291, +
  • The query ID, description, and its sequence length (ID is 42291, description is ‘mystery_seq’, and it is 61 nucleotides long) -
  • The target database to search against (refseq_rna) -
  • A quick overview of the resulting hits. For our query sequence, there are +
  • The target database to search against (refseq_rna) +
  • A quick overview of the resulting hits. For our query sequence, there are 100 potential hits (numbered 0–99 in the table). For each hit, we can also see how many HSPs it contains, its ID, and a snippet of its description. Notice -here that Bio.SearchIO truncates the hit table overview, by showing +here that Bio.SearchIO truncates the hit table overview, by showing only hits numbered 0–29, and then 97–99. -

Now let’s check our BLAT results using the same procedure as above:

>>> blat_qresult = SearchIO.read('my_blat.psl', 'blat-psl')
->>> print blat_qresult
+

Now let’s check our BLAT results using the same procedure as above:

>>> blat_qresult = SearchIO.read('my_blat.psl', 'blat-psl')
+>>> print(blat_qresult)
 Program: blat (<unknown version>)
   Query: mystery_seq (61)
          <unknown description>
@@ -3761,44 +3876,44 @@
             #  # HSP  ID + description                                          
          ----  -----  ----------------------------------------------------------
             0     17  chr19  <unknown description>                              
-

You’ll immediately notice that there are some differences. Some of these are +

You’ll immediately notice that there are some differences. Some of these are caused by the way PSL format stores its details, as you’ll see. The rest are caused by the genuine program and target database differences between our BLAST -and BLAT searches:

  • -The program name and version. Bio.SearchIO knows that the program +and BLAT searches:

    • +The program name and version. Bio.SearchIO knows that the program is BLAT, but in the output file there is no information regarding the program version so it defaults to ‘<unknown version>’. -
    • The query ID, description, and its sequence length. Notice here that these +
    • The query ID, description, and its sequence length. Notice here that these details are slightly different from the ones we saw in BLAST. The ID is ‘mystery_seq’ instead of 42991, there is no known description, but the query length is still 61. This is actually a difference introduced by the file formats themselves. BLAST sometimes creates its own query IDs and uses your original ID as the sequence description. -
    • The target database is not known, as it is not stated in the BLAT output +
    • The target database is not known, as it is not stated in the BLAT output file. -
    • And finally, the list of hits we have is completely different. Here, we +
    • And finally, the list of hits we have is completely different. Here, we see that our query sequence only hits the ‘chr19’ database entry, but in it we see 17 HSP regions. This should not be surprising however, given that we are using a different program, each with its own target database. -

    All the details you saw when invoking the print method can be accessed +

All the details you saw when invoking the print method can be accessed individually using Python’s object attribute access notation (a.k.a. the dot notation). There are also other format-specific attributes that you can access -using the same method.

>>> print "%s %s" % (blast_qresult.program, blast_qresult.version)
+using the same method.

>>> print("%s %s" % (blast_qresult.program, blast_qresult.version))
 blastn 2.2.27+
->>> print "%s %s" % (blat_qresult.program, blat_qresult.version)
+>>> print("%s %s" % (blat_qresult.program, blat_qresult.version))
 blat <unknown version>
 >>> blast_qresult.param_evalue_threshold    # blast-xml specific
 10.0
-

For a complete list of accessible attributes, you can check each format-specific +

For a complete list of accessible attributes, you can check each format-specific documentation. Here are the ones -for BLAST +for BLAST and for -BLAT.

Having looked at using print on QueryResult objects, let’s drill -down deeper. What exactly is a QueryResult? In terms of Python objects, -QueryResult is a hybrid between a list and a dictionary. In other words, +BLAT.

Having looked at using print on QueryResult objects, let’s drill +down deeper. What exactly is a QueryResult? In terms of Python objects, +QueryResult is a hybrid between a list and a dictionary. In other words, it is a container object with all the convenient features of lists and -dictionaries.

Like Python lists and dictionaries, QueryResult objects are iterable. -Each iteration returns a Hit object:

>>> for hit in blast_qresult:
+dictionaries.

Like Python lists and dictionaries, QueryResult objects are iterable. +Each iteration returns a Hit object:

>>> for hit in blast_qresult:
 ...     hit
 Hit(id='gi|262205317|ref|NR_030195.1|', query_id='42291', 1 hsps)
 Hit(id='gi|301171311|ref|NR_035856.1|', query_id='42291', 1 hsps)
@@ -3806,20 +3921,20 @@
 Hit(id='gi|301171322|ref|NR_035857.1|', query_id='42291', 2 hsps)
 Hit(id='gi|301171267|ref|NR_035851.1|', query_id='42291', 1 hsps)
 ...
-

To check how many items (hits) a QueryResult has, you can simply invoke -Python’s len method:

>>> len(blast_qresult)
+

To check how many items (hits) a QueryResult has, you can simply invoke +Python’s len method:

>>> len(blast_qresult)
 100
 >>> len(blat_qresult)
 1
-

Like Python lists, you can retrieve items (hits) from a QueryResult using -the slice notation:

>>> blast_qresult[0]        # retrieves the top hit
+

Like Python lists, you can retrieve items (hits) from a QueryResult using +the slice notation:

>>> blast_qresult[0]        # retrieves the top hit
 Hit(id='gi|262205317|ref|NR_030195.1|', query_id='42291', 1 hsps)
 >>> blast_qresult[-1]       # retrieves the last hit
 Hit(id='gi|397513516|ref|XM_003827011.1|', query_id='42291', 1 hsps)
-

To retrieve multiple hits, you can slice QueryResult objects using the +

To retrieve multiple hits, you can slice QueryResult objects using the slice notation as well. In this case, the slice will return a new -QueryResult object containing only the sliced hits:

>>> blast_slice = blast_qresult[:3]     # slices the first three hits
->>> print blast_slice
+QueryResult object containing only the sliced hits:

>>> blast_slice = blast_qresult[:3]     # slices the first three hits
+>>> print(blast_slice)
 Program: blastn (2.2.27+)
   Query: 42291 (61)
          mystery_seq
@@ -3830,36 +3945,36 @@
             0      1  gi|262205317|ref|NR_030195.1|  Homo sapiens microRNA 52...
             1      1  gi|301171311|ref|NR_035856.1|  Pan troglodytes microRNA...
             2      1  gi|270133242|ref|NR_032573.1|  Macaca mulatta microRNA ...
-

Like Python dictionaries, you can also retrieve hits using the hit’s ID. This is +

Like Python dictionaries, you can also retrieve hits using the hit’s ID. This is particularly useful if you know a given hit ID exists within a search query -results:

>>> blast_qresult['gi|262205317|ref|NR_030195.1|']
+results:

>>> blast_qresult['gi|262205317|ref|NR_030195.1|']
 Hit(id='gi|262205317|ref|NR_030195.1|', query_id='42291', 1 hsps)
-

You can also get a full list of Hit objects using hits and a full -list of Hit IDs using hit_keys:

>>> blast_qresult.hits
+

You can also get a full list of Hit objects using hits and a full +list of Hit IDs using hit_keys:

>>> blast_qresult.hits
 [...]       # list of all hits
 >>> blast_qresult.hit_keys
 [...]       # list of all hit IDs
-

What if you just want to check whether a particular hit is present in the query -results? You can do a simple Python membership test using the in keyword:

>>> 'gi|262205317|ref|NR_030195.1|' in blast_qresult
+

What if you just want to check whether a particular hit is present in the query +results? You can do a simple Python membership test using the in keyword:

>>> 'gi|262205317|ref|NR_030195.1|' in blast_qresult
 True
 >>> 'gi|262205317|ref|NR_030194.1|' in blast_qresult
 False
-

Sometimes, knowing whether a hit is present is not enough; you also want to know -the rank of the hit. Here, the index method comes to the rescue:

>>> blast_qresult.index('gi|301171437|ref|NR_035870.1|')
+

Sometimes, knowing whether a hit is present is not enough; you also want to know +the rank of the hit. Here, the index method comes to the rescue:

>>> blast_qresult.index('gi|301171437|ref|NR_035870.1|')
 22
-

Remember that we’re using Python’s indexing style here, which is zero-based. -This means our hit above is ranked at no. 23, not 22.

Also, note that the hit rank you see here is based on the native hit ordering +

Remember that we’re using Python’s indexing style here, which is zero-based. +This means our hit above is ranked at no. 23, not 22.

Also, note that the hit rank you see here is based on the native hit ordering present in the original search output file. Different search tools may order -these hits based on different criteria.

If the native hit ordering doesn’t suit your taste, you can use the sort -method of the QueryResult object. It is very similar to Python’s -list.sort method, with the addition of an option to create a new sorted -QueryResult object or not.

Here is an example of using QueryResult.sort to sort the hits based on +these hits based on different criteria.

If the native hit ordering doesn’t suit your taste, you can use the sort +method of the QueryResult object. It is very similar to Python’s +list.sort method, with the addition of an option to create a new sorted +QueryResult object or not.

Here is an example of using QueryResult.sort to sort the hits based on each hit’s full sequence length. For this particular sort, we’ll set the -in_place flag to False so that sorting will return a new -QueryResult object and leave our initial object unsorted. We’ll also set -the reverse flag to True so that we sort in descending order.

>>> for hit in blast_qresult[:5]:   # id and sequence length of the first five hits
-...     print hit.id, hit.seq_len
-...
+in_place flag to False so that sorting will return a new
+QueryResult object and leave our initial object unsorted. We’ll also set
+the reverse flag to True so that we sort in descending order.

>>> for hit in blast_qresult[:5]:   # id and sequence length of the first five hits
+...     print("%s %i" % (hit.id, hit.seq_len))
+... 
 gi|262205317|ref|NR_030195.1| 61
 gi|301171311|ref|NR_035856.1| 60
 gi|270133242|ref|NR_032573.1| 85
@@ -3869,76 +3984,77 @@
 >>> sort_key = lambda hit: hit.seq_len
 >>> sorted_qresult = blast_qresult.sort(key=sort_key, reverse=True, in_place=False)
 >>> for hit in sorted_qresult[:5]:
-...     print hit.id, hit.seq_len
-...
+...     print("%s %i" % (hit.id, hit.seq_len))
+... 
 gi|397513516|ref|XM_003827011.1| 6002
 gi|390332045|ref|XM_776818.2| 4082
 gi|390332043|ref|XM_003723358.1| 4079
 gi|356517317|ref|XM_003527287.1| 3251
 gi|356543101|ref|XM_003539954.1| 2936
-

The advantage of having the in_place flag here is that we’re preserving +

The advantage of having the in_place flag here is that we’re preserving the native ordering, so we may use it again later. You should note that this is -not the default behavior of QueryResult.sort, however, which is why we -needed to set the in_place flag to True explicitly.

At this point, you’ve known enough about QueryResult objects to make it -work for you. But before we go on to the next object in the Bio.SearchIO +not the default behavior of QueryResult.sort, however, which is why we +needed to set the in_place flag to True explicitly.

At this point, you’ve known enough about QueryResult objects to make it +work for you. But before we go on to the next object in the Bio.SearchIO model, let’s take a look at two more sets of methods that could make it even -easier to work with QueryResult objects: the filter and map -methods.

If you’re familiar with Python’s list comprehensions, generator expressions -or the built in filter and map functions, +easier to work with QueryResult objects: the filter and map +methods.

If you’re familiar with Python’s list comprehensions, generator expressions +or the built in filter and map functions, you’ll know how useful they are for working with list-like objects (if you’re not, check them out!). You can use these built in methods to manipulate -QueryResult objects, but you’ll end up with regular Python lists and lose -the ability to do more interesting manipulations.

That’s why, QueryResult objects provide its own flavor of -filter and map methods. Analogous to filter, there are -hit_filter and hsp_filter methods. As their name implies, these -methods filter its QueryResult object either on its Hit objects -or HSP objects. Similarly, analogous to map, QueryResult -objects also provide the hit_map and hsp_map methods. These -methods apply a given function to all hits or HSPs in a QueryResult -object, respectively.

Let’s see these methods in action, beginning with hit_filter. This method -accepts a callback function that checks whether a given Hit object passes +QueryResult objects, but you’ll end up with regular Python lists and lose +the ability to do more interesting manipulations.

That’s why, QueryResult objects provide its own flavor of +filter and map methods. Analogous to filter, there are +hit_filter and hsp_filter methods. As their name implies, these +methods filter its QueryResult object either on its Hit objects +or HSP objects. Similarly, analogous to map, QueryResult +objects also provide the hit_map and hsp_map methods. These +methods apply a given function to all hits or HSPs in a QueryResult +object, respectively.

Let’s see these methods in action, beginning with hit_filter. This method +accepts a callback function that checks whether a given Hit object passes the condition you set or not. In other words, the function must accept as its -argument a single Hit object and returns True or False.

Here is an example of using hit_filter to filter out Hit objects -that only have one HSP:

>>> filter_func = lambda hit: len(hit.hsps) > 1     # the callback function
+argument a single Hit object and returns True or False.

Here is an example of using hit_filter to filter out Hit objects +that only have one HSP:

>>> filter_func = lambda hit: len(hit.hsps) > 1     # the callback function
 >>> len(blast_qresult)      # no. of hits before filtering
 100
 >>> filtered_qresult = blast_qresult.hit_filter(filter_func)
 >>> len(filtered_qresult)   # no. of hits after filtering
 37
 >>> for hit in filtered_qresult[:5]:    # quick check for the hit lengths
-...     print hit.id, len(hit.hsps)
+...     print("%s %i" % (hit.id, len(hit.hsps)))
 gi|301171322|ref|NR_035857.1| 2
 gi|262205330|ref|NR_030198.1| 2
 gi|301171447|ref|NR_035871.1| 2
 gi|262205298|ref|NR_030190.1| 2
 gi|270132717|ref|NR_032716.1| 2
-

hsp_filter works the same as hit_filter, only instead of looking -at the Hit objects, it performs filtering on the HSP objects in -each hits.

As for the map methods, they too accept a callback function as their -arguments. However, instead of returning True or False, the -callback function must return the modified Hit or HSP object -(depending on whether you’re using hit_map or hsp_map).

Let’s see an example where we’re using hit_map to rename the hit IDs:

>>> def map_func(hit):
+

hsp_filter works the same as hit_filter, only instead of looking +at the Hit objects, it performs filtering on the HSP objects in +each hits.

As for the map methods, they too accept a callback function as their +arguments. However, instead of returning True or False, the +callback function must return the modified Hit or HSP object +(depending on whether you’re using hit_map or hsp_map).

Let’s see an example where we’re using hit_map to rename the hit IDs:

>>> def map_func(hit):
 ...     hit.id = hit.id.split('|')[3]   # renames 'gi|301171322|ref|NR_035857.1|' to 'NR_035857.1'
 ...     return hit
 ...
 >>> mapped_qresult = blast_qresult.hit_map(map_func)
 >>> for hit in mapped_qresult[:5]:
-...     print hit.id
+...     print(hit.id)
 NR_030195.1
 NR_035856.1
 NR_032573.1
 NR_035857.1
 NR_035851.1
-

Again, hsp_map works the same as hit_map, but on HSP -objects instead of Hit objects.

-

8.1.2  Hit

-

Hit objects represent all query results from a single database entry. -They are the second-level container in the Bio.SearchIO object hierarchy. -You’ve seen that they are contained by QueryResult objects, but they -themselves contain HSP objects.

Let’s see what they look like, beginning with our BLAST search:

>>> from Bio import SearchIO
+

Again, hsp_map works the same as hit_map, but on HSP +objects instead of Hit objects.

+ +

8.1.2  Hit

+

Hit objects represent all query results from a single database entry. +They are the second-level container in the Bio.SearchIO object hierarchy. +You’ve seen that they are contained by QueryResult objects, but they +themselves contain HSP objects.

Let’s see what they look like, beginning with our BLAST search:

>>> from Bio import SearchIO
 >>> blast_qresult = SearchIO.read('my_blast.xml', 'blast-xml')
 >>> blast_hit = blast_qresult[3]    # fourth hit from the query result
-
>>> print blast_hit
+>>> print(blast_hit)
 Query: 42291
        mystery_seq
   Hit: gi|301171322|ref|NR_035857.1| (86)
@@ -3948,22 +4064,22 @@
        ----  --------  ---------  ------  ---------------  ---------------------
           0   8.9e-20     100.47      60           [1:61]                [13:73]
           1   3.3e-06      55.39      60           [0:60]                [13:73]
-

You see that we’ve got the essentials covered here:

  • +

You see that we’ve got the essentials covered here:

  • The query ID and description is present. A hit is always tied to a query, so we want to keep track of the originating query as well. These values can -be accessed from a hit using the query_id and -query_description attributes. -
  • We also have the unique hit ID, description, and full sequence lengths. -They can be accessed using id, description, and -seq_len, respectively. -
  • Finally, there’s a table containing quick information about the HSPs this +be accessed from a hit using the query_id and +query_description attributes. +
  • We also have the unique hit ID, description, and full sequence lengths. +They can be accessed using id, description, and +seq_len, respectively. +
  • Finally, there’s a table containing quick information about the HSPs this hit contains. In each row, we’ve got the important HSP details listed: the HSP index, its e-value, its bit score, its span (the alignment length including gaps), its query coordinates, and its hit coordinates. -

Now let’s contrast this with the BLAT search. Remember that in the BLAT search we -had one hit with 17 HSPs.

>>> blat_qresult = SearchIO.read('my_blat.psl', 'blat-psl')
+

Now let’s contrast this with the BLAT search. Remember that in the BLAT search we +had one hit with 17 HSPs.

>>> blat_qresult = SearchIO.read('my_blat.psl', 'blat-psl')
 >>> blat_hit = blat_qresult[0]      # the only hit
->>> print blat_hit
+>>> print(blat_hit)
 Query: mystery_seq
        <unknown description>
   Hit: chr19 (59128983)
@@ -3988,36 +4104,36 @@
          14         ?          ?       ?           [8:61]    [54212018:54212071]
          15         ?          ?       ?           [8:51]    [54234278:54234321]
          16         ?          ?       ?           [8:61]    [54238143:54238196]
-

Here, we’ve got a similar level of detail as with the BLAST hit we saw earlier. -There are some differences worth explaining, though:

  • +

Here, we’ve got a similar level of detail as with the BLAST hit we saw earlier. +There are some differences worth explaining, though:

  • The e-value and bit score column values. As BLAT HSPs do not have e-values and bit scores, the display defaults to ‘?’. -
  • What about the span column? The span values is meant to display the +
  • What about the span column? The span values is meant to display the complete alignment length, which consists of all residues and any gaps that may be present. The PSL format do not have this information readily available -and Bio.SearchIO does not attempt to try guess what it is, so we get a +and Bio.SearchIO does not attempt to try guess what it is, so we get a ‘?’ similar to the e-value and bit score columns. -

In terms of Python objects, Hit behaves almost the same as Python lists, -but contain HSP objects exclusively. If you’re familiar with lists, you -should encounter no difficulties working with the Hit object.

Just like Python lists, Hit objects are iterable, and each iteration -returns one HSP object it contains:

>>> for hsp in blast_hit:
+

In terms of Python objects, Hit behaves almost the same as Python lists, +but contain HSP objects exclusively. If you’re familiar with lists, you +should encounter no difficulties working with the Hit object.

Just like Python lists, Hit objects are iterable, and each iteration +returns one HSP object it contains:

>>> for hsp in blast_hit:
 ...     hsp
 HSP(hit_id='gi|301171322|ref|NR_035857.1|', query_id='42291', 1 fragments)
 HSP(hit_id='gi|301171322|ref|NR_035857.1|', query_id='42291', 1 fragments)
-

You can invoke len on a Hit to see how many HSP objects it -has:

>>> len(blast_hit)
+

You can invoke len on a Hit to see how many HSP objects it +has:

>>> len(blast_hit)
 2
 >>> len(blat_hit)
 17
-

You can use the slice notation on Hit objects, whether to retrieve single -HSP or multiple HSP objects. Like QueryResult, if you slice -for multiple HSP, a new Hit object will be returned containing -only the sliced HSP objects:

>>> blat_hit[0]                 # retrieve single items
+

You can use the slice notation on Hit objects, whether to retrieve single +HSP or multiple HSP objects. Like QueryResult, if you slice +for multiple HSP, a new Hit object will be returned containing +only the sliced HSP objects:

>>> blat_hit[0]                 # retrieve single items
 HSP(hit_id='chr19', query_id='mystery_seq', 1 fragments)
 >>> sliced_hit = blat_hit[4:9]  # retrieve multiple items
 >>> len(sliced_hit)
 5
->>> print sliced_hit
+>>> print(sliced_hit)
 Query: mystery_seq
        <unknown description>
   Hit: chr19 (59128983)
@@ -4030,25 +4146,26 @@
           2         ?          ?       ?           [0:61]    [54238143:54240175]
           3         ?          ?       ?           [0:60]    [54189735:54189795]
           4         ?          ?       ?           [0:61]    [54185425:54185486]
-

You can also sort the HSP inside a Hit, using the exact same -arguments like the sort method you saw in the QueryResult object.

Finally, there are also the filter and map methods you can use -on Hit objects. Unlike in the QueryResult object, Hit -objects only have one variant of filter (Hit.filter) and one -variant of map (Hit.map). Both of Hit.filter and -Hit.map work on the HSP objects a Hit has.

-

8.1.3  HSP

-

HSP (high-scoring pair) represents region(s) in the hit sequence that +

You can also sort the HSP inside a Hit, using the exact same +arguments like the sort method you saw in the QueryResult object.

Finally, there are also the filter and map methods you can use +on Hit objects. Unlike in the QueryResult object, Hit +objects only have one variant of filter (Hit.filter) and one +variant of map (Hit.map). Both of Hit.filter and +Hit.map work on the HSP objects a Hit has.

+ +

8.1.3  HSP

+

HSP (high-scoring pair) represents region(s) in the hit sequence that contains significant alignment(s) to the query sequence. It contains the actual match between your query sequence and a database entry. As this match is -determined by the sequence search tool’s algorithms, the HSP object +determined by the sequence search tool’s algorithms, the HSP object contains the bulk of the statistics computed by the search tool. This also makes -the distinction between HSP objects from different search tools more -apparent compared to the differences you’ve seen in QueryResult or -Hit objects.

Let’s see some examples from our BLAST and BLAT searches. We’ll look at the -BLAST HSP first:

>>> from Bio import SearchIO
+the distinction between HSP objects from different search tools more
+apparent compared to the differences you’ve seen in QueryResult or
+Hit objects.

Let’s see some examples from our BLAST and BLAT searches. We’ll look at the +BLAST HSP first:

>>> from Bio import SearchIO
 >>> blast_qresult = SearchIO.read('my_blast.xml', 'blast-xml')
 >>> blast_hsp = blast_qresult[0][0]    # first hit, first hsp
-
>>> print blast_hsp
+>>> print(blast_hsp)
       Query: 42291 mystery_seq
         Hit: gi|262205317|ref|NR_030195.1| Homo sapiens microRNA 520b (MIR520...
 Query range: [0:61] (1)
@@ -4058,102 +4175,102 @@
      Query - CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG
              |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
        Hit - CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG
-

Just like QueryResult and Hit, invoking print on an -HSP shows its general details: -

  • +

Just like QueryResult and Hit, invoking print on an +HSP shows its general details: +

  • There are the query and hit IDs and descriptions. We need these to -identify our HSP. -
  • We’ve also got the matching range of the query and hit sequences. The +identify our HSP. +
  • We’ve also got the matching range of the query and hit sequences. The slice notation we’re using here is an indication that the range is displayed using Python’s indexing style (zero-based, half open). The number inside the parenthesis denotes the strand. In this case, both sequences have the plus strand. -
  • Some quick statistics are available: the e-value and bitscore. -
  • There is information about the HSP fragments. Ignore this for now; it will +
  • Some quick statistics are available: the e-value and bitscore. +
  • There is information about the HSP fragments. Ignore this for now; it will be explained later on. -
  • And finally, we have the query and hit sequence alignment itself. -

These details can be accessed on their own using the dot notation, just like in -QueryResult and Hit:

>>> blast_hsp.query_range
+
  • And finally, we have the query and hit sequence alignment itself. +
  • These details can be accessed on their own using the dot notation, just like in +QueryResult and Hit:

    >>> blast_hsp.query_range
     (0, 61)
    -
    >>> blast_hsp.evalue
    +
    >>> blast_hsp.evalue
     4.91307e-23
    -

    They’re not the only attributes available, though. HSP objects come with +

    They’re not the only attributes available, though. HSP objects come with a default set of properties that makes it easy to probe their various -details. Here are some examples:

    >>> blast_hsp.hit_start         # start coordinate of the hit sequence
    +details. Here are some examples:

    >>> blast_hsp.hit_start         # start coordinate of the hit sequence
     0
     >>> blast_hsp.query_span        # how many residues in the query sequence
     61
     >>> blast_hsp.aln_span          # how long the alignment is
     61
    -

    Check out the HSP -documentation -for a full list of these predefined properties.

    Furthermore, each sequence search tool usually computes its own statistics / -details for its HSP objects. For example, an XML BLAST search also +

    Check out the HSP +documentation +for a full list of these predefined properties.

    Furthermore, each sequence search tool usually computes its own statistics / +details for its HSP objects. For example, an XML BLAST search also outputs the number of gaps and identical residues. These attributes can be -accessed like so:

    >>> blast_hsp.gap_num       # number of gaps
    +accessed like so:

    >>> blast_hsp.gap_num       # number of gaps
     0
     >>> blast_hsp.ident_num     # number of identical residues
     61
    -

    These details are format-specific; they may not be present in other formats. +

    These details are format-specific; they may not be present in other formats. To see which details are available for a given sequence search tool, you -should check the format’s documentation in Bio.SearchIO. Alternatively, -you may also use .__dict__.keys() for a quick list of what’s available:

    >>> blast_hsp.__dict__.keys()
    +should check the format’s documentation in Bio.SearchIO. Alternatively,
    +you may also use .__dict__.keys() for a quick list of what’s available:

    >>> blast_hsp.__dict__.keys()
     ['bitscore', 'evalue', 'ident_num', 'gap_num', 'bitscore_raw', 'pos_num', '_items']
    -

    Finally, you may have noticed that the query and hit attributes -of our HSP are not just regular strings:

    >>> blast_hsp.query
    +

    Finally, you may have noticed that the query and hit attributes +of our HSP are not just regular strings:

    >>> blast_hsp.query
     SeqRecord(seq=Seq('CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTT...GGG', DNAAlphabet()), id='42291', name='aligned query sequence', description='mystery_seq', dbxrefs=[])
     >>> blast_hsp.hit
     SeqRecord(seq=Seq('CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTT...GGG', DNAAlphabet()), id='gi|262205317|ref|NR_030195.1|', name='aligned hit sequence', description='Homo sapiens microRNA 520b (MIR520B), microRNA', dbxrefs=[])
    -

    They are SeqRecord objects you saw earlier in -Section 4! This means that you can do all sorts of -interesting things you can do with SeqRecord objects on HSP.query -and/or HSP.hit.

    It should not surprise you now that the HSP object has an -alignment property which is a MultipleSeqAlignment object:

    >>> print blast_hsp.aln
    +

    They are SeqRecord objects you saw earlier in +Section 4! This means that you can do all sorts of +interesting things you can do with SeqRecord objects on HSP.query +and/or HSP.hit.

    It should not surprise you now that the HSP object has an +alignment property which is a MultipleSeqAlignment object:

    >>> print(blast_hsp.aln)
     DNAAlphabet() alignment with 2 rows and 61 columns
     CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAG...GGG 42291
     CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAG...GGG gi|262205317|ref|NR_030195.1|
    -

    Having probed the BLAST HSP, let’s now take a look at HSPs from our BLAT +

    Having probed the BLAST HSP, let’s now take a look at HSPs from our BLAT results for a different kind of HSP. As usual, we’ll begin by invoking -print on it:

    >>> blat_qresult = SearchIO.read('my_blat.psl', 'blat-psl')
    +print on it:

    >>> blat_qresult = SearchIO.read('my_blat.psl', 'blat-psl')
     >>> blat_hsp = blat_qresult[0][0]       # first hit, first hsp
    ->>> print blat_hsp
    +>>> print(blat_hsp)
           Query: mystery_seq <unknown description>
             Hit: chr19 <unknown description>
     Query range: [0:61] (1)
       Hit range: [54204480:54204541] (1)
     Quick stats: evalue ?; bitscore ?
       Fragments: 1 (? columns)
    -

    Some of the outputs you may have already guessed. We have the query and hit IDs +

    Some of the outputs you may have already guessed. We have the query and hit IDs and descriptions and the sequence coordinates. Values for evalue and bitscore is ‘?’ as BLAT HSPs do not have these attributes. But The biggest difference here is that you don’t see any sequence alignments displayed. If you look closer, PSL formats themselves do not have any hit or query sequences, so -Bio.SearchIO won’t create any sequence or alignment objects. What happens -if you try to access HSP.query, HSP.hit, or HSP.aln? -You’ll get the default values for these attributes, which is None:

    >>> blat_hsp.hit is None
    +Bio.SearchIO won’t create any sequence or alignment objects. What happens
    +if you try to access HSP.query, HSP.hit, or HSP.aln?
    +You’ll get the default values for these attributes, which is None:

    >>> blat_hsp.hit is None
     True
     >>> blat_hsp.query is None
     True
     >>> blat_hsp.aln is None
     True
    -

    This does not affect other attributes, though. For example, you can still +

    This does not affect other attributes, though. For example, you can still access the length of the query or hit alignment. Despite not displaying any -attributes, the PSL format still have this information so Bio.SearchIO -can extract them:

    >>> blat_hsp.query_span     # length of query match
    +attributes, the PSL format still have this information so Bio.SearchIO
    +can extract them:

    >>> blat_hsp.query_span     # length of query match
     61
     >>> blat_hsp.hit_span       # length of hit match
     61
    -

    Other format-specific attributes are still present as well:

    >>> blat_hsp.score          # PSL score
    +

    Other format-specific attributes are still present as well:

    >>> blat_hsp.score          # PSL score
     61
     >>> blat_hsp.mismatch_num   # the mismatch column
     0
    -

    So far so good? Things get more interesting when you look at another ‘variant’ +

    So far so good? Things get more interesting when you look at another ‘variant’ of HSP present in our BLAT results. You might recall that in BLAT searches, sometimes we get our results separated into ‘blocks’. These blocks are essentially alignment fragments that may have some intervening sequence between -them.

    Let’s take a look at a BLAT HSP that contains multiple blocks to see how -Bio.SearchIO deals with this:

    >>> blat_hsp2 = blat_qresult[0][1]      # first hit, second hsp
    ->>> print blat_hsp2
    +them.

    Let’s take a look at a BLAT HSP that contains multiple blocks to see how +Bio.SearchIO deals with this:

    >>> blat_hsp2 = blat_qresult[0][1]      # first hit, second hsp
    +>>> print(blat_hsp2)
           Query: mystery_seq <unknown description>
             Hit: chr19 <unknown description>
     Query range: [0:61] (1)
    @@ -4164,20 +4281,20 @@
                  ---  --------------  ----------------------  ----------------------
                    0               ?                  [0:18]     [54233104:54233122]
                    1               ?                 [18:61]     [54264420:54264463]
    -

    What’s happening here? We still some essential details covered: the IDs and +

    What’s happening here? We still some essential details covered: the IDs and descriptions, the coordinates, and the quick statistics are similar to what you’ve seen before. But the fragments detail is all different. Instead of -showing ‘Fragments: 1’, we now have a table with two data rows.

    This is how Bio.SearchIO deals with HSPs having multiple fragments. As +showing ‘Fragments: 1’, we now have a table with two data rows.

    This is how Bio.SearchIO deals with HSPs having multiple fragments. As mentioned before, an HSP alignment may be separated by intervening sequences into fragments. The intervening sequences are not part of the query-hit match, so they should not be considered part of query nor hit sequence. However, they -do affect how we deal with sequence coordinates, so we can’t ignore them.

    Take a look at the hit coordinate of the HSP above. In the Hit range: field, -we see that the coordinate is [54233104:54264463]. But looking at the +do affect how we deal with sequence coordinates, so we can’t ignore them.

    Take a look at the hit coordinate of the HSP above. In the Hit range: field, +we see that the coordinate is [54233104:54264463]. But looking at the table rows, we see that not the entire region spanned by this coordinate matches -our query. Specifically, the intervening region spans from 54233122 to -54264420.

    Why then, is the query coordinates seem to be contiguous, you ask? This is +our query. Specifically, the intervening region spans from 54233122 to +54264420.

    Why then, is the query coordinates seem to be contiguous, you ask? This is perfectly fine. In this case it means that the query match is contiguous (no -intervening regions), while the hit match is not.

    All these attributes are accessible from the HSP directly, by the way:

    >>> blat_hsp2.hit_range         # hit start and end coordinates of the entire HSP
    +intervening regions), while the hit match is not.

    All these attributes are accessible from the HSP directly, by the way:

    >>> blat_hsp2.hit_range         # hit start and end coordinates of the entire HSP
     (54233104, 54264463)
     >>> blat_hsp2.hit_range_all     # hit start and end coordinates of each fragment
     [(54233104, 54233122), (54264420, 54264463)]
    @@ -4189,39 +4306,40 @@
     [(54233122, 54264420)]
     >>> blat_hsp2.hit_inter_spans   # span of intervening regions in the hit sequence
     [31298]
    -

    Most of these attributes are not readily available from the PSL file we have, -but Bio.SearchIO calculates them for you on the fly when you parse the -PSL file. All it needs are the start and end coordinates of each fragment.

    What about the query, hit, and aln attributes? If the +

    Most of these attributes are not readily available from the PSL file we have, +but Bio.SearchIO calculates them for you on the fly when you parse the +PSL file. All it needs are the start and end coordinates of each fragment.

    What about the query, hit, and aln attributes? If the HSP has multiple fragments, you won’t be able to use these attributes as they -only fetch single SeqRecord or MultipleSeqAlignment objects. -However, you can use their *_all counterparts: query_all, -hit_all, and aln_all. These properties will return a list containing -SeqRecord or MultipleSeqAlignment objects from each of the HSP +only fetch single SeqRecord or MultipleSeqAlignment objects. +However, you can use their *_all counterparts: query_all, +hit_all, and aln_all. These properties will return a list containing +SeqRecord or MultipleSeqAlignment objects from each of the HSP fragment. There are other attributes that behave similarly, i.e. they only work -for HSPs with one fragment. Check out the HSP documentation -for a full list.

    Finally, to check whether you have multiple fragments or not, you can use the -is_fragmented property like so:

    >>> blat_hsp2.is_fragmented     # BLAT HSP with 2 fragments
    +for HSPs with one fragment. Check out the HSP documentation
    +for a full list.

    Finally, to check whether you have multiple fragments or not, you can use the +is_fragmented property like so:

    >>> blat_hsp2.is_fragmented     # BLAT HSP with 2 fragments
     True
     >>> blat_hsp.is_fragmented      # BLAT HSP from earlier, with one fragment
     False
    -

    Before we move on, you should also know that we can use the slice notation on -HSP objects, just like QueryResult or Hit objects. When -you use this notation, you’ll get an HSPFragment object in return, the -last component of the object model.

    -

    8.1.4  HSPFragment

    -

    HSPFragment represents a single, contiguous match between the query and +

    Before we move on, you should also know that we can use the slice notation on +HSP objects, just like QueryResult or Hit objects. When +you use this notation, you’ll get an HSPFragment object in return, the +last component of the object model.

    + +

    8.1.4  HSPFragment

    +

    HSPFragment represents a single, contiguous match between the query and hit sequences. You could consider it the core of the object model and search result, since it is the presence of these fragments that determine whether your -search have results or not.

    In most cases, you don’t have to deal with HSPFragment objects directly +search have results or not.

    In most cases, you don’t have to deal with HSPFragment objects directly since not that many sequence search tools fragment their HSPs. When you do have -to deal with them, what you should remember is that HSPFragment objects +to deal with them, what you should remember is that HSPFragment objects were written with to be as compact as possible. In most cases, they only contain attributes directly related to sequences: strands, reading frames, alphabets, -coordinates, the sequences themselves, and their IDs and descriptions.

    These attributes are readily shown when you invoke print on an -HSPFragment. Here’s an example, taken from our BLAST search:

    >>> from Bio import SearchIO
    +coordinates, the sequences themselves, and their IDs and descriptions.

    These attributes are readily shown when you invoke print on an +HSPFragment. Here’s an example, taken from our BLAST search:

    >>> from Bio import SearchIO
     >>> blast_qresult = SearchIO.read('my_blast.xml', 'blast-xml')
     >>> blast_frag = blast_qresult[0][0][0]    # first hit, first hsp, first fragment
    ->>> print blast_frag
    +>>> print(blast_frag)
           Query: 42291 mystery_seq
             Hit: gi|262205317|ref|NR_030195.1| Homo sapiens microRNA 520b (MIR520...
     Query range: [0:61] (1)
    @@ -4230,195 +4348,202 @@
          Query - CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG
                  |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
            Hit - CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG
    -

    At this level, the BLAT fragment looks quite similar to the BLAST fragment, save -for the query and hit sequences which are not present:

    >>> blat_qresult = SearchIO.read('my_blat.psl', 'blat-psl')
    +

    At this level, the BLAT fragment looks quite similar to the BLAST fragment, save +for the query and hit sequences which are not present:

    >>> blat_qresult = SearchIO.read('my_blat.psl', 'blat-psl')
     >>> blat_frag = blat_qresult[0][0][0]    # first hit, first hsp, first fragment
    ->>> print blat_frag
    +>>> print(blat_frag)
           Query: mystery_seq <unknown description>
             Hit: chr19 <unknown description>
     Query range: [0:61] (1)
       Hit range: [54204480:54204541] (1)
       Fragments: 1 (? columns)
    -

    In all cases, these attributes are accessible using our favorite dot notation. -Some examples:

    >>> blast_frag.query_start      # query start coordinate
    +

    In all cases, these attributes are accessible using our favorite dot notation. +Some examples:

    >>> blast_frag.query_start      # query start coordinate
     0
     >>> blast_frag.hit_strand       # hit sequence strand
     1
     >>> blast_frag.hit              # hit sequence, as a SeqRecord object
     SeqRecord(seq=Seq('CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTT...GGG', DNAAlphabet()), id='gi|262205317|ref|NR_030195.1|', name='aligned hit sequence', description='Homo sapiens microRNA 520b (MIR520B), microRNA', dbxrefs=[])
    -
    -

    8.2  A note about standards and conventions

    -

    Before we move on to the main functions, there is something you ought to know -about the standards Bio.SearchIO uses. If you’ve worked with multiple +

    + +

    8.2  A note about standards and conventions

    +

    Before we move on to the main functions, there is something you ought to know +about the standards Bio.SearchIO uses. If you’ve worked with multiple sequence search tools, you might have had to deal with the many different ways each program deals with things like sequence coordinates. It might not have been a pleasant experience as these search tools usually have their own standards. For example, one tools might use one-based coordinates, while the other uses zero-based coordinates. Or, one program might reverse the start and end coordinates if the strand is minus, while others don’t. In short, these often -creates unnecessary mess must be dealt with.

    We realize this problem ourselves and we intend to address it in -Bio.SearchIO. After all, one of the goals of Bio.SearchIO is to +creates unnecessary mess must be dealt with.

    We realize this problem ourselves and we intend to address it in +Bio.SearchIO. After all, one of the goals of Bio.SearchIO is to create a common, easy to use interface to deal with various search output files. -This means creating standards that extend beyond the object model you just saw.

    Now, you might complain, "Not another standard!". Well, eventually we have to +This means creating standards that extend beyond the object model you just saw.

    Now, you might complain, "Not another standard!". Well, eventually we have to choose one convention or the other, so this is necessary. Plus, we’re not creating something entirely new here; just adopting a standard we think is best -for a Python programmer (it is Biopython, after all).

    There are three implicit standards that you can expect when working with -Bio.SearchIO:

    • -The first one pertains to sequence coordinates. In Bio.SearchIO, +for a Python programmer (it is Biopython, after all).

      There are three implicit standards that you can expect when working with +Bio.SearchIO:

      • +The first one pertains to sequence coordinates. In Bio.SearchIO, all sequence coordinates follows Python’s coordinate style: zero-based and half open. For example, if in a BLAST XML output file the start and end coordinates of an HSP are 10 and 28, they would become 9 and 28 in -Bio.SearchIO. The start coordinate becomes 9 because Python indices +Bio.SearchIO. The start coordinate becomes 9 because Python indices start from zero, while the end coordinate remains 28 as Python slices omit the last item in an interval. -
      • The second is on sequence coordinate orders. In Bio.SearchIO, start +
      • The second is on sequence coordinate orders. In Bio.SearchIO, start coordinates are always less than or equal to end coordinates. This isn’t always the case with all sequence search tools, as some of them have larger start coordinates when the sequence strand is minus. -
      • The last one is on strand and reading frame values. For strands, there are -only four valid choices: 1 (plus strand), -1 (minus strand), -0 (protein sequences), and None (no strand). For reading -frames, the valid choices are integers from -3 to 3 and -None. -

      Note that these standards only exist in Bio.SearchIO objects. If you -write Bio.SearchIO objects into an output format, Bio.SearchIO +

    • The last one is on strand and reading frame values. For strands, there are +only four valid choices: 1 (plus strand), -1 (minus strand), +0 (protein sequences), and None (no strand). For reading +frames, the valid choices are integers from -3 to 3 and +None. +

    Note that these standards only exist in Bio.SearchIO objects. If you +write Bio.SearchIO objects into an output format, Bio.SearchIO will use the format’s standard for the output. It does not force its standard -over to your output file.

    -

    8.3  Reading search output files

    -

    There are two functions you can use for reading search output files into -Bio.SearchIO objects: read and parse. They’re essentially -similar to read and parse functions in other submodules like -Bio.SeqIO or Bio.AlignIO. In both cases, you need to supply the +over to your output file.

    + +

    8.3  Reading search output files

    +

    There are two functions you can use for reading search output files into +Bio.SearchIO objects: read and parse. They’re essentially +similar to read and parse functions in other submodules like +Bio.SeqIO or Bio.AlignIO. In both cases, you need to supply the search output file name and the file format name, both as Python strings. You -can check the documentation for a list of format names Bio.SearchIO -recognizes.

    Bio.SearchIO.read is used for reading search output files with only one -query and returns a QueryResult object. You’ve seen read used in -our previous examples. What you haven’t seen is that read may also accept -additional keyword arguments, depending on the file format.

    Here are some examples. In the first one, we use read just like +can check the documentation for a list of format names Bio.SearchIO +recognizes.

    Bio.SearchIO.read is used for reading search output files with only one +query and returns a QueryResult object. You’ve seen read used in +our previous examples. What you haven’t seen is that read may also accept +additional keyword arguments, depending on the file format.

    Here are some examples. In the first one, we use read just like previously to read a BLAST tabular output file. In the second one, we use a keyword argument to modify so it parses the BLAST tabular variant with comments -in it:

    >>> from Bio import SearchIO
    +in it:

    >>> from Bio import SearchIO
     >>> qresult = SearchIO.read('tab_2226_tblastn_003.txt', 'blast-tab')
     >>> qresult
     QueryResult(id='gi|16080617|ref|NP_391444.1|', 3 hits)
     >>> qresult2 = SearchIO.read('tab_2226_tblastn_007.txt', 'blast-tab', comments=True)
     >>> qresult2
     QueryResult(id='gi|16080617|ref|NP_391444.1|', 3 hits)
    -

    These keyword arguments differs among file formats. Check the format +

    These keyword arguments differs among file formats. Check the format documentation to see if it has keyword arguments that modifies its parser’s -behavior.

    As for the Bio.SearchIO.parse, it is used for reading search output +behavior.

    As for the Bio.SearchIO.parse, it is used for reading search output files with any number of queries. The function returns a generator object that -yields a QueryResult object in each iteration. Like -Bio.SearchIO.read, it also accepts format-specific keyword arguments:

    >>> from Bio import SearchIO
    +yields a QueryResult object in each iteration. Like
    +Bio.SearchIO.read, it also accepts format-specific keyword arguments:

    >>> from Bio import SearchIO
     >>> qresults = SearchIO.parse('tab_2226_tblastn_001.txt', 'blast-tab')
     >>> for qresult in qresults:
    -...     print qresult.id
    +...     print(qresult.id)
     gi|16080617|ref|NP_391444.1|
     gi|11464971:4-101
     >>> qresults2 = SearchIO.parse('tab_2226_tblastn_005.txt', 'blast-tab', comments=True)
     >>> for qresult in qresults2:
    -...     print qresult.id
    +...     print(qresult.id)
     random_s00
     gi|16080617|ref|NP_391444.1|
     gi|11464971:4-101
    -
    -

    8.4  Dealing with large search output files with indexing

    -

    Sometimes, you’re handed a search output file containing hundreds or thousands +

    + +

    8.4  Dealing with large search output files with indexing

    +

    Sometimes, you’re handed a search output file containing hundreds or thousands of queries that you need to parse. You can of course use -Bio.SearchIO.parse for this file, but that would be grossly inefficient -if you need to access only a few of the queries. This is because parse -will parse all queries it sees before it fetches your query of interest.

    In this case, the ideal choice would be to index the file using -Bio.SearchIO.index or Bio.SearchIO.index_db. If the names sound -familiar, it’s because you’ve seen them before in Section 5.4.2. -These functions also behave similarly to their Bio.SeqIO counterparts, -with the addition of format-specific keyword arguments.

    Here are some examples. You can use index with just the filename and -format name:

    >>> from Bio import SearchIO
    +Bio.SearchIO.parse for this file, but that would be grossly inefficient
    +if you need to access only a few of the queries. This is because parse
    +will parse all queries it sees before it fetches your query of interest.

    In this case, the ideal choice would be to index the file using +Bio.SearchIO.index or Bio.SearchIO.index_db. If the names sound +familiar, it’s because you’ve seen them before in Section 5.4.2. +These functions also behave similarly to their Bio.SeqIO counterparts, +with the addition of format-specific keyword arguments.

    Here are some examples. You can use index with just the filename and +format name:

    >>> from Bio import SearchIO
     >>> idx = SearchIO.index('tab_2226_tblastn_001.txt', 'blast-tab')
     >>> sorted(idx.keys())
     ['gi|11464971:4-101', 'gi|16080617|ref|NP_391444.1|']
     >>> idx['gi|16080617|ref|NP_391444.1|']
     QueryResult(id='gi|16080617|ref|NP_391444.1|', 3 hits)
    -

    Or also with the format-specific keyword argument:

    >>> idx = SearchIO.index('tab_2226_tblastn_005.txt', 'blast-tab', comments=True)
    +

    Or also with the format-specific keyword argument:

    >>> idx = SearchIO.index('tab_2226_tblastn_005.txt', 'blast-tab', comments=True)
     >>> sorted(idx.keys())
     ['gi|11464971:4-101', 'gi|16080617|ref|NP_391444.1|', 'random_s00']
     >>> idx['gi|16080617|ref|NP_391444.1|']
     QueryResult(id='gi|16080617|ref|NP_391444.1|', 3 hits)
    -

    Or with the key_function argument, as in Bio.SeqIO:

    >>> key_function = lambda id: id.upper()    # capitalizes the keys
    +

    Or with the key_function argument, as in Bio.SeqIO:

    >>> key_function = lambda id: id.upper()    # capitalizes the keys
     >>> idx = SearchIO.index('tab_2226_tblastn_001.txt', 'blast-tab', key_function=key_function)
     >>> sorted(idx.keys())
     ['GI|11464971:4-101', 'GI|16080617|REF|NP_391444.1|']
     >>> idx['GI|16080617|REF|NP_391444.1|']
     QueryResult(id='gi|16080617|ref|NP_391444.1|', 3 hits)
    -

    Bio.SearchIO.index_db works like as index, only it writes the -query offsets into an SQLite database file.

    -

    8.5  Writing and converting search output files

    -

    It is occasionally useful to be able to manipulate search results from an output -file and write it again to a new file. Bio.SearchIO provides a -write function that lets you do exactly this. It takes as its arguments -an iterable returning QueryResult objects, the output filename to write +

    Bio.SearchIO.index_db works like as index, only it writes the +query offsets into an SQLite database file.

    + +

    8.5  Writing and converting search output files

    +

    It is occasionally useful to be able to manipulate search results from an output +file and write it again to a new file. Bio.SearchIO provides a +write function that lets you do exactly this. It takes as its arguments +an iterable returning QueryResult objects, the output filename to write to, the format name to write to, and optionally some format-specific keyword arguments. It returns a four-item tuple, which denotes the number or -QueryResult, Hit, HSP, and HSPFragment objects that -were written.

    >>> from Bio import SearchIO
    +QueryResult, Hit, HSP, and HSPFragment objects that
    +were written.

    >>> from Bio import SearchIO
     >>> qresults = SearchIO.parse('mirna.xml', 'blast-xml')     # read XML file
     >>> SearchIO.write(qresults, 'results.tab', 'blast-tab')    # write to tabular file
     (3, 239, 277, 277)
    -

    You should note different file formats require different attributes of the -QueryResult, Hit, HSP and HSPFragment objects. If +

    You should note different file formats require different attributes of the +QueryResult, Hit, HSP and HSPFragment objects. If these attributes are not present, writing won’t work. In other words, you can’t always write to the output format that you want. For example, if you read a BLAST XML file, you wouldn’t be able to write the results to a PSL file as PSL files require attributes not calculated by BLAST (e.g. the number of repeat matches). You can always set these attributes manually, if you really want to -write to PSL, though.

    Like read, parse, index, and index_db, write +write to PSL, though.

    Like read, parse, index, and index_db, write also accepts format-specific keyword arguments. Check out the documentation for -a complete list of formats Bio.SearchIO can write to and their arguments.

    Finally, Bio.SearchIO also provides a convert function, which is -simply a shortcut for Bio.SearchIO.parse and Bio.SearchIO.write. -Using the convert function, our example above would be:

    >>> from Bio import SearchIO
    +a complete list of formats Bio.SearchIO can write to and their arguments.

    Finally, Bio.SearchIO also provides a convert function, which is +simply a shortcut for Bio.SearchIO.parse and Bio.SearchIO.write. +Using the convert function, our example above would be:

    >>> from Bio import SearchIO
     >>> SearchIO.convert('mirna.xml', 'blast-xml', 'results.tab', 'blast-tab')
     (3, 239, 277, 277)
    -

    As convert uses write, it is only limited to format conversions +

    As convert uses write, it is only limited to format conversions that have all the required attributes. Here, the BLAST XML file provides all the default values a BLAST tabular file requires, so it works just fine. However, other format conversions are less likely to work since you need to manually -assign the required attributes first.

    -

    Chapter 9  Accessing NCBI’s Entrez databases

    -

    Entrez (http://www.ncbi.nlm.nih.gov/Entrez) is a data retrieval system that provides users access to NCBI’s databases such as PubMed, GenBank, GEO, and many others. You can access Entrez from a web browser to manually enter queries, or you can use Biopython’s Bio.Entrez module for programmatic access to Entrez. The latter allows you for example to search PubMed or download GenBank records from within a Python script.

    The Bio.Entrez module makes use of the Entrez Programming Utilities (also known as EUtils), consisting of eight tools that are described in detail on NCBI’s page at http://www.ncbi.nlm.nih.gov/entrez/utils/. -Each of these tools corresponds to one Python function in the Bio.Entrez module, as described in the sections below. This module makes sure that the correct URL is used for the queries, and that not more than one request is made every three seconds, as required by NCBI.

    The output returned by the Entrez Programming Utilities is typically in XML format. To parse such output, you have several options: -

    1. -Use Bio.Entrez’s parser to parse the XML output into a Python object; -
    2. Use the DOM (Document Object Model) parser in Python’s standard library; -
    3. Use the SAX (Simple API for XML) parser in Python’s standard library; -
    4. Read the XML output as raw text, and parse it by string searching and manipulation. -

    -For the DOM and SAX parsers, see the Python documentation. The parser in Bio.Entrez is discussed below.

    NCBI uses DTD (Document Type Definition) files to describe the structure of the information contained in XML files. Most of the DTD files used by NCBI are included in the Biopython distribution. The Bio.Entrez parser makes use of the DTD files when parsing an XML file returned by NCBI Entrez.

    Occasionally, you may find that the DTD file associated with a specific XML file is missing in the Biopython distribution. In particular, this may happen when NCBI updates its DTD files. If this happens, Entrez.read will show a warning message with the name and URL of the missing DTD file. The parser will proceed to access the missing DTD file through the internet, allowing the parsing of the XML file to continue. However, the parser is much faster if the DTD file is available locally. For this purpose, please download the DTD file from the URL in the warning message and place it in the directory ...site-packages/Bio/Entrez/DTDs, containing the other DTD files. If you don’t have write access to this directory, you can also place the DTD file in ~/.biopython/Bio/Entrez/DTDs, where ~ represents your home directory. Since this directory is read before the directory ...site-packages/Bio/Entrez/DTDs, you can also put newer versions of DTD files there if the ones in ...site-packages/Bio/Entrez/DTDs become outdated. Alternatively, if you installed Biopython from source, you can add the DTD file to the source code’s Bio/Entrez/DTDs directory, and reinstall Biopython. This will install the new DTD file in the correct location together with the other DTD files.

    The Entrez Programming Utilities can also generate output in other formats, such as the Fasta or GenBank file formats for sequence databases, or the MedLine format for the literature database, discussed in Section 9.12.

    -

    9.1  Entrez Guidelines

    - -Before using Biopython to access the NCBI’s online resources (via Bio.Entrez or some of the other modules), please read the -NCBI’s Entrez User Requirements. -If the NCBI finds you are abusing their systems, they can and will ban your access!

    To paraphrase:

    • +assign the required attributes first.

      + +

      Chapter 9  Accessing NCBI’s Entrez databases

      +

      Entrez (http://www.ncbi.nlm.nih.gov/Entrez) is a data retrieval system that provides users access to NCBI’s databases such as PubMed, GenBank, GEO, and many others. You can access Entrez from a web browser to manually enter queries, or you can use Biopython’s Bio.Entrez module for programmatic access to Entrez. The latter allows you for example to search PubMed or download GenBank records from within a Python script.

      The Bio.Entrez module makes use of the Entrez Programming Utilities (also known as EUtils), consisting of eight tools that are described in detail on NCBI’s page at http://www.ncbi.nlm.nih.gov/entrez/utils/. +Each of these tools corresponds to one Python function in the Bio.Entrez module, as described in the sections below. This module makes sure that the correct URL is used for the queries, and that not more than one request is made every three seconds, as required by NCBI.

      The output returned by the Entrez Programming Utilities is typically in XML format. To parse such output, you have several options: +

      1. +Use Bio.Entrez’s parser to parse the XML output into a Python object; +
      2. Use the DOM (Document Object Model) parser in Python’s standard library; +
      3. Use the SAX (Simple API for XML) parser in Python’s standard library; +
      4. Read the XML output as raw text, and parse it by string searching and manipulation. +

      +For the DOM and SAX parsers, see the Python documentation. The parser in Bio.Entrez is discussed below.

      NCBI uses DTD (Document Type Definition) files to describe the structure of the information contained in XML files. Most of the DTD files used by NCBI are included in the Biopython distribution. The Bio.Entrez parser makes use of the DTD files when parsing an XML file returned by NCBI Entrez.

      Occasionally, you may find that the DTD file associated with a specific XML file is missing in the Biopython distribution. In particular, this may happen when NCBI updates its DTD files. If this happens, Entrez.read will show a warning message with the name and URL of the missing DTD file. The parser will proceed to access the missing DTD file through the internet, allowing the parsing of the XML file to continue. However, the parser is much faster if the DTD file is available locally. For this purpose, please download the DTD file from the URL in the warning message and place it in the directory ...site-packages/Bio/Entrez/DTDs, containing the other DTD files. If you don’t have write access to this directory, you can also place the DTD file in ~/.biopython/Bio/Entrez/DTDs, where ~ represents your home directory. Since this directory is read before the directory ...site-packages/Bio/Entrez/DTDs, you can also put newer versions of DTD files there if the ones in ...site-packages/Bio/Entrez/DTDs become outdated. Alternatively, if you installed Biopython from source, you can add the DTD file to the source code’s Bio/Entrez/DTDs directory, and reinstall Biopython. This will install the new DTD file in the correct location together with the other DTD files.

      The Entrez Programming Utilities can also generate output in other formats, such as the Fasta or GenBank file formats for sequence databases, or the MedLine format for the literature database, discussed in Section 9.12.

      + +

      9.1  Entrez Guidelines

      + +Before using Biopython to access the NCBI’s online resources (via Bio.Entrez or some of the other modules), please read the +NCBI’s Entrez User Requirements. +If the NCBI finds you are abusing their systems, they can and will ban your access!

      To paraphrase:

      • For any series of more than 100 requests, do this at weekends or outside USA peak times. This is up to you to obey. -
      • Use the http://eutils.ncbi.nlm.nih.gov address, not the standard NCBI Web address. Biopython uses this web address. -
      • Make no more than three requests every seconds (relaxed from at most one request every three seconds in early 2009). This is automatically enforced by Biopython. -
      • Use the optional email parameter so the NCBI can contact you if there is a problem. You can either explicitly set this as a parameter with each call to Entrez (e.g. include email="A.N.Other@example.com" in the argument list), or you can set a global email address: -
        >>> from Bio import Entrez
        +
      • Use the http://eutils.ncbi.nlm.nih.gov address, not the standard NCBI Web address. Biopython uses this web address. +
      • Make no more than three requests every seconds (relaxed from at most one request every three seconds in early 2009). This is automatically enforced by Biopython. +
      • Use the optional email parameter so the NCBI can contact you if there is a problem. You can either explicitly set this as a parameter with each call to Entrez (e.g. include email="A.N.Other@example.com" in the argument list), or you can set a global email address: +
        >>> from Bio import Entrez
         >>> Entrez.email = "A.N.Other@example.com"
        -
        Bio.Entrez will then use this email address with each call to Entrez. The example.com address is a reserved domain name specifically for documentation (RFC 2606). Please DO NOT use a random email – it’s better not to give an email at all. The email parameter will be mandatory from June 1, 2010. In case of excessive usage, NCBI will attempt to contact a user at the e-mail address provided prior to blocking access to the E-utilities. -
      • If you are using Biopython within some larger software suite, use the tool parameter to specify this. You can either explicitly set the tool name as a parameter with each call to Entrez (e.g. include tool="MyLocalScript" in the argument list), or you can set a global tool name: -
        >>> from Bio import Entrez
        +
        Bio.Entrez will then use this email address with each call to Entrez. The example.com address is a reserved domain name specifically for documentation (RFC 2606). Please DO NOT use a random email – it’s better not to give an email at all. The email parameter will be mandatory from June 1, 2010. In case of excessive usage, NCBI will attempt to contact a user at the e-mail address provided prior to blocking access to the E-utilities. +
      • If you are using Biopython within some larger software suite, use the tool parameter to specify this. You can either explicitly set the tool name as a parameter with each call to Entrez (e.g. include tool="MyLocalScript" in the argument list), or you can set a global tool name: +
        >>> from Bio import Entrez
         >>> Entrez.tool = "MyLocalScript"
        -
        The tool parameter will default to Biopython. -
      • For large queries, the NCBI also recommend using their session history feature (the WebEnv session cookie string, see Section 9.15). This is only slightly more complicated. -

      In conclusion, be sensible with your usage levels. If you plan to download lots of data, consider other options. For example, if you want easy access to all the human genes, consider fetching each chromosome by FTP as a GenBank file, and importing these into your own BioSQL database (see Section 18.5).

      -

      9.2  EInfo: Obtaining information about the Entrez databases

      - +The tool parameter will default to Biopython. +

    • For large queries, the NCBI also recommend using their session history feature (the WebEnv session cookie string, see Section 9.15). This is only slightly more complicated. +

    In conclusion, be sensible with your usage levels. If you plan to download lots of data, consider other options. For example, if you want easy access to all the human genes, consider fetching each chromosome by FTP as a GenBank file, and importing these into your own BioSQL database (see Section 18.5).

    + +

    9.2  EInfo: Obtaining information about the Entrez databases

    + EInfo provides field index term counts, last update, and available links for each of NCBI’s databases. In addition, you can use EInfo to obtain a list of all database names accessible through the Entrez utilities: -

    >>> from Bio import Entrez
    +

    >>> from Bio import Entrez
     >>> Entrez.email = "A.N.Other@example.com"     # Always tell NCBI who you are
     >>> handle = Entrez.einfo()
     >>> result = handle.read()
    -

    The variable result now contains a list of databases in XML format: -

    >>> print result
    +

    The variable result now contains a list of databases in XML format: +

    >>> print(result)
     <?xml version="1.0"?>
     <!DOCTYPE eInfoResult PUBLIC "-//NLM//DTD eInfoResult, 11 May 2002//EN"
      "http://www.ncbi.nlm.nih.gov/entrez/query/DTD/eInfo_020511.dtd">
    @@ -4463,23 +4588,23 @@
             <DbName>unists</DbName>
     </DbList>
     </eInfoResult>
    -

    Since this is a fairly simple XML file, we could extract the information it contains simply by string searching. Using Bio.Entrez’s parser instead, we can directly parse this XML file into a Python object: -

    >>> from Bio import Entrez
    +

    Since this is a fairly simple XML file, we could extract the information it contains simply by string searching. Using Bio.Entrez’s parser instead, we can directly parse this XML file into a Python object: +

    >>> from Bio import Entrez
     >>> handle = Entrez.einfo()
     >>> record = Entrez.read(handle)
    -

    Now record is a dictionary with exactly one key: -

    >>> record.keys()
    +

    Now record is a dictionary with exactly one key: +

    >>> record.keys()
     [u'DbList']
    -

    The values stored in this key is the list of database names shown in the XML above: -

    >>> record["DbList"]
    +

    The values stored in this key is the list of database names shown in the XML above: +

    >>> record["DbList"]
     ['pubmed', 'protein', 'nucleotide', 'nuccore', 'nucgss', 'nucest',
      'structure', 'genome', 'books', 'cancerchromosomes', 'cdd', 'gap',
      'domains', 'gene', 'genomeprj', 'gensat', 'geo', 'gds', 'homologene',
      'journals', 'mesh', 'ncbisearch', 'nlmcatalog', 'omia', 'omim', 'pmc',
      'popset', 'probe', 'proteinclusters', 'pcassay', 'pccompound',
      'pcsubstance', 'snp', 'taxonomy', 'toolkit', 'unigene', 'unists']
    -

    For each of these databases, we can use EInfo again to obtain more information: -

    >>> handle = Entrez.einfo(db="pubmed")
    +

    For each of these databases, we can use EInfo again to obtain more information: +

    >>> handle = Entrez.einfo(db="pubmed")
     >>> record = Entrez.read(handle)
     >>> record["DbInfo"]["Description"]
     'PubMed bibliographic record'
    @@ -4487,9 +4612,9 @@
     '17989604'
     >>> record["DbInfo"]["LastUpdate"]
     '2008/05/24 06:45'
    -

    Try record["DbInfo"].keys() for other information stored in this record. -One of the most useful is a list of possible search fields for use with ESearch:

    >>> for field in record["DbInfo"]["FieldList"]:
    -...     print "%(Name)s, %(FullName)s, %(Description)s" % field
    +

    Try record["DbInfo"].keys() for other information stored in this record. +One of the most useful is a list of possible search fields for use with ESearch:

    >>> for field in record["DbInfo"]["FieldList"]:
    +...     print("%(Name)s, %(FullName)s, %(Description)s" % field)
     ALL, All Fields, All terms from all searchable fields
     UID, UID, Unique number assigned to publication
     FILT, Filter, Limits the records
    @@ -4501,32 +4626,33 @@
     JOUR, Journal, Journal abbreviation of publication
     AFFL, Affiliation, Author's institutional affiliation and address
     ...
    -

    That’s a long list, but indirectly this tells you that for the PubMed -database, you can do things like Jones[AUTH] to search the -author field, or Sanger[AFFL] to restrict to authors at the +

    That’s a long list, but indirectly this tells you that for the PubMed +database, you can do things like Jones[AUTH] to search the +author field, or Sanger[AFFL] to restrict to authors at the Sanger Centre. This can be very handy - especially if you are not so -familiar with a particular database.

    -

    9.3  ESearch: Searching the Entrez databases

    - -To search any of these databases, we use Bio.Entrez.esearch(). For example, let’s search in PubMed for publications related to Biopython: -

    >>> from Bio import Entrez
    +familiar with a particular database.

    + +

    9.3  ESearch: Searching the Entrez databases

    + +To search any of these databases, we use Bio.Entrez.esearch(). For example, let’s search in PubMed for publications related to Biopython: +

    >>> from Bio import Entrez
     >>> Entrez.email = "A.N.Other@example.com"     # Always tell NCBI who you are
     >>> handle = Entrez.esearch(db="pubmed", term="biopython")
     >>> record = Entrez.read(handle)
     >>> record["IdList"]
     ['19304878', '18606172', '16403221', '16377612', '14871861', '14630660', '12230038']
    -

    In this output, you see seven PubMed IDs (including 19304878 which is the PMID for the Biopython application note), which can be retrieved by EFetch (see section 9.6).

    You can also use ESearch to search GenBank. Here we’ll do a quick -search for the matK gene in Cypripedioideae orchids -(see Section 9.2 about EInfo for one way to -find out which fields you can search in each Entrez database):

    >>> handle = Entrez.esearch(db="nucleotide",term="Cypripedioideae[Orgn] AND matK[Gene]")
    +

    In this output, you see seven PubMed IDs (including 19304878 which is the PMID for the Biopython application note), which can be retrieved by EFetch (see section 9.6).

    You can also use ESearch to search GenBank. Here we’ll do a quick +search for the matK gene in Cypripedioideae orchids +(see Section 9.2 about EInfo for one way to +find out which fields you can search in each Entrez database):

    >>> handle = Entrez.esearch(db="nucleotide", term="Cypripedioideae[Orgn] AND matK[Gene]")
     >>> record = Entrez.read(handle)
     >>> record["Count"]
     '25'
     >>> record["IdList"]
     ['126789333', '37222967', '37222966', '37222965', ..., '61585492']
    -

    Each of the IDs (126789333, 37222967, 37222966, …) is a GenBank identifier. -See section 9.6 for information on how to actually download these GenBank records.

    Note that instead of a species name like Cypripedioideae[Orgn], you can restrict the search using an NCBI taxon identifier, here this would be txid158330[Orgn]. This isn’t currently documented on the ESearch help page - the NCBI explained this in reply to an email query. You can often deduce the search term formatting by playing with the Entrez web interface. For example, including complete[prop] in a genome search restricts to just completed genomes.

    As a final example, let’s get a list of computational journal titles: -

    >>> handle = Entrez.esearch(db="journals", term="computational")
    +

    Each of the IDs (126789333, 37222967, 37222966, …) is a GenBank identifier. +See section 9.6 for information on how to actually download these GenBank records.

    Note that instead of a species name like Cypripedioideae[Orgn], you can restrict the search using an NCBI taxon identifier, here this would be txid158330[Orgn]. This isn’t currently documented on the ESearch help page - the NCBI explained this in reply to an email query. You can often deduce the search term formatting by playing with the Entrez web interface. For example, including complete[prop] in a genome search restricts to just completed genomes.

    As a final example, let’s get a list of computational journal titles: +

    >>> handle = Entrez.esearch(db="journals", term="computational")
     >>> record = Entrez.read(handle)
     >>> record["Count"]
     '16'
    @@ -4534,23 +4660,24 @@
     ['30367', '33843', '33823', '32989', '33190', '33009', '31986',
      '34502', '8799', '22857', '32675', '20258', '33859', '32534',
      '32357', '32249']
    -

    Again, we could use EFetch to obtain more information for each of these journal IDs.

    ESearch has many useful options — see the ESearch help page for more information.

    -

    9.4  EPost: Uploading a list of identifiers

    +

    Again, we could use EFetch to obtain more information for each of these journal IDs.

    ESearch has many useful options — see the ESearch help page for more information.

    + +

    9.4  EPost: Uploading a list of identifiers

    EPost uploads a list of UIs for use in subsequent search strategies; see the -EPost help page for more information. It is available from Biopython through -the Bio.Entrez.epost() function.

    To give an example of when this is useful, suppose you have a long list of IDs +EPost help page for more information. It is available from Biopython through +the Bio.Entrez.epost() function.

    To give an example of when this is useful, suppose you have a long list of IDs you want to download using EFetch (maybe sequences, maybe citations – anything). When you make a request with EFetch your list of IDs, the database etc, are all turned into a long URL sent to the server. If your list of IDs is long, this URL gets long, and long URLs can break (e.g. some proxies don’t -cope well).

    Instead, you can break this up into two steps, first uploading the list of IDs +cope well).

    Instead, you can break this up into two steps, first uploading the list of IDs using EPost (this uses an “HTML post” internally, rather than an “HTML get”, getting round the long URL problem). With the history support, you can then -refer to this long list of IDs, and download the associated data with EFetch.

    Let’s look at a simple example to see how EPost works – uploading some PubMed identifiers: -

    >>> from Bio import Entrez
    +refer to this long list of IDs, and download the associated data with EFetch.

    Let’s look at a simple example to see how EPost works – uploading some PubMed identifiers: +

    >>> from Bio import Entrez
     >>> Entrez.email = "A.N.Other@example.com"     # Always tell NCBI who you are
     >>> id_list = ["19304878", "18606172", "16403221", "16377612", "14871861", "14630660"]
    ->>> print Entrez.epost("pubmed", id=",".join(id_list)).read()
    +>>> print(Entrez.epost("pubmed", id=",".join(id_list)).read())
     <?xml version="1.0"?>
     <!DOCTYPE ePostResult PUBLIC "-//NLM//DTD ePostResult, 11 May 2002//EN"
      "http://www.ncbi.nlm.nih.gov/entrez/query/DTD/ePost_020511.dtd">
    @@ -4558,18 +4685,19 @@
      <QueryKey>1</QueryKey>
      <WebEnv>NCID_01_206841095_130.14.22.101_9001_1242061629</WebEnv>
     </ePostResult>
    -

    The returned XML includes two important strings, QueryKey and WebEnv which together define your history session. +

    The returned XML includes two important strings, QueryKey and WebEnv which together define your history session. You would extract these values for use with another Entrez call such as EFetch: -

    >>> from Bio import Entrez
    +

    >>> from Bio import Entrez
     >>> Entrez.email = "A.N.Other@example.com"     # Always tell NCBI who you are
     >>> id_list = ["19304878", "18606172", "16403221", "16377612", "14871861", "14630660"]
     >>> search_results = Entrez.read(Entrez.epost("pubmed", id=",".join(id_list)))
     >>> webenv = search_results["WebEnv"]
     >>> query_key = search_results["QueryKey"] 
    -

    Section 9.15 shows how to use the history feature.

    -

    9.5  ESummary: Retrieving summaries from primary IDs

    -ESummary retrieves document summaries from a list of primary IDs (see the ESummary help page for more information). In Biopython, ESummary is available as Bio.Entrez.esummary(). Using the search result above, we can for example find out more about the journal with ID 30367: -

    >>> from Bio import Entrez
    +

    Section 9.15 shows how to use the history feature.

    + +

    9.5  ESummary: Retrieving summaries from primary IDs

    +ESummary retrieves document summaries from a list of primary IDs (see the ESummary help page for more information). In Biopython, ESummary is available as Bio.Entrez.esummary(). Using the search result above, we can for example find out more about the journal with ID 30367: +

    >>> from Bio import Entrez
     >>> Entrez.email = "A.N.Other@example.com"     # Always tell NCBI who you are
     >>> handle = Entrez.esummary(db="journals", id="30367")
     >>> record = Entrez.read(handle)
    @@ -4579,13 +4707,14 @@
     'Computational biology and chemistry'
     >>> record[0]["Publisher"]
     'Pergamon,'
    -
    -

    9.6  EFetch: Downloading full records from Entrez

    -

    EFetch is what you use when you want to retrieve a full record from Entrez. -This covers several possible databases, as described on the main EFetch Help page.

    For most of their databases, the NCBI support several different file formats. Requesting a specific file format from Entrez using Bio.Entrez.efetch() requires specifying the rettype and/or retmode optional arguments. The different combinations are described for each database type on the pages linked to on NCBI efetch webpage (e.g. literature, sequences and taxonomy).

    One common usage is downloading sequences in the FASTA or GenBank/GenPept plain text formats (which can then be parsed with Bio.SeqIO, see Sections 5.3.1 and 9.6). From the Cypripedioideae example above, we can download GenBank record 186972394 using Bio.Entrez.efetch:

    >>> from Bio import Entrez
    +
    + +

    9.6  EFetch: Downloading full records from Entrez

    +

    EFetch is what you use when you want to retrieve a full record from Entrez. +This covers several possible databases, as described on the main EFetch Help page.

    For most of their databases, the NCBI support several different file formats. Requesting a specific file format from Entrez using Bio.Entrez.efetch() requires specifying the rettype and/or retmode optional arguments. The different combinations are described for each database type on the pages linked to on NCBI efetch webpage (e.g. literature, sequences and taxonomy).

    One common usage is downloading sequences in the FASTA or GenBank/GenPept plain text formats (which can then be parsed with Bio.SeqIO, see Sections 5.3.1 and 9.6). From the Cypripedioideae example above, we can download GenBank record 186972394 using Bio.Entrez.efetch:

    >>> from Bio import Entrez
     >>> Entrez.email = "A.N.Other@example.com"     # Always tell NCBI who you are
     >>> handle = Entrez.efetch(db="nucleotide", id="186972394", rettype="gb", retmode="text")
    ->>> print handle.read()
    +>>> print(handle.read())
     LOCUS       EU490707                1302 bp    DNA     linear   PLN 05-MAY-2008
     DEFINITION  Selenipedium aequinoctiale maturase K (matK) gene, partial cds;
                 chloroplast.
    @@ -4656,22 +4785,22 @@
          1201 tcgtgtgcta gaactttggc acggaaacat aaaagtacag tacgcacttt tatgcgaaga
          1261 ttaggttcgg gattattaga agaattcttt atggaagaag aa
     //
    -

    The arguments rettype="gb" and retmode="text" let us download this record in the GenBank format.

    Note that until Easter 2009, the Entrez EFetch API let you use “genbank” as the +

    The arguments rettype="gb" and retmode="text" let us download this record in the GenBank format.

    Note that until Easter 2009, the Entrez EFetch API let you use “genbank” as the return type, however the NCBI now insist on using the official return types of “gb” or “gbwithparts” (or “gp” for proteins) as described on online. Also not that until Feb 2012, the Entrez EFetch API would default to returning -plain text files, but now defaults to XML.

    Alternatively, you could for example use rettype="fasta" to get the Fasta-format; see the EFetch Sequences Help page for other options. Remember – the available formats depend on which database you are downloading from - see the main EFetch Help page.

    If you fetch the record in one of the formats accepted by Bio.SeqIO (see Chapter 5), you could directly parse it into a SeqRecord:

    >>> from Bio import Entrez, SeqIO
    ->>> handle = Entrez.efetch(db="nucleotide", id="186972394",rettype="gb", retmode="text")
    +plain text files, but now defaults to XML.

    Alternatively, you could for example use rettype="fasta" to get the Fasta-format; see the EFetch Sequences Help page for other options. Remember – the available formats depend on which database you are downloading from - see the main EFetch Help page.

    If you fetch the record in one of the formats accepted by Bio.SeqIO (see Chapter 5), you could directly parse it into a SeqRecord:

    >>> from Bio import Entrez, SeqIO
    +>>> handle = Entrez.efetch(db="nucleotide", id="186972394", rettype="gb", retmode="text")
     >>> record = SeqIO.read(handle, "genbank")
     >>> handle.close()
    ->>> print record
    +>>> print(record)
     ID: EU490707.1
     Name: EU490707
     Description: Selenipedium aequinoctiale maturase K (matK) gene, partial cds; chloroplast.
     Number of features: 3
     ...
     Seq('ATTTTTTACGAACCTGTGGAAATTTTTGGTTATGACAATAAATCTAGTTTAGTA...GAA', IUPACAmbiguousDNA())
    -

    Note that a more typical use would be to save the sequence data to a local file, and then parse it with Bio.SeqIO. This can save you having to re-download the same file repeatedly while working on your script, and places less load on the NCBI’s servers. For example:

    import os
    +

    Note that a more typical use would be to save the sequence data to a local file, and then parse it with Bio.SeqIO. This can save you having to re-download the same file repeatedly while working on your script, and places less load on the NCBI’s servers. For example:

    import os
     from Bio import SeqIO
     from Bio import Entrez
     Entrez.email = "A.N.Other@example.com"     # Always tell NCBI who you are
    @@ -4683,12 +4812,12 @@
         out_handle.write(net_handle.read())
         out_handle.close()
         net_handle.close()
    -    print "Saved"
    +    print("Saved")
     
    -print "Parsing..."
    +print("Parsing...")
     record = SeqIO.read(filename, "genbank")
    -print record
    -

    To get the output in XML format, which you can parse using the Bio.Entrez.read() function, use retmode="xml":

    >>> from Bio import Entrez
    +print(record)
    +

    To get the output in XML format, which you can parse using the Bio.Entrez.read() function, use retmode="xml":

    >>> from Bio import Entrez
     >>> handle = Entrez.efetch(db="nucleotide", id="186972394", retmode="xml")
     >>> record = Entrez.read(handle)
     >>> handle.close()
    @@ -4696,36 +4825,38 @@
     'Selenipedium aequinoctiale maturase K (matK) gene, partial cds; chloroplast'
     >>> record[0]["GBSeq_source"] 
     'chloroplast Selenipedium aequinoctiale'
    -

    So, that dealt with sequences. For examples of parsing file formats specific to the other databases (e.g. the MEDLINE format used in PubMed), see Section 9.12.

    If you want to perform a search with Bio.Entrez.esearch(), and then download the records with Bio.Entrez.efetch(), you should use the WebEnv history feature – see Section 9.15.

    -

    9.7  ELink: Searching for related items in NCBI Entrez

    -

    ELink, available from Biopython as Bio.Entrez.elink(), can be used to find related items in the NCBI Entrez databases. For example, you can us this to find nucleotide entries for an entry in the gene database, -and other cool stuff.

    Let’s use ELink to find articles related to the Biopython application note published in Bioinformatics in 2009. The PubMed ID of this article is 19304878:

    >>> from Bio import Entrez
    +

    So, that dealt with sequences. For examples of parsing file formats specific to the other databases (e.g. the MEDLINE format used in PubMed), see Section 9.12.

    If you want to perform a search with Bio.Entrez.esearch(), and then download the records with Bio.Entrez.efetch(), you should use the WebEnv history feature – see Section 9.15.

    + +

    9.7  ELink: Searching for related items in NCBI Entrez

    +

    ELink, available from Biopython as Bio.Entrez.elink(), can be used to find related items in the NCBI Entrez databases. For example, you can us this to find nucleotide entries for an entry in the gene database, +and other cool stuff.

    Let’s use ELink to find articles related to the Biopython application note published in Bioinformatics in 2009. The PubMed ID of this article is 19304878:

    >>> from Bio import Entrez
     >>> Entrez.email = "A.N.Other@example.com"
     >>> pmid = "19304878"
     >>> record = Entrez.read(Entrez.elink(dbfrom="pubmed", id=pmid))
    -

    The record variable consists of a Python list, one for each database in which we searched. Since we specified only one PubMed ID to search for, record contains only one item. This item is a dictionary containing information about our search term, as well as all the related items that were found:

    >>> record[0]["DbFrom"]
    +

    The record variable consists of a Python list, one for each database in which we searched. Since we specified only one PubMed ID to search for, record contains only one item. This item is a dictionary containing information about our search term, as well as all the related items that were found:

    >>> record[0]["DbFrom"]
     'pubmed'
     >>> record[0]["IdList"]
     ['19304878']
    -

    The "LinkSetDb" key contains the search results, stored as a list consisting of one item for each target database. In our search results, we only find hits in the PubMed database (although sub-divided into categories):

    >>> len(record[0]["LinkSetDb"])
    +

    The "LinkSetDb" key contains the search results, stored as a list consisting of one item for each target database. In our search results, we only find hits in the PubMed database (although sub-divided into categories):

    >>> len(record[0]["LinkSetDb"])
     5
     >>> for linksetdb in record[0]["LinkSetDb"]:
    -...     print linksetdb["DbTo"], linksetdb["LinkName"], len(linksetdb["Link"])
    +...     print(linksetdb["DbTo"], linksetdb["LinkName"], len(linksetdb["Link"]))
     ... 
     pubmed pubmed_pubmed 110
     pubmed pubmed_pubmed_combined 6
     pubmed pubmed_pubmed_five 6
     pubmed pubmed_pubmed_reviews 5
     pubmed pubmed_pubmed_reviews_five 5
    -

    The actual search results are stored as under the "Link" key. In total, 110 items were found under +

    The actual search results are stored as under the "Link" key. In total, 110 items were found under standard search. Let’s now at the first search result: -

    >>> record[0]["LinkSetDb"][0]["Link"][0]
    +

    >>> record[0]["LinkSetDb"][0]["Link"][0]
     {u'Id': '19304878'}
    -

    This is the article we searched for, which doesn’t help us much, so let’s look at the second search result:

    >>> record[0]["LinkSetDb"][0]["Link"][1]
    +

    This is the article we searched for, which doesn’t help us much, so let’s look at the second search result:

    >>> record[0]["LinkSetDb"][0]["Link"][1]
     {u'Id': '14630660'}
    -

    This paper, with PubMed ID 14630660, is about the Biopython PDB parser.

    We can use a loop to print out all PubMed IDs: -

    >>> for link in record[0]["LinkSetDb"][0]["Link"] : print link["Id"]
    +

    This paper, with PubMed ID 14630660, is about the Biopython PDB parser.

    We can use a loop to print out all PubMed IDs: +

    >>> for link in record[0]["LinkSetDb"][0]["Link"]:
    +...     print(link["Id"])
     19304878
     14630660
     18689808
    @@ -4733,23 +4864,26 @@
     16377612
     12368254
     ......
    -

    Now that was nice, but personally I am often more interested to find out if a paper has been cited. -Well, ELink can do that too – at least for journals in Pubmed Central (see Section 9.15.3).

    For help on ELink, see the ELink help page. -There is an entire sub-page just for the link names, describing how different databases can be cross referenced.

    -

    9.8  EGQuery: Global Query - counts for search terms

    -EGQuery provides counts for a search term in each of the Entrez databases (i.e. a global query). This is particularly useful to find out how many items your search terms would find in each database without actually performing lots of separate searches with ESearch (see the example in 9.14.2 below).

    In this example, we use Bio.Entrez.egquery() to obtain the counts for “Biopython”:

    >>> from Bio import Entrez
    +

    Now that was nice, but personally I am often more interested to find out if a paper has been cited. +Well, ELink can do that too – at least for journals in Pubmed Central (see Section 9.15.3).

    For help on ELink, see the ELink help page. +There is an entire sub-page just for the link names, describing how different databases can be cross referenced.

    + +

    9.8  EGQuery: Global Query - counts for search terms

    +EGQuery provides counts for a search term in each of the Entrez databases (i.e. a global query). This is particularly useful to find out how many items your search terms would find in each database without actually performing lots of separate searches with ESearch (see the example in 9.14.2 below).

    In this example, we use Bio.Entrez.egquery() to obtain the counts for “Biopython”:

    >>> from Bio import Entrez
     >>> Entrez.email = "A.N.Other@example.com"     # Always tell NCBI who you are
     >>> handle = Entrez.egquery(term="biopython")
     >>> record = Entrez.read(handle)
    ->>> for row in record["eGQueryResult"]: print row["DbName"], row["Count"]
    -...
    +>>> for row in record["eGQueryResult"]:
    +...     print(row["DbName"], row["Count"])
    +... 
     pubmed 6
     pmc 62
     journals 0
     ...
    -

    See the EGQuery help page for more information.

    -

    9.9  ESpell: Obtaining spelling suggestions

    -ESpell retrieves spelling suggestions. In this example, we use Bio.Entrez.espell() to obtain the correct spelling of Biopython:

    >>> from Bio import Entrez
    +

    See the EGQuery help page for more information.

    + +

    9.9  ESpell: Obtaining spelling suggestions

    +ESpell retrieves spelling suggestions. In this example, we use Bio.Entrez.espell() to obtain the correct spelling of Biopython:

    >>> from Bio import Entrez
     >>> Entrez.email = "A.N.Other@example.com"     # Always tell NCBI who you are
     >>> handle = Entrez.espell(term="biopythooon")
     >>> record = Entrez.read(handle)
    @@ -4757,10 +4891,11 @@
     'biopythooon'
     >>> record["CorrectedQuery"]
     'biopython'
    -

    See the ESpell help page for more information. -The main use of this is for GUI tools to provide automatic suggestions for search terms.

    -

    9.10  Parsing huge Entrez XML files

    The Entrez.read function reads the entire XML file returned by Entrez into a single Python object, which is kept in memory. To parse Entrez XML files too large to fit in memory, you can use the function Entrez.parse. This is a generator function that reads records in the XML file one by one. This function is only useful if the XML file reflects a Python list object (in other words, if Entrez.read on a computer with infinite memory resources would return a Python list).

    For example, you can download the entire Entrez Gene database for a given organism as a file from NCBI’s ftp site. These files can be very large. As an example, on September 4, 2009, the file Homo_sapiens.ags.gz, containing the Entrez Gene database for human, had a size of 116576 kB. This file, which is in the ASN format, can be converted into an XML file using NCBI’s gene2xml program (see NCBI’s ftp site for more information):

    gene2xml -b T -i Homo_sapiens.ags -o Homo_sapiens.xml
    -

    The resulting XML file has a size of 6.1 GB. Attempting Entrez.read on this file will result in a MemoryError on many computers.

    The XML file Homo_sapiens.xml consists of a list of Entrez gene records, each corresponding to one Entrez gene in human. Entrez.parse retrieves these gene records one by one. You can then print out or store the relevant information in each record by iterating over the records. For example, this script iterates over the Entrez gene records and prints out the gene numbers and names for all current genes:

    >>> from Bio import Entrez
    +

    See the ESpell help page for more information. +The main use of this is for GUI tools to provide automatic suggestions for search terms.

    + +

    9.10  Parsing huge Entrez XML files

    The Entrez.read function reads the entire XML file returned by Entrez into a single Python object, which is kept in memory. To parse Entrez XML files too large to fit in memory, you can use the function Entrez.parse. This is a generator function that reads records in the XML file one by one. This function is only useful if the XML file reflects a Python list object (in other words, if Entrez.read on a computer with infinite memory resources would return a Python list).

    For example, you can download the entire Entrez Gene database for a given organism as a file from NCBI’s ftp site. These files can be very large. As an example, on September 4, 2009, the file Homo_sapiens.ags.gz, containing the Entrez Gene database for human, had a size of 116576 kB. This file, which is in the ASN format, can be converted into an XML file using NCBI’s gene2xml program (see NCBI’s ftp site for more information):

    gene2xml -b T -i Homo_sapiens.ags -o Homo_sapiens.xml
    +

    The resulting XML file has a size of 6.1 GB. Attempting Entrez.read on this file will result in a MemoryError on many computers.

    The XML file Homo_sapiens.xml consists of a list of Entrez gene records, each corresponding to one Entrez gene in human. Entrez.parse retrieves these gene records one by one. You can then print out or store the relevant information in each record by iterating over the records. For example, this script iterates over the Entrez gene records and prints out the gene numbers and names for all current genes:

    >>> from Bio import Entrez
     >>> handle = open("Homo_sapiens.xml")
     >>> records = Entrez.parse(handle)
     
    @@ -4770,9 +4905,9 @@
     ...         continue
     ...     geneid = record['Entrezgene_track-info']['Gene-track']['Gene-track_geneid']
     ...     genename = record['Entrezgene_gene']['Gene-ref']['Gene-ref_locus']
    -...     print geneid, genename
    -

    This will print: -

    1 A1BG
    +...     print(geneid, genename)
    +

    This will print: +

    1 A1BG
     2 A2M
     3 A2MP
     8 AA
    @@ -4786,14 +4921,15 @@
     16 AARS
     17 AAVS1
     ...
    -
    -

    9.11  Handling errors

    Three things can go wrong when parsing an XML file: -

    • +
    + +

    9.11  Handling errors

    Three things can go wrong when parsing an XML file: +

    • The file may not be an XML file to begin with; -
    • The file may end prematurely or otherwise be corrupted; -
    • The file may be correct XML, but contain items that are not represented in the associated DTD. -

    The first case occurs if, for example, you try to parse a Fasta file as if it were an XML file: -

    >>> from Bio import Entrez
    +
  • The file may end prematurely or otherwise be corrupted; +
  • The file may be correct XML, but contain items that are not represented in the associated DTD. +
  • The first case occurs if, for example, you try to parse a Fasta file as if it were an XML file: +

    >>> from Bio import Entrez
     >>> handle = open("NC_005816.fna") # a Fasta file
     >>> record = Entrez.read(handle)
     Traceback (most recent call last):
    @@ -4803,9 +4939,9 @@
       File "/usr/local/lib/python2.7/site-packages/Bio/Entrez/Parser.py", line 164, in read
         raise NotXMLError(e)
     Bio.Entrez.Parser.NotXMLError: Failed to parse the XML data (syntax error: line 1, column 0). Please make sure that the input data are in XML format.
    -

    Here, the parser didn’t find the <?xml ... tag with which an XML file is supposed to start, and therefore decides (correctly) that the file is not an XML file.

    When your file is in the XML format but is corrupted (for example, by ending prematurely), the parser will raise a CorruptedXMLError. +

    Here, the parser didn’t find the <?xml ... tag with which an XML file is supposed to start, and therefore decides (correctly) that the file is not an XML file.

    When your file is in the XML format but is corrupted (for example, by ending prematurely), the parser will raise a CorruptedXMLError. Here is an example of an XML file that ends prematurely: -

    <?xml version="1.0"?>
    +

    <?xml version="1.0"?>
     <!DOCTYPE eInfoResult PUBLIC "-//NLM//DTD eInfoResult, 11 May 2002//EN" "http://www.ncbi.nlm.nih.gov/entrez/query/DTD/eInfo_020511.dtd">
     <eInfoResult>
     <DbList>
    @@ -4820,8 +4956,8 @@
             <DbName>books</DbName>
             <DbName>cancerchromosomes</DbName>
             <DbName>cdd</DbName>
    -

    which will generate the following traceback: -

    >>> Entrez.read(handle)
    +

    which will generate the following traceback: +

    >>> Entrez.read(handle)
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
       File "/usr/local/lib/python2.7/site-packages/Bio/Entrez/__init__.py", line 257, in read
    @@ -4831,7 +4967,7 @@
     Bio.Entrez.Parser.CorruptedXMLError: Failed to parse the XML data (no element found: line 16, column 0). Please make sure that the input data are not corrupted.
     
     >>>
    -

    Note that the error message tells you at what point in the XML file the error was detected.

    The third type of error occurs if the XML file contains tags that do not have a description in the corresponding DTD file. This is an example of such an XML file:

    <?xml version="1.0"?>
    +

    Note that the error message tells you at what point in the XML file the error was detected.

    The third type of error occurs if the XML file contains tags that do not have a description in the corresponding DTD file. This is an example of such an XML file:

    <?xml version="1.0"?>
     <!DOCTYPE eInfoResult PUBLIC "-//NLM//DTD eInfoResult, 11 May 2002//EN" "http://www.ncbi.nlm.nih.gov/entrez/query/DTD/eInfo_020511.dtd">
     <eInfoResult>
             <DbInfo>
    @@ -4856,7 +4992,7 @@
     ...
             </DbInfo>
     </eInfoResult>
    -

    In this file, for some reason the tag <DocsumList> (and several others) are not listed in the DTD file eInfo_020511.dtd, which is specified on the second line as the DTD for this XML file. By default, the parser will stop and raise a ValidationError if it cannot find some tag in the DTD:

    >>> from Bio import Entrez
    +

    In this file, for some reason the tag <DocsumList> (and several others) are not listed in the DTD file eInfo_020511.dtd, which is specified on the second line as the DTD for this XML file. By default, the parser will stop and raise a ValidationError if it cannot find some tag in the DTD:

    >>> from Bio import Entrez
     >>> handle = open("einfo3.xml")
     >>> record = Entrez.read(handle)
     Traceback (most recent call last):
    @@ -4868,17 +5004,19 @@
       File "/usr/local/lib/python2.7/site-packages/Bio/Entrez/Parser.py", line 246, in startElementHandler
         raise ValidationError(name)
     Bio.Entrez.Parser.ValidationError: Failed to find tag 'DocsumList' in the DTD. To skip all tags that are not represented in the DTD, please call Bio.Entrez.read or Bio.Entrez.parse with validate=False.
    -

    Optionally, you can instruct the parser to skip such tags instead of raising a ValidationError. This is done by calling Entrez.read or Entrez.parse with the argument validate equal to False: -

    >>> from Bio import Entrez
    +

    Optionally, you can instruct the parser to skip such tags instead of raising a ValidationError. This is done by calling Entrez.read or Entrez.parse with the argument validate equal to False: +

    >>> from Bio import Entrez
     >>> handle = open("einfo3.xml")
    ->>> record = Entrez.read(handle,validate=False)
    +>>> record = Entrez.read(handle, validate=False)
     >>>
    -

    Of course, the information contained in the XML tags that are not in the DTD are not present in the record returned by Entrez.read.

    -

    9.12  Specialized parsers

    -

    The Bio.Entrez.read() function can parse most (if not all) XML output returned by Entrez. Entrez typically allows you to retrieve records in other formats, which may have some advantages compared to the XML format in terms of readability (or download size).

    To request a specific file format from Entrez using Bio.Entrez.efetch() requires specifying the rettype and/or retmode optional arguments. The different combinations are described for each database type on the NCBI efetch webpage.

    One obvious case is you may prefer to download sequences in the FASTA or GenBank/GenPept plain text formats (which can then be parsed with Bio.SeqIO, see Sections 5.3.1 and 9.6). For the literature databases, Biopython contains a parser for the MEDLINE format used in PubMed.

    -

    9.12.1  Parsing Medline records

    - -You can find the Medline parser in Bio.Medline. Suppose we want to parse the file pubmed_result1.txt, containing one Medline record. You can find this file in Biopython’s Tests\Medline directory. The file looks like this:

    PMID- 12230038
    +

    Of course, the information contained in the XML tags that are not in the DTD are not present in the record returned by Entrez.read.

    + +

    9.12  Specialized parsers

    +

    The Bio.Entrez.read() function can parse most (if not all) XML output returned by Entrez. Entrez typically allows you to retrieve records in other formats, which may have some advantages compared to the XML format in terms of readability (or download size).

    To request a specific file format from Entrez using Bio.Entrez.efetch() requires specifying the rettype and/or retmode optional arguments. The different combinations are described for each database type on the NCBI efetch webpage.

    One obvious case is you may prefer to download sequences in the FASTA or GenBank/GenPept plain text formats (which can then be parsed with Bio.SeqIO, see Sections 5.3.1 and 9.6). For the literature databases, Biopython contains a parser for the MEDLINE format used in PubMed.

    + +

    9.12.1  Parsing Medline records

    + +You can find the Medline parser in Bio.Medline. Suppose we want to parse the file pubmed_result1.txt, containing one Medline record. You can find this file in Biopython’s Tests\Medline directory. The file looks like this:

    PMID- 12230038
     OWN - NLM
     STAT- MEDLINE
     DA  - 20020916
    @@ -4894,14 +5032,14 @@
     AB  - Bioinformatics research is often difficult to do with commercial software. The
           Open Source BioPerl, BioPython and Biojava projects provide toolkits with
     ...
    -

    We first open the file and then parse it: -

    >>> from Bio import Medline
    +

    We first open the file and then parse it: +

    >>> from Bio import Medline
     >>> input = open("pubmed_result1.txt")
     >>> record = Medline.read(input)
    -

    The record now contains the Medline record as a Python dictionary: -

    >>> record["PMID"]
    +

    The record now contains the Medline record as a Python dictionary: +

    >>> record["PMID"]
     '12230038'
    -
    >>> record["AB"]
    +
    >>> record["AB"]
     'Bioinformatics research is often difficult to do with commercial software.
     The Open Source BioPerl, BioPython and Biojava projects provide toolkits with
     multiple functionality that make it easier to create customised pipelines or
    @@ -4909,33 +5047,33 @@
     and the functionality, documentation, utility and relative advantages of the
     Bio counterparts, particularly from the point of view of the beginning
     biologist programmer.'
    -

    The key names used in a Medline record can be rather obscure; use -

    >>> help(record)
    -

    for a brief summary.

    To parse a file containing multiple Medline records, you can use the parse function instead: -

    >>> from Bio import Medline
    +

    The key names used in a Medline record can be rather obscure; use +

    >>> help(record)
    +

    for a brief summary.

    To parse a file containing multiple Medline records, you can use the parse function instead: +

    >>> from Bio import Medline
     >>> input = open("pubmed_result2.txt")
     >>> records = Medline.parse(input)
     >>> for record in records:
    -...     print record["TI"]
    +...     print(record["TI"])
     A high level interface to SCOP and ASTRAL implemented in python.
     GenomeDiagram: a python package for the visualization of large-scale genomic data.
     Open source clustering software.
     PDB file parser and structure class implemented in Python.
    -

    Instead of parsing Medline records stored in files, you can also parse Medline records downloaded by Bio.Entrez.efetch. For example, let’s look at all Medline records in PubMed related to Biopython: -

    >>> from Bio import Entrez
    +

    Instead of parsing Medline records stored in files, you can also parse Medline records downloaded by Bio.Entrez.efetch. For example, let’s look at all Medline records in PubMed related to Biopython: +

    >>> from Bio import Entrez
     >>> Entrez.email = "A.N.Other@example.com"     # Always tell NCBI who you are
    ->>> handle = Entrez.esearch(db="pubmed",term="biopython")
    +>>> handle = Entrez.esearch(db="pubmed", term="biopython")
     >>> record = Entrez.read(handle)
     >>> record["IdList"]
     ['19304878', '18606172', '16403221', '16377612', '14871861', '14630660', '12230038']
    -

    We now use Bio.Entrez.efetch to download these Medline records: -

    >>> idlist = record["IdList"]
    ->>> handle = Entrez.efetch(db="pubmed",id=idlist,rettype="medline",retmode="text")
    -

    Here, we specify rettype="medline", retmode="text" to obtain the Medline records in plain-text Medline format. Now we use Bio.Medline to parse these records: -

    >>> from Bio import Medline
    +

    We now use Bio.Entrez.efetch to download these Medline records: +

    >>> idlist = record["IdList"]
    +>>> handle = Entrez.efetch(db="pubmed", id=idlist, rettype="medline", retmode="text")
    +

    Here, we specify rettype="medline", retmode="text" to obtain the Medline records in plain-text Medline format. Now we use Bio.Medline to parse these records: +

    >>> from Bio import Medline
     >>> records = Medline.parse(handle)
     >>> for record in records:
    -...     print record["AU"]
    +...     print(record["AU"])
     ['Cock PJ', 'Antao T', 'Chang JT', 'Chapman BA', 'Cox CJ', 'Dalke A', ..., 'de Hoon MJ']
     ['Munteanu CR', 'Gonzalez-Diaz H', 'Magalhaes AL']
     ['Casbon JA', 'Crooks GE', 'Saqi MA']
    @@ -4943,12 +5081,12 @@
     ['de Hoon MJ', 'Imoto S', 'Nolan J', 'Miyano S']
     ['Hamelryck T', 'Manderick B']
     ['Mangalam H']
    -

    For comparison, here we show an example using the XML format: -

    >>> idlist = record["IdList"]
    ->>> handle = Entrez.efetch(db="pubmed",id=idlist,rettype="medline",retmode="xml")
    +

    For comparison, here we show an example using the XML format: +

    >>> idlist = record["IdList"]
    +>>> handle = Entrez.efetch(db="pubmed", id=idlist, rettype="medline", retmode="xml")
     >>> records = Entrez.read(handle)
     >>> for record in records:
    -...     print record["MedlineCitation"]["Article"]["ArticleTitle"]
    +...     print(record["MedlineCitation"]["Article"]["ArticleTitle"])
     Biopython: freely available Python tools for computational molecular biology and
      bioinformatics.
     Enzymes/non-enzymes classification model complexity based on composition, sequence,
    @@ -4958,35 +5096,37 @@
     Open source clustering software.
     PDB file parser and structure class implemented in Python.
     The Bio* toolkits--a brief overview.
    -

    Note that in both of these examples, for simplicity we have naively combined ESearch and EFetch. +

    Note that in both of these examples, for simplicity we have naively combined ESearch and EFetch. In this situation, the NCBI would expect you to use their history feature, -as illustrated in Section 9.15.

    -

    9.12.2  Parsing GEO records

    GEO (Gene Expression Omnibus) +as illustrated in Section 9.15.

    + +

    9.12.2  Parsing GEO records

    GEO (Gene Expression Omnibus) is a data repository of high-throughput gene expression and hybridization -array data. The Bio.Geo module can be used to parse GEO-formatted -data.

    The following code fragment shows how to parse the example GEO file -GSE16.txt into a record and print the record:

    >>> from Bio import Geo
    +array data. The Bio.Geo module can be used to parse GEO-formatted
    +data.

    The following code fragment shows how to parse the example GEO file +GSE16.txt into a record and print the record:

    >>> from Bio import Geo
     >>> handle = open("GSE16.txt")
     >>> records = Geo.parse(handle)
     >>> for record in records:
    -...     print record
    -

    You can search the “gds” database (GEO datasets) with ESearch:

    >>> from Bio import Entrez
    +...     print(record)
    +

    You can search the “gds” database (GEO datasets) with ESearch:

    >>> from Bio import Entrez
     >>> Entrez.email = "A.N.Other@example.com" # Always tell NCBI who you are
    ->>> handle = Entrez.esearch(db="gds",term="GSE16")
    +>>> handle = Entrez.esearch(db="gds", term="GSE16")
     >>> record = Entrez.read(handle)
     >>> record["Count"]
     2
     >>> record["IdList"]
     ['200000016', '100000028']
    -

    From the Entrez website, UID “200000016” is GDS16 while the other hit +

    From the Entrez website, UID “200000016” is GDS16 while the other hit “100000028” is for the associated platform, GPL28. Unfortunately, at the time of writing the NCBI don’t seem to support downloading GEO files using -Entrez (not as XML, nor in the Simple Omnibus Format in Text (SOFT) -format).

    However, it is actually pretty straight forward to download the GEO files by FTP -from ftp://ftp.ncbi.nih.gov/pub/geo/ instead. In this case you might want -ftp://ftp.ncbi.nih.gov/pub/geo/DATA/SOFT/by_series/GSE16/GSE16_family.soft.gz -(a compressed file, see the Python module gzip).

    -

    9.12.3  Parsing UniGene records

    UniGene is an NCBI database of the transcriptome, with each UniGene record showing the set of transcripts that are associated with a particular gene in a specific organism. A typical UniGene record looks like this:

    ID          Hs.2
    +Entrez (not as XML, nor in the Simple Omnibus Format in Text (SOFT)
    +format).

    However, it is actually pretty straight forward to download the GEO files by FTP +from ftp://ftp.ncbi.nih.gov/pub/geo/ instead. In this case you might want +ftp://ftp.ncbi.nih.gov/pub/geo/DATA/SOFT/by_series/GSE16/GSE16_family.soft.gz +(a compressed file, see the Python module gzip).

    + +

    9.12.3  Parsing UniGene records

    UniGene is an NCBI database of the transcriptome, with each UniGene record showing the set of transcripts that are associated with a particular gene in a specific organism. A typical UniGene record looks like this:

    ID          Hs.2
     TITLE       N-acetyltransferase 2 (arylamine N-acetyltransferase)
     GENE        NAT2
     CYTOBAND    8p22
    @@ -5018,125 +5158,129 @@
     ...
     SEQUENCE    ACC=AU099534.1; NID=g13550663; CLONE=HSI08034; END=5'; LID=8800; SEQTYPE=EST
     //
    -

    This particular record shows the set of transcripts (shown in the SEQUENCE lines) that originate from the human gene NAT2, encoding en N-acetyltransferase. The PROTSIM lines show proteins with significant similarity to NAT2, whereas the STS lines show the corresponding sequence-tagged sites in the genome.

    To parse UniGene files, use the Bio.UniGene module: -

    >>> from Bio import UniGene
    +

    This particular record shows the set of transcripts (shown in the SEQUENCE lines) that originate from the human gene NAT2, encoding en N-acetyltransferase. The PROTSIM lines show proteins with significant similarity to NAT2, whereas the STS lines show the corresponding sequence-tagged sites in the genome.

    To parse UniGene files, use the Bio.UniGene module: +

    >>> from Bio import UniGene
     >>> input = open("myunigenefile.data")
     >>> record = UniGene.read(input)
    -

    The record returned by UniGene.read is a Python object with attributes corresponding to the fields in the UniGene record. For example, -

    >>> record.ID
    +

    The record returned by UniGene.read is a Python object with attributes corresponding to the fields in the UniGene record. For example, +

    >>> record.ID
     "Hs.2"
     >>> record.title
     "N-acetyltransferase 2 (arylamine N-acetyltransferase)"
    -

    The EXPRESS and RESTR_EXPR lines are stored as Python lists of strings: -

    ['bone', 'connective tissue', 'intestine', 'liver', 'liver tumor', 'normal', 'soft tissue/muscle tissue tumor', 'adult']
    -

    Specialized objects are returned for the STS, PROTSIM, and SEQUENCE lines, storing the keys shown in each line as attributes: -

    >>> record.sts[0].acc
    +

    The EXPRESS and RESTR_EXPR lines are stored as Python lists of strings: +

    ['bone', 'connective tissue', 'intestine', 'liver', 'liver tumor', 'normal', 'soft tissue/muscle tissue tumor', 'adult']
    +

    Specialized objects are returned for the STS, PROTSIM, and SEQUENCE lines, storing the keys shown in each line as attributes: +

    >>> record.sts[0].acc
     'PMC310725P3'
     >>> record.sts[0].unists
     '272646'
    -

    and similarly for the PROTSIM and SEQUENCE lines.

    To parse a file containing more than one UniGene record, use the parse function in Bio.UniGene:

    >>> from Bio import UniGene
    +

    and similarly for the PROTSIM and SEQUENCE lines.

    To parse a file containing more than one UniGene record, use the parse function in Bio.UniGene:

    >>> from Bio import UniGene
     >>> input = open("unigenerecords.data")
     >>> records = UniGene.parse(input)
     >>> for record in records:
    -...     print record.ID
    -
    -

    9.13  Using a proxy

    Normally you won’t have to worry about using a proxy, but if this is an issue -on your network here is how to deal with it. Internally, Bio.Entrez -uses the standard Python library urllib for accessing the NCBI servers. -This will check an environment variable called http_proxy to configure +... print(record.ID) +

    + +

    9.13  Using a proxy

    Normally you won’t have to worry about using a proxy, but if this is an issue +on your network here is how to deal with it. Internally, Bio.Entrez +uses the standard Python library urllib for accessing the NCBI servers. +This will check an environment variable called http_proxy to configure any simple proxy automatically. Unfortunately this module does not support -the use of proxies which require authentication.

    You may choose to set the http_proxy environment variable once (how you +the use of proxies which require authentication.

    You may choose to set the http_proxy environment variable once (how you do this will depend on your operating system). Alternatively you can set this -within Python at the start of your script, for example:

    import os
    +within Python at the start of your script, for example:

    import os
     os.environ["http_proxy"] = "http://proxyhost.example.com:8080"
    -

    See the urllib documentation for more details.

    -

    9.14  Examples

    -

    -

    9.14.1  PubMed and Medline

    -

    If you are in the medical field or interested in human issues (and many times even if you are not!), PubMed (http://www.ncbi.nlm.nih.gov/PubMed/) is an excellent source of all kinds of goodies. So like other things, we’d like to be able to grab information from it and use it in Python scripts.

    In this example, we will query PubMed for all articles having to do with orchids (see section 2.3 for our motivation). We first check how many of such articles there are:

    >>> from Bio import Entrez
    +

    See the urllib documentation for more details.

    + +

    9.14  Examples

    +

    + +

    9.14.1  PubMed and Medline

    +

    If you are in the medical field or interested in human issues (and many times even if you are not!), PubMed (http://www.ncbi.nlm.nih.gov/PubMed/) is an excellent source of all kinds of goodies. So like other things, we’d like to be able to grab information from it and use it in Python scripts.

    In this example, we will query PubMed for all articles having to do with orchids (see section 2.3 for our motivation). We first check how many of such articles there are:

    >>> from Bio import Entrez
     >>> Entrez.email = "A.N.Other@example.com"     # Always tell NCBI who you are
     >>> handle = Entrez.egquery(term="orchid")
     >>> record = Entrez.read(handle)
     >>> for row in record["eGQueryResult"]:
     ...     if row["DbName"]=="pubmed":
    -...         print row["Count"]
    +...         print(row["Count"])
     463
    -

    Now we use the Bio.Entrez.efetch function to download the PubMed IDs of these 463 articles: -

    >>> handle = Entrez.esearch(db="pubmed", term="orchid", retmax=463)
    +

    Now we use the Bio.Entrez.efetch function to download the PubMed IDs of these 463 articles: +

    >>> handle = Entrez.esearch(db="pubmed", term="orchid", retmax=463)
     >>> record = Entrez.read(handle)
     >>> idlist = record["IdList"]
    ->>> print idlist
    -

    This returns a Python list containing all of the PubMed IDs of articles related to orchids: -

    ['18680603', '18665331', '18661158', '18627489', '18627452', '18612381',
    +>>> print(idlist)
    +

    This returns a Python list containing all of the PubMed IDs of articles related to orchids: +

    ['18680603', '18665331', '18661158', '18627489', '18627452', '18612381',
     '18594007', '18591784', '18589523', '18579475', '18575811', '18575690',
     ...
    -

    Now that we’ve got them, we obviously want to get the corresponding Medline records and extract the information from them. Here, we’ll download the Medline records in the Medline flat-file format, and use the Bio.Medline module to parse them: -

    >>> from Bio import Medline
    +

    Now that we’ve got them, we obviously want to get the corresponding Medline records and extract the information from them. Here, we’ll download the Medline records in the Medline flat-file format, and use the Bio.Medline module to parse them: +

    >>> from Bio import Medline
     >>> handle = Entrez.efetch(db="pubmed", id=idlist, rettype="medline",
                                retmode="text")
     >>> records = Medline.parse(handle)
    -

    NOTE - We’ve just done a separate search and fetch here, the NCBI much prefer you to take advantage of their history support in this situation. See Section 9.15.

    Keep in mind that records is an iterator, so you can iterate through the records only once. If you want to save the records, you can convert them to a list: -

    >>> records = list(records)
    -

    Let’s now iterate over the records to print out some information about each record: -

    >>> for record in records:
    -...     print "title:", record.get("TI", "?")
    -...     print "authors:", record.get("AU", "?")
    -...     print "source:", record.get("SO", "?")
    -...     print
    -

    The output for this looks like: -

    title: Sex pheromone mimicry in the early spider orchid (ophrys sphegodes):
    +

    NOTE - We’ve just done a separate search and fetch here, the NCBI much prefer you to take advantage of their history support in this situation. See Section 9.15.

    Keep in mind that records is an iterator, so you can iterate through the records only once. If you want to save the records, you can convert them to a list: +

    >>> records = list(records)
    +

    Let’s now iterate over the records to print out some information about each record: +

    >>> for record in records:
    +...     print("title:", record.get("TI", "?"))
    +...     print("authors:", record.get("AU", "?"))
    +...     print("source:", record.get("SO", "?"))
    +...     print("")
    +

    The output for this looks like: +

    title: Sex pheromone mimicry in the early spider orchid (ophrys sphegodes):
     patterns of hydrocarbons as the key mechanism for pollination by sexual
     deception [In Process Citation]
     authors: ['Schiestl FP', 'Ayasse M', 'Paulus HF', 'Lofstedt C', 'Hansson BS',
     'Ibarra F', 'Francke W']
     source: J Comp Physiol [A] 2000 Jun;186(6):567-74
    -

    Especially interesting to note is the list of authors, which is returned as a standard Python list. This makes it easy to manipulate and search using standard Python tools. For instance, we could loop through a whole bunch of entries searching for a particular author with code like the following: -

    >>> search_author = "Waits T"
    +

    Especially interesting to note is the list of authors, which is returned as a standard Python list. This makes it easy to manipulate and search using standard Python tools. For instance, we could loop through a whole bunch of entries searching for a particular author with code like the following: +

    >>> search_author = "Waits T"
     
     >>> for record in records:
     ...     if not "AU" in record:
     ...         continue
     ...     if search_author in record["AU"]:
    -...         print "Author %s found: %s" % (search_author, record["SO"])
    -

    Hopefully this section gave you an idea of the power and flexibility of the Entrez and Medline interfaces and how they can be used together.

    -

    9.14.2  Searching, downloading, and parsing Entrez Nucleotide records

    -

    Here we’ll show a simple example of performing a remote Entrez query. In section 2.3 of the parsing examples, we talked about using NCBI’s Entrez website to search the NCBI nucleotide databases for info on Cypripedioideae, our friends the lady slipper orchids. Now, we’ll look at how to automate that process using a Python script. In this example, we’ll just show how to connect, get the results, and parse them, with the Entrez module doing all of the work.

    First, we use EGQuery to find out the number of results we will get before actually downloading them. EGQuery will tell us how many search results were found in each of the databases, but for this example we are only interested in nucleotides: -

    >>> from Bio import Entrez
    +...         print("Author %s found: %s" % (search_author, record["SO"]))
    +

    Hopefully this section gave you an idea of the power and flexibility of the Entrez and Medline interfaces and how they can be used together.

    + +

    9.14.2  Searching, downloading, and parsing Entrez Nucleotide records

    +

    Here we’ll show a simple example of performing a remote Entrez query. In section 2.3 of the parsing examples, we talked about using NCBI’s Entrez website to search the NCBI nucleotide databases for info on Cypripedioideae, our friends the lady slipper orchids. Now, we’ll look at how to automate that process using a Python script. In this example, we’ll just show how to connect, get the results, and parse them, with the Entrez module doing all of the work.

    First, we use EGQuery to find out the number of results we will get before actually downloading them. EGQuery will tell us how many search results were found in each of the databases, but for this example we are only interested in nucleotides: +

    >>> from Bio import Entrez
     >>> Entrez.email = "A.N.Other@example.com"     # Always tell NCBI who you are
     >>> handle = Entrez.egquery(term="Cypripedioideae")
     >>> record = Entrez.read(handle)
     >>> for row in record["eGQueryResult"]:
     ...     if row["DbName"]=="nuccore":
    -...         print row["Count"]
    +...         print(row["Count"])
     814
    -

    So, we expect to find 814 Entrez Nucleotide records (this is the number I obtained in 2008; it is likely to increase in the future). If you find some ridiculously high number of hits, you may want to reconsider if you really want to download all of them, which is our next step: -

    >>> from Bio import Entrez
    +

    So, we expect to find 814 Entrez Nucleotide records (this is the number I obtained in 2008; it is likely to increase in the future). If you find some ridiculously high number of hits, you may want to reconsider if you really want to download all of them, which is our next step: +

    >>> from Bio import Entrez
     >>> handle = Entrez.esearch(db="nucleotide", term="Cypripedioideae", retmax=814)
     >>> record = Entrez.read(handle)
    -

    Here, record is a Python dictionary containing the search results and some auxiliary information. Just for information, let’s look at what is stored in this dictionary: -

    >>> print record.keys()
    +

    Here, record is a Python dictionary containing the search results and some auxiliary information. Just for information, let’s look at what is stored in this dictionary: +

    >>> print(record.keys())
     [u'Count', u'RetMax', u'IdList', u'TranslationSet', u'RetStart', u'QueryTranslation']
    -

    First, let’s check how many results were found: -

    >>> print record["Count"]
    +

    First, let’s check how many results were found: +

    >>> print(record["Count"])
     '814'
    -

    which is the number we expected. The 814 results are stored in record['IdList']: -

    >>> print len(record["IdList"])
    +

    which is the number we expected. The 814 results are stored in record['IdList']: +

    >>> len(record["IdList"])
     814
    -

    Let’s look at the first five results: -

    >>> print record["IdList"][:5]
    +

    Let’s look at the first five results: +

    >>> record["IdList"][:5]
     ['187237168', '187372713', '187372690', '187372688', '187372686']
    -

    -We can download these records using efetch. +

    +We can download these records using efetch. While you could download these records one by one, to reduce the load on NCBI’s servers, it is better to fetch a bunch of records at the same time, shown below. -However, in this situation you should ideally be using the history feature described later in Section 9.15.

    >>> idlist = ",".join(record["IdList"][:5])
    ->>> print idlist
    +However, in this situation you should ideally be using the history feature described later in Section 9.15.

    >>> idlist = ",".join(record["IdList"][:5])
    +>>> print(idlist)
     187237168,187372713,187372690,187372688,187372686
     >>> handle = Entrez.efetch(db="nucleotide", id=idlist, retmode="xml")
     >>> records = Entrez.read(handle)
    ->>> print len(records)
    +>>> len(records)
     5
    -

    Each of these records corresponds to one GenBank record. -

    >>> print records[0].keys()
    +

    Each of these records corresponds to one GenBank record. +

    >>> print(records[0].keys())
     [u'GBSeq_moltype', u'GBSeq_source', u'GBSeq_sequence',
      u'GBSeq_primary-accession', u'GBSeq_definition', u'GBSeq_accession-version',
      u'GBSeq_topology', u'GBSeq_length', u'GBSeq_feature-table',
    @@ -5144,41 +5288,42 @@
      u'GBSeq_taxonomy', u'GBSeq_references', u'GBSeq_update-date',
      u'GBSeq_organism', u'GBSeq_locus', u'GBSeq_strandedness']
     
    ->>> print records[0]["GBSeq_primary-accession"]
    +>>> print(records[0]["GBSeq_primary-accession"])
     DQ110336
     
    ->>> print records[0]["GBSeq_other-seqids"]
    +>>> print(records[0]["GBSeq_other-seqids"])
     ['gb|DQ110336.1|', 'gi|187237168']
     
    ->>> print records[0]["GBSeq_definition"]
    +>>> print(records[0]["GBSeq_definition"])
     Cypripedium calceolus voucher Davis 03-03 A maturase (matR) gene, partial cds;
     mitochondrial
     
    ->>> print records[0]["GBSeq_organism"]
    +>>> print(records[0]["GBSeq_organism"])
     Cypripedium calceolus
    -

    You could use this to quickly set up searches – but for heavy usage, see Section 9.15.

    -

    9.14.3  Searching, downloading, and parsing GenBank records

    -

    The GenBank record format is a very popular method of holding information about sequences, sequence features, and other associated sequence information. The format is a good way to get information from the NCBI databases at http://www.ncbi.nlm.nih.gov/.

    In this example we’ll show how to query the NCBI databases,to retrieve the records from the query, and then parse them using Bio.SeqIO - something touched on in Section 5.3.1. -For simplicity, this example does not take advantage of the WebEnv history feature – see Section 9.15 for this.

    First, we want to make a query and find out the ids of the records to retrieve. Here we’ll do a quick search for one of our favorite organisms, Opuntia (prickly-pear cacti). We can do quick search and get back the GIs (GenBank identifiers) for all of the corresponding records. First we check how many records there are:

    >>> from Bio import Entrez
    +

    You could use this to quickly set up searches – but for heavy usage, see Section 9.15.

    + +

    9.14.3  Searching, downloading, and parsing GenBank records

    +

    The GenBank record format is a very popular method of holding information about sequences, sequence features, and other associated sequence information. The format is a good way to get information from the NCBI databases at http://www.ncbi.nlm.nih.gov/.

    In this example we’ll show how to query the NCBI databases,to retrieve the records from the query, and then parse them using Bio.SeqIO - something touched on in Section 5.3.1. +For simplicity, this example does not take advantage of the WebEnv history feature – see Section 9.15 for this.

    First, we want to make a query and find out the ids of the records to retrieve. Here we’ll do a quick search for one of our favorite organisms, Opuntia (prickly-pear cacti). We can do quick search and get back the GIs (GenBank identifiers) for all of the corresponding records. First we check how many records there are:

    >>> from Bio import Entrez
     >>> Entrez.email = "A.N.Other@example.com"     # Always tell NCBI who you are
     >>> handle = Entrez.egquery(term="Opuntia AND rpl16")
     >>> record = Entrez.read(handle)
     >>> for row in record["eGQueryResult"]:
     ...     if row["DbName"]=="nuccore":
    -...         print row["Count"]
    +...         print(row["Count"])
     ...
     9
    -

    Now we download the list of GenBank identifiers: -

    >>> handle = Entrez.esearch(db="nuccore", term="Opuntia AND rpl16")
    +

    Now we download the list of GenBank identifiers: +

    >>> handle = Entrez.esearch(db="nuccore", term="Opuntia AND rpl16")
     >>> record = Entrez.read(handle)
     >>> gi_list = record["IdList"]
     >>> gi_list
     ['57240072', '57240071', '6273287', '6273291', '6273290', '6273289', '6273286',
     '6273285', '6273284']
    -

    Now we use these GIs to download the GenBank records - note that with older versions of Biopython you had to supply a comma separated list of GI numbers to Entrez, as of Biopython 1.59 you can pass a list and this is converted for you:

    >>> gi_str = ",".join(gi_list)
    +

    Now we use these GIs to download the GenBank records - note that with older versions of Biopython you had to supply a comma separated list of GI numbers to Entrez, as of Biopython 1.59 you can pass a list and this is converted for you:

    >>> gi_str = ",".join(gi_list)
     >>> handle = Entrez.efetch(db="nuccore", id=gi_str, rettype="gb", retmode="text")
    -

    If you want to look at the raw GenBank files, you can read from this handle and print out the result:

    >>> text = handle.read()
    ->>> print text
    +

    If you want to look at the raw GenBank files, you can read from this handle and print out the result:

    >>> text = handle.read()
    +>>> print(text)
     LOCUS       AY851612                 892 bp    DNA     linear   PLN 10-APR-2007
     DEFINITION  Opuntia subulata rpl16 gene, intron; chloroplast.
     ACCESSION   AY851612
    @@ -5192,13 +5337,13 @@
     REFERENCE   1  (bases 1 to 892)
       AUTHORS   Butterworth,C.A. and Wallace,R.S.
     ...
    -

    In this case, we are just getting the raw records. To get the records in a more Python-friendly form, we can use Bio.SeqIO to parse the GenBank data into SeqRecord objects, including SeqFeature objects (see Chapter 5):

    >>> from Bio import SeqIO
    +

    In this case, we are just getting the raw records. To get the records in a more Python-friendly form, we can use Bio.SeqIO to parse the GenBank data into SeqRecord objects, including SeqFeature objects (see Chapter 5):

    >>> from Bio import SeqIO
     >>> handle = Entrez.efetch(db="nuccore", id=gi_str, rettype="gb", retmode="text")
     >>> records = SeqIO.parse(handle, "gb")
    -

    We can now step through the records and look at the information we are interested in: -

    >>> for record in records: 
    ->>> ...    print "%s, length %i, with %i features" \
    ->>> ...           % (record.name, len(record), len(record.features))
    +

    We can now step through the records and look at the information we are interested in: +

    >>> for record in records: 
    +>>> ...    print("%s, length %i, with %i features" \
    +>>> ...           % (record.name, len(record), len(record.features)))
     AY851612, length 892, with 3 features
     AY851611, length 881, with 3 features
     AF191661, length 895, with 3 features
    @@ -5208,10 +5353,11 @@
     AF191660, length 893, with 3 features
     AF191659, length 894, with 3 features
     AF191658, length 896, with 3 features
    -

    Using these automated query retrieval functionality is a big plus over doing things by hand. Although the module should obey the NCBI’s max three queries per second rule, the NCBI have other recommendations like avoiding peak hours. See Section 9.1. -In particular, please note that for simplicity, this example does not use the WebEnv history feature. You should use this for any non-trivial search and download work, see Section 9.15.

    Finally, if plan to repeat your analysis, rather than downloading the files from the NCBI and parsing them immediately (as shown in this example), you should just download the records once and save them to your hard disk, and then parse the local file.

    -

    9.14.4  Finding the lineage of an organism

    Staying with a plant example, let’s now find the lineage of the Cypripedioideae orchid family. First, we search the Taxonomy database for Cypripedioideae, which yields exactly one NCBI taxonomy identifier: -

    >>> from Bio import Entrez
    +

    Using these automated query retrieval functionality is a big plus over doing things by hand. Although the module should obey the NCBI’s max three queries per second rule, the NCBI have other recommendations like avoiding peak hours. See Section 9.1. +In particular, please note that for simplicity, this example does not use the WebEnv history feature. You should use this for any non-trivial search and download work, see Section 9.15.

    Finally, if plan to repeat your analysis, rather than downloading the files from the NCBI and parsing them immediately (as shown in this example), you should just download the records once and save them to your hard disk, and then parse the local file.

    + +

    9.14.4  Finding the lineage of an organism

    Staying with a plant example, let’s now find the lineage of the Cypripedioideae orchid family. First, we search the Taxonomy database for Cypripedioideae, which yields exactly one NCBI taxonomy identifier: +

    >>> from Bio import Entrez
     >>> Entrez.email = "A.N.Other@example.com"     # Always tell NCBI who you are
     >>> handle = Entrez.esearch(db="Taxonomy", term="Cypripedioideae")
     >>> record = Entrez.read(handle)
    @@ -5219,53 +5365,55 @@
     ['158330']
     >>> record["IdList"][0]
     '158330'
    -

    Now, we use efetch to download this entry in the Taxonomy database, and then parse it: -

    >>> handle = Entrez.efetch(db="Taxonomy", id="158330", retmode="xml")
    +

    Now, we use efetch to download this entry in the Taxonomy database, and then parse it: +

    >>> handle = Entrez.efetch(db="Taxonomy", id="158330", retmode="xml")
     >>> records = Entrez.read(handle)
    -

    Again, this record stores lots of information: -

    >>> records[0].keys()
    +

    Again, this record stores lots of information: +

    >>> records[0].keys()
     [u'Lineage', u'Division', u'ParentTaxId', u'PubDate', u'LineageEx',
      u'CreateDate', u'TaxId', u'Rank', u'GeneticCode', u'ScientificName',
      u'MitoGeneticCode', u'UpdateDate']
    -

    We can get the lineage directly from this record: -

    >>> records[0]["Lineage"]
    +

    We can get the lineage directly from this record: +

    >>> records[0]["Lineage"]
     'cellular organisms; Eukaryota; Viridiplantae; Streptophyta; Streptophytina;
      Embryophyta; Tracheophyta; Euphyllophyta; Spermatophyta; Magnoliophyta;
      Liliopsida; Asparagales; Orchidaceae'
    -

    The record data contains much more than just the information shown here - for example look under "LineageEx" instead of "Lineage" and you’ll get the NCBI taxon identifiers of the lineage entries too.

    -

    9.15  Using the history and WebEnv

    -

    Often you will want to make a series of linked queries. Most typically, +

    The record data contains much more than just the information shown here - for example look under "LineageEx" instead of "Lineage" and you’ll get the NCBI taxon identifiers of the lineage entries too.

    + +

    9.15  Using the history and WebEnv

    +

    Often you will want to make a series of linked queries. Most typically, running a search, perhaps refining the search, and then retrieving detailed -search results. You can do this by making a series of separate calls +search results. You can do this by making a series of separate calls to Entrez. However, the NCBI prefer you to take advantage of their history -support - for example combining ESearch and EFetch.

    Another typical use of the history support would be to combine EPost and +support - for example combining ESearch and EFetch.

    Another typical use of the history support would be to combine EPost and EFetch. You use EPost to upload a list of identifiers, which starts a new history session. You then download the records with EFetch by referring -to the session (instead of the identifiers).

    -

    9.15.1  Searching for and downloading sequences using the history

    -Suppose we want to search and download all the Opuntia rpl16 +to the session (instead of the identifiers).

    + +

    9.15.1  Searching for and downloading sequences using the history

    +Suppose we want to search and download all the Opuntia rpl16 nucleotide sequences, and store them in a FASTA file. As shown in -Section 9.14.3, we can naively combine -Bio.Entrez.esearch() to get a list of GI numbers, and then call -Bio.Entrez.efetch() to download them all.

    However, the approved approach is to run the search with the history +Section 9.14.3, we can naively combine +Bio.Entrez.esearch() to get a list of GI numbers, and then call +Bio.Entrez.efetch() to download them all.

    However, the approved approach is to run the search with the history feature. Then, we can fetch the results by reference to the search -results - which the NCBI can anticipate and cache.

    To do this, call Bio.Entrez.esearch() as normal, but with the -additional argument of usehistory="y",

    >>> from Bio import Entrez
    +results - which the NCBI can anticipate and cache.

    To do this, call Bio.Entrez.esearch() as normal, but with the +additional argument of usehistory="y",

    >>> from Bio import Entrez
     >>> Entrez.email = "history.user@example.com"
     >>> search_handle = Entrez.esearch(db="nucleotide",term="Opuntia[orgn] and rpl16",
                                        usehistory="y")
     >>> search_results = Entrez.read(search_handle)
     >>> search_handle.close()
    -

    When you get the XML output back, it will still include the usual search results:

    >>> gi_list = search_results["IdList"]
    +

    When you get the XML output back, it will still include the usual search results:

    >>> gi_list = search_results["IdList"]
     >>> count = int(search_results["Count"])
     >>> assert count == len(gi_list)
    -

    However, you also get given two additional pieces of information, the WebEnv session cookie, and the QueryKey:

    >>> webenv = search_results["WebEnv"]
    +

    However, you also get given two additional pieces of information, the WebEnv session cookie, and the QueryKey:

    >>> webenv = search_results["WebEnv"]
     >>> query_key = search_results["QueryKey"] 
    -

    Having stored these values in variables session_cookie and query_key we can use them as parameters to Bio.Entrez.efetch() instead of giving the GI numbers as identifiers.

    While for small searches you might be OK downloading everything at once, it is better to download in batches. You use the retstart and retmax parameters to specify which range of search results you want returned (starting entry using zero-based counting, and maximum number of results to return). For example,

    batch_size = 3
    +

    Having stored these values in variables session_cookie and query_key we can use them as parameters to Bio.Entrez.efetch() instead of giving the GI numbers as identifiers.

    While for small searches you might be OK downloading everything at once, it is better to download in batches. You use the retstart and retmax parameters to specify which range of search results you want returned (starting entry using zero-based counting, and maximum number of results to return). For example,

    batch_size = 3
     out_handle = open("orchid_rpl16.fasta", "w")
     for start in range(0,count,batch_size):
         end = min(count, start+batch_size)
    -    print "Going to download record %i to %i" % (start+1, end)
    +    print("Going to download record %i to %i" % (start+1, end))
         fetch_handle = Entrez.efetch(db="nucleotide", rettype="fasta", retmode="text",
                                      retstart=start, retmax=batch_size,
                                      webenv=webenv, query_key=query_key)
    @@ -5273,22 +5421,23 @@
         fetch_handle.close()
         out_handle.write(data)
     out_handle.close()
    -

    For illustrative purposes, this example downloaded the FASTA records in batches of three. Unless you are downloading genomes or chromosomes, you would normally pick a larger batch size.

    -

    9.15.2  Searching for and downloading abstracts using the history

    -Here is another history example, searching for papers published in the last year about the Opuntia, and then downloading them into a file in MedLine format:

    from Bio import Entrez
    +

    For illustrative purposes, this example downloaded the FASTA records in batches of three. Unless you are downloading genomes or chromosomes, you would normally pick a larger batch size.

    + +

    9.15.2  Searching for and downloading abstracts using the history

    +Here is another history example, searching for papers published in the last year about the Opuntia, and then downloading them into a file in MedLine format:

    from Bio import Entrez
     Entrez.email = "history.user@example.com"
     search_results = Entrez.read(Entrez.esearch(db="pubmed",
                                                 term="Opuntia[ORGN]",
                                                 reldate=365, datetype="pdat",
                                                 usehistory="y"))
     count = int(search_results["Count"])
    -print "Found %i results" % count
    +print("Found %i results" % count)
     
     batch_size = 10
     out_handle = open("recent_orchid_papers.txt", "w")
     for start in range(0,count,batch_size):
         end = min(count, start+batch_size)
    -    print "Going to download record %i to %i" % (start+1, end)
    +    print("Going to download record %i to %i" % (start+1, end))
         fetch_handle = Entrez.efetch(db="pubmed",
                                      rettype="medline", retmode="text",
                                      retstart=start, retmax=batch_size,
    @@ -5298,12 +5447,13 @@
         fetch_handle.close()
         out_handle.write(data)
     out_handle.close()
    -

    At the time of writing, this gave 28 matches - but because this is a date dependent search, this will of course vary. As described in Section 9.12.1 above, you can then use Bio.Medline to parse the saved records.

    -

    9.15.3  Searching for citations

    -

    Back in Section 9.7 we mentioned ELink can be used to search for citations of a given paper. +

    At the time of writing, this gave 28 matches - but because this is a date dependent search, this will of course vary. As described in Section 9.12.1 above, you can then use Bio.Medline to parse the saved records.

    + +

    9.15.3  Searching for citations

    +

    Back in Section 9.7 we mentioned ELink can be used to search for citations of a given paper. Unfortunately this only covers journals indexed for PubMed Central (doing it for all the journals in PubMed would mean a lot more work for the NIH). -Let’s try this for the Biopython PDB parser paper, PubMed ID 14630660:

    >>> from Bio import Entrez
    +Let’s try this for the Biopython PDB parser paper, PubMed ID 14630660:

    >>> from Bio import Entrez
     >>> Entrez.email = "A.N.Other@example.com"
     >>> pmid = "14630660"
     >>> results = Entrez.read(Entrez.elink(dbfrom="pubmed", db="pmc",
    @@ -5311,59 +5461,62 @@
     >>> pmc_ids = [link["Id"] for link in results[0]["LinkSetDb"][0]["Link"]]
     >>> pmc_ids
     ['2744707', '2705363', '2682512', ..., '1190160']
    -

    Great - eleven articles. But why hasn’t the Biopython application note been +

    Great - eleven articles. But why hasn’t the Biopython application note been found (PubMed ID 19304878)? Well, as you might have guessed from the variable names, there are not actually PubMed IDs, but PubMed Central IDs. Our -application note is the third citing paper in that list, PMCID 2682512.

    So, what if (like me) you’d rather get back a list of PubMed IDs? Well we +application note is the third citing paper in that list, PMCID 2682512.

    So, what if (like me) you’d rather get back a list of PubMed IDs? Well we can call ELink again to translate them. This becomes a two step process, so by now you should expect to use the history feature to accomplish it -(Section 9.15).

    But first, taking the more straightforward approach of making a second -(separate) call to ELink:

    >>> results2 = Entrez.read(Entrez.elink(dbfrom="pmc", db="pubmed", LinkName="pmc_pubmed",
    +(Section 9.15).

    But first, taking the more straightforward approach of making a second +(separate) call to ELink:

    >>> results2 = Entrez.read(Entrez.elink(dbfrom="pmc", db="pubmed", LinkName="pmc_pubmed",
     ...                                     from_uid=",".join(pmc_ids)))
     >>> pubmed_ids = [link["Id"] for link in results2[0]["LinkSetDb"][0]["Link"]]
     >>> pubmed_ids
     ['19698094', '19450287', '19304878', ..., '15985178']
    -

    This time you can immediately spot the Biopython application note -as the third hit (PubMed ID 19304878).

    Now, let’s do that all again but with the history …TODO.

    And finally, don’t forget to include your own email address in the Entrez calls.

    -

    Chapter 10  Swiss-Prot and ExPASy

    -

    -

    10.1  Parsing Swiss-Prot files

    Swiss-Prot (http://www.expasy.org/sprot) is a hand-curated database of protein sequences. Biopython can parse the “plain text” Swiss-Prot file format, which is still used for the UniProt Knowledgebase which combined Swiss-Prot, TrEMBL and PIR-PSD. We do not (yet) support the UniProtKB XML file format.

    -

    10.1.1  Parsing Swiss-Prot records

    In Section 5.3.2, we described how to extract the sequence of a Swiss-Prot record as a SeqRecord object. Alternatively, you can store the Swiss-Prot record in a Bio.SwissProt.Record object, which in fact stores the complete information contained in the Swiss-Prot record. In this Section, we describe how to extract Bio.SwissProt.Record objects from a Swiss-Prot file.

    To parse a Swiss-Prot record, we first get a handle to a Swiss-Prot record. There are several ways to do so, depending on where and how the Swiss-Prot record is stored: -

    • -Open a Swiss-Prot file locally:
      ->>> handle = open("myswissprotfile.dat") -
    • Open a gzipped Swiss-Prot file: -
      >>> import gzip
      +

      This time you can immediately spot the Biopython application note +as the third hit (PubMed ID 19304878).

      Now, let’s do that all again but with the history …TODO.

      And finally, don’t forget to include your own email address in the Entrez calls.

      + +

      Chapter 10  Swiss-Prot and ExPASy

      +

      + +

      10.1  Parsing Swiss-Prot files

      Swiss-Prot (http://www.expasy.org/sprot) is a hand-curated database of protein sequences. Biopython can parse the “plain text” Swiss-Prot file format, which is still used for the UniProt Knowledgebase which combined Swiss-Prot, TrEMBL and PIR-PSD. We do not (yet) support the UniProtKB XML file format.

      + +

      10.1.1  Parsing Swiss-Prot records

      In Section 5.3.2, we described how to extract the sequence of a Swiss-Prot record as a SeqRecord object. Alternatively, you can store the Swiss-Prot record in a Bio.SwissProt.Record object, which in fact stores the complete information contained in the Swiss-Prot record. In this Section, we describe how to extract Bio.SwissProt.Record objects from a Swiss-Prot file.

      To parse a Swiss-Prot record, we first get a handle to a Swiss-Prot record. There are several ways to do so, depending on where and how the Swiss-Prot record is stored: +

      • +Open a Swiss-Prot file locally:
        +>>> handle = open("myswissprotfile.dat") +
      • Open a gzipped Swiss-Prot file: +
        >>> import gzip
         >>> handle = gzip.open("myswissprotfile.dat.gz")
        -
      • Open a Swiss-Prot file over the internet: -
        >>> import urllib
        +
      • Open a Swiss-Prot file over the internet: +
        >>> import urllib
         >>> handle = urllib.urlopen("http://www.somelocation.org/data/someswissprotfile.dat")
        -
      • Open a Swiss-Prot file over the internet from the ExPASy database -(see section 10.5.1): -
        >>> from Bio import ExPASy
        +
      • Open a Swiss-Prot file over the internet from the ExPASy database +(see section 10.5.1): +
        >>> from Bio import ExPASy
         >>> handle = ExPASy.get_sprot_raw(myaccessionnumber)
        -

      -The key point is that for the parser, it doesn’t matter how the handle was created, as long as it points to data in the Swiss-Prot format.

      We can use Bio.SeqIO as described in Section 5.3.2 to get file format agnostic SeqRecord objects. Alternatively, we can use Bio.SwissProt get Bio.SwissProt.Record objects, which are a much closer match to the underlying file format.

      To read one Swiss-Prot record from the handle, we use the function read(): -

      >>> from Bio import SwissProt
      +

    +The key point is that for the parser, it doesn’t matter how the handle was created, as long as it points to data in the Swiss-Prot format.

    We can use Bio.SeqIO as described in Section 5.3.2 to get file format agnostic SeqRecord objects. Alternatively, we can use Bio.SwissProt get Bio.SwissProt.Record objects, which are a much closer match to the underlying file format.

    To read one Swiss-Prot record from the handle, we use the function read(): +

    >>> from Bio import SwissProt
     >>> record = SwissProt.read(handle)
    -

    This function should be used if the handle points to exactly one Swiss-Prot record. It raises a ValueError if no Swiss-Prot record was found, and also if more than one record was found.

    We can now print out some information about this record: -

    >>> print record.description
    +

    This function should be used if the handle points to exactly one Swiss-Prot record. It raises a ValueError if no Swiss-Prot record was found, and also if more than one record was found.

    We can now print out some information about this record: +

    >>> print(record.description)
     'RecName: Full=Chalcone synthase 3; EC=2.3.1.74; AltName: Full=Naringenin-chalcone synthase 3;'
     >>> for ref in record.references:
    -...     print "authors:", ref.authors
    -...     print "title:", ref.title
    -...
    +...     print("authors:", ref.authors)
    +...     print("title:", ref.title)
    +... 
     authors: Liew C.F., Lim S.H., Loh C.S., Goh C.J.;
     title: "Molecular cloning and sequence analysis of chalcone synthase cDNAs of
     Bromheadia finlaysoniana.";
    ->>> print record.organism_classification
    +>>> print(record.organism_classification)
     ['Eukaryota', 'Viridiplantae', 'Streptophyta', 'Embryophyta', ..., 'Bromheadia']
    -

    To parse a file that contains more than one Swiss-Prot record, we use the parse function instead. This function allows us to iterate over the records in the file.

    For example, let’s parse the full Swiss-Prot database and collect all the descriptions. -You can download this from the ExPAYs FTP site as a single gzipped-file uniprot_sprot.dat.gz (about 300MB). This is a compressed file containing a single file, uniprot_sprot.dat (over 1.5GB).

    As described at the start of this section, you can use the Python library gzip to open and uncompress a .gz file, like this:

    >>> import gzip
    +

    To parse a file that contains more than one Swiss-Prot record, we use the parse function instead. This function allows us to iterate over the records in the file.

    For example, let’s parse the full Swiss-Prot database and collect all the descriptions. +You can download this from the ExPAYs FTP site as a single gzipped-file uniprot_sprot.dat.gz (about 300MB). This is a compressed file containing a single file, uniprot_sprot.dat (over 1.5GB).

    As described at the start of this section, you can use the Python library gzip to open and uncompress a .gz file, like this:

    >>> import gzip
     >>> handle = gzip.open("uniprot_sprot.dat.gz")
    -

    However, uncompressing a large file takes time, and each time you open the file for reading in this way, it has to be decompressed on the fly. So, if you can spare the disk space you’ll save time in the long run if you first decompress the file to disk, to get the uniprot_sprot.dat file inside. Then you can open the file for reading as usual:

    >>> handle = open("uniprot_sprot.dat")
    -

    As of June 2009, the full Swiss-Prot database downloaded from ExPASy contained 468851 Swiss-Prot records. One concise way to build up a list of the record descriptions is with a list comprehension: -

    >>> from Bio import SwissProt
    +

    However, uncompressing a large file takes time, and each time you open the file for reading in this way, it has to be decompressed on the fly. So, if you can spare the disk space you’ll save time in the long run if you first decompress the file to disk, to get the uniprot_sprot.dat file inside. Then you can open the file for reading as usual:

    >>> handle = open("uniprot_sprot.dat")
    +

    As of June 2009, the full Swiss-Prot database downloaded from ExPASy contained 468851 Swiss-Prot records. One concise way to build up a list of the record descriptions is with a list comprehension: +

    >>> from Bio import SwissProt
     >>> handle = open("uniprot_sprot.dat")
     >>> descriptions = [record.description for record in SwissProt.parse(handle)]
     >>> len(descriptions)
    @@ -5375,8 +5528,8 @@
      'RecName: Full=Protein MGF 100-1R;',
      'RecName: Full=Protein MGF 100-2L;']
     
    -

    Or, using a for loop over the record iterator: -

    >>> from Bio import SwissProt
    +

    Or, using a for loop over the record iterator: +

    >>> from Bio import SwissProt
     >>> descriptions = []
     >>> handle = open("uniprot_sprot.dat")
     >>> for record in SwissProt.parse(handle):
    @@ -5384,16 +5537,17 @@
     ...
     >>> len(descriptions)
     468851
    -

    Because this is such a large input file, either way takes about eleven minutes on my new desktop computer (using the uncompressed uniprot_sprot.dat file as input).

    It is equally easy to extract any kind of information you’d like from Swiss-Prot records. To see the members of a Swiss-Prot record, use -

    >>> dir(record)
    +

    Because this is such a large input file, either way takes about eleven minutes on my new desktop computer (using the uncompressed uniprot_sprot.dat file as input).

    It is equally easy to extract any kind of information you’d like from Swiss-Prot records. To see the members of a Swiss-Prot record, use +

    >>> dir(record)
     ['__doc__', '__init__', '__module__', 'accessions', 'annotation_update',
     'comments', 'created', 'cross_references', 'data_class', 'description',
     'entry_name', 'features', 'gene_name', 'host_organism', 'keywords',
     'molecule_type', 'organelle', 'organism', 'organism_classification',
     'references', 'seqinfo', 'sequence', 'sequence_length',
     'sequence_update', 'taxonomy_id']
    -
    -

    10.1.2  Parsing the Swiss-Prot keyword and category list

    Swiss-Prot also distributes a file keywlist.txt, which lists the keywords and categories used in Swiss-Prot. The file contains entries in the following form:

    ID   2Fe-2S.
    +
    + +

    10.1.2  Parsing the Swiss-Prot keyword and category list

    Swiss-Prot also distributes a file keywlist.txt, which lists the keywords and categories used in Swiss-Prot. The file contains entries in the following form:

    ID   2Fe-2S.
     AC   KW-0001
     DE   Protein which contains at least one 2Fe-2S iron-sulfur cluster: 2 iron
     DE   atoms complexed to 2 inorganic sulfides and 4 sulfur atoms of
    @@ -5416,67 +5570,70 @@
     //
     ID   3Fe-4S.
     ...
    -

    The entries in this file can be parsed by the parse function in the Bio.SwissProt.KeyWList module. Each entry is then stored as a Bio.SwissProt.KeyWList.Record, which is a Python dictionary.

    >>> from Bio.SwissProt import KeyWList
    +

    The entries in this file can be parsed by the parse function in the Bio.SwissProt.KeyWList module. Each entry is then stored as a Bio.SwissProt.KeyWList.Record, which is a Python dictionary.

    >>> from Bio.SwissProt import KeyWList
     >>> handle = open("keywlist.txt")
     >>> records = KeyWList.parse(handle)
     >>> for record in records:
    -...     print record['ID']
    -...     print record['DE']
    -

    This prints -

    2Fe-2S.
    +...     print(record['ID'])
    +...     print(record['DE'])
    +

    This prints +

    2Fe-2S.
     Protein which contains at least one 2Fe-2S iron-sulfur cluster: 2 iron atoms
     complexed to 2 inorganic sulfides and 4 sulfur atoms of cysteines from the
     protein.
     ...
    -
    -

    10.2  Parsing Prosite records

    Prosite is a database containing protein domains, protein families, functional sites, as well as the patterns and profiles to recognize them. Prosite was developed in parallel with Swiss-Prot. In Biopython, a Prosite record is represented by the Bio.ExPASy.Prosite.Record class, whose members correspond to the different fields in a Prosite record.

    In general, a Prosite file can contain more than one Prosite records. For example, the full set of Prosite records, which can be downloaded as a single file (prosite.dat) from the ExPASy FTP site, contains 2073 records (version 20.24 released on 4 December 2007). To parse such a file, we again make use of an iterator:

    >>> from Bio.ExPASy import Prosite
    +
    + +

    10.2  Parsing Prosite records

    Prosite is a database containing protein domains, protein families, functional sites, as well as the patterns and profiles to recognize them. Prosite was developed in parallel with Swiss-Prot. In Biopython, a Prosite record is represented by the Bio.ExPASy.Prosite.Record class, whose members correspond to the different fields in a Prosite record.

    In general, a Prosite file can contain more than one Prosite records. For example, the full set of Prosite records, which can be downloaded as a single file (prosite.dat) from the ExPASy FTP site, contains 2073 records (version 20.24 released on 4 December 2007). To parse such a file, we again make use of an iterator:

    >>> from Bio.ExPASy import Prosite
     >>> handle = open("myprositefile.dat")
     >>> records = Prosite.parse(handle)
    -

    We can now take the records one at a time and print out some information. For example, using the file containing the complete Prosite database, we’d find -

    >>> from Bio.ExPASy import Prosite
    +

    We can now take the records one at a time and print out some information. For example, using the file containing the complete Prosite database, we’d find +

    >>> from Bio.ExPASy import Prosite
     >>> handle = open("prosite.dat")
     >>> records = Prosite.parse(handle)
    ->>> record = records.next()
    +>>> record = next(records)
     >>> record.accession
     'PS00001'
     >>> record.name
     'ASN_GLYCOSYLATION'
     >>> record.pdoc
     'PDOC00001'
    ->>> record = records.next()
    +>>> record = next(records)
     >>> record.accession
     'PS00004'
     >>> record.name
     'CAMP_PHOSPHO_SITE'
     >>> record.pdoc
     'PDOC00004'
    ->>> record = records.next()
    +>>> record = next(records)
     >>> record.accession
     'PS00005'
     >>> record.name
     'PKC_PHOSPHO_SITE'
     >>> record.pdoc
     'PDOC00005'
    -

    and so on. If you’re interested in how many Prosite records there are, you could use -

    >>> from Bio.ExPASy import Prosite
    +

    and so on. If you’re interested in how many Prosite records there are, you could use +

    >>> from Bio.ExPASy import Prosite
     >>> handle = open("prosite.dat")
     >>> records = Prosite.parse(handle)
     >>> n = 0
     >>> for record in records: n+=1
     ...
    ->>> print n
    +>>> n
     2073
    -

    To read exactly one Prosite from the handle, you can use the read function: -

    >>> from Bio.ExPASy import Prosite
    +

    To read exactly one Prosite from the handle, you can use the read function: +

    >>> from Bio.ExPASy import Prosite
     >>> handle = open("mysingleprositerecord.dat")
     >>> record = Prosite.read(handle)
    -

    This function raises a ValueError if no Prosite record is found, and also if more than one Prosite record is found.

    -

    10.3  Parsing Prosite documentation records

    In the Prosite example above, the record.pdoc accession numbers 'PDOC00001', 'PDOC00004', 'PDOC00005' and so on refer to Prosite documentation. The Prosite documentation records are available from ExPASy as individual files, and as one file (prosite.doc) containing all Prosite documentation records.

    We use the parser in Bio.ExPASy.Prodoc to parse Prosite documentation records. For example, to create a list of all accession numbers of Prosite documentation record, you can use

    >>> from Bio.ExPASy import Prodoc
    +

    This function raises a ValueError if no Prosite record is found, and also if more than one Prosite record is found.

    + +

    10.3  Parsing Prosite documentation records

    In the Prosite example above, the record.pdoc accession numbers 'PDOC00001', 'PDOC00004', 'PDOC00005' and so on refer to Prosite documentation. The Prosite documentation records are available from ExPASy as individual files, and as one file (prosite.doc) containing all Prosite documentation records.

    We use the parser in Bio.ExPASy.Prodoc to parse Prosite documentation records. For example, to create a list of all accession numbers of Prosite documentation record, you can use

    >>> from Bio.ExPASy import Prodoc
     >>> handle = open("prosite.doc")
     >>> records = Prodoc.parse(handle)
     >>> accessions = [record.accession for record in records]
    -

    Again a read() function is provided to read exactly one Prosite documentation record from the handle.

    -

    10.4  Parsing Enzyme records

    ExPASy’s Enzyme database is a repository of information on enzyme nomenclature. A typical Enzyme record looks as follows:

    ID   3.1.1.34
    +

    Again a read() function is provided to read exactly one Prosite documentation record from the handle.

    + +

    10.4  Parsing Enzyme records

    ExPASy’s Enzyme database is a repository of information on enzyme nomenclature. A typical Enzyme record looks as follows:

    ID   3.1.1.34
     DE   Lipoprotein lipase.
     AN   Clearing factor lipase.
     AN   Diacylglycerol lipase.
    @@ -5491,7 +5648,7 @@
     DR   O46647, LIPL_MUSVI ;  P49060, LIPL_PAPAN ;  P49923, LIPL_PIG   ;
     DR   Q06000, LIPL_RAT   ;  Q29524, LIPL_SHEEP ;
     //
    -

    In this example, the first line shows the EC (Enzyme Commission) number of lipoprotein lipase (second line). Alternative names of lipoprotein lipase are "clearing factor lipase", "diacylglycerol lipase", and "diglyceride lipase" (lines 3 through 5). The line starting with "CA" shows the catalytic activity of this enzyme. Comment lines start with "CC". The "PR" line shows references to the Prosite Documentation records, and the "DR" lines show references to Swiss-Prot records. Not of these entries are necessarily present in an Enzyme record.

    In Biopython, an Enzyme record is represented by the Bio.ExPASy.Enzyme.Record class. This record derives from a Python dictionary and has keys corresponding to the two-letter codes used in Enzyme files. To read an Enzyme file containing one Enzyme record, use the read function in Bio.ExPASy.Enzyme:

    >>> from Bio.ExPASy import Enzyme
    +

    In this example, the first line shows the EC (Enzyme Commission) number of lipoprotein lipase (second line). Alternative names of lipoprotein lipase are "clearing factor lipase", "diacylglycerol lipase", and "diglyceride lipase" (lines 3 through 5). The line starting with "CA" shows the catalytic activity of this enzyme. Comment lines start with "CC". The "PR" line shows references to the Prosite Documentation records, and the "DR" lines show references to Swiss-Prot records. Not of these entries are necessarily present in an Enzyme record.

    In Biopython, an Enzyme record is represented by the Bio.ExPASy.Enzyme.Record class. This record derives from a Python dictionary and has keys corresponding to the two-letter codes used in Enzyme files. To read an Enzyme file containing one Enzyme record, use the read function in Bio.ExPASy.Enzyme:

    >>> from Bio.ExPASy import Enzyme
     >>> handle = open("lipoprotein.txt")
     >>> record = Enzyme.read(handle)
     >>> record["ID"]
    @@ -5504,7 +5661,7 @@
     'Triacylglycerol + H(2)O = diacylglycerol + a carboxylate.'
     >>> record["PR"]
     ['PDOC00110']
    -
    >>> record["CC"]
    +
    >>> record["CC"]
     ['Hydrolyzes triacylglycerols in chylomicrons and very low-density lipoproteins
     (VLDL).', 'Also hydrolyzes diacylglycerol.']
     >>> record["DR"]
    @@ -5512,24 +5669,26 @@
     ['P55031', 'LIPL_FELCA'], ['P06858', 'LIPL_HUMAN'], ['P11152', 'LIPL_MOUSE'],
     ['O46647', 'LIPL_MUSVI'], ['P49060', 'LIPL_PAPAN'], ['P49923', 'LIPL_PIG'],
     ['Q06000', 'LIPL_RAT'], ['Q29524', 'LIPL_SHEEP']]
    -

    The read function raises a ValueError if no Enzyme record is found, and also if more than one Enzyme record is found.

    The full set of Enzyme records can be downloaded as a single file (enzyme.dat) from the ExPASy FTP site, containing 4877 records (release of 3 March 2009). To parse such a file containing multiple Enzyme records, use the parse function in Bio.ExPASy.Enzyme to obtain an iterator:

    >>> from Bio.ExPASy import Enzyme
    +

    The read function raises a ValueError if no Enzyme record is found, and also if more than one Enzyme record is found.

    The full set of Enzyme records can be downloaded as a single file (enzyme.dat) from the ExPASy FTP site, containing 4877 records (release of 3 March 2009). To parse such a file containing multiple Enzyme records, use the parse function in Bio.ExPASy.Enzyme to obtain an iterator:

    >>> from Bio.ExPASy import Enzyme
     >>> handle = open("enzyme.dat")
     >>> records = Enzyme.parse(handle)
    -

    We can now iterate over the records one at a time. For example, we can make a list of all EC numbers for which an Enzyme record is available: -

    >>> ecnumbers = [record["ID"] for record in records]
    -
    -

    10.5  Accessing the ExPASy server

    Swiss-Prot, Prosite, and Prosite documentation records can be downloaded from the ExPASy web server at http://www.expasy.org. Six kinds of queries are available from ExPASy: -

    -get_prodoc_entry
    To download a Prosite documentation record in HTML format -
    get_prosite_entry
    To download a Prosite record in HTML format -
    get_prosite_raw
    To download a Prosite or Prosite documentation record in raw format -
    get_sprot_raw
    To download a Swiss-Prot record in raw format -
    sprot_search_ful
    To search for a Swiss-Prot record -
    sprot_search_de
    To search for a Swiss-Prot record -

    -To access this web server from a Python script, we use the Bio.ExPASy module.

    -

    10.5.1  Retrieving a Swiss-Prot record

    -

    Let’s say we are looking at chalcone synthases for Orchids (see section 2.3 for some justification for looking for interesting things about orchids). Chalcone synthase is involved in flavanoid biosynthesis in plants, and flavanoids make lots of cool things like pigment colors and UV protectants.

    If you do a search on Swiss-Prot, you can find three orchid proteins for Chalcone Synthase, id numbers O23729, O23730, O23731. Now, let’s write a script which grabs these, and parses out some interesting information.

    First, we grab the records, using the get_sprot_raw() function of Bio.ExPASy. This function is very nice since you can feed it an id and get back a handle to a raw text record (no html to mess with!). We can the use Bio.SwissProt.read to pull out the Swiss-Prot record, or Bio.SeqIO.read to get a SeqRecord. The following code accomplishes what I just wrote:

    >>> from Bio import ExPASy
    +

    We can now iterate over the records one at a time. For example, we can make a list of all EC numbers for which an Enzyme record is available: +

    >>> ecnumbers = [record["ID"] for record in records]
    +
    + +

    10.5  Accessing the ExPASy server

    Swiss-Prot, Prosite, and Prosite documentation records can be downloaded from the ExPASy web server at http://www.expasy.org. Six kinds of queries are available from ExPASy: +

    +get_prodoc_entry
    To download a Prosite documentation record in HTML format +
    get_prosite_entry
    To download a Prosite record in HTML format +
    get_prosite_raw
    To download a Prosite or Prosite documentation record in raw format +
    get_sprot_raw
    To download a Swiss-Prot record in raw format +
    sprot_search_ful
    To search for a Swiss-Prot record +
    sprot_search_de
    To search for a Swiss-Prot record +

    +To access this web server from a Python script, we use the Bio.ExPASy module.

    + +

    10.5.1  Retrieving a Swiss-Prot record

    +

    Let’s say we are looking at chalcone synthases for Orchids (see section 2.3 for some justification for looking for interesting things about orchids). Chalcone synthase is involved in flavanoid biosynthesis in plants, and flavanoids make lots of cool things like pigment colors and UV protectants.

    If you do a search on Swiss-Prot, you can find three orchid proteins for Chalcone Synthase, id numbers O23729, O23730, O23731. Now, let’s write a script which grabs these, and parses out some interesting information.

    First, we grab the records, using the get_sprot_raw() function of Bio.ExPASy. This function is very nice since you can feed it an id and get back a handle to a raw text record (no html to mess with!). We can the use Bio.SwissProt.read to pull out the Swiss-Prot record, or Bio.SeqIO.read to get a SeqRecord. The following code accomplishes what I just wrote:

    >>> from Bio import ExPASy
     >>> from Bio import SwissProt
     
     >>> accessions = ["O23729", "O23730", "O23731"]
    @@ -5539,26 +5698,27 @@
     ...     handle = ExPASy.get_sprot_raw(accession)
     ...     record = SwissProt.read(handle)
     ...     records.append(record)
    -

    If the accession number you provided to ExPASy.get_sprot_raw does not exist, then SwissProt.read(handle) will raise a ValueError. You can catch ValueException exceptions to detect invalid accession numbers:

    >>> for accession in accessions:
    +

    If the accession number you provided to ExPASy.get_sprot_raw does not exist, then SwissProt.read(handle) will raise a ValueError. You can catch ValueException exceptions to detect invalid accession numbers:

    >>> for accession in accessions:
     ...     handle = ExPASy.get_sprot_raw(accession)
     ...     try:
     ...         record = SwissProt.read(handle)
     ...     except ValueException:
    -...         print "WARNING: Accession %s not found" % accession
    +...         print("WARNING: Accession %s not found" % accession)
     ...     records.append(record)
    -
    -

    10.5.2  Searching Swiss-Prot

    Now, you may remark that I knew the records’ accession numbers -beforehand. Indeed, get_sprot_raw() needs either the entry name +

    + +

    10.5.2  Searching Swiss-Prot

    Now, you may remark that I knew the records’ accession numbers +beforehand. Indeed, get_sprot_raw() needs either the entry name or an accession number. When you don’t have them handy, you can use -one of the sprot_search_de() or sprot_search_ful() -functions.

    sprot_search_de() searches in the ID, DE, GN, OS and OG lines; -sprot_search_ful() searches in (nearly) all the fields. They +one of the sprot_search_de() or sprot_search_ful() +functions.

    sprot_search_de() searches in the ID, DE, GN, OS and OG lines; +sprot_search_ful() searches in (nearly) all the fields. They are detailed on -http://www.expasy.org/cgi-bin/sprot-search-de and -http://www.expasy.org/cgi-bin/sprot-search-ful +http://www.expasy.org/cgi-bin/sprot-search-de and +http://www.expasy.org/cgi-bin/sprot-search-ful respectively. Note that they don’t search in TrEMBL by default -(argument trembl). Note also that they return html pages; -however, accession numbers are quite easily extractable:

    >>> from Bio import ExPASy
    +(argument trembl). Note also that they return html pages;
    +however, accession numbers are quite easily extractable:

    >>> from Bio import ExPASy
     >>> import re
     
     >>> handle = ExPASy.sprot_search_de("Orchid Chalcone Synthase")
    @@ -5569,42 +5729,44 @@
     ...     ids = re.findall(r'HREF="/uniprot/(\w+)"', html_results)
     ... else:
     ...     ids = re.findall(r'href="/cgi-bin/niceprot\.pl\?(\w+)"', html_results)
    -
    -

    10.5.3  Retrieving Prosite and Prosite documentation records

    Prosite and Prosite documentation records can be retrieved either in HTML format, or in raw format. To parse Prosite and Prosite documentation records with Biopython, you should retrieve the records in raw format. For other purposes, however, you may be interested in these records in HTML format.

    To retrieve a Prosite or Prosite documentation record in raw format, use get_prosite_raw(). For example, to download a Prosite record and print it out in raw text format, use

    >>> from Bio import ExPASy
    +
    + +

    10.5.3  Retrieving Prosite and Prosite documentation records

    Prosite and Prosite documentation records can be retrieved either in HTML format, or in raw format. To parse Prosite and Prosite documentation records with Biopython, you should retrieve the records in raw format. For other purposes, however, you may be interested in these records in HTML format.

    To retrieve a Prosite or Prosite documentation record in raw format, use get_prosite_raw(). For example, to download a Prosite record and print it out in raw text format, use

    >>> from Bio import ExPASy
     >>> handle = ExPASy.get_prosite_raw('PS00001')
     >>> text = handle.read()
    ->>> print text
    -

    To retrieve a Prosite record and parse it into a Bio.Prosite.Record object, use

    >>> from Bio import ExPASy
    +>>> print(text)
    +

    To retrieve a Prosite record and parse it into a Bio.Prosite.Record object, use

    >>> from Bio import ExPASy
     >>> from Bio import Prosite
     >>> handle = ExPASy.get_prosite_raw('PS00001')
     >>> record = Prosite.read(handle)
    -

    The same function can be used to retrieve a Prosite documentation record and parse it into a Bio.ExPASy.Prodoc.Record object:

    >>> from Bio import ExPASy
    +

    The same function can be used to retrieve a Prosite documentation record and parse it into a Bio.ExPASy.Prodoc.Record object:

    >>> from Bio import ExPASy
     >>> from Bio.ExPASy import Prodoc
     >>> handle = ExPASy.get_prosite_raw('PDOC00001')
     >>> record = Prodoc.read(handle)
    -

    For non-existing accession numbers, ExPASy.get_prosite_raw returns a handle to an emptry string. When faced with an empty string, Prosite.read and Prodoc.read will raise a ValueError. You can catch these exceptions to detect invalid accession numbers.

    The functions get_prosite_entry() and get_prodoc_entry() are used to download Prosite and Prosite documentation records in HTML format. To create a web page showing one Prosite record, you can use

    >>> from Bio import ExPASy
    +

    For non-existing accession numbers, ExPASy.get_prosite_raw returns a handle to an emptry string. When faced with an empty string, Prosite.read and Prodoc.read will raise a ValueError. You can catch these exceptions to detect invalid accession numbers.

    The functions get_prosite_entry() and get_prodoc_entry() are used to download Prosite and Prosite documentation records in HTML format. To create a web page showing one Prosite record, you can use

    >>> from Bio import ExPASy
     >>> handle = ExPASy.get_prosite_entry('PS00001')
     >>> html = handle.read()
     >>> output = open("myprositerecord.html", "w")
     >>> output.write(html)
     >>> output.close()
    -

    and similarly for a Prosite documentation record:

    >>> from Bio import ExPASy
    +

    and similarly for a Prosite documentation record:

    >>> from Bio import ExPASy
     >>> handle = ExPASy.get_prodoc_entry('PDOC00001')
     >>> html = handle.read()
     >>> output = open("myprodocrecord.html", "w")
     >>> output.write(html)
     >>> output.close()
    -

    For these functions, an invalid accession number returns an error message in HTML format.

    -

    10.6  Scanning the Prosite database

    ScanProsite allows you to scan protein sequences online against the Prosite database by providing a UniProt or PDB sequence identifier or the sequence itself. For more information about ScanProsite, please see the ScanProsite documentation as well as the documentation for programmatic access of ScanProsite.

    You can use Biopython’s Bio.ExPASy.ScanProsite module to scan the Prosite database from Python. This module both helps you to access ScanProsite programmatically, and to parse the results returned by ScanProsite. To scan for Prosite patterns in the following protein sequence:

    MEHKEVVLLLLLFLKSGQGEPLDDYVNTQGASLFSVTKKQLGAGSIEECAAKCEEDEEFT
    +

    For these functions, an invalid accession number returns an error message in HTML format.

    + +

    10.6  Scanning the Prosite database

    ScanProsite allows you to scan protein sequences online against the Prosite database by providing a UniProt or PDB sequence identifier or the sequence itself. For more information about ScanProsite, please see the ScanProsite documentation as well as the documentation for programmatic access of ScanProsite.

    You can use Biopython’s Bio.ExPASy.ScanProsite module to scan the Prosite database from Python. This module both helps you to access ScanProsite programmatically, and to parse the results returned by ScanProsite. To scan for Prosite patterns in the following protein sequence:

    MEHKEVVLLLLLFLKSGQGEPLDDYVNTQGASLFSVTKKQLGAGSIEECAAKCEEDEEFT
     CRAFQYHSKEQQCVIMAENRKSSIIIRMRDVVLFEKKVYLSECKTGNGKNYRGTMSKTKN
    -

    you can use the following code:

    >>> sequence = "MEHKEVVLLLLLFLKSGQGEPLDDYVNTQGASLFSVTKKQLGAGSIEECAAKCEEDEEFT
    +

    you can use the following code:

    >>> sequence = "MEHKEVVLLLLLFLKSGQGEPLDDYVNTQGASLFSVTKKQLGAGSIEECAAKCEEDEEFT
     CRAFQYHSKEQQCVIMAENRKSSIIIRMRDVVLFEKKVYLSECKTGNGKNYRGTMSKTKN"
     >>> from Bio.ExPASy import ScanProsite
     >>> handle = ScanProsite.scan(seq=sequence)
    -

    By executing handle.read(), you can obtain the search results in raw XML format. Instead, let’s use Bio.ExPASy.ScanProsite.read to parse the raw XML into a Python object:

    >>> result = ScanProsite.read(handle)
    +

    By executing handle.read(), you can obtain the search results in raw XML format. Instead, let’s use Bio.ExPASy.ScanProsite.read to parse the raw XML into a Python object:

    >>> result = ScanProsite.read(handle)
     >>> type(result)
     <class 'Bio.ExPASy.ScanProsite.Record'>
    -

    A Bio.ExPASy.ScanProsite.Record object is derived from a list, with each element in the list storing one ScanProsite hit. This object also stores the number of hits, as well as the number of search sequences, as returned by ScanProsite. This ScanProsite search resulted in six hits:

    >>> result.n_seq
    +

    A Bio.ExPASy.ScanProsite.Record object is derived from a list, with each element in the list storing one ScanProsite hit. This object also stores the number of hits, as well as the number of search sequences, as returned by ScanProsite. This ScanProsite search resulted in six hits:

    >>> result.n_seq
     1
     >>> result.n_match
     6
    @@ -5622,92 +5784,99 @@
     {'start': 80, 'stop': 83, 'sequence_ac': u'USERSEQ1', 'signature_ac': u'PS00004'}
     >>> result[5]
     {'start': 106, 'stop': 111, 'sequence_ac': u'USERSEQ1', 'signature_ac': u'PS00008'}
    -

    Other ScanProsite parameters can be passed as keyword arguments; see the documentation for programmatic access of ScanProsite for more information. As an example, passing lowscore=1 to include matches with low level scores lets use find one additional hit:

    >>> handle = ScanProsite.scan(seq=sequence, lowscore=1)
    +

    Other ScanProsite parameters can be passed as keyword arguments; see the documentation for programmatic access of ScanProsite for more information. As an example, passing lowscore=1 to include matches with low level scores lets use find one additional hit:

    >>> handle = ScanProsite.scan(seq=sequence, lowscore=1)
     >>> result = ScanProsite.read(handle)
     >>> result.n_match
     7
    -
    -

    Chapter 11  Going 3D: The PDB module

    Bio.PDB is a Biopython module that focuses on working with crystal structures of biological macromolecules. Among other things, Bio.PDB includes a PDBParser class that produces a Structure object, which can be used to access the atomic data in the file in a convenient manner. There is limited support for parsing the information contained in the PDB header.

    -

    11.1  Reading and writing crystal structure files

    -

    11.1.1  Reading a PDB file

    First we create a PDBParser object:

    >>> from Bio.PDB.PDBParser import PDBParser
    +
    + +

    Chapter 11  Going 3D: The PDB module

    Bio.PDB is a Biopython module that focuses on working with crystal structures of biological macromolecules. Among other things, Bio.PDB includes a PDBParser class that produces a Structure object, which can be used to access the atomic data in the file in a convenient manner. There is limited support for parsing the information contained in the PDB header.

    + +

    11.1  Reading and writing crystal structure files

    + +

    11.1.1  Reading a PDB file

    First we create a PDBParser object:

    >>> from Bio.PDB.PDBParser import PDBParser
     >>> p = PDBParser(PERMISSIVE=1)
    -

    The PERMISSIVE flag indicates that a number of common problems (see 11.7.1) associated with PDB files will be ignored (but note that some atoms and/or residues will be missing). If the flag is not present a PDBConstructionException will be generated if any problems are detected during the parse operation.

    The Structure object is then produced by letting the PDBParser object parse a PDB file (the PDB file in this case is called ’pdb1fat.ent’, ’1fat’ is a user defined name for the structure):

    >>> structure_id = "1fat"
    +

    The PERMISSIVE flag indicates that a number of common problems (see 11.7.1) associated with PDB files will be ignored (but note that some atoms and/or residues will be missing). If the flag is not present a PDBConstructionException will be generated if any problems are detected during the parse operation.

    The Structure object is then produced by letting the PDBParser object parse a PDB file (the PDB file in this case is called ’pdb1fat.ent’, ’1fat’ is a user defined name for the structure):

    >>> structure_id = "1fat"
     >>> filename = "pdb1fat.ent"
     >>> s = p.get_structure(structure_id, filename)
    -

    You can extract the header and trailer (simple lists of strings) of the PDB -file from the PDBParser object with the get_header and get_trailer +

    You can extract the header and trailer (simple lists of strings) of the PDB +file from the PDBParser object with the get_header and get_trailer methods. Note however that many PDB files contain headers with incomplete or erroneous information. Many of the errors have been -fixed in the equivalent mmCIF files. Hence, if you are interested +fixed in the equivalent mmCIF files. Hence, if you are interested in the header information, it is a good idea to extract information -from mmCIF files using the MMCIF2Dict tool -described below, instead of parsing the PDB header.

    Now that is clarified, let’s return to parsing the PDB header. The -structure object has an attribute called header which is -a Python dictionary that maps header records to their values.

    Example:

    >>> resolution = structure.header['resolution']
    +from mmCIF files using the MMCIF2Dict tool
    +described below, instead of parsing the PDB header. 

    Now that is clarified, let’s return to parsing the PDB header. The +structure object has an attribute called header which is +a Python dictionary that maps header records to their values.

    Example:

    >>> resolution = structure.header['resolution']
     >>> keywords = structure.header['keywords']
    -

    The available keys are name, head, deposition_date, release_date, structure_method, resolution, structure_reference (which maps to a list of references), journal_reference, author, and compound (which maps to a dictionary with various information about the crystallized compound).

    The dictionary can also be created without creating a Structure -object, ie. directly from the PDB file:

    >>> file = open(filename,'r')
    +

    The available keys are name, head, deposition_date, release_date, structure_method, resolution, structure_reference (which maps to a list of references), journal_reference, author, and compound (which maps to a dictionary with various information about the crystallized compound).

    The dictionary can also be created without creating a Structure +object, ie. directly from the PDB file:

    >>> file = open(filename, 'r')
     >>> header_dict = parse_pdb_header(file)
     >>> file.close()
    -
    -

    11.1.2  Reading an mmCIF file

    Similarly to the case the case of PDB files, first create an MMCIFParser object:

    >>> from Bio.PDB.MMCIFParser import MMCIFParser
    +
    + +

    11.1.2  Reading an mmCIF file

    Similarly to the case the case of PDB files, first create an MMCIFParser object:

    >>> from Bio.PDB.MMCIFParser import MMCIFParser
     >>> parser = MMCIFParser()
    -

    Then use this parser to create a structure object from the mmCIF file: -

    >>> structure = parser.get_structure('1fat', '1fat.cif')
    -

    To have some more low level access to an mmCIF file, you can use the MMCIF2Dict class to create a Python dictionary that maps all mmCIF +

    Then use this parser to create a structure object from the mmCIF file: +

    >>> structure = parser.get_structure('1fat', '1fat.cif')
    +

    To have some more low level access to an mmCIF file, you can use the MMCIF2Dict class to create a Python dictionary that maps all mmCIF tags in an mmCIF file to their values. If there are multiple values -(like in the case of tag _atom_site.Cartn_y, which holds -the y coordinates of all atoms), the tag is mapped to a list of values. -The dictionary is created from the mmCIF file as follows:

    >>> from Bio.PDB.MMCIF2Dict import MMCIF2Dict
    +(like in the case of tag _atom_site.Cartn_y, which holds
    +the y coordinates of all atoms), the tag is mapped to a list of values.
    +The dictionary is created from the mmCIF file as follows:

    >>> from Bio.PDB.MMCIF2Dict import MMCIF2Dict
     >>> mmcif_dict = MMCIF2Dict('1FAT.cif')
    -

    Example: get the solvent content from an mmCIF file: -

    >>> sc = mmcif_dict['_exptl_crystal.density_percent_sol']
    -

    Example: get the list of the y coordinates of all atoms -

    >>> y_list = mmcif_dict['_atom_site.Cartn_y']
    -
    -

    11.1.3  Reading files in the PDB XML format

    That’s not yet supported, but we are definitely planning to support that +

    Example: get the solvent content from an mmCIF file: +

    >>> sc = mmcif_dict['_exptl_crystal.density_percent_sol']
    +

    Example: get the list of the y coordinates of all atoms +

    >>> y_list = mmcif_dict['_atom_site.Cartn_y']
    +
    + +

    11.1.3  Reading files in the PDB XML format

    That’s not yet supported, but we are definitely planning to support that in the future (it’s not a lot of work). Contact the Biopython developers -(biopython-dev@biopython.org) if you need this).

    -

    11.1.4  Writing PDB files

    Use the PDBIO class for this. It’s easy to write out specific parts -of a structure too, of course.

    Example: saving a structure

    >>> io = PDBIO()
    +(biopython-dev@biopython.org) if you need this).

    + +

    11.1.4  Writing PDB files

    Use the PDBIO class for this. It’s easy to write out specific parts +of a structure too, of course.

    Example: saving a structure

    >>> io = PDBIO()
     >>> io.set_structure(s)
     >>> io.save('out.pdb')
    -

    If you want to write out a part of the structure, make use of the -Select class (also in PDBIO). Select has four methods:

    • -accept_model(model) -
    • accept_chain(chain) -
    • accept_residue(residue) -
    • accept_atom(atom) -

    +

    If you want to write out a part of the structure, make use of the +Select class (also in PDBIO). Select has four methods:

    • +accept_model(model) +
    • accept_chain(chain) +
    • accept_residue(residue) +
    • accept_atom(atom) +

    By default, every method returns 1 (which means the model/chain/residue/atom -is included in the output). By subclassing Select and returning +is included in the output). By subclassing Select and returning 0 when appropriate you can exclude models, chains, etc. from the output. Cumbersome maybe, but very powerful. The following code only writes -out glycine residues:

    >>> class GlySelect(Select):
    +out glycine residues:

    >>> class GlySelect(Select):
     ...     def accept_residue(self, residue):
     ...         if residue.get_name()=='GLY':
     ...             return True
     ...         else:
     ...             return False
    -...
    +... 
     >>> io = PDBIO()
     >>> io.set_structure(s)
     >>> io.save('gly_only.pdb', GlySelect())
    -

    If this is all too complicated for you, the Dice module contains -a handy extract function that writes out all residues in -a chain between a start and end residue.

    -

    11.2  Structure representation

    The overall layout of a Structure object follows the so-called SMCRA -(Structure/Model/Chain/Residue/Atom) architecture:

    • +

    If this is all too complicated for you, the Dice module contains +a handy extract function that writes out all residues in +a chain between a start and end residue.

    + +

    11.2  Structure representation

    The overall layout of a Structure object follows the so-called SMCRA +(Structure/Model/Chain/Residue/Atom) architecture:

    • A structure consists of models -
    • A model consists of chains -
    • A chain consists of residues -
    • A residue consists of atoms -

    +

  • A model consists of chains +
  • A chain consists of residues +
  • A residue consists of atoms +
  • This is the way many structural biologists/bioinformaticians think about structure, and provides a simple but efficient way to deal with structure. Additional stuff is essentially added when needed. A UML -diagram of the Structure object (forget about the Disordered -classes for now) is shown in Fig. 11.1. Such a data structure is not +diagram of the Structure object (forget about the Disordered +classes for now) is shown in Fig. 11.1. Such a data structure is not necessarily best suited for the representation of the macromolecular content of a structure, but it is absolutely necessary for a good interpretation of the data present in a file that describes the structure (typically a PDB or MMCIF @@ -5716,124 +5885,129 @@ the structure unambiguously. If a SMCRA data structure cannot be generated, there is reason to suspect a problem. Parsing a PDB file can thus be used to detect likely problems. We will give several examples of this in section -11.7.1.


    +11.7.1.


    - + -
    +
    Figure 11.1: UML diagram of SMCRA architecture of the Structure class used to represent a macromolecular structure. +
    -
    Figure 11.1: UML diagram of SMCRA architecture of the Structure class used to represent a macromolecular structure. Full lines with diamonds denote aggregation, full lines with arrows denote referencing, full lines with triangles denote inheritance -and dashed lines with triangles denote interface realization.
    - -

    Structure, Model, Chain and Residue are all subclasses of the Entity base class. +and dashed lines with triangles denote interface realization.

    + +

    Structure, Model, Chain and Residue are all subclasses of the Entity base class. The Atom class only (partly) implements the Entity interface (because an Atom -does not have children).

    For each Entity subclass, you can extract a child by using a unique id for that +does not have children).

    For each Entity subclass, you can extract a child by using a unique id for that child as a key (e.g. you can extract an Atom object from a Residue object by using an atom name string as a key, you can extract a Chain object from a Model -object by using its chain identifier as a key).

    Disordered atoms and residues are represented by DisorderedAtom and DisorderedResidue +object by using its chain identifier as a key).

    Disordered atoms and residues are represented by DisorderedAtom and DisorderedResidue classes, which are both subclasses of the DisorderedEntityWrapper base class. They hide the complexity associated with disorder and behave exactly as Atom -and Residue objects.

    In general, a child Entity object (i.e. Atom, Residue, Chain, Model) can be +and Residue objects.

    In general, a child Entity object (i.e. Atom, Residue, Chain, Model) can be extracted from its parent (i.e. Residue, Chain, Model, Structure, respectively) -by using an id as a key.

    >>> child_entity = parent_entity[child_id]
    -

    You can also get a list of all child Entities of a parent Entity object. Note +by using an id as a key.

    >>> child_entity = parent_entity[child_id]
    +

    You can also get a list of all child Entities of a parent Entity object. Note that this list is sorted in a specific way (e.g. according to chain identifier -for Chain objects in a Model object).

    >>> child_list = parent_entity.get_list()
    -

    You can also get the parent from a child: -

    >>> parent_entity = child_entity.get_parent()
    -

    At all levels of the SMCRA hierarchy, you can also extract a full id. +for Chain objects in a Model object).

    >>> child_list = parent_entity.get_list()
    +

    You can also get the parent from a child: +

    >>> parent_entity = child_entity.get_parent()
    +

    At all levels of the SMCRA hierarchy, you can also extract a full id. The full id is a tuple containing all id’s starting from the top object (Structure) down to the current object. A full id for a Residue object e.g. is something -like:

    >>> full_id = residue.get_full_id()
    ->>> print full_id
    +like:

    >>> full_id = residue.get_full_id()
    +>>> print(full_id)
     ("1abc", 0, "A", ("", 10, "A"))
    -

    This corresponds to:

    • +

    This corresponds to:

    • The Structure with id "1abc" -
    • The Model with id 0 -
    • The Chain with id "A" -
    • The Residue with id (" ", 10, "A"). -

    +

  • The Model with id 0 +
  • The Chain with id "A" +
  • The Residue with id (" ", 10, "A"). +
  • The Residue id indicates that the residue is not a hetero-residue (nor a water) because it has a blank hetero field, that its sequence identifier is 10 and -that its insertion code is "A".

    To get the entity’s id, use the get_id method: -

    >>> entity.get_id()
    -

    You can check if the entity has a child with a given id by using the has_id method: -

    >>> entity.has_id(entity_id)
    -

    The length of an entity is equal to its number of children: -

    >>> nr_children = len(entity)
    -

    It is possible to delete, rename, add, etc. child entities from a parent entity, +that its insertion code is "A".

    To get the entity’s id, use the get_id method: +

    >>> entity.get_id()
    +

    You can check if the entity has a child with a given id by using the has_id method: +

    >>> entity.has_id(entity_id)
    +

    The length of an entity is equal to its number of children: +

    >>> nr_children = len(entity)
    +

    It is possible to delete, rename, add, etc. child entities from a parent entity, but this does not include any sanity checks (e.g. it is possible to add two residues with the same id to one chain). This really should be done via a nice Decorator class that includes integrity checking, but you can take a look at -the code (Entity.py) if you want to use the raw interface.

    -

    11.2.1  Structure

    The Structure object is at the top of the hierarchy. Its id is a user given +the code (Entity.py) if you want to use the raw interface.

    + +

    11.2.1  Structure

    The Structure object is at the top of the hierarchy. Its id is a user given string. The Structure contains a number of Model children. Most crystal structures (but not all) contain a single model, while NMR structures typically consist of several models. Disorder in crystal structures of large parts of molecules -can also result in several models.

    -

    11.2.2  Model

    The id of the Model object is an integer, which is derived from the position +can also result in several models.

    + +

    11.2.2  Model

    The id of the Model object is an integer, which is derived from the position of the model in the parsed file (they are automatically numbered starting from 0). -Crystal structures generally have only one model (with id 0), while NMR files usually have several models. Whereas many PDB parsers assume that there is only one model, the Structure class in Bio.PDB is designed such that it can easily handle PDB files with more than one model.

    As an example, to get the first model from a Structure object, use -

    >>> first_model = structure[0]
    -

    The Model object stores a list of Chain children.

    -

    11.2.3  Chain

    The id of a Chain object is derived from the chain identifier in the PDB/mmCIF +Crystal structures generally have only one model (with id 0), while NMR files usually have several models. Whereas many PDB parsers assume that there is only one model, the Structure class in Bio.PDB is designed such that it can easily handle PDB files with more than one model.

    As an example, to get the first model from a Structure object, use +

    >>> first_model = structure[0]
    +

    The Model object stores a list of Chain children.

    + +

    11.2.3  Chain

    The id of a Chain object is derived from the chain identifier in the PDB/mmCIF file, and is a single character (typically a letter). Each Chain in a Model object has a unique id. As an example, to get the Chain object with identifier “A” from a Model object, use -

    >>> chain_A = model["A"]
    -

    The Chain object stores a list of Residue children.

    -

    11.2.4  Residue

    A residue id is a tuple with three elements:

    • -The hetero-field (hetfield): this is -
      • -'W' in the case of a water molecule; -
      • 'H_' followed by the residue name for other hetero residues (e.g. 'H_GLC' in the case of a glucose molecule); -
      • blank for standard amino and nucleic acids. -
      -This scheme is adopted for reasons described in section 11.4.1. -
    • The sequence identifier (resseq), an integer describing the position of the residue in the chain (e.g., 100); -
    • The insertion code (icode); a string, e.g. ’A’. The insertion code is sometimes used to preserve a certain desirable residue numbering scheme. A Ser 80 insertion mutant (inserted e.g. between a Thr 80 and an Asn 81 +

      >>> chain_A = model["A"]
      +

      The Chain object stores a list of Residue children.

      + +

      11.2.4  Residue

      A residue id is a tuple with three elements:

      • +The hetero-field (hetfield): this is +
        • +'W' in the case of a water molecule; +
        • 'H_' followed by the residue name for other hetero residues (e.g. 'H_GLC' in the case of a glucose molecule); +
        • blank for standard amino and nucleic acids. +
        +This scheme is adopted for reasons described in section 11.4.1. +
      • The sequence identifier (resseq), an integer describing the position of the residue in the chain (e.g., 100); +
      • The insertion code (icode); a string, e.g. ’A’. The insertion code is sometimes used to preserve a certain desirable residue numbering scheme. A Ser 80 insertion mutant (inserted e.g. between a Thr 80 and an Asn 81 residue) could e.g. have sequence identifiers and insertion codes as follows: Thr 80 A, Ser 80 B, Asn 81. In this way the residue numbering scheme stays in tune with that of the wild type structure. -

      -The id of the above glucose residue would thus be (’H_GLC’, -100, ’A’). If the hetero-flag and insertion code are blank, the sequence -identifier alone can be used:

      # Full id
      +

    +The id of the above glucose residue would thus be (’H_GLC’, +100, ’A’). If the hetero-flag and insertion code are blank, the sequence +identifier alone can be used:

    # Full id
     >>> residue=chain[(' ', 100, ' ')]
     # Shortcut id
     >>> residue=chain[100]
    -

    The reason for the hetero-flag is that many, many PDB files use the +

    The reason for the hetero-flag is that many, many PDB files use the same sequence identifier for an amino acid and a hetero-residue or a water, which would create obvious problems if the hetero-flag was -not used.

    Unsurprisingly, a Residue object stores a set of Atom children. It also contains a string that specifies the residue name (e.g. “ASN”) +not used.

    Unsurprisingly, a Residue object stores a set of Atom children. It also contains a string that specifies the residue name (e.g. “ASN”) and the segment identifier of the residue (well known to X-PLOR users, but not -used in the construction of the SMCRA data structure).

    Let’s look at some examples. Asn 10 with a blank insertion code would have residue -id (’ ’, 10, ’ ’). Water 10 would have residue id (’W’, 10, ’ ’). +used in the construction of the SMCRA data structure).

    Let’s look at some examples. Asn 10 with a blank insertion code would have residue +id (’ ’, 10, ’ ’). Water 10 would have residue id (’W’, 10, ’ ’). A glucose molecule (a hetero residue with residue name GLC) with sequence identifier -10 would have residue id (’H_GLC’, 10, ’ ’). In this way, the three +10 would have residue id (’H_GLC’, 10, ’ ’). In this way, the three residues (with the same insertion code and sequence identifier) can be part -of the same chain because their residue id’s are distinct.

    In most cases, the hetflag and insertion code fields will be blank, e.g. (’ ’, 10, ’ ’). +of the same chain because their residue id’s are distinct.

    In most cases, the hetflag and insertion code fields will be blank, e.g. (’ ’, 10, ’ ’). In these cases, the sequence identifier can be used as a shortcut for the full -id:

    # use full id
    +id:

    # use full id
     >>> res10 = chain[(' ', 10, ' ')]
     # use shortcut
     >>> res10 = chain[10]
    -

    Each Residue object in a Chain object should have a unique id. However, disordered -residues are dealt with in a special way, as described in section 11.3.3.

    A Residue object has a number of additional methods:

    >>> residue.get_resname()       # returns the residue name, e.g. "ASN"
    +

    Each Residue object in a Chain object should have a unique id. However, disordered +residues are dealt with in a special way, as described in section 11.3.3.

    A Residue object has a number of additional methods:

    >>> residue.get_resname()       # returns the residue name, e.g. "ASN"
     >>> residue.is_disordered()     # returns 1 if the residue has disordered atoms
     >>> residue.get_segid()         # returns the SEGID, e.g. "CHN1"
     >>> residue.has_id(name)        # test if a residue has a certain atom
    -

    You can use is_aa(residue) to test if a Residue object is an amino acid.

    -

    11.2.5  Atom

    The Atom object stores the data associated with an atom, and has no children. +

    You can use is_aa(residue) to test if a Residue object is an amino acid.

    + +

    11.2.5  Atom

    The Atom object stores the data associated with an atom, and has no children. The id of an atom is its atom name (e.g. “OG” for the side chain oxygen -of a Ser residue). An Atom id needs to be unique in a Residue. Again, an exception is made for disordered atoms, as described in section 11.3.2.

    The atom id is simply the atom name (eg. ’CA’). In practice, +of a Ser residue). An Atom id needs to be unique in a Residue. Again, an exception is made for disordered atoms, as described in section 11.3.2.

    The atom id is simply the atom name (eg. ’CA’). In practice, the atom name is created by stripping all spaces from the atom name -in the PDB file.

    However, in PDB files, a space can be part of an atom name. Often, -calcium atoms are called ’CA..’ in order to distinguish them -from Cα atoms (which are called ’.CA.’). In cases +in the PDB file.

    However, in PDB files, a space can be part of an atom name. Often, +calcium atoms are called ’CA..’ in order to distinguish them +from Cα atoms (which are called ’.CA.’). In cases were stripping the spaces would create problems (ie. two atoms called -’CA’ in the same residue) the spaces are kept.

    In a PDB file, an atom name consists of 4 chars, typically with leading and +’CA’ in the same residue) the spaces are kept.

    In a PDB file, an atom name consists of 4 chars, typically with leading and trailing spaces. Often these spaces can be removed for ease of use (e.g. an amino acid C α atom is labeled “.CA.” in a PDB file, where the dots represent spaces). To generate an atom name (and thus an atom id) the @@ -5841,13 +6015,13 @@ (i.e. two Atom objects with the same atom name and id). In the latter case, the atom name including spaces is tried. This situation can e.g. happen when one residue contains atoms with names “.CA.” and “CA..”, although -this is not very likely.

    The atomic data stored includes the atom name, the atomic coordinates (including +this is not very likely.

    The atomic data stored includes the atom name, the atomic coordinates (including standard deviation if present), the B factor (including anisotropic B factors and standard deviation if present), the altloc specifier and the full atom name including spaces. Less used items like the atom element number or the atomic -charge sometimes specified in a PDB file are not stored.

    To manipulate the atomic coordinates, use the transform method of -the Atom object. Use the set_coord method to specify the -atomic coordinates directly.

    An Atom object has the following additional methods:

    >>> a.get_name()       # atom name (spaces stripped, e.g. "CA")
    +charge sometimes specified in a PDB file are not stored.

    To manipulate the atomic coordinates, use the transform method of +the Atom object. Use the set_coord method to specify the +atomic coordinates directly.

    An Atom object has the following additional methods:

    >>> a.get_name()       # atom name (spaces stripped, e.g. "CA")
     >>> a.get_id()         # id (equals atom name)
     >>> a.get_coord()      # atomic coordinates
     >>> a.get_vector()     # atomic coordinates as Vector object
    @@ -5858,15 +6032,15 @@
     >>> a.get_siguij()     # standard deviation of anisotropic B factor
     >>> a.get_anisou()     # anisotropic B factor
     >>> a.get_fullname()   # atom name (with spaces, e.g. ".CA.")
    -

    To represent the atom coordinates, siguij, anisotropic B factor and sigatm Numpy -arrays are used.

    The get_vector method returns a Vector object representation of the coordinates of the Atom object, allowing you to do vector operations on atomic coordinates. Vector implements the full set of 3D vector operations, matrix multiplication (left and right) and some advanced rotation-related operations as well.

    As an example of the capabilities of Bio.PDB’s Vector module, +

    To represent the atom coordinates, siguij, anisotropic B factor and sigatm Numpy +arrays are used.

    The get_vector method returns a Vector object representation of the coordinates of the Atom object, allowing you to do vector operations on atomic coordinates. Vector implements the full set of 3D vector operations, matrix multiplication (left and right) and some advanced rotation-related operations as well.

    As an example of the capabilities of Bio.PDB’s Vector module, suppose that you would like to find the position of a Gly residue’s Cβ atom, if it had one. Rotating the N atom of the Gly residue along the Cα-C bond over -120 degrees roughly puts it in the position of a virtual Cβ atom. Here’s how to -do it, making use of the rotaxis method (which can be used -to construct a rotation around a certain axis) of the Vector -module:

    # get atom coordinates as vectors
    +do it, making use of the rotaxis method (which can be used
    +to construct a rotation around a certain axis) of the Vector
    +module:

    # get atom coordinates as vectors
     >>> n = residue['N'].get_vector() 
     >>> c = residue['C'].get_vector() 
     >>> ca = residue['CA'].get_vector()
    @@ -5880,24 +6054,27 @@
     >>> cb_at_origin = n.left_multiply(rot)
     # put on top of ca atom
     >>> cb = cb_at_origin+ca
    -

    This example shows that it’s possible to do some quite nontrivial +

    This example shows that it’s possible to do some quite nontrivial vector operations on atomic data, which can be quite useful. In addition -to all the usual vector operations (cross (use **), and -dot (use *) product, angle, norm, etc.) and the above mentioned -rotaxis function, the Vector module also has methods -to rotate (rotmat) or reflect (refmat) one vector -on top of another.

    -

    11.2.6  Extracting a specific Atom/Residue/Chain/Model -from a Structure

    These are some examples:

    >>> model = structure[0]
    +

    11.2.6  Extracting a specific Atom/Residue/Chain/Model +from a Structure

    These are some examples:

    >>> model = structure[0]
     >>> chain = model['A']
     >>> residue = chain[100]
     >>> atom = residue['CA']
    -

    Note that you can use a shortcut:

    >>> atom = structure[0]['A'][100]['CA']
    -
    -

    11.3  Disorder

    Bio.PDB can handle both disordered atoms and point mutations (i.e. a -Gly and an Ala residue in the same position).

    -

    11.3.1  General approach

    Disorder should be dealt with from two points of view: the atom and the residue +

    Note that you can use a shortcut:

    >>> atom = structure[0]['A'][100]['CA']
    +
    + +

    11.3  Disorder

    Bio.PDB can handle both disordered atoms and point mutations (i.e. a +Gly and an Ala residue in the same position).

    + +

    11.3.1  General approach

    Disorder should be dealt with from two points of view: the atom and the residue points of view. In general, we have tried to encapsulate all the complexity that arises from disorder. If you just want to loop over all Cα atoms, you do not care that some residues have a disordered side chain. On the other @@ -5906,134 +6083,141 @@ that behave as if there is no disorder. This is done by only representing a subset of the disordered atoms or residues. Which subset is picked (e.g. which of the two disordered OG side chain atom positions of a Ser residue is used) -can be specified by the user.

    -

    11.3.2  Disordered atoms

    Disordered atoms are represented by ordinary Atom objects, but -all Atom objects that represent the same physical atom are stored -in a DisorderedAtom object (see Fig. 11.1). -Each Atom object in a DisorderedAtom object can -be uniquely indexed using its altloc specifier. The DisorderedAtom +can be specified by the user.

    + +

    11.3.2  Disordered atoms

    Disordered atoms are represented by ordinary Atom objects, but +all Atom objects that represent the same physical atom are stored +in a DisorderedAtom object (see Fig. 11.1). +Each Atom object in a DisorderedAtom object can +be uniquely indexed using its altloc specifier. The DisorderedAtom object forwards all uncaught method calls to the selected Atom object, by default the one that represents the atom with the highest -occupancy. The user can of course change the selected Atom +occupancy. The user can of course change the selected Atom object, making use of its altloc specifier. In this way atom disorder is represented correctly without much additional complexity. In other words, if you are not interested in atom disorder, you will not be -bothered by it.

    Each disordered atom has a characteristic altloc identifier. You can -specify that a DisorderedAtom object should behave like -the Atom object associated with a specific altloc identifier:

    >>> atom.disordered_select('A') # select altloc A atom
    ->>> print atom.get_altloc()
    +bothered by it.

    Each disordered atom has a characteristic altloc identifier. You can +specify that a DisorderedAtom object should behave like +the Atom object associated with a specific altloc identifier:

    >>> atom.disordered_select('A') # select altloc A atom
    +>>> print(atom.get_altloc())
     "A"
     >>> atom.disordered_select('B') # select altloc B atom
    ->>> print atom.get_altloc()
    +>>> print(atom.get_altloc())
     "B"
    -
    -

    11.3.3  Disordered residues

    -

    Common case

    The most common case is a residue that contains one or more disordered atoms. +

    + +

    11.3.3  Disordered residues

    +

    Common case

    The most common case is a residue that contains one or more disordered atoms. This is evidently solved by using DisorderedAtom objects to represent the disordered atoms, and storing the DisorderedAtom object in a Residue object just like ordinary Atom objects. The DisorderedAtom will behave exactly like an ordinary atom (in fact the atom with the highest occupancy) by forwarding all uncaught method -calls to one of the Atom objects (the selected Atom object) it contains.

    -

    Point mutations

    A special case arises when disorder is due to a point mutation, i.e. when two +calls to one of the Atom objects (the selected Atom object) it contains.

    +

    Point mutations

    A special case arises when disorder is due to a point mutation, i.e. when two or more point mutants of a polypeptide are present in the crystal. An example -of this can be found in PDB structure 1EN2.

    Since these residues belong to a different residue type (e.g. let’s -say Ser 60 and Cys 60) they should not be stored in a single Residue +of this can be found in PDB structure 1EN2.

    Since these residues belong to a different residue type (e.g. let’s +say Ser 60 and Cys 60) they should not be stored in a single Residue object as in the common case. In this case, each residue is represented -by one Residue object, and both Residue objects -are stored in a single DisorderedResidue object (see Fig. -11.1).

    The DisorderedResidue object forwards all uncaught methods to -the selected Residue object (by default the last Residue +by one Residue object, and both Residue objects +are stored in a single DisorderedResidue object (see Fig. +11.1).

    The DisorderedResidue object forwards all uncaught methods to +the selected Residue object (by default the last Residue object added), and thus behaves like an ordinary residue. Each -Residue object in a DisorderedResidue object can be +Residue object in a DisorderedResidue object can be uniquely identified by its residue name. In the above example, residue Ser 60 -would have id “SER” in the DisorderedResidue object, while +would have id “SER” in the DisorderedResidue object, while residue Cys 60 would have id “CYS”. The user can select the active -Residue object in a DisorderedResidue object via this id.

    Example: suppose that a chain has a point mutation at position 10, +Residue object in a DisorderedResidue object via this id.

    Example: suppose that a chain has a point mutation at position 10, consisting of a Ser and a Cys residue. Make sure that residue 10 of this chain behaves as the Cys residue. -

    >>> residue = chain[10]
    +

    >>> residue = chain[10]
     >>> residue.disordered_select('CYS')
    -

    In addition, you can get a list of all Atom objects (ie. -all DisorderedAtom objects are ’unpacked’ to their individual -Atom objects) using the get_unpacked_list method -of a (Disordered)Residue object.

    -

    11.4  Hetero residues

    -

    11.4.1  Associated problems

    A common problem with hetero residues is that several hetero and non-hetero +

    In addition, you can get a list of all Atom objects (ie. +all DisorderedAtom objects are ’unpacked’ to their individual +Atom objects) using the get_unpacked_list method +of a (Disordered)Residue object.

    + +

    11.4  Hetero residues

    + +

    11.4.1  Associated problems

    A common problem with hetero residues is that several hetero and non-hetero residues present in the same chain share the same sequence identifier (and insertion code). Therefore, to generate a unique id for each hetero residue, waters and -other hetero residues are treated in a different way.

    Remember that Residue object have the tuple (hetfield, resseq, icode) as id. +other hetero residues are treated in a different way.

    Remember that Residue object have the tuple (hetfield, resseq, icode) as id. The hetfield is blank (“ ”) for amino and nucleic acids, and a string for waters and other hetero residues. The content of the hetfield is explained -below.

    -

    11.4.2  Water residues

    The hetfield string of a water residue consists of the letter “W”. So -a typical residue id for a water is (“W”, 1, “ ”).

    -

    11.4.3  Other hetero residues

    The hetfield string for other hetero residues starts with “H_” followed +below.

    + +

    11.4.2  Water residues

    The hetfield string of a water residue consists of the letter “W”. So +a typical residue id for a water is (“W”, 1, “ ”).

    + +

    11.4.3  Other hetero residues

    The hetfield string for other hetero residues starts with “H_” followed by the residue name. A glucose molecule e.g. with residue name “GLC” would have hetfield “H_GLC”. Its residue id could e.g. be (“H_GLC”, -1, “ ”).

    -

    11.5  Navigating through a Structure object

    -

    Parse a PDB file, and extract some Model, Chain, Residue and Atom objects

    >>> from Bio.PDB.PDBParser import PDBParser
    +1, “ ”).

    + +

    11.5  Navigating through a Structure object

    +

    Parse a PDB file, and extract some Model, Chain, Residue and Atom objects

    >>> from Bio.PDB.PDBParser import PDBParser
     >>> parser = PDBParser()
     >>> structure = parser.get_structure("test", "1fat.pdb")
     >>> model = structure[0]
     >>> chain = model["A"]
     >>> residue = chain[1]
     >>> atom = residue["CA"]
    -
    -

    Iterating through all atoms of a structure

    >>> p = PDBParser()
    +
    +

    Iterating through all atoms of a structure

    >>> p = PDBParser()
     >>> structure = p.get_structure('X', 'pdb1fat.ent')
     >>> for model in structure:
     ...     for chain in model:
     ...         for residue in chain:
     ...             for atom in residue:
    -...                 print atom
    +...                 print(atom)
     ...
    -

    There is a shortcut if you want to iterate over all atoms in a structure: -

    >>> atoms = structure.get_atoms()
    +

    There is a shortcut if you want to iterate over all atoms in a structure: +

    >>> atoms = structure.get_atoms()
     >>> for atom in atoms:
    -...     print atom
    +...     print(atom)
     ...
    -

    Similarly, to iterate over all atoms in a chain, use -

    >>> atoms = chain.get_atoms()
    +

    Similarly, to iterate over all atoms in a chain, use +

    >>> atoms = chain.get_atoms()
     >>> for atom in atoms:
    -...     print atom
    +...     print(atom)
     ...
    -
    -

    Iterating over all residues of a model

    or if you want to iterate over all residues in a model: -

    >>> residues = model.get_residues()
    +
    +

    Iterating over all residues of a model

    or if you want to iterate over all residues in a model: +

    >>> residues = model.get_residues()
     >>> for residue in residues:
    -...     print residue
    +...     print(residue)
     ...
    -

    You can also use the Selection.unfold_entities function to get all residues from a structure: -

    >>> res_list = Selection.unfold_entities(structure, 'R')
    -

    or to get all atoms from a chain: -

    >>> atom_list = Selection.unfold_entities(chain, 'A')
    -

    Obviously, A=atom, R=residue, C=chain, M=model, S=structure. +

    You can also use the Selection.unfold_entities function to get all residues from a structure: +

    >>> res_list = Selection.unfold_entities(structure, 'R')
    +

    or to get all atoms from a chain: +

    >>> atom_list = Selection.unfold_entities(chain, 'A')
    +

    Obviously, A=atom, R=residue, C=chain, M=model, S=structure. You can use this to go up in the hierarchy, e.g. to get a list of -(unique) Residue or Chain parents from a list of -Atoms:

    >>> residue_list = Selection.unfold_entities(atom_list, 'R')
    +(unique) Residue or Chain parents from a list of
    +Atoms:

    >>> residue_list = Selection.unfold_entities(atom_list, 'R')
     >>> chain_list = Selection.unfold_entities(atom_list, 'C')
    -

    For more info, see the API documentation.

    -

    Extract a hetero residue from a chain (e.g. a glucose (GLC) moiety with resseq 10)

    >>> residue_id = ("H_GLC", 10, " ")
    +

    For more info, see the API documentation.

    +

    Extract a hetero residue from a chain (e.g. a glucose (GLC) moiety with resseq 10)

    >>> residue_id = ("H_GLC", 10, " ")
     >>> residue = chain[residue_id]
    -
    -

    Print all hetero residues in chain

    >>> for residue in chain.get_list():
    +
    +

    Print all hetero residues in chain

    >>> for residue in chain.get_list():
     ...    residue_id = residue.get_id()
     ...    hetfield = residue_id[0]
     ...    if hetfield[0]=="H":
    -...        print residue_id
    +...        print(residue_id)
     ...
    -
    -

    Print out the coordinates of all CA atoms in a structure with B factor greater than 50

    >>> for model in structure.get_list():
    +
    +

    Print out the coordinates of all CA atoms in a structure with B factor greater than 50

    >>> for model in structure.get_list():
     ...     for chain in model.get_list():
     ...         for residue in chain.get_list():
     ...             if residue.has_id("CA"):
     ...                 ca = residue["CA"]
     ...                 if ca.get_bfactor() > 50.0:
    -...                     print ca.get_coord()
    +...                     print(ca.get_coord())
     ...
    -
    -

    Print out all the residues that contain disordered atoms

    >>> for model in structure.get_list():
    +
    +

    Print out all the residues that contain disordered atoms

    >>> for model in structure.get_list():
     ...     for chain in model.get_list():
     ...         for residue in chain.get_list():
     ...             if residue.is_disordered():
    @@ -6041,12 +6225,12 @@
     ...                 resname = residue.get_resname()
     ...                 model_id = model.get_id()
     ...                 chain_id = chain.get_id()
    -...                 print model_id, chain_id, resname, resseq
    -...
    -
    -

    Loop over all disordered atoms, and select all atoms with altloc A (if present)

    +... print(model_id, chain_id, resname, resseq) +... +

    +

    Loop over all disordered atoms, and select all atoms with altloc A (if present)

    This will make sure that the SMCRA data structure will behave as if only the -atoms with altloc A are present.

    >>> for model in structure.get_list():
    +atoms with altloc A are present.

    >>> for model in structure.get_list():
     ...     for chain in model.get_list():
     ...         for residue in chain.get_list():
     ...             if residue.is_disordered():
    @@ -6055,98 +6239,106 @@
     ...                         if atom.disordered_has_id("A"):
     ...                             atom.disordered_select("A")
     ...
    -
    -

    Extracting polypeptides from a Structure object

    To extract polypeptides from a structure, construct a list of Polypeptide objects from a Structure object using PolypeptideBuilder as follows:

    >>> model_nr = 1
    +
    +

    Extracting polypeptides from a Structure object

    To extract polypeptides from a structure, construct a list of Polypeptide objects from a Structure object using PolypeptideBuilder as follows:

    >>> model_nr = 1
     >>> polypeptide_list = build_peptides(structure, model_nr)
     >>> for polypeptide in polypeptide_list:
    -...     print polypeptide
    +...     print(polypeptide)
     ...
    -

    A Polypeptide object is simply a UserList of Residue objects, and is always created from a single Model (in this case model 1). -You can use the resulting Polypeptide object to get the sequence as a Seq object or to get a list of Cα atoms as well. Polypeptides can be built using a C-N or a Cα-Cα distance criterion.

    Example:

    # Using C-N 
    +

    A Polypeptide object is simply a UserList of Residue objects, and is always created from a single Model (in this case model 1). +You can use the resulting Polypeptide object to get the sequence as a Seq object or to get a list of Cα atoms as well. Polypeptides can be built using a C-N or a Cα-Cα distance criterion.

    Example:

    # Using C-N 
     >>> ppb=PPBuilder()
     >>> for pp in ppb.build_peptides(structure): 
    -...     print pp.get_sequence()
    +...     print(pp.get_sequence())
     ...
     # Using CA-CA
     >>> ppb=CaPPBuilder()
     >>> for pp in ppb.build_peptides(structure): 
    -...     print pp.get_sequence()
    +...     print(pp.get_sequence())
     ...
    -

    Note that in the above case only model 0 of the structure is considered -by PolypeptideBuilder. However, it is possible to use PolypeptideBuilder -to build Polypeptide objects from Model and Chain -objects as well.

    -

    Obtaining the sequence of a structure

    The first thing to do is to extract all polypeptides from the structure +

    Note that in the above case only model 0 of the structure is considered +by PolypeptideBuilder. However, it is possible to use PolypeptideBuilder +to build Polypeptide objects from Model and Chain +objects as well.

    +

    Obtaining the sequence of a structure

    The first thing to do is to extract all polypeptides from the structure (as above). The sequence of each polypeptide can then easily -be obtained from the Polypeptide objects. The sequence is -represented as a Biopython Seq object, and its alphabet is -defined by a ProteinAlphabet object.

    Example:

    >>> seq = polypeptide.get_sequence()
    ->>> print seq
    +be obtained from the Polypeptide objects. The sequence is
    +represented as a Biopython Seq object, and its alphabet is
    +defined by a ProteinAlphabet object.

    Example:

    >>> seq = polypeptide.get_sequence()
    +>>> print(seq)
     Seq('SNVVE...', <class Bio.Alphabet.ProteinAlphabet>)
    -
    -

    11.6  Analyzing structures

    -

    11.6.1  Measuring distances

    +

    + +

    11.6  Analyzing structures

    + +

    11.6.1  Measuring distances

    The minus operator for atoms has been overloaded to return the distance between two atoms. -

    # Get some atoms
    +

    # Get some atoms
     >>> ca1 = residue1['CA']
     >>> ca2 = residue2['CA']
     # Simply subtract the atoms to get their distance
     >>> distance = ca1-ca2
    -
    -

    11.6.2  Measuring angles

    +

    + +

    11.6.2  Measuring angles

    Use the vector representation of the atomic coordinates, and -the calc_angle function from the Vector module: -

    >>> vector1 = atom1.get_vector()
    +the calc_angle function from the Vector module:
    +

    >>> vector1 = atom1.get_vector()
     >>> vector2 = atom2.get_vector()
     >>> vector3 = atom3.get_vector()
     >>> angle = calc_angle(vector1, vector2, vector3)
    -
    -

    11.6.3  Measuring torsion angles

    +

    + +

    11.6.3  Measuring torsion angles

    Use the vector representation of the atomic coordinates, and -the calc_dihedral function from the Vector module: -

    >>> vector1 = atom1.get_vector()
    +the calc_dihedral function from the Vector module:
    +

    >>> vector1 = atom1.get_vector()
     >>> vector2 = atom2.get_vector()
     >>> vector3 = atom3.get_vector()
     >>> vector4 = atom4.get_vector()
     >>> angle = calc_dihedral(vector1, vector2, vector3, vector4)
    -
    -

    11.6.4  Determining atom-atom contacts

    Use NeighborSearch to perform neighbor lookup. -The neighbor lookup is done using a KD tree module written in C (see Bio.KDTree), making it very fast. -It also includes a fast method to find all point pairs within a certain distance of each other.

    -

    11.6.5  Superimposing two structures

    Use a Superimposer object to superimpose two coordinate sets. +

    + +

    11.6.4  Determining atom-atom contacts

    Use NeighborSearch to perform neighbor lookup. +The neighbor lookup is done using a KD tree module written in C (see Bio.KDTree), making it very fast. +It also includes a fast method to find all point pairs within a certain distance of each other.

    + +

    11.6.5  Superimposing two structures

    Use a Superimposer object to superimpose two coordinate sets. This object calculates the rotation and translation matrix that rotates two lists of atoms on top of each other in such a way that their RMSD is minimized. Of course, the two lists need to contain the same number -of atoms. The Superimposer object can also apply the rotation/translation +of atoms. The Superimposer object can also apply the rotation/translation to a list of atoms. The rotation and translation are stored as a tuple -in the rotran attribute of the Superimposer object +in the rotran attribute of the Superimposer object (note that the rotation is right multiplying!). The RMSD is stored -in the rmsd attribute.

    The algorithm used by Superimposer comes from [17, Golub & Van Loan] and makes use of singular value decomposition (this is implemented in the general Bio.SVDSuperimposer module).

    Example:

    >>> sup = Superimposer()
    +in the rmsd attribute.

    The algorithm used by Superimposer comes from [17, Golub & Van Loan] and makes use of singular value decomposition (this is implemented in the general Bio.SVDSuperimposer module).

    Example:

    >>> sup = Superimposer()
     # Specify the atom lists
     # 'fixed' and 'moving' are lists of Atom objects
     # The moving atoms will be put on the fixed atoms
     >>> sup.set_atoms(fixed, moving)
     # Print rotation/translation/rmsd
    ->>> print sup.rotran
    ->>> print sup.rms 
    +>>> print(sup.rotran)
    +>>> print(sup.rms) 
     # Apply rotation/translation to the moving atoms
     >>> sup.apply(moving)
    -

    To superimpose two structures based on their active sites, use the active site atoms to calculate the rotation/translation matrices (as above), and apply these to the whole molecule.

    -

    11.6.6  Mapping the residues of two related structures onto each other

    First, create an alignment file in FASTA format, then use the StructureAlignment +

    To superimpose two structures based on their active sites, use the active site atoms to calculate the rotation/translation matrices (as above), and apply these to the whole molecule.

    + +

    11.6.6  Mapping the residues of two related structures onto each other

    First, create an alignment file in FASTA format, then use the StructureAlignment class. This class can also be used for alignments with more than two -structures.

    -

    11.6.7  Calculating the Half Sphere Exposure

    Half Sphere Exposure (HSE) is a new, 2D measure of solvent exposure -[20]. +structures.

    + +

    11.6.7  Calculating the Half Sphere Exposure

    Half Sphere Exposure (HSE) is a new, 2D measure of solvent exposure +[20]. Basically, it counts the number of Cα atoms around a residue in the direction of its side chain, and in the opposite direction (within a radius of 13 Å). Despite its simplicity, it outperforms -many other measures of solvent exposure.

    HSE comes in two flavors: HSEα and HSEβ. The former +many other measures of solvent exposure.

    HSE comes in two flavors: HSEα and HSEβ. The former only uses the Cα atom positions, while the latter uses the Cα and Cβ atom positions. The HSE measure is calculated -by the HSExposure class, which can also calculate the contact +by the HSExposure class, which can also calculate the contact number. The latter class has methods which return dictionaries that -map a Residue object to its corresponding HSEα, HSEβ -and contact number values.

    Example:

    >>> model = structure[0]
    +map a Residue object to its corresponding HSEα, HSEβ
    +and contact number values.

    Example:

    >>> model = structure[0]
     >>> hse = HSExposure()
     # Calculate HSEalpha
     >>> exp_ca = hse.calc_hs_exposure(model, option='CA3')
    @@ -6155,80 +6347,86 @@
     # Calculate classical coordination number
     >>> exp_fs = hse.calc_fs_exposure(model)
     # Print HSEalpha for a residue
    ->>> print exp_ca[some_residue]
    -
    -

    11.6.8  Determining the secondary structure

    For this functionality, you need to install DSSP (and obtain a license -for it — free for academic use, see http://www.cmbi.kun.nl/gv/dssp/). -Then use the DSSP class, which maps Residue objects +>>> print(exp_ca[some_residue]) +

    + +

    11.6.8  Determining the secondary structure

    For this functionality, you need to install DSSP (and obtain a license +for it — free for academic use, see http://www.cmbi.kun.nl/gv/dssp/). +Then use the DSSP class, which maps Residue objects to their secondary structure (and accessible surface area). The DSSP -codes are listed in Table 11.1. Note that DSSP (the +codes are listed in Table 11.1. Note that DSSP (the program, and thus by consequence the class) cannot handle multiple -models!


    - - - - - - - - - -
    CodeSecondary structure
    Hα-helix
    BIsolated β-bridge residue
    EStrand
    G3-10 helix
    IΠ-helix
    TTurn
    SBend
    -Other
    -
    -
    Table 11.1: DSSP codes in Bio.PDB.
    -

    The DSSP class can also be used to calculate the accessible surface area of a residue. But see also section 11.6.9.

    -

    11.6.9  Calculating the residue depth

    Residue depth is the average distance of a residue’s atoms from the +models!


    + + + + + + + + + +
    CodeSecondary structure
    Hα-helix
    BIsolated β-bridge residue
    EStrand
    G3-10 helix
    IΠ-helix
    TTurn
    SBend
    -Other
    +
    +
    Table 11.1: DSSP codes in Bio.PDB.
    +

    The DSSP class can also be used to calculate the accessible surface area of a residue. But see also section 11.6.9.

    + +

    11.6.9  Calculating the residue depth

    Residue depth is the average distance of a residue’s atoms from the solvent accessible surface. It’s a fairly new and very powerful parameterization of solvent accessibility. For this functionality, you need to install -Michel Sanner’s MSMS program (http://www.scripps.edu/pub/olson-web/people/sanner/html/msms_home.html). -Then use the ResidueDepth class. This class behaves as a -dictionary which maps Residue objects to corresponding (residue +Michel Sanner’s MSMS program (http://www.scripps.edu/pub/olson-web/people/sanner/html/msms_home.html). +Then use the ResidueDepth class. This class behaves as a +dictionary which maps Residue objects to corresponding (residue depth, Cα depth) tuples. The Cα depth is the distance -of a residue’s Cα atom to the solvent accessible surface.

    Example:

    >>> model = structure[0]
    +of a residue’s Cα atom to the solvent accessible surface. 

    Example:

    >>> model = structure[0]
     >>> rd = ResidueDepth(model, pdb_file)
     >>> residue_depth, ca_depth=rd[some_residue]
    -

    You can also get access to the molecular surface itself (via the get_surface -function), in the form of a Numeric Python array with the surface points.

    -

    11.7  Common problems in PDB files

    It is well known that many PDB files contain semantic errors (not the +

    You can also get access to the molecular surface itself (via the get_surface +function), in the form of a Numeric Python array with the surface points.

    + +

    11.7  Common problems in PDB files

    It is well known that many PDB files contain semantic errors (not the structures themselves, but their representation in PDB files). Bio.PDB tries to handle this in two ways. The PDBParser object can behave in two ways: a restrictive way and a permissive -way, which is the default.

    Example:

    # Permissive parser
    +way, which is the default.

    Example:

    # Permissive parser
     >>> parser = PDBParser(PERMISSIVE=1)
     >>> parser = PDBParser() # The same (default)
     # Strict parser
     >>> strict_parser = PDBParser(PERMISSIVE=0)
    -

    In the permissive state (DEFAULT), PDB files that obviously contain +

    In the permissive state (DEFAULT), PDB files that obviously contain errors are “corrected” (i.e. some residues or atoms are left out). -These errors include:

    • +These errors include:

      • Multiple residues with the same identifier -
      • Multiple atoms with the same identifier (taking into account the altloc +
      • Multiple atoms with the same identifier (taking into account the altloc identifier) -

      +

    These errors indicate real problems in the PDB file (for details see -[18, Hamelryck and Manderick, 2003]). In the restrictive state, PDB files with errors cause an exception to occur. This is useful to find errors in PDB files.

    Some errors however are automatically corrected. Normally each disordered +[18, Hamelryck and Manderick, 2003]). In the restrictive state, PDB files with errors cause an exception to occur. This is useful to find errors in PDB files.

    Some errors however are automatically corrected. Normally each disordered atom should have a non-blank altloc identifier. However, there are many structures that do not follow this convention, and have a blank and a non-blank identifier for two disordered positions of the same -atom. This is automatically interpreted in the right way.

    Sometimes a structure contains a list of residues belonging to chain +atom. This is automatically interpreted in the right way.

    Sometimes a structure contains a list of residues belonging to chain A, followed by residues belonging to chain B, and again followed by residues belonging to chain A, i.e. the chains are ’broken’. This -is also correctly interpreted.

    -

    11.7.1  Examples

    The PDBParser/Structure class was tested on about 800 structures (each belonging +is also correctly interpreted.

    + +

    11.7.1  Examples

    The PDBParser/Structure class was tested on about 800 structures (each belonging to a unique SCOP superfamily). This takes about 20 minutes, or on average 1.5 seconds per structure. Parsing the structure of the large ribosomal subunit -(1FKK), which contains about 64000 atoms, takes 10 seconds on a 1000 MHz PC.

    Three exceptions were generated in cases where an unambiguous data structure +(1FKK), which contains about 64000 atoms, takes 10 seconds on a 1000 MHz PC.

    Three exceptions were generated in cases where an unambiguous data structure could not be built. In all three cases, the likely cause is an error in the PDB file that should be corrected. Generating an exception in these cases is much better than running the chance of incorrectly describing -the structure in a data structure.

    -

    11.7.1.1  Duplicate residues

    One structure contains two amino acid residues in one chain with the same sequence +the structure in a data structure.

    + +

    11.7.1.1  Duplicate residues

    One structure contains two amino acid residues in one chain with the same sequence identifier (resseq 3) and icode. Upon inspection it was found that this chain contains the residues Thr A3, …, Gly A202, Leu A3, Glu A204. Clearly, Leu A3 should be Leu A203. A couple of similar situations exist for structure 1FFK (which e.g. contains Gly B64, Met B65, Glu B65, Thr B67, i.e. residue Glu -B65 should be Glu B66).

    -

    11.7.1.2  Duplicate atoms

    Structure 1EJG contains a Ser/Pro point mutation in chain A at position 22. +B65 should be Glu B66).

    + +

    11.7.1.2  Duplicate atoms

    Structure 1EJG contains a Ser/Pro point mutation in chain A at position 22. In turn, Ser 22 contains some disordered atoms. As expected, all atoms belonging to Ser 22 have a non-blank altloc specifier (B or C). All atoms of Pro 22 have altloc A, except the N atom which has a blank altloc. This generates an exception, @@ -6236,141 +6434,158 @@ non-blank altloc. It turns out that this atom is probably shared by Ser and Pro 22, as Ser 22 misses the N atom. Again, this points to a problem in the file: the N atom should be present in both the Ser and the Pro residue, in both -cases associated with a suitable altloc identifier.

    -

    11.7.2  Automatic correction

    Some errors are quite common and can be easily corrected without much risk of -making a wrong interpretation. These cases are listed below.

    -

    11.7.2.1  A blank altloc for a disordered atom

    Normally each disordered atom should have a non-blank altloc identifier. However, +cases associated with a suitable altloc identifier.

    + +

    11.7.2  Automatic correction

    Some errors are quite common and can be easily corrected without much risk of +making a wrong interpretation. These cases are listed below.

    + +

    11.7.2.1  A blank altloc for a disordered atom

    Normally each disordered atom should have a non-blank altloc identifier. However, there are many structures that do not follow this convention, and have a blank and a non-blank identifier for two disordered positions of the same atom. This -is automatically interpreted in the right way.

    -

    11.7.2.2  Broken chains

    Sometimes a structure contains a list of residues belonging to chain A, followed +is automatically interpreted in the right way.

    + +

    11.7.2.2  Broken chains

    Sometimes a structure contains a list of residues belonging to chain A, followed by residues belonging to chain B, and again followed by residues belonging to -chain A, i.e. the chains are “broken”. This is correctly interpreted.

    -

    11.7.3  Fatal errors

    Sometimes a PDB file cannot be unambiguously interpreted. Rather than guessing +chain A, i.e. the chains are “broken”. This is correctly interpreted.

    + +

    11.7.3  Fatal errors

    Sometimes a PDB file cannot be unambiguously interpreted. Rather than guessing and risking a mistake, an exception is generated, and the user is expected to -correct the PDB file. These cases are listed below.

    -

    11.7.3.1  Duplicate residues

    All residues in a chain should have a unique id. This id is generated based -on:

    • +correct the PDB file. These cases are listed below.

      + +

      11.7.3.1  Duplicate residues

      All residues in a chain should have a unique id. This id is generated based +on:

      • The sequence identifier (resseq). -
      • The insertion code (icode). -
      • The hetfield string (“W” for waters and “H_” followed by the +
      • The insertion code (icode). +
      • The hetfield string (“W” for waters and “H_” followed by the residue name for other hetero residues) -
      • The residue names of the residues in the case of point mutations (to store the +
      • The residue names of the residues in the case of point mutations (to store the Residue objects in a DisorderedResidue object). -

      +

    If this does not lead to a unique id something is quite likely wrong, and an -exception is generated.

    -

    11.7.3.2  Duplicate atoms

    All atoms in a residue should have a unique id. This id is generated based on:

    • +exception is generated.

      + +

      11.7.3.2  Duplicate atoms

      All atoms in a residue should have a unique id. This id is generated based on:

      • The atom name (without spaces, or with spaces if a problem arises). -
      • The altloc specifier. -

      +

    • The altloc specifier. +

    If this does not lead to a unique id something is quite likely wrong, and an -exception is generated.

    -

    11.8  Accessing the Protein Data Bank

    -

    11.8.1  Downloading structures from the Protein Data Bank

    Structures can be downloaded from the PDB (Protein Data Bank) -by using the retrieve_pdb_file method on a PDBList object. -The argument for this method is the PDB identifier of the structure.

    >>> pdbl = PDBList()
    +exception is generated.

    + +

    11.8  Accessing the Protein Data Bank

    + +

    11.8.1  Downloading structures from the Protein Data Bank

    Structures can be downloaded from the PDB (Protein Data Bank) +by using the retrieve_pdb_file method on a PDBList object. +The argument for this method is the PDB identifier of the structure.

    >>> pdbl = PDBList()
     >>> pdbl.retrieve_pdb_file('1FAT')
    -

    The PDBList class can also be used as a command-line tool: -

    python PDBList.py 1fat
    -

    The downloaded file will be called pdb1fat.ent and stored -in the current working directory. Note that the retrieve_pdb_file -method also has an optional argument pdir that specifies -a specific directory in which to store the downloaded PDB files.

    The retrieve_pdb_file method also has some options to specify +

    The PDBList class can also be used as a command-line tool: +

    python PDBList.py 1fat
    +

    The downloaded file will be called pdb1fat.ent and stored +in the current working directory. Note that the retrieve_pdb_file +method also has an optional argument pdir that specifies +a specific directory in which to store the downloaded PDB files.

    The retrieve_pdb_file method also has some options to specify the compression format used for the download, and the program used -for local decompression (default .Z format and gunzip). +for local decompression (default .Z format and gunzip). In addition, the PDB ftp site can be specified upon creation of the -PDBList object. By default, the server of the Worldwide Protein Data Bank (ftp://ftp.wwpdb.org/pub/pdb/data/structures/divided/pdb/) +PDBList object. By default, the server of the Worldwide Protein Data Bank (ftp://ftp.wwpdb.org/pub/pdb/data/structures/divided/pdb/) is used. See the API documentation for more details. Thanks again -to Kristian Rother for donating this module.

    -

    11.8.2  Downloading the entire PDB

    The following commands will store all PDB files in the /data/pdb -directory:

    python PDBList.py all /data/pdb
    +to Kristian Rother for donating this module.

    + +

    11.8.2  Downloading the entire PDB

    The following commands will store all PDB files in the /data/pdb +directory:

    python PDBList.py all /data/pdb
     
     python PDBList.py all /data/pdb -d
    -

    The API method for this is called download_entire_pdb. -Adding the -d option will store all files in the same directory. +

    The API method for this is called download_entire_pdb. +Adding the -d option will store all files in the same directory. Otherwise, they are sorted into PDB-style subdirectories according to their PDB ID’s. Depending on the traffic, a complete download will -take 2-4 days.

    -

    11.8.3  Keeping a local copy of the PDB up to date

    This can also be done using the PDBList object. One simply -creates a PDBList object (specifying the directory where -the local copy of the PDB is present) and calls the update_pdb -method:

    >>> pl = PDBList(pdb='/data/pdb')
    +take 2-4 days. 

    + +

    11.8.3  Keeping a local copy of the PDB up to date

    This can also be done using the PDBList object. One simply +creates a PDBList object (specifying the directory where +the local copy of the PDB is present) and calls the update_pdb +method:

    >>> pl = PDBList(pdb='/data/pdb')
     >>> pl.update_pdb()
    -

    One can of course make a weekly cronjob out of this to keep +

    One can of course make a weekly cronjob out of this to keep the local copy automatically up-to-date. The PDB ftp site can also -be specified (see API documentation).

    PDBList has some additional methods that can be of use. The -get_all_obsolete method can be used to get a list of all -obsolete PDB entries. The changed_this_week method can +be specified (see API documentation).

    PDBList has some additional methods that can be of use. The +get_all_obsolete method can be used to get a list of all +obsolete PDB entries. The changed_this_week method can be used to obtain the entries that were added, modified or obsoleted -during the current week. For more info on the possibilities of PDBList, -see the API documentation.

    -

    11.9  General questions

    -

    11.9.1  How well tested is Bio.PDB?

    Pretty well, actually. Bio.PDB has been extensively tested on nearly +during the current week. For more info on the possibilities of PDBList, +see the API documentation.

    + +

    11.9  General questions

    + +

    11.9.1  How well tested is Bio.PDB?

    Pretty well, actually. Bio.PDB has been extensively tested on nearly 5500 structures from the PDB - all structures seemed to be parsed correctly. More details can be found in the Bio.PDB Bioinformatics article. Bio.PDB has been used/is being used in many research projects as a reliable tool. In fact, I’m using Bio.PDB almost daily for research -purposes and continue working on improving it and adding new features.

    -

    11.9.2  How fast is it?

    The PDBParser performance was tested on about 800 structures +purposes and continue working on improving it and adding new features.

    + +

    11.9.2  How fast is it?

    The PDBParser performance was tested on about 800 structures (each belonging to a unique SCOP superfamily). This takes about 20 minutes, or on average 1.5 seconds per structure. Parsing the structure of the large ribosomal subunit (1FKK), which contains about 64000 atoms, takes 10 seconds on a 1000 MHz PC. In short: it’s more than -fast enough for many applications.

    -

    11.9.3  Is there support for molecular graphics?

    Not directly, mostly since there are quite a few Python based/Python +fast enough for many applications.

    + +

    11.9.3  Is there support for molecular graphics?

    Not directly, mostly since there are quite a few Python based/Python aware solutions already, that can potentially be used with Bio.PDB. My choice is Pymol, BTW (I’ve used this successfully with Bio.PDB, and there will probably be specific PyMol modules in Bio.PDB soon/some -day). Python based/aware molecular graphics solutions include:

    -

    11.9.4  Who’s using Bio.PDB?

    Bio.PDB was used in the construction of DISEMBL, a web server that -predicts disordered regions in proteins (http://dis.embl.de/), +day). Python based/aware molecular graphics solutions include:

    + +

    11.9.4  Who’s using Bio.PDB?

    Bio.PDB was used in the construction of DISEMBL, a web server that +predicts disordered regions in proteins (http://dis.embl.de/), and COLUMBA, a website that provides annotated protein structures -(http://www.columba-db.de/). Bio.PDB has also been used to +(http://www.columba-db.de/). Bio.PDB has also been used to perform a large scale search for active sites similarities between -protein structures in the PDB [19, Hamelryck, 2003], and to develop a new algorithm -that identifies linear secondary structure elements [26, Majumdar et al., 2005].

    Judging from requests for features and information, Bio.PDB is also -used by several LPCs (Large Pharmaceutical Companies :-).

    -

    Chapter 12  Bio.PopGen: Population genetics

    Bio.PopGen is a Biopython module supporting population genetics, -available in Biopython 1.44 onwards.

    The medium term objective for the module is to support widely used data +protein structures in the PDB [19, Hamelryck, 2003], and to develop a new algorithm +that identifies linear secondary structure elements [26, Majumdar et al., 2005].

    Judging from requests for features and information, Bio.PDB is also +used by several LPCs (Large Pharmaceutical Companies :-).

    + +

    Chapter 12  Bio.PopGen: Population genetics

    Bio.PopGen is a Biopython module supporting population genetics, +available in Biopython 1.44 onwards.

    The medium term objective for the module is to support widely used data formats, applications and databases. This module is currently under intense development and support for new features should appear at a rather fast pace. Unfortunately this might also entail some instability on the API, especially if you are using a development version. APIs that are made available on -our official public releases should be much more stable.

    -

    12.1  GenePop

    GenePop (http://genepop.curtin.edu.au/) is a popular population +our official public releases should be much more stable.

    + +

    12.1  GenePop

    GenePop (http://genepop.curtin.edu.au/) is a popular population genetics software package supporting Hardy-Weinberg tests, linkage -desiquilibrium, population diferentiation, basic statistics, Fst and +desiquilibrium, population diferentiation, basic statistics, Fst and migration estimates, among others. GenePop does not supply sequence based statistics as it doesn’t handle sequence data. The GenePop file format is supported by a wide range of other population genetic software applications, thus making it a relevant format in the -population genetics field.

    Bio.PopGen provides a parser and generator of GenePop file format. +population genetics field.

    Bio.PopGen provides a parser and generator of GenePop file format. Utilities to manipulate the content of a record are also provided. Here is an example on how to read a GenePop file (you can find -example GenePop data files in the Test/PopGen directory of Biopython):

    from Bio.PopGen import GenePop
    +example GenePop data files in the Test/PopGen directory of Biopython):

    from Bio.PopGen import GenePop
     
     handle = open("example.gen")
     rec = GenePop.read(handle)
     handle.close()
    -

    This will read a file called example.gen and parse it. If you -do print rec, the record will be output again, in GenePop format.

    The most important information in rec will be the loci names and +

    This will read a file called example.gen and parse it. If you +do print rec, the record will be output again, in GenePop format.

    The most important information in rec will be the loci names and population information (but there is more – use help(GenePop.Record) to check the API documentation). Loci names can be found on rec.loci_list. Population information can be found on rec.populations. Populations is a list with one element per population. Each element is itself a list of individuals, each individual is a pair composed by individual name and a list of alleles (2 per marker), here is an example for -rec.populations:

    [
    +rec.populations:

    [
         [
             ('Ind1', [(1, 2),    (3, 3), (200, 201)],
             ('Ind2', [(2, None), (3, 3), (None, None)],
    @@ -6379,12 +6594,12 @@
             ('Other1', [(1, 1),  (4, 3), (200, 200)],
         ]
     ]
    -

    So we have two populations, the first with two individuals, the +

    So we have two populations, the first with two individuals, the second with only one. The first individual of the first population is called Ind1, allelic information for each of the 3 loci follows. Please note that for any locus, information -might be missing (see as an example, Ind2 above).

    A few utility functions to manipulate GenePop records are made -available, here is an example:

    from Bio.PopGen import GenePop
    +might be missing (see as an example, Ind2 above).

    A few utility functions to manipulate GenePop records are made +available, here is an example:

    from Bio.PopGen import GenePop
     
     #Imagine that you have loaded rec, as per the code snippet above...
     
    @@ -6419,77 +6634,80 @@
     #  they are passed in array (pop_names).
     #  The value of each dictionary entry is the GenePop record.
     #  rec is not altered.
    -

    GenePop does not support population names, a limitation which can be +

    GenePop does not support population names, a limitation which can be cumbersome at times. Functionality to enable population names is currently being planned for Biopython. These extensions won’t break compatibility in any way with the standard format. In the medium term, we would also like to -support the GenePop web service.

    -

    12.2  Coalescent simulation

    A coalescent simulation is a backward model of population genetics with relation to +support the GenePop web service.

    + +

    12.2  Coalescent simulation

    A coalescent simulation is a backward model of population genetics with relation to time. A simulation of ancestry is done until the Most Recent Common Ancestor (MRCA) is found. This ancestry relationship starting on the MRCA and ending on the current generation sample is sometimes called a genealogy. Simple cases assume a population of constant size in time, haploidy, no population structure, and simulate the alleles of a single -locus under no selection pressure.

    Coalescent theory is used in many fields like selection detection, estimation of -demographic parameters of real populations or disease gene mapping.

    The strategy followed in the Biopython implementation of the coalescent was not +locus under no selection pressure.

    Coalescent theory is used in many fields like selection detection, estimation of +demographic parameters of real populations or disease gene mapping.

    The strategy followed in the Biopython implementation of the coalescent was not to create a new, built-in, simulator from scratch but to use an existing one, -SIMCOAL2 (http://cmpg.unibe.ch/software/simcoal2/). SIMCOAL2 allows for, +SIMCOAL2 (http://cmpg.unibe.ch/software/simcoal2/). SIMCOAL2 allows for, among others, population structure, multiple demographic events, simulation of multiple types of loci (SNPs, sequences, STRs/microsatellites and RFLPs) with recombination, diploidy multiple chromosomes or ascertainment bias. Notably SIMCOAL2 doesn’t support any selection model. We recommend reading SIMCOAL2’s -documentation, available in the link above.

    The input for SIMCOAL2 is a file specifying the desired demography and genome, +documentation, available in the link above.

    The input for SIMCOAL2 is a file specifying the desired demography and genome, the output is a set of files (typically around 1000) with the simulated genomes of a sample of individuals per subpopulation. This set of files can be used in many ways, like to compute confidence intervals where which certain -statistics (e.g., Fst or Tajima D) are expected to lie. Real population -genetics datasets statistics can then be compared to those confidence intervals.

    Biopython coalescent code allows to create demographic scenarios and genomes and -to run SIMCOAL2.

    -

    12.2.1  Creating scenarios

    Creating a scenario involves both creating a demography and a chromosome structure. +statistics (e.g., Fst or Tajima D) are expected to lie. Real population +genetics datasets statistics can then be compared to those confidence intervals.

    Biopython coalescent code allows to create demographic scenarios and genomes and +to run SIMCOAL2.

    + +

    12.2.1  Creating scenarios

    Creating a scenario involves both creating a demography and a chromosome structure. In many cases (e.g. when doing Approximate Bayesian Computations – ABC) it is important to test many parameter variations (e.g. vary the effective population size, -Ne, between 10, 50, 500 and 1000 individuals). The code provided allows for -the simulation of scenarios with different demographic parameters very easily.

    Below we see how we can create scenarios and then how simulate them.

    -

    12.2.1.1  Demography

    A few predefined demographies are built-in, all have two shared parameters: sample size +Ne, between 10, 50, 500 and 1000 individuals). The code provided allows for +the simulation of scenarios with different demographic parameters very easily.

    Below we see how we can create scenarios and then how simulate them.

    + +

    12.2.1.1  Demography

    A few predefined demographies are built-in, all have two shared parameters: sample size (called sample_size on the template, see below for its use) per deme and deme size, i.e. subpopulation size (pop_size). All demographies are available as templates where all parameters can be varied, each template has a system name. The prefedined -demographies/templates are:

    -Single population, constant size
    The standard parameters are enough to specify +demographies/templates are:

    +Single population, constant size
    The standard parameters are enough to specify it. Template name: simple. -
    Single population, bottleneck
    As seen on figure 12.2.1.1. The parameters +
    Single population, bottleneck
    As seen on figure 12.2.1.1. The parameters are current population size (pop_size on template ne3 on figure), time of expansion, given as the generation in the past when it occurred (expand_gen), effective population size during bottleneck (ne2), time of contraction (contract_gen) and original size in the remote past (ne3). Template name: bottle. -
    Island model
    The typical island model. The total number of demes is specified +
    Island model
    The typical island model. The total number of demes is specified by total_demes and the migration rate by mig. Template name island. -
    Stepping stone model - 1 dimension
    The stepping stone model in 1 dimension, +
    Stepping stone model - 1 dimension
    The stepping stone model in 1 dimension, extremes disconnected. The total number of demes is total_demes, migration rate is mig. Template name is ssm_1d. -
    Stepping stone model - 2 dimensions
    The stepping stone model in 2 dimensions, +
    Stepping stone model - 2 dimensions
    The stepping stone model in 2 dimensions, extremes disconnected. The parameters are x for the horizontal dimension and y for the vertical (being the total number of demes x times y), migration rate is mig. Template name is ssm_2d. -

    - - -

    In our first example, we will generate a template for a single population, constant size -model with a sample size of 30 and a deme size of 500. The code for this is:

    from Bio.PopGen.SimCoal.Template import generate_simcoal_from_template
    +

    + + +

    In our first example, we will generate a template for a single population, constant size +model with a sample size of 30 and a deme size of 500. The code for this is:

    from Bio.PopGen.SimCoal.Template import generate_simcoal_from_template
     
     generate_simcoal_from_template('simple',
         [(1, [('SNP', [24, 0.0005, 0.0])])],
         [('sample_size', [30]),
         ('pop_size', [100])])
    -

    Executing this code snippet will generate a file on the current directory called +

    Executing this code snippet will generate a file on the current directory called simple_100_300.par this file can be given as input to SIMCOAL2 to simulate the -demography (below we will see how Biopython can take care of calling SIMCOAL2).

    This code consists of a single function call, let’s discuss it parameter by parameter.

    The first parameter is the template id (from the list above). We are using the id -’simple’ which is the template for a single population of constant size along time.

    The second parameter is the chromosome structure. Please ignore it for now, it will be -explained in the next section.

    The third parameter is a list of all required parameters (recall that the simple model +demography (below we will see how Biopython can take care of calling SIMCOAL2).

    This code consists of a single function call, let’s discuss it parameter by parameter.

    The first parameter is the template id (from the list above). We are using the id +’simple’ which is the template for a single population of constant size along time.

    The second parameter is the chromosome structure. Please ignore it for now, it will be +explained in the next section.

    The third parameter is a list of all required parameters (recall that the simple model only needs sample_size and pop_size) and possible values (in this case each -parameter only has a possible value).

    Now, let’s consider an example where we want to generate several island models, and we +parameter only has a possible value).

    Now, let’s consider an example where we want to generate several island models, and we are interested in varying the number of demes: 10, 50 and 100 with a migration rate of 1%. Sample size and deme -size will be the same as before. Here is the code:

    from Bio.PopGen.SimCoal.Template import generate_simcoal_from_template
    +size will be the same as before. Here is the code:

    from Bio.PopGen.SimCoal.Template import generate_simcoal_from_template
     
     generate_simcoal_from_template('island',
         [(1, [('SNP', [24, 0.0005, 0.0])])],
    @@ -6497,22 +6715,23 @@
         ('pop_size', [100]),
         ('mig', [0.01]),
         ('total_demes', [10, 50, 100])])
    -

    In this case, 3 files will be generated: island_100_0.01_100_30.par, +

    In this case, 3 files will be generated: island_100_0.01_100_30.par, island_10_0.01_100_30.par and island_50_0.01_100_30.par. Notice the rule to make file names: template name, followed by parameter values in -reverse order.

    A few, arguably more esoteric template demographies exist (please check the +reverse order.

    A few, arguably more esoteric template demographies exist (please check the Bio/PopGen/SimCoal/data directory on Biopython source tree). Furthermore it is possible for the user to create new templates. That functionality will be discussed in a future -version of this document.

    -

    12.2.1.2  Chromosome structure

    We strongly recommend reading SIMCOAL2 documentation to understand the full potential +version of this document.

    + +

    12.2.1.2  Chromosome structure

    We strongly recommend reading SIMCOAL2 documentation to understand the full potential available in modeling chromosome structures. In this subsection we only discuss how to implement chromosome structures using the Biopython interface, not the underlying -SIMCOAL2 capabilities.

    We will start by implementing a single chromosome, with 24 SNPs with +SIMCOAL2 capabilities.

    We will start by implementing a single chromosome, with 24 SNPs with a recombination rate immediately on the right of each locus of 0.0005 and a minimum frequency of the minor allele of 0. This will be specified by the following list (to be passed as second parameter to the function -generate_simcoal_from_template):

    [(1, [('SNP', [24, 0.0005, 0.0])])]
    -

    This is actually the chromosome structure used in the above examples.

    The chromosome structure is represented by a list of chromosomes, +generate_simcoal_from_template):

    [(1, [('SNP', [24, 0.0005, 0.0])])]
    +

    This is actually the chromosome structure used in the above examples.

    The chromosome structure is represented by a list of chromosomes, each chromosome (i.e., each element in the list) is composed by a tuple (a pair): the first element is the number of times the chromosome is to be repeated (as there @@ -6525,7 +6744,7 @@ a single instance (therefore not to be repeated), it is composed of 24 SNPs, with a recombination rate of 0.0005 between each consecutive SNP, the minimum frequency of the minor allele is -0.0 (i.e, it can be absent from a certain population).

    Let’s see a more complicated example:

    [
    +0.0 (i.e, it can be absent from a certain population).

    Let’s see a more complicated example:

    [
       (5, [
            ('SNP', [24, 0.0005, 0.0])
           ]
    @@ -6537,7 +6756,7 @@
           ]
       )
     ]
    -

    We start by having 5 chromosomes with the same structure as +

    We start by having 5 chromosomes with the same structure as above (i.e., 24 SNPs). We then have 2 chromosomes which have a DNA sequence with 10 nucleotides, 0.0 recombination rate, 0.0005 mutation rate, and a transition rate of 0.33. Then we @@ -6550,15 +6769,16 @@ of 0.0 (for information about this parameters please consult the SIMCOAL2 documentation, you can use them to simulate various mutation models, including the typical – for microsatellites – -stepwise mutation model among others).

    -

    12.2.2  Running SIMCOAL2

    We now discuss how to run SIMCOAL2 from inside Biopython. It is required +stepwise mutation model among others).

    + +

    12.2.2  Running SIMCOAL2

    We now discuss how to run SIMCOAL2 from inside Biopython. It is required that the binary for SIMCOAL2 is called simcoal2 (or simcoal2.exe on Windows based platforms), please note that the typical name when downloading the program is in the format simcoal2_x_y. As such, when installing SIMCOAL2 you will need to rename of the downloaded executable so that Biopython can -find it.

    It is possible to run SIMCOAL2 on files that were not generated using the method +find it.

    It is possible to run SIMCOAL2 on files that were not generated using the method above (e.g., writing a parameter file by hand), but we will show an -example by creating a model using the framework presented above.

    from Bio.PopGen.SimCoal.Template import generate_simcoal_from_template
    +example by creating a model using the framework presented above.

    from Bio.PopGen.SimCoal.Template import generate_simcoal_from_template
     from Bio.PopGen.SimCoal.Controller import SimCoalController
     
     
    @@ -6580,10 +6800,10 @@
     
     ctrl = SimCoalController('.')
     ctrl.run_simcoal('simple_100_30.par', 50)
    -

    The lines of interest are the last two (plus the new import). +

    The lines of interest are the last two (plus the new import). Firstly a controller for the application is created. The directory where the binary is located has -to be specified.

    The simulator is then run on the last line: we know, from the rules explained +to be specified.

    The simulator is then run on the last line: we know, from the rules explained above, that the input file name is simple_100_30.par for the simulation parameter file created. We then specify that we want to run 50 independent simulations, by default Biopython @@ -6594,37 +6814,39 @@ with the simulation results. The results can now be analysed (typically studying the data with Arlequin3). In the future Biopython might support reading the Arlequin3 format and thus allowing for the analysis of SIMCOAL2 -data inside Biopython.

    -

    12.3  Other applications

    Here we discuss interfaces and utilities to deal with population genetics’ -applications which arguably have a smaller user base.

    -

    12.3.1  FDist: Detecting selection and molecular adaptation

    FDist is a selection detection application suite based on computing -(i.e. simulating) a “neutral” confidence interval based on Fst and +data inside Biopython.

    + +

    12.3  Other applications

    Here we discuss interfaces and utilities to deal with population genetics’ +applications which arguably have a smaller user base.

    + +

    12.3.1  FDist: Detecting selection and molecular adaptation

    FDist is a selection detection application suite based on computing +(i.e. simulating) a “neutral” confidence interval based on Fst and heterozygosity. Markers (which can be SNPs, microsatellites, AFLPs among others) which lie outside the “neutral” interval are to be -considered as possible candidates for being under selection.

    FDist is mainly used when the number of markers is considered enough -to estimate an average Fst, but not enough to either have outliers +considered as possible candidates for being under selection.

    FDist is mainly used when the number of markers is considered enough +to estimate an average Fst, but not enough to either have outliers calculated from the dataset directly or, with even more markers for which the relative positions in the genome are known, to use -approaches based on, e.g., Extended Haplotype Heterozygosity (EHH).

    The typical usage pattern for FDist is as follows:

    1. +approaches based on, e.g., Extended Haplotype Heterozygosity (EHH).

      The typical usage pattern for FDist is as follows:

      1. Import a dataset from an external format into FDist format. -
      2. Compute average Fst. This is done by datacal inside FDist. -
      3. Simulate “neutral” markers based on the -average Fst and expected number of total populations. +
      4. Compute average Fst. This is done by datacal inside FDist. +
      5. Simulate “neutral” markers based on the +average Fst and expected number of total populations. This is the core operation, done by fdist inside FDist. -
      6. Calculate the confidence interval, based on the desired +
      7. Calculate the confidence interval, based on the desired confidence boundaries (typically 95% or 99%). This is done by cplot and is mainly used to plot the interval. -
      8. Assess each marker status against the simulation “neutral” +
      9. Assess each marker status against the simulation “neutral” confidence interval. Done by pv. This is used to detect the outlier status of each marker against the simulation. -

      We will now discuss each step with illustrating example code +

    We will now discuss each step with illustrating example code (for this example to work FDist binaries have to be on the -executable PATH).

    The FDist data format is application specific and is not used at +executable PATH).

    The FDist data format is application specific and is not used at all by other applications, as such you will probably have to convert your data for use with FDist. Biopython can help you do this. Here is an example converting from GenePop format to FDist format -(along with imports that will be needed on examples further below):

    from Bio.PopGen import GenePop
    +(along with imports that will be needed on examples further below):

    from Bio.PopGen import GenePop
     from Bio.PopGen import FDist
     from Bio.PopGen.FDist import Controller
     from Bio.PopGen.FDist.Utils import convert_genepop_to_fdist
    @@ -6634,108 +6856,113 @@
     in_file = open("infile", "w")
     in_file.write(str(fd_rec))
     in_file.close()
    -

    In this code we simply parse a GenePop file and convert it to a FDist -record.

    Printing an FDist record will generate +

    In this code we simply parse a GenePop file and convert it to a FDist +record.

    Printing an FDist record will generate a string that can be directly saved to a file and supplied to FDist. FDist requires the input file to be called infile, therefore we save the record on -a file with that name.

    The most important fields on a FDist record are: num_pops, the number of +a file with that name.

    The most important fields on a FDist record are: num_pops, the number of populations; num_loci, the number of loci and loci_data with the marker data itself. Most probably the details of the record are of no interest -to the user, as the record only purpose is to be passed to FDist.

    The next step is to calculate the average Fst of the dataset (along -with the sample size):

    ctrl = Controller.FDistController()
    +to the user, as the record only purpose is to be passed to FDist.

    The next step is to calculate the average Fst of the dataset (along +with the sample size):

    ctrl = Controller.FDistController()
     fst, samp_size = ctrl.run_datacal()
    -

    On the first line we create an object to control the call of FDist +

    On the first line we create an object to control the call of FDist suite, this object will be used further on in order to call other -suite applications.

    On the second line we call the datacal application which computes the -average Fst -and the sample size. It is worth noting that the Fst computed by -datacal is a variation of Weir and Cockerham’s θ.

    We can now call the main fdist application in order to simulate neutral -markers.

    sim_fst = ctrl.run_fdist(npops = 15, nsamples = fd_rec.num_pops, fst = fst,
    +suite applications.

    On the second line we call the datacal application which computes the +average Fst +and the sample size. It is worth noting that the Fst computed by +datacal is a variation of Weir and Cockerham’s θ.

    We can now call the main fdist application in order to simulate neutral +markers.

    sim_fst = ctrl.run_fdist(npops = 15, nsamples = fd_rec.num_pops, fst = fst,
         sample_size = samp_size, mut = 0, num_sims = 40000)
    -
    -npops
    Number of populations existing in nature. This is really a +
    +npops
    Number of populations existing in nature. This is really a “guestimate”. Has to be lower than 100. -
    nsamples
    Number of populations sampled, has to be lower than npops. -
    fst
    Average Fst. -
    sample_size
    Average number of individuals sampled on each population. -
    mut
    Mutation model: 0 - Infinite alleles; 1 - Stepwise mutations -
    num_sims
    Number of simulations to perform. Typically a number around +
    nsamples
    Number of populations sampled, has to be lower than npops. +
    fst
    Average Fst. +
    sample_size
    Average number of individuals sampled on each population. +
    mut
    Mutation model: 0 - Infinite alleles; 1 - Stepwise mutations +
    num_sims
    Number of simulations to perform. Typically a number around 40000 will be OK, but if you get a confidence interval that looks sharp (this can be detected when plotting the confidence interval computed below) the value can be increased (a suggestion would be steps of 10000 simulations). -

    The confusion in wording between number of samples and sample size -stems from the original application.

    A file named out.dat will be created with the simulated heterozygosities -and Fsts, it will have as many lines as the number of simulations -requested.

    Note that fdist returns the average Fst that it was capable of +

    The confusion in wording between number of samples and sample size +stems from the original application.

    A file named out.dat will be created with the simulated heterozygosities +and Fsts, it will have as many lines as the number of simulations +requested.

    Note that fdist returns the average Fst that it was capable of simulating, for more details about this issue please read below the paragraph -on approximating the desired average Fst.

    The next (optional) step is to calculate the confidence interval:

    cpl_interval = ctrl.run_cplot(ci=0.99)
    -

    You can only call cplot after having run fdist.

    This will calculate the confidence intervals (99% in this case) +on approximating the desired average Fst.

    The next (optional) step is to calculate the confidence interval:

    cpl_interval = ctrl.run_cplot(ci=0.99)
    +

    You can only call cplot after having run fdist.

    This will calculate the confidence intervals (99% in this case) for a previous fdist run. A list of quadruples is returned. The first element represents the heterozygosity, the second the lower -bound of Fst confidence interval for that heterozygosity, +bound of Fst confidence interval for that heterozygosity, the third the average and the fourth the upper bound. This can be used to trace the confidence interval contour. This list -is also written to a file, out.cpl.

    The main purpose of this step is return a set of points which can +is also written to a file, out.cpl.

    The main purpose of this step is return a set of points which can be easily used to plot a confidence interval. It can be skipped if the objective is only to assess the status of each marker against -the simulation, which is the next step...

    pv_data = ctrl.run_pv()
    -

    You can only call cplot after having run datacal and fdist.

    This will use the simulated markers to assess the status of each +the simulation, which is the next step...

    pv_data = ctrl.run_pv()
    +

    You can only call cplot after having run datacal and fdist.

    This will use the simulated markers to assess the status of each individual real marker. A list, in the same order than the loci_list that is on the FDist record (which is in the same order that the GenePop record) is returned. Each element in the list is a quadruple, the fundamental member of each quadruple is the last element (regarding the other elements, please refer to the pv documentation – for the sake of simplicity we will not discuss them here) which returns the -probability of the simulated Fst being lower than the marker Fst. +probability of the simulated Fst being lower than the marker Fst. Higher values would indicate a stronger candidate for positive selection, lower values a candidate for balancing selection, and intermediate values a possible neutral marker. What is “higher”, “lower” or “intermediate” is really a subjective issue, but taking a “confidence interval” approach and considering a 95% confidence interval, “higher” would be between 0.95 and 1.0, “lower” between 0.0 and 0.05 and “intermediate” between 0.05 and -0.95.

    -

    12.3.1.1  Approximating the desired average Fst

    Fdist tries to approximate the desired average Fst by doing a -coalescent simulation using migration rates based on the formula

    -
    Nm =  - - -
    1 − Fst
    4Fst
     

    This formula assumes a few premises like an infinite number of populations.

    In practice, when the number of populations is low, the mutation model +0.95.

    + +

    12.3.1.1  Approximating the desired average Fst

    Fdist tries to approximate the desired average Fst by doing a +coalescent simulation using migration rates based on the formula

    +
    Nm =  + + +
    1 − Fst
    4Fst
     

    This formula assumes a few premises like an infinite number of populations.

    In practice, when the number of populations is low, the mutation model is stepwise and the sample size increases, fdist will not be able to -simulate an acceptable approximate average Fst.

    To address that, a function is provided to iteratively approach the desired +simulate an acceptable approximate average Fst.

    To address that, a function is provided to iteratively approach the desired value by running several fdists in sequence. This approach is computationally more intensive than running a single fdist run, but yields good results. -The following code runs fdist approximating the desired Fst:

    sim_fst = ctrl.run_fdist_force_fst(npops = 15, nsamples = fd_rec.num_pops,
    +The following code runs fdist approximating the desired Fst:

    sim_fst = ctrl.run_fdist_force_fst(npops = 15, nsamples = fd_rec.num_pops,
         fst = fst, sample_size = samp_size, mut = 0, num_sims = 40000,
         limit = 0.05)
    -

    The only new optional parameter, when comparing with run_fdist, is limit +

    The only new optional parameter, when comparing with run_fdist, is limit which is the desired maximum error. run_fdist can (and probably should) -be safely replaced with run_fdist_force_fst.

    -

    12.3.1.2  Final notes

    The process to determine the average Fst can be more sophisticated than +be safely replaced with run_fdist_force_fst.

    + +

    12.3.1.2  Final notes

    The process to determine the average Fst can be more sophisticated than the one presented here. For more information we refer you to the FDist README file. Biopython’s code can be used to implement more sophisticated -approaches.

    -

    12.4  Future Developments

    The most desired future developments would be the ones you add yourself ;) .

    That being said, already existing fully functional code is currently being +approaches.

    + +

    12.4  Future Developments

    The most desired future developments would be the ones you add yourself ;) .

    That being said, already existing fully functional code is currently being incorporated in Bio.PopGen, that code covers the applications FDist and SimCoal2, the HapMap and UCSC Table Browser databases and some simple statistics -like Fst, or allele counts.

    -

    Chapter 13  Phylogenetics with Bio.Phylo

    -

    The Bio.Phylo module was introduced in Biopython 1.54. Following the lead of SeqIO and AlignIO, +like Fst, or allele counts.

    + +

    Chapter 13  Phylogenetics with Bio.Phylo

    +

    The Bio.Phylo module was introduced in Biopython 1.54. Following the lead of SeqIO and AlignIO, it aims to provide a common way to work with phylogenetic trees independently of the source data -format, as well as a consistent API for I/O operations.

    Bio.Phylo is described in an open-access journal article [9, Talevich -et al., 2012], which you might also find helpful.

    -

    13.1  Demo: What’s in a Tree?

    To get acquainted with the module, let’s start with a tree that we’ve already constructed, and +format, as well as a consistent API for I/O operations.

    Bio.Phylo is described in an open-access journal article [9, Talevich +et al., 2012], which you might also find helpful.

    + +

    13.1  Demo: What’s in a Tree?

    To get acquainted with the module, let’s start with a tree that we’ve already constructed, and inspect it a few different ways. Then we’ll colorize the branches, to use a special phyloXML -feature, and finally save it.

    In a terminal, create a simple Newick file using your favorite text editor:

    % cat > simple.dnd <<EOF
    +feature, and finally save it.

    In a terminal, create a simple Newick file using your favorite text editor:

    % cat > simple.dnd <<EOF
     > (((A,B),(C,D)),(E,F,G));
     > EOF
    -

    This tree has no branch lengths, only a topology and labelled terminals. (If you have a real -tree file available, you can follow this demo using that instead.)

    Launch the Python interpreter of your choice:

    % ipython -pylab
    -

    For interactive work, launching the IPython interpreter with the -pylab flag enables -matplotlib integration, so graphics will pop up automatically. We’ll use that during -this demo.

    Now, within Python, read the tree file, giving the file name and the name of the format.

    >>> from Bio import Phylo
    +

    This tree has no branch lengths, only a topology and labelled terminals. (If you have a real +tree file available, you can follow this demo using that instead.)

    Launch the Python interpreter of your choice:

    % ipython -pylab
    +

    For interactive work, launching the IPython interpreter with the -pylab flag enables +matplotlib integration, so graphics will pop up automatically. We’ll use that during +this demo.

    Now, within Python, read the tree file, giving the file name and the name of the format.

    >>> from Bio import Phylo
     >>> tree = Phylo.read("simple.dnd", "newick")
    -

    Printing the tree object as a string gives us a look at the entire object hierarchy.

    >>> print tree
    +

    Printing the tree object as a string gives us a look at the entire object hierarchy.

    >>> print(tree)
     
     Tree(weight=1.0, rooted=False, name="")
         Clade(branch_length=1.0)
    @@ -6750,11 +6977,11 @@
                 Clade(branch_length=1.0, name="E")
                 Clade(branch_length=1.0, name="F")
                 Clade(branch_length=1.0, name="G")
    -

    The Tree object contains global information about the tree, such as whether it’s +

    The Tree object contains global information about the tree, such as whether it’s rooted or unrooted. It has one root clade, and under that, it’s nested lists of clades all the -way down to the tips.

    The function draw_ascii creates a simple ASCII-art (plain text) dendrogram. This is a +way down to the tips.

    The function draw_ascii creates a simple ASCII-art (plain text) dendrogram. This is a convenient visualization for interactive exploration, in case better graphical tools aren’t -available.

    >>> Phylo.draw_ascii(tree)
    +available.

    >>> Phylo.draw_ascii(tree)
                                                         ________________________ A
                                ________________________|
                               |                        |________________________ B
    @@ -6769,53 +6996,54 @@
                               |
                               |________________________ G
     
    -

    If you have matplotlib or pylab installed, you can create a graphic -using the draw function (see Fig. 13.1):

    >>> tree.rooted = True
    +

    If you have matplotlib or pylab installed, you can create a graphic +using the draw function (see Fig. 13.1):

    >>> tree.rooted = True
     >>> Phylo.draw(tree)
    -

    - - -

    -

    13.1.1  Coloring branches within a tree

    The functions draw and draw_graphviz support the display of different +

    + + +

    + +

    13.1.1  Coloring branches within a tree

    The functions draw and draw_graphviz support the display of different colors and branch widths in a tree. -As of Biopython 1.59, the color and width attributes are available on the +As of Biopython 1.59, the color and width attributes are available on the basic Clade object and there’s nothing extra required to use them. Both attributes refer to the branch leading the given clade, and apply recursively, so all descendent branches will also inherit the assigned width and color values during -display.

    In earlier versions of Biopython, these were special features of PhyloXML trees, and +display.

    In earlier versions of Biopython, these were special features of PhyloXML trees, and using the attributes required first converting the tree to a subclass of the basic tree -object called Phylogeny, from the Bio.Phylo.PhyloXML module.

    In Biopython 1.55 and later, this is a convenient tree method:

    >>> tree = tree.as_phyloxml()
    -

    In Biopython 1.54, you can accomplish the same thing with one extra import:

    >>> from Bio.Phylo.PhyloXML import Phylogeny
    +object called Phylogeny, from the Bio.Phylo.PhyloXML module.

    In Biopython 1.55 and later, this is a convenient tree method:

    >>> tree = tree.as_phyloxml()
    +

    In Biopython 1.54, you can accomplish the same thing with one extra import:

    >>> from Bio.Phylo.PhyloXML import Phylogeny
     >>> tree = Phylogeny.from_tree(tree)
    -

    Note that the file formats Newick and Nexus don’t support branch colors or widths, so +

    Note that the file formats Newick and Nexus don’t support branch colors or widths, so if you use these attributes in Bio.Phylo, you will only be able to save the values in PhyloXML format. (You can still save a tree as Newick or Nexus, but the color and width -values will be skipped in the output file.)

    Now we can begin assigning colors. +values will be skipped in the output file.)

    Now we can begin assigning colors. First, we’ll color the root clade gray. We can do that by assigning the 24-bit color value as an RGB triple, an HTML-style hex string, or the name of one of the predefined -colors.

    >>> tree.root.color = (128, 128, 128)
    -

    Or:

    >>> tree.root.color = "#808080"
    -

    Or:

    >>> tree.root.color = "gray"
    -

    Colors for a clade are treated as cascading down through the entire clade, so when we colorize +colors.

    >>> tree.root.color = (128, 128, 128)
    +

    Or:

    >>> tree.root.color = "#808080"
    +

    Or:

    >>> tree.root.color = "gray"
    +

    Colors for a clade are treated as cascading down through the entire clade, so when we colorize the root here, it turns the whole tree gray. We can override that by assigning a different -color lower down on the tree.

    Let’s target the most recent common ancestor (MRCA) of the nodes named “E” and “F”. The -common_ancestor method returns a reference to that clade in the original tree, so when -we color that clade “salmon”, the color will show up in the original tree.

    >>> mrca = tree.common_ancestor({"name": "E"}, {"name": "F"})
    +color lower down on the tree.

    Let’s target the most recent common ancestor (MRCA) of the nodes named “E” and “F”. The +common_ancestor method returns a reference to that clade in the original tree, so when +we color that clade “salmon”, the color will show up in the original tree.

    >>> mrca = tree.common_ancestor({"name": "E"}, {"name": "F"})
     >>> mrca.color = "salmon"
    -

    If we happened to know exactly where a certain clade is in the tree, in terms of nested list +

    If we happened to know exactly where a certain clade is in the tree, in terms of nested list entries, we can jump directly to that position in the tree by indexing it. Here, the index -[0,1] refers to the second child of the first child of the root.

    >>> tree.clade[0,1].color = "blue"
    -

    Finally, show our work (see Fig. 13.1.1):

    >>> Phylo.draw(tree)
    -

    - - -

    Note that a clade’s color includes the branch leading to that clade, as well as its +[0,1] refers to the second child of the first child of the root.

    >>> tree.clade[0, 1].color = "blue"
    +

    Finally, show our work (see Fig. 13.1.1):

    >>> Phylo.draw(tree)
    +

    + + +

    Note that a clade’s color includes the branch leading to that clade, as well as its descendents. The common ancestor of E and F turns out to be just under the root, and with this -coloring we can see exactly where the root of the tree is.

    My, we’ve accomplished a lot! Let’s take a break here and save our work. Call the -write function with a file name or handle — here we use standard output, to see what -would be written — and the format phyloxml. PhyloXML saves the colors we assigned, +coloring we can see exactly where the root of the tree is.

    My, we’ve accomplished a lot! Let’s take a break here and save our work. Call the +write function with a file name or handle — here we use standard output, to see what +would be written — and the format phyloxml. PhyloXML saves the colors we assigned, so you can open this phyloXML file in another tree viewer like Archaeopteryx, and the colors -will show up there, too.

    >>> import sys
    +will show up there, too.

    >>> import sys
     >>> Phylo.write(tree, sys.stdout, "phyloxml")
     
     <phy:phyloxml xmlns:phy="http://www.phyloxml.org">
    @@ -6834,39 +7062,41 @@
               <phy:clade>
                 <phy:name>A</phy:name>
                 ...
    -

    The rest of this chapter covers the core functionality of Bio.Phylo in greater detail. For more -examples of using Bio.Phylo, see the cookbook page on Biopython.org:

    http://biopython.org/wiki/Phylo_cookbook

    -

    13.2  I/O functions

    Like SeqIO and AlignIO, Phylo handles file input and output through four functions: -parse, read, write and convert, +

    The rest of this chapter covers the core functionality of Bio.Phylo in greater detail. For more +examples of using Bio.Phylo, see the cookbook page on Biopython.org:

    http://biopython.org/wiki/Phylo_cookbook

    + +

    13.2  I/O functions

    Like SeqIO and AlignIO, Phylo handles file input and output through four functions: +parse, read, write and convert, all of which support the tree file formats Newick, NEXUS, phyloXML and NeXML, as -well as the Comparative Data Analysis Ontology (CDAO).

    The read function parses a single tree in the given file and returns it. Careful; it -will raise an error if the file contains more than one tree, or no trees.

    >>> from Bio import Phylo
    +well as the Comparative Data Analysis Ontology (CDAO).

    The read function parses a single tree in the given file and returns it. Careful; it +will raise an error if the file contains more than one tree, or no trees.

    >>> from Bio import Phylo
     >>> tree = Phylo.read("Tests/Nexus/int_node_labels.nwk", "newick")
    ->>> print tree
    -

    (Example files are available in the Tests/Nexus/ and Tests/PhyloXML/ -directories of the Biopython distribution.)

    To handle multiple (or an unknown number of) trees, use the parse function iterates -through each of the trees in the given file:

    >>> trees = Phylo.parse("Tests/PhyloXML/phyloxml_examples.xml", "phyloxml")
    +>>> print(tree)
    +

    (Example files are available in the Tests/Nexus/ and Tests/PhyloXML/ +directories of the Biopython distribution.)

    To handle multiple (or an unknown number of) trees, use the parse function iterates +through each of the trees in the given file:

    >>> trees = Phylo.parse("Tests/PhyloXML/phyloxml_examples.xml", "phyloxml")
     >>> for tree in trees:
    -...     print tree
    -

    Write a tree or iterable of trees back to file with the write function:

    >>> trees = list(Phylo.parse("phyloxml_examples.xml", "phyloxml"))
    +...     print(tree)
    +

    Write a tree or iterable of trees back to file with the write function:

    >>> trees = list(Phylo.parse("phyloxml_examples.xml", "phyloxml"))
     >>> tree1 = trees[0]
     >>> others = trees[1:]
     >>> Phylo.write(tree1, "tree1.xml", "phyloxml")
     1
     >>> Phylo.write(others, "other_trees.xml", "phyloxml")
     12
    -

    Convert files between any of the supported formats with the convert function:

    >>> Phylo.convert("tree1.dnd", "newick", "tree1.xml", "nexml")
    +

    Convert files between any of the supported formats with the convert function:

    >>> Phylo.convert("tree1.dnd", "newick", "tree1.xml", "nexml")
     1
     >>> Phylo.convert("other_trees.xml", "phyloxml", "other_trees.nex", 'nexus")
     12
    -

    To use strings as input or output instead of actual files, use StringIO as you would -with SeqIO and AlignIO:

    >>> from Bio import Phylo
    +

    To use strings as input or output instead of actual files, use StringIO as you would +with SeqIO and AlignIO:

    >>> from Bio import Phylo
     >>> from StringIO import StringIO
     >>> handle = StringIO("(((A,B),(C,D)),(E,F,G));")
     >>> tree = Phylo.read(handle, "newick")
    -
    -

    13.3  View and export trees

    The simplest way to get an overview of a Tree object is to print it:

    >>> tree = Phylo.read("Tests/PhyloXML/example.xml", "phyloxml")
    ->>> print tree
    +
    + +

    13.3  View and export trees

    The simplest way to get an overview of a Tree object is to print it:

    >>> tree = Phylo.read("Tests/PhyloXML/example.xml", "phyloxml")
    +>>> print(tree)
     Phylogeny(rooted='True', description='phyloXML allows to use either a "branch_length"
     attribute...', name='example from Prof. Joe Felsenstein's book "Inferring Phyl...')
         Clade()
    @@ -6874,11 +7104,11 @@
                 Clade(branch_length='0.102', name='A')
                 Clade(branch_length='0.23', name='B')
             Clade(branch_length='0.4', name='C')
    -

    This is essentially an outline of the object hierarchy Biopython uses to represent a tree. But -more likely, you’d want to see a drawing of the tree. There are three functions to do this.

    As we saw in the demo, draw_ascii prints an ascii-art drawing of the tree (a +

    This is essentially an outline of the object hierarchy Biopython uses to represent a tree. But +more likely, you’d want to see a drawing of the tree. There are three functions to do this.

    As we saw in the demo, draw_ascii prints an ascii-art drawing of the tree (a rooted phylogram) to standard output, or an open file handle if given. Not all of the available information about the tree is shown, but it provides a way to quickly view the -tree without relying on any external dependencies.

    >>> tree = Phylo.read("example.xml", "phyloxml")
    +tree without relying on any external dependencies.

    >>> tree = Phylo.read("example.xml", "phyloxml")
     >>> Phylo.draw_ascii(tree)
                  __________________ A
       __________|
    @@ -6886,227 +7116,234 @@
      |
      |___________________________________________________________________________ C
     
    -

    The draw function draws a more attractive image using the matplotlib +

    The draw function draws a more attractive image using the matplotlib library. See the API documentation for details on the arguments it accepts to -customize the output.

    >>> tree = Phylo.read("example.xml", "phyloxml")
    +customize the output.

    >>> tree = Phylo.read("example.xml", "phyloxml")
     >>> Phylo.draw(tree, branch_labels=lambda c: c.branch_length)
    -

    - - -

    draw_graphviz draws an unrooted cladogram, but requires that you have Graphviz, +

    + + +

    draw_graphviz draws an unrooted cladogram, but requires that you have Graphviz, PyDot or PyGraphviz, NetworkX, and matplotlib (or pylab) installed. Using the same example as -above, and the dot program included with Graphviz, let’s draw a rooted tree (see -Fig. 13.3):

    >>> tree = Phylo.read("example.xml", "phyloxml")
    +above, and the dot program included with Graphviz, let’s draw a rooted tree (see
    +Fig. 13.3):

    >>> tree = Phylo.read("example.xml", "phyloxml")
     >>> Phylo.draw_graphviz(tree, prog='dot')
     >>> import pylab
     >>> pylab.show()                    # Displays the tree in an interactive viewer
     >>> pylab.savefig('phylo-dot.png')  # Creates a PNG file of the same graphic
    -

    - - -

    (Tip: If you execute IPython with the -pylab option, calling draw_graphviz causes -the matplotlib viewer to launch automatically without manually calling show().)

    This exports the tree object to a NetworkX graph, uses Graphviz to lay out the nodes, and +

    + + +

    (Tip: If you execute IPython with the -pylab option, calling draw_graphviz causes +the matplotlib viewer to launch automatically without manually calling show().)

    This exports the tree object to a NetworkX graph, uses Graphviz to lay out the nodes, and displays it using matplotlib. There are a number of keyword arguments that can modify the resulting diagram, including -most of those accepted by the NetworkX functions networkx.draw and -networkx.draw_graphviz.

    The display is also affected by the rooted attribute of the given tree object. +most of those accepted by the NetworkX functions networkx.draw and +networkx.draw_graphviz.

    The display is also affected by the rooted attribute of the given tree object. Rooted trees are shown with a “head” on each branch indicating direction (see -Fig. 13.3):

    >>> tree = Phylo.read("simple.dnd", "newick")
    +Fig. 13.3):

    >>> tree = Phylo.read("simple.dnd", "newick")
     >>> tree.rooted = True
     >>> Phylo.draw_graphiz(tree)
    -

    - - -

    The “prog” argument specifies the Graphviz engine used for layout. The default, -twopi, behaves well for any size tree, reliably avoiding crossed branches. The -neato program may draw more attractive moderately-sized trees, but sometimes will -cross branches (see Fig. 13.3). The dot program may be useful -with small trees, but tends to do surprising things with the layout of larger trees.

    >>> Phylo.draw_graphviz(tree, prog="neato")
    -

    - - -

    This viewing mode is particularly handy for exploring larger trees, because the matplotlib +

    + + +

    The “prog” argument specifies the Graphviz engine used for layout. The default, +twopi, behaves well for any size tree, reliably avoiding crossed branches. The +neato program may draw more attractive moderately-sized trees, but sometimes will +cross branches (see Fig. 13.3). The dot program may be useful +with small trees, but tends to do surprising things with the layout of larger trees.

    >>> Phylo.draw_graphviz(tree, prog="neato")
    +

    + + +

    This viewing mode is particularly handy for exploring larger trees, because the matplotlib viewer can zoom in on a selected region, thinning out a cluttered graphic. -

    >>> tree = Phylo.read("apaf.xml", "phyloxml")
    +

    >>> tree = Phylo.read("apaf.xml", "phyloxml")
     >>> Phylo.draw_graphviz(tree, prog="neato", node_size=0)
    -

    - - - - -

    Note that branch lengths are not displayed accurately, because Graphviz ignores them when +

    + + + + +

    Note that branch lengths are not displayed accurately, because Graphviz ignores them when creating the node layouts. The branch lengths are retained when exporting a tree as a NetworkX -graph object (to_networkx), however.

    See the Phylo page on the Biopython wiki (http://biopython.org/wiki/Phylo) for -descriptions and examples of the more advanced functionality in draw_ascii, -draw_graphviz and to_networkx.

    -

    13.4  Using Tree and Clade objects

    The Tree objects produced by parse and read are containers for recursive -sub-trees, attached to the Tree object at the root attribute (whether or not the -phylogenic tree is actually considered rooted). A Tree has globally applied information -for the phylogeny, such as rootedness, and a reference to a single Clade; a -Clade has node- and clade-specific information, such as branch length, and a list of -its own descendent Clade instances, attached at the clades attribute.

    So there is a distinction between tree and tree.root. In practice, though, you -rarely need to worry about it. To smooth over the difference, both Tree and -Clade inherit from TreeMixin, which contains the implementations for methods +graph object (to_networkx), however.

    See the Phylo page on the Biopython wiki (http://biopython.org/wiki/Phylo) for +descriptions and examples of the more advanced functionality in draw_ascii, +draw_graphviz and to_networkx.

    + +

    13.4  Using Tree and Clade objects

    The Tree objects produced by parse and read are containers for recursive +sub-trees, attached to the Tree object at the root attribute (whether or not the +phylogenic tree is actually considered rooted). A Tree has globally applied information +for the phylogeny, such as rootedness, and a reference to a single Clade; a +Clade has node- and clade-specific information, such as branch length, and a list of +its own descendent Clade instances, attached at the clades attribute.

    So there is a distinction between tree and tree.root. In practice, though, you +rarely need to worry about it. To smooth over the difference, both Tree and +Clade inherit from TreeMixin, which contains the implementations for methods that would be commonly used to search, inspect or modify a tree or any of its clades. This -means that almost all of the methods supported by tree are also available on -tree.root and any clade below it. (Clade also has a root property, which -returns the clade object itself.)

    -

    13.4.1  Search and traversal methods

    For convenience, we provide a couple of simplified methods that return all external or internal -nodes directly as a list:

    -get_terminals
    makes a list of all of this tree’s terminal (leaf) nodes. -
    get_nonterminals
    makes a list of all of this tree’s nonterminal (internal) +means that almost all of the methods supported by tree are also available on +tree.root and any clade below it. (Clade also has a root property, which +returns the clade object itself.)

    + +

    13.4.1  Search and traversal methods

    For convenience, we provide a couple of simplified methods that return all external or internal +nodes directly as a list:

    +get_terminals
    makes a list of all of this tree’s terminal (leaf) nodes. +
    get_nonterminals
    makes a list of all of this tree’s nonterminal (internal) nodes. -

    These both wrap a method with full control over tree traversal, find_clades. Two more -traversal methods, find_elements and find_any, rely on the same core +

    These both wrap a method with full control over tree traversal, find_clades. Two more +traversal methods, find_elements and find_any, rely on the same core functionality and accept the same arguments, which we’ll call a “target specification” for lack of a better description. These specify which objects in the tree will be matched and -returned during iteration. The first argument can be any of the following types:

    • -A TreeElement instance, which tree elements will match by identity — so -searching with a Clade instance as the target will find that clade in the tree;
    • A string, which matches tree elements’ string representation — in -particular, a clade’s name (added in Biopython 1.56);
    • A class or type, where every tree element of the same type (or -sub-type) will be matched;
    • A dictionary where keys are tree element attributes and values are matched to the -corresponding attribute of each tree element. This one gets even more elaborate:
      • -If an int is given, it matches numerically equal attributes, e.g. 1 will -match 1 or 1.0
      • If a boolean is given (True or False), the corresponding attribute value is -evaluated as a boolean and checked for the same
      • None matches None
      • If a string is given, the value is treated as a regular expression (which must +returned during iteration. The first argument can be any of the following types:

        • +A TreeElement instance, which tree elements will match by identity — so +searching with a Clade instance as the target will find that clade in the tree;
        • A string, which matches tree elements’ string representation — in +particular, a clade’s name (added in Biopython 1.56);
        • A class or type, where every tree element of the same type (or +sub-type) will be matched;
        • A dictionary where keys are tree element attributes and values are matched to the +corresponding attribute of each tree element. This one gets even more elaborate:
          • +If an int is given, it matches numerically equal attributes, e.g. 1 will +match 1 or 1.0
          • If a boolean is given (True or False), the corresponding attribute value is +evaluated as a boolean and checked for the same
          • None matches None
          • If a string is given, the value is treated as a regular expression (which must match the whole string in the corresponding element attribute, not just a prefix). A given string without special regex characters will match string attributes exactly, so if you don’t use regexes, don’t worry about it. For example, in a tree with clade -names Foo1, Foo2 and Foo3, tree.find_clades({"name": "Foo1"}) matches Foo1, -{"name": "Foo.*"} matches all three clades, and {"name": "Foo"} doesn’t -match anything.

          Since floating-point arithmetic can produce some strange behavior, we don’t support -matching floats directly. Instead, use the boolean True to match every +names Foo1, Foo2 and Foo3, tree.find_clades({"name": "Foo1"}) matches Foo1, +{"name": "Foo.*"} matches all three clades, and {"name": "Foo"} doesn’t +match anything.

        Since floating-point arithmetic can produce some strange behavior, we don’t support +matching floats directly. Instead, use the boolean True to match every element with a nonzero value in the specified attribute, then filter on that attribute -manually with an inequality (or exact number, if you like living dangerously).

        If the dictionary contains multiple entries, a matching element must match each of the -given attribute values — think “and”, not “or”.

      • A function taking a single argument (it will be applied to each element in the +manually with an inequality (or exact number, if you like living dangerously).

        If the dictionary contains multiple entries, a matching element must match each of the +given attribute values — think “and”, not “or”.

      • A function taking a single argument (it will be applied to each element in the tree), returning True or False. For convenience, LookupError, AttributeError and ValueError are silenced, so this provides another safe way to search for floating-point values in the -tree, or some more complex characteristic.

      After the target, there are two optional keyword arguments:

      -terminal
      — A boolean value to select for or against terminal clades (a.k.a. leaf +tree, or some more complex characteristic.

    After the target, there are two optional keyword arguments:

    +terminal
    — A boolean value to select for or against terminal clades (a.k.a. leaf nodes): True searches for only terminal clades, False for non-terminal (internal) clades, and the default, None, searches both terminal and non-terminal clades, as well as any tree -elements lacking the is_terminal method.
    order
    — Tree traversal order: "preorder" (default) is depth-first search, -"postorder" is DFS with child nodes preceding parents, and "level" is -breadth-first search.

    Finally, the methods accept arbitrary keyword arguments which are treated the same way as a +elements lacking the is_terminal method.

    order
    — Tree traversal order: "preorder" (default) is depth-first search, +"postorder" is DFS with child nodes preceding parents, and "level" is +breadth-first search.

    Finally, the methods accept arbitrary keyword arguments which are treated the same way as a dictionary target specification: keys indicate the name of the element attribute to search for, and the argument value (string, integer, None or boolean) is compared to the value of each attribute found. If no keyword arguments are given, then any TreeElement types are matched. The code for this is generally shorter than passing a dictionary as the target specification: -tree.find_clades({"name": "Foo1"}) can be shortened to -tree.find_clades(name="Foo1").

    (In Biopython 1.56 or later, this can be even shorter: tree.find_clades("Foo1"))

    Now that we’ve mastered target specifications, here are the methods used to traverse a tree:

    -find_clades
    +tree.find_clades({"name": "Foo1"}) can be shortened to +tree.find_clades(name="Foo1").

    (In Biopython 1.56 or later, this can be even shorter: tree.find_clades("Foo1"))

    Now that we’ve mastered target specifications, here are the methods used to traverse a tree:

    +find_clades
    Find each clade containing a matching element. That is, find each element as with -find_elements, but return the corresponding clade object. (This is usually what you -want.)

    The result is an iterable through all matching objects, searching depth-first by default. +find_elements, but return the corresponding clade object. (This is usually what you +want.)

    The result is an iterable through all matching objects, searching depth-first by default. This is not necessarily the same order as the elements appear in the Newick, Nexus or XML -source file!

    find_elements
    +source file!

    find_elements
    Find all tree elements matching the given attributes, and return the matching elements themselves. Simple Newick trees don’t have complex sub-elements, so this behaves the same -as find_clades on them. PhyloXML trees often do have complex objects attached to -clades, so this method is useful for extracting those.
    find_any
    -Return the first element found by find_elements(), or None. This is also useful for -checking whether any matching element exists in the tree, and can be used in a conditional.

    Two more methods help navigating between nodes in the tree:

    -get_path
    +as find_clades on them. PhyloXML trees often do have complex objects attached to +clades, so this method is useful for extracting those.
    find_any
    +Return the first element found by find_elements(), or None. This is also useful for +checking whether any matching element exists in the tree, and can be used in a conditional.

    Two more methods help navigating between nodes in the tree:

    +get_path
    List the clades directly between the tree root (or current clade) and the given target. Returns a list of all clade objects along this path, ending with the given target, but -excluding the root clade.
    trace
    +excluding the root clade.
    trace
    List of all clade object between two targets in this tree. Excluding start, including -finish.
    -

    13.4.2  Information methods

    These methods provide information about the whole tree (or any clade).

    -common_ancestor
    +finish.
    + +

    13.4.2  Information methods

    These methods provide information about the whole tree (or any clade).

    +common_ancestor
    Find the most recent common ancestor of all the given targets. (This will be a Clade object). If no target is given, returns the root of the current clade (the one this method is called from); if 1 target is given, this returns the target itself. However, if any of the -specified targets are not found in the current tree (or clade), an exception is raised.
    count_terminals
    -Counts the number of terminal (leaf) nodes within the tree.
    depths
    +specified targets are not found in the current tree (or clade), an exception is raised.
    count_terminals
    +Counts the number of terminal (leaf) nodes within the tree.
    depths
    Create a mapping of tree clades to depths. The result is a dictionary where the keys are all of the Clade instances in the tree, and the values are the distance from the root to each clade (including terminals). By default the distance is the cumulative branch length -leading to the clade, but with the unit_branch_lengths=True option, only the number -of branches (levels in the tree) is counted.
    distance
    +leading to the clade, but with the unit_branch_lengths=True option, only the number +of branches (levels in the tree) is counted.
    distance
    Calculate the sum of the branch lengths between two targets. If only one target is -specified, the other is the root of this tree.
    total_branch_length
    +specified, the other is the root of this tree.
    total_branch_length
    Calculate the sum of all the branch lengths in this tree. This is usually just called the “length” of the tree in phylogenetics, but we use a more explicit name to avoid confusion -with Python terminology.

    The rest of these methods are boolean checks:

    -is_bifurcating
    +with Python terminology.

    The rest of these methods are boolean checks:

    +is_bifurcating
    True if the tree is strictly bifurcating; i.e. all nodes have either 2 or 0 children (internal or external, respectively). The root may have 3 descendents and still be -considered part of a bifurcating tree.
    is_monophyletic
    +considered part of a bifurcating tree.
    is_monophyletic
    Test if all of the given targets comprise a complete subclade — i.e., there exists a clade such that its terminals are the same set as the given targets. The targets should be terminals of the tree. For convenience, this method returns the common ancestor -(MCRA) of the targets if they are monophyletic (instead of the value True), and -False otherwise.
    is_parent_of
    True if target is a descendent of this tree — not required +(MCRA) of the targets if they are monophyletic (instead of the value True), and +False otherwise.
    is_parent_of
    True if target is a descendent of this tree — not required to be a direct descendent. To check direct descendents of a clade, simply use list -membership testing: if subclade in clade: ...
    is_preterminal
    True if all direct descendents are terminal; False if any -direct descendent is not terminal.
    -

    13.4.3  Modification methods

    These methods modify the tree in-place. If you want to keep the original tree intact, make a -complete copy of the tree first, using Python’s copy module:

    tree = Phylo.read('example.xml', 'phyloxml')
    +membership testing: if subclade in clade: ...
    is_preterminal
    True if all direct descendents are terminal; False if any +direct descendent is not terminal.
    + +

    13.4.3  Modification methods

    These methods modify the tree in-place. If you want to keep the original tree intact, make a +complete copy of the tree first, using Python’s copy module:

    tree = Phylo.read('example.xml', 'phyloxml')
     import copy
     newtree = copy.deepcopy(tree)
    -
    -collapse
    -Deletes the target from the tree, relinking its children to its parent.
    collapse_all
    +
    +collapse
    +Deletes the target from the tree, relinking its children to its parent.
    collapse_all
    Collapse all the descendents of this tree, leaving only terminals. Branch lengths are preserved, i.e. the distance to each terminal stays the same. With a target specification -(see above), collapses only the internal nodes matching the specification.
    ladderize
    +(see above), collapses only the internal nodes matching the specification.
    ladderize
    Sort clades in-place according to the number of terminal nodes. Deepest clades are placed -last by default. Use reverse=True to sort clades deepest-to-shallowest.
    prune
    +last by default. Use reverse=True to sort clades deepest-to-shallowest.
    prune
    Prunes a terminal clade from the tree. If taxon is from a bifurcation, the connecting node will be collapsed and its branch length added to remaining terminal node. This might no -longer be a meaningful value.
    root_with_outgroup
    +longer be a meaningful value.
    root_with_outgroup
    Reroot this tree with the outgroup clade containing the given targets, i.e. the common -ancestor of the outgroup. This method is only available on Tree objects, not Clades.

    If the outgroup is identical to self.root, no change occurs. If the outgroup clade is +ancestor of the outgroup. This method is only available on Tree objects, not Clades.

    If the outgroup is identical to self.root, no change occurs. If the outgroup clade is terminal (e.g. a single terminal node is given as the outgroup), a new bifurcating root clade is created with a 0-length branch to the given outgroup. Otherwise, the internal node at the base of the outgroup becomes a trifurcating root for the whole tree. If the original -root was bifurcating, it is dropped from the tree.

    In all cases, the total branch length of the tree stays the same.

    root_at_midpoint
    +root was bifurcating, it is dropped from the tree.

    In all cases, the total branch length of the tree stays the same.

    root_at_midpoint
    Reroot this tree at the calculated midpoint between the two most distant -tips of the tree. (This uses root_with_outgroup under the hood.)
    split
    -Generate n (default 2) new descendants. In a species tree, this is a speciation -event. New clades have the given branch_length and the same name as this clade’s +tips of the tree. (This uses root_with_outgroup under the hood.)
    split
    +Generate n (default 2) new descendants. In a species tree, this is a speciation +event. New clades have the given branch_length and the same name as this clade’s root plus an integer suffix (counting from 0) — for example, splitting a clade named -“A” produces the sub-clades “A0” and “A1”.

    See the Phylo page on the Biopython wiki (http://biopython.org/wiki/Phylo) for -more examples of using the available methods.

    -

    13.4.4  Features of PhyloXML trees

    -

    The phyloXML file format includes fields for annotating trees with additional data types and -visual cues.

    See the PhyloXML page on the Biopython wiki (http://biopython.org/wiki/PhyloXML) for -descriptions and examples of using the additional annotation features provided by PhyloXML.

    -

    13.5  Running external applications

    -

    While Bio.Phylo doesn’t infer trees from alignments itself, there are third-party +“A” produces the sub-clades “A0” and “A1”.

    See the Phylo page on the Biopython wiki (http://biopython.org/wiki/Phylo) for +more examples of using the available methods.

    + +

    13.4.4  Features of PhyloXML trees

    +

    The phyloXML file format includes fields for annotating trees with additional data types and +visual cues.

    See the PhyloXML page on the Biopython wiki (http://biopython.org/wiki/PhyloXML) for +descriptions and examples of using the additional annotation features provided by PhyloXML.

    + +

    13.5  Running external applications

    +

    While Bio.Phylo doesn’t infer trees from alignments itself, there are third-party programs available that do. These are supported through the module -Bio.Phylo.Applications, using the same general framework as -Bio.Emboss.Applications, Bio.Align.Applications and others.

    Biopython 1.58 introduced a wrapper for PhyML -(http://www.atgc-montpellier.fr/phyml/). The program accepts an input alignment in -phylip-relaxed format (that’s Phylip format, but without the 10-character limit -on taxon names) and a variety of options. A quick example:

    >>> from Bio import Phylo
    +Bio.Phylo.Applications, using the same general framework as
    +Bio.Emboss.Applications, Bio.Align.Applications and others.

    Biopython 1.58 introduced a wrapper for PhyML +(http://www.atgc-montpellier.fr/phyml/). The program accepts an input alignment in +phylip-relaxed format (that’s Phylip format, but without the 10-character limit +on taxon names) and a variety of options. A quick example:

    >>> from Bio import Phylo
     >>> from Bio.Phylo.Applications import PhymlCommandline
     >>> cmd = PhymlCommandline(input='Tests/Phylip/random.phy')
     >>> out_log, err_log = cmd()
    -

    This generates a tree file and a stats file with the names -[input filename]_phyml_tree.txt and -[input filename]_phyml_stats.txt. The tree file is in Newick format:

    >>> tree = Phylo.read('Tests/Phylip/random.phy_phyml_tree.txt', 'newick')
    +

    This generates a tree file and a stats file with the names +[input filename]_phyml_tree.txt and +[input filename]_phyml_stats.txt. The tree file is in Newick format:

    >>> tree = Phylo.read('Tests/Phylip/random.phy_phyml_tree.txt', 'newick')
     >>> Phylo.draw_ascii(tree)
    -

    A similar wrapper for RAxML (http://sco.h-its.org/exelixis/software.html) +

    A similar wrapper for RAxML (http://sco.h-its.org/exelixis/software.html) was added in Biopython 1.60, and FastTree -(http://www.microbesonline.org/fasttree/) in Biopython 1.62.

    Note that some popular Phylip programs, including dnaml and protml, -are already available through the EMBOSS wrappers in Bio.Emboss.Applications if +(http://www.microbesonline.org/fasttree/) in Biopython 1.62.

    Note that some popular Phylip programs, including dnaml and protml, +are already available through the EMBOSS wrappers in Bio.Emboss.Applications if you have the Phylip extensions to EMBOSS installed on your system. -See Section 6.4 for some examples and clues on how to use -programs like these.

    -

    13.6  PAML integration

    -

    Biopython 1.58 brought support for PAML -(http://abacus.gene.ucl.ac.uk/software/paml.html), a suite of programs for +See Section 6.4 for some examples and clues on how to use +programs like these.

    + +

    13.6  PAML integration

    +

    Biopython 1.58 brought support for PAML +(http://abacus.gene.ucl.ac.uk/software/paml.html), a suite of programs for phylogenetic analysis by maximum likelihood. Currently the programs codeml, baseml and yn00 are implemented. Due to PAML’s usage of control files rather than command line arguments to control runtime options, usage of this wrapper strays from the format of -other application wrappers in Biopython.

    A typical workflow would be to initialize a PAML object, specifying an alignment file, a +other application wrappers in Biopython.

    A typical workflow would be to initialize a PAML object, specifying an alignment file, a tree file, an output file and a working directory. Next, runtime options are set via the -set_options() method or by reading an existing control file. Finally, the -program is run via the run() method and the output file is automatically parsed -to a results dictionary.

    Here is an example of typical usage of codeml: -

    >>> from Bio.Phylo.PAML import codeml
    +set_options() method or by reading an existing control file. Finally, the
    +program is run via the run() method and the output file is automatically parsed
    +to a results dictionary.

    Here is an example of typical usage of codeml: +

    >>> from Bio.Phylo.PAML import codeml
     >>> cml = codeml.Codeml()
     >>> cml.alignment = "Tests/PAML/alignment.phylip"
     >>> cml.tree = "Tests/PAML/species.tree"
    @@ -7126,56 +7363,60 @@
     >>> ns_sites = results.get("NSsites")
     >>> m0 = ns_sites.get(0)
     >>> m0_params = m0.get("parameters")
    ->>> print m0_params.get("omega")
    -

    Existing output files may be parsed as well using a module’s read() function: -

    >>> results = codeml.read("Tests/PAML/Results/codeml/codeml_NSsites_all.out")
    ->>> print results.get("lnL max")
    -

    Detailed documentation for this new module currently lives on the Biopython wiki: -http://biopython.org/wiki/PAML

    -

    13.7  Future plans

    -

    Bio.Phylo is under active development. Here are some features we might add in future -releases:

    -New methods
    +>>> print(m0_params.get("omega")) +

    Existing output files may be parsed as well using a module’s read() function: +

    >>> results = codeml.read("Tests/PAML/Results/codeml/codeml_NSsites_all.out")
    +>>> print(results.get("lnL max"))
    +

    Detailed documentation for this new module currently lives on the Biopython wiki: +http://biopython.org/wiki/PAML

    + +

    13.7  Future plans

    +

    Bio.Phylo is under active development. Here are some features we might add in future +releases:

    +New methods
    Generally useful functions for operating on Tree or Clade objects appear on the Biopython wiki first, so that casual users can test them and decide if they’re useful before we add -them to Bio.Phylo:

    http://biopython.org/wiki/Phylo_cookbook

    Bio.Nexus port
    +them to Bio.Phylo:

    http://biopython.org/wiki/Phylo_cookbook

    Bio.Nexus port
    Much of this module was written during Google Summer of Code 2009, under the auspices of NESCent, as a project to implement Python support for the phyloXML data format (see -13.4.4). Support for Newick and Nexus formats was added by porting part of the -existing Bio.Nexus module to the new classes used by Bio.Phylo.

    Currently, Bio.Nexus contains some useful features that have not yet been ported to +13.4.4). Support for Newick and Nexus formats was added by porting part of the +existing Bio.Nexus module to the new classes used by Bio.Phylo.

    Currently, Bio.Nexus contains some useful features that have not yet been ported to Bio.Phylo classes — notably, calculating a consensus tree. If you find some functionality -lacking in Bio.Phylo, try poking throught Bio.Nexus to see if it’s there instead.

    We’re open to any suggestions for improving the functionality and usability of this module; -just let us know on the mailing list or our bug database.

    Finally, if you need additional functionality not yet included in the Phylo +lacking in Bio.Phylo, try poking throught Bio.Nexus to see if it’s there instead.

    We’re open to any suggestions for improving the functionality and usability of this module; +just let us know on the mailing list or our bug database.

    Finally, if you need additional functionality not yet included in the Phylo module, check if it’s available in another of the high-quality Python libraries -for phylogenetics such as DendroPy (http://pythonhosted.org/DendroPy/) or -PyCogent (http://pycogent.org/). Since these libraries also support +for phylogenetics such as DendroPy (http://pythonhosted.org/DendroPy/) or +PyCogent (http://pycogent.org/). Since these libraries also support standard file formats for phylogenetic trees, you can easily transfer data -between libraries by writing to a temporary file or StringIO object.

    -

    Chapter 14  Sequence motif analysis using Bio.motifs

    This chapter gives an overview of the functionality of the -Bio.motifs package included in Biopython. It is intended +between libraries by writing to a temporary file or StringIO object.

    + +

    Chapter 14  Sequence motif analysis using Bio.motifs

    This chapter gives an overview of the functionality of the +Bio.motifs package included in Biopython. It is intended for people who are involved in the analysis of sequence motifs, so I’ll assume that you are familiar with basic notions of motif analysis. In -case something is unclear, please look at Section 14.10 -for some relevant links.

    Most of this chapter describes the new Bio.motifs package included -in Biopython 1.61 onwards, which is replacing the older Bio.Motif package +case something is unclear, please look at Section 14.10 +for some relevant links.

    Most of this chapter describes the new Bio.motifs package included +in Biopython 1.61 onwards, which is replacing the older Bio.Motif package introduced with Biopython 1.50, which was in turn based on two older former -Biopython modules, Bio.AlignAce and Bio.MEME. It provides -most of their functionality with a unified motif object implementation.

    Speaking of other libraries, if you are reading this you might be -interested in TAMO, another python library -designed to deal with sequence motifs. It supports more de-novo +Biopython modules, Bio.AlignAce and Bio.MEME. It provides +most of their functionality with a unified motif object implementation.

    Speaking of other libraries, if you are reading this you might be +interested in TAMO, another python library +designed to deal with sequence motifs. It supports more de-novo motif finders, but it is not a part of Biopython and has some restrictions -on commercial use.

    -

    14.1  Motif objects

    -

    Since we are interested in motif analysis, we need to take a look at -Motif objects in the first place. For that we need to import +on commercial use.

    + +

    14.1  Motif objects

    +

    Since we are interested in motif analysis, we need to take a look at +Motif objects in the first place. For that we need to import the Bio.motifs library: -

    >>> from Bio import motifs
    -

    and we can start creating our first motif objects. We can either create -a Motif object from a list of instances of the motif, or we can -obtain a Motif object by parsing a file from a motif database -or motif finding software.

    -

    14.1.1  Creating a motif from instances

    Suppose we have these instances of a DNA motif: -

    >>> from Bio.Seq import Seq
    +

    >>> from Bio import motifs
    +

    and we can start creating our first motif objects. We can either create +a Motif object from a list of instances of the motif, or we can +obtain a Motif object by parsing a file from a motif database +or motif finding software.

    + +

    14.1.1  Creating a motif from instances

    Suppose we have these instances of a DNA motif: +

    >>> from Bio.Seq import Seq
     >>> instances = [Seq("TACAA"),
     ...              Seq("TACGC"),
     ...              Seq("TACAC"),
    @@ -7184,11 +7425,11 @@
     ...              Seq("AATGC"),
     ...              Seq("AATGC"),
     ...             ]
    -

    then we can create a Motif object as follows: -

    >>> m = motifs.create(instances)
    -

    The instances are saved in an attribute m.instances, which is essentially a Python list with some added functionality, as described below. +

    then we can create a Motif object as follows: +

    >>> m = motifs.create(instances)
    +

    The instances are saved in an attribute m.instances, which is essentially a Python list with some added functionality, as described below. Printing out the Motif object shows the instances from which it was constructed: -

    >>> print m
    +

    >>> print(m)
     TACAA
     TACGC
     TACAC
    @@ -7197,35 +7438,35 @@
     AATGC
     AATGC
     <BLANKLINE>
    -

    The length of the motif defined as the sequence length, which should be the same for all instances: -

    >>> len(m)
    +

    The length of the motif defined as the sequence length, which should be the same for all instances: +

    >>> len(m)
     5
    -

    The Motif object has an attribute .counts containing the counts of each +

    The Motif object has an attribute .counts containing the counts of each nucleotide at each position. Printing this counts matrix shows it in an easily readable format: -

    >>> print m.counts
    +

    >>> print(m.counts)
             0      1      2      3      4
     A:   3.00   7.00   0.00   2.00   1.00
     C:   0.00   0.00   5.00   2.00   6.00
     G:   0.00   0.00   0.00   3.00   0.00
     T:   4.00   0.00   2.00   0.00   0.00
     <BLANKLINE>
    -

    You can access these counts as a dictionary: -

    >>> m.counts['A']
    +

    You can access these counts as a dictionary: +

    >>> m.counts['A']
     [3, 7, 0, 2, 1]
    -

    but you can also think of it as a 2D array with the nucleotide as the first +

    but you can also think of it as a 2D array with the nucleotide as the first dimension and the position as the second dimension: -

    >>> m.counts['T',0]
    +

    >>> m.counts['T', 0]
     4
    ->>> m.counts['T',2]
    +>>> m.counts['T', 2]
     2
    ->>> m.counts['T',3]
    +>>> m.counts['T', 3]
     0
    -

    You can also directly access columns of the counts matrix -

    >>> m.counts[:,3]
    +

    You can also directly access columns of the counts matrix +

    >>> m.counts[:, 3]
     {'A': 2, 'C': 2, 'T': 0, 'G': 3}
    -

    Instead of the nucleotide itself, you can also use the index of the nucleotide +

    Instead of the nucleotide itself, you can also use the index of the nucleotide in the sorted letters in the alphabet of the motif: -

    >>> m.alphabet
    +

    >>> m.alphabet
     IUPACUnambiguousDNA()
     >>> m.alphabet.letters
     'GATC'
    @@ -7235,29 +7476,29 @@
     (3, 7, 0, 2, 1)
     >>> m.counts[0,:]
     (3, 7, 0, 2, 1)
    -

    The motif has an associated consensus sequence, defined as the sequence of +

    The motif has an associated consensus sequence, defined as the sequence of letters along the positions of the motif for which the largest value in the -corresponding columns of the .counts matrix is obtained: -

    >>> m.consensus
    +corresponding columns of the .counts matrix is obtained:
    +

    >>> m.consensus
     Seq('TACGC', IUPACUnambiguousDNA())
    -

    as well as an anticonsensus sequence, corresponding to the smallest values in -the columns of the .counts matrix: -

    >>> m.anticonsensus
    +

    as well as an anticonsensus sequence, corresponding to the smallest values in +the columns of the .counts matrix: +

    >>> m.anticonsensus
     Seq('GGGTG', IUPACUnambiguousDNA())
    -

    You can also ask for a degenerate consensus sequence, in which ambiguous +

    You can also ask for a degenerate consensus sequence, in which ambiguous nucleotides are used for positions where there are multiple nucleotides with high counts: -

    >>> m.degenerate_consensus
    +

    >>> m.degenerate_consensus
     Seq('WACVC', IUPACAmbiguousDNA())
    -

    Here, W and R follow the IUPAC nucleotide ambiguity codes: W is either A or T, -and V is A, C, or G [10]. The degenerate consensus sequence is -constructed following the rules specified by Cavener [11].

    We can also get the reverse complement of a motif: -

    >>> r = m.reverse_complement()
    +

    Here, W and R follow the IUPAC nucleotide ambiguity codes: W is either A or T, +and V is A, C, or G [10]. The degenerate consensus sequence is +constructed following the rules specified by Cavener [11].

    We can also get the reverse complement of a motif: +

    >>> r = m.reverse_complement()
     >>> r.consensus
     Seq('GCGTA', IUPACUnambiguousDNA())
     >>> r.degenerate_consensus
     Seq('GBGTW', IUPACAmbiguousDNA())
    ->>> print r
    +>>> print(r)
     TTGTA
     GCGTA
     GTGTA
    @@ -7266,36 +7507,39 @@
     GCATT
     GCATT
     <BLANKLINE>
    -

    The reverse complement and the degenerate consensus sequence are -only defined for DNA motifs.

    -

    14.1.2  Creating a sequence logo

    -If we have internet access, we can create a weblogo: -

    >>> m.weblogo("mymotif.png")
    -

    We should get our logo saved as a PNG in the specified file.

    -

    14.2  Reading motifs

    -

    Creating motifs from instances by hand is a bit boring, so it’s +

    The reverse complement and the degenerate consensus sequence are +only defined for DNA motifs.

    + +

    14.1.2  Creating a sequence logo

    +If we have internet access, we can create a weblogo: +

    >>> m.weblogo("mymotif.png")
    +

    We should get our logo saved as a PNG in the specified file.

    + +

    14.2  Reading motifs

    +

    Creating motifs from instances by hand is a bit boring, so it’s useful to have some I/O functions for reading and writing motifs. There are not any really well established standards for storing motifs, but there are a couple of formats that are more used than -others.

    -

    14.2.1  JASPAR

    -One of the most popular motif databases is JASPAR. In addition to the motif sequence information, the JASPAR database stores a lot of meta-information for each motif. The module Bio.motifs contains a specialized class jaspar.Motif in which this meta-information is represented as attributes: -

    • -matrix_id - the unique JASPAR motif ID, e.g. ’MA0004.1’ -
    • name - the name of the TF, e.g. ’Arnt’ -
    • collection - the JASPAR collection to which the motif belongs, e.g. ’CORE’ -
    • tf_class - the structual class of this TF, e.g. ’Zipper-Type’ -
    • tf_family - the family to which this TF belongs, e.g. ’Helix-Loop-Helix’ -
    • species - the species to which this TF belongs, may have multiple values, these are specified as taxonomy IDs, e.g. 10090 -
    • tax_group - the taxonomic supergroup to which this motif belongs, e.g. ’vertebrates’ -
    • acc - the accesion number of the TF protein, e.g. ’P53762’ -
    • data_type - the type of data used to construct this motif, e.g. ’SELEX’ -
    • medline - the Pubmed ID of literature supporting this motif, may be multiple values, e.g. 7592839 -
    • pazar_id - external reference to the TF in the PAZAR database, e.g. ’TF0000003’ -
    • comment - free form text containing notes about the construction of the motif -

    The jaspar.Motif class inherits from the generic Motif class and therefore provides all the facilities of any of the motif formats — reading motifs, writing motifs, scanning sequences for motif instances etc.

    JASPAR stores motifs in several different ways including three different flat file formats and as an SQL database. All of these formats facilitate the construction of a counts matrix. However, the amount of meta information described above that is available varies with the format.

    -

    The JASPAR sites format

    The first of the three flat file formats contains a list of instances. As an example, these are the beginning and ending lines of the JASPAR Arnt.sites file showing known binding sites of the mouse helix-loop-helix transcription factor Arnt. -

    >MA0004 ARNT 1
    +others.

    + +

    14.2.1  JASPAR

    +One of the most popular motif databases is JASPAR. In addition to the motif sequence information, the JASPAR database stores a lot of meta-information for each motif. The module Bio.motifs contains a specialized class jaspar.Motif in which this meta-information is represented as attributes: +

    • +matrix_id - the unique JASPAR motif ID, e.g. ’MA0004.1’ +
    • name - the name of the TF, e.g. ’Arnt’ +
    • collection - the JASPAR collection to which the motif belongs, e.g. ’CORE’ +
    • tf_class - the structual class of this TF, e.g. ’Zipper-Type’ +
    • tf_family - the family to which this TF belongs, e.g. ’Helix-Loop-Helix’ +
    • species - the species to which this TF belongs, may have multiple values, these are specified as taxonomy IDs, e.g. 10090 +
    • tax_group - the taxonomic supergroup to which this motif belongs, e.g. ’vertebrates’ +
    • acc - the accesion number of the TF protein, e.g. ’P53762’ +
    • data_type - the type of data used to construct this motif, e.g. ’SELEX’ +
    • medline - the Pubmed ID of literature supporting this motif, may be multiple values, e.g. 7592839 +
    • pazar_id - external reference to the TF in the PAZAR database, e.g. ’TF0000003’ +
    • comment - free form text containing notes about the construction of the motif +

    The jaspar.Motif class inherits from the generic Motif class and therefore provides all the facilities of any of the motif formats — reading motifs, writing motifs, scanning sequences for motif instances etc.

    JASPAR stores motifs in several different ways including three different flat file formats and as an SQL database. All of these formats facilitate the construction of a counts matrix. However, the amount of meta information described above that is available varies with the format.

    +

    The JASPAR sites format

    The first of the three flat file formats contains a list of instances. As an example, these are the beginning and ending lines of the JASPAR Arnt.sites file showing known binding sites of the mouse helix-loop-helix transcription factor Arnt. +

    >MA0004 ARNT 1
     CACGTGatgtcctc
     >MA0004 ARNT 2
     CACGTGggaggtac
    @@ -7308,14 +7552,14 @@
     AACGTGcacatcgtcc
     >MA0004 ARNT 20
     aggaatCGCGTGc
    -

    The parts of the sequence in capital letters are the motif instances that were found to align to each other.

    We can create a Motif object from these instances as follows: -

    >>> from Bio import motifs
    +

    The parts of the sequence in capital letters are the motif instances that were found to align to each other.

    We can create a Motif object from these instances as follows: +

    >>> from Bio import motifs
     >>> arnt = motifs.read(open("Arnt.sites"), "sites")
    -

    The instances from which this motif was created is stored in the .instances property: -

    >>> print arnt.instances[:3]
    +

    The instances from which this motif was created is stored in the .instances property: +

    >>> print(arnt.instances[:3])
     [Seq('CACGTG', IUPACUnambiguousDNA()), Seq('CACGTG', IUPACUnambiguousDNA()), Seq('CACGTG', IUPACUnambiguousDNA())]
     >>> for instance in arnt.instances:
    -...     print instance
    +...     print(instance)
     ...
     CACGTG
     CACGTG
    @@ -7337,43 +7581,43 @@
     AACGTG
     AACGTG
     CGCGTG
    -

    The counts matrix of this motif is automatically calculated from the instances: -

    >>> print arnt.counts
    +

    The counts matrix of this motif is automatically calculated from the instances: +

    >>> print(arnt.counts)
             0      1      2      3      4      5
     A:   4.00  19.00   0.00   0.00   0.00   0.00
     C:  16.00   0.00  20.00   0.00   0.00   0.00
     G:   0.00   1.00   0.00  20.00   0.00  20.00
     T:   0.00   0.00   0.00   0.00  20.00   0.00
     <BLANKLINE>
    -

    This format does not store any meta information.

    -

    The JASPAR pfm format

    JASPAR also makes motifs available directly as a count matrix, -without the instances from which it was created. This pfm format only +

    This format does not store any meta information.

    +

    The JASPAR pfm format

    JASPAR also makes motifs available directly as a count matrix, +without the instances from which it was created. This pfm format only stores the counts matrix for a single motif. -For example, this is the JASPAR file SRF.pfm containing the counts matrix for the human SRF transcription factor: -

     2 9 0 1 32 3 46 1 43 15 2 2
    +For example, this is the JASPAR file SRF.pfm containing the counts matrix for the human SRF transcription factor:
    +

     2 9 0 1 32 3 46 1 43 15 2 2
      1 33 45 45 1 1 0 0 0 1 0 1
     39 2 1 0 0 0 0 0 0 0 44 43
      4 2 0 0 13 42 0 45 3 30 0 0
    -

    We can create a motif for this count matrix as follows: -

    >>> srf = motifs.read(open("SRF.pfm"),"pfm")
    ->>> print srf.counts
    +

    We can create a motif for this count matrix as follows: +

    >>> srf = motifs.read(open("SRF.pfm"), "pfm")
    +>>> print(srf.counts)
             0      1      2      3      4      5      6      7      8      9     10     11
     A:   2.00   9.00   0.00   1.00  32.00   3.00  46.00   1.00  43.00  15.00   2.00   2.00
     C:   1.00  33.00  45.00  45.00   1.00   1.00   0.00   0.00   0.00   1.00   0.00   1.00
     G:  39.00   2.00   1.00   0.00   0.00   0.00   0.00   0.00   0.00   0.00  44.00  43.00
     T:   4.00   2.00   0.00   0.00  13.00  42.00   0.00  45.00   3.00  30.00   0.00   0.00
     <BLANKLINE>
    -

    As this motif was created from the counts matrix directly, it has no instances associated with it: -

    >>> print srf.instances
    +

    As this motif was created from the counts matrix directly, it has no instances associated with it: +

    >>> print(srf.instances)
     None
    -

    We can now ask for the consensus sequence of these two motifs: -

    >>> print arnt.counts.consensus
    +

    We can now ask for the consensus sequence of these two motifs: +

    >>> print(arnt.counts.consensus)
     CACGTG
    ->>> print srf.counts.consensus
    +>>> print(srf.counts.consensus)
     GCCCATATATGG
    -

    As with the instances file, not meta information is stored in this format.

    -

    The JASPAR format jaspar

    The jaspar file format allows multiple motifs to be specified in a single file. In this format each of the motif records consist of a header line followed by four lines defining the counts matrix. The header line begins with a > character (similar to the Fasta file format) and is followed by the unique JASPAR matrix ID and the TF name. The following example shows a jaspar formatted file containing the three motifs Arnt, RUNX1 and MEF2A: -

    >MA0004.1 Arnt
    +

    As with the instances file, not meta information is stored in this format.

    +

    The JASPAR format jaspar

    The jaspar file format allows multiple motifs to be specified in a single file. In this format each of the motif records consist of a header line followed by four lines defining the counts matrix. The header line begins with a > character (similar to the Fasta file format) and is followed by the unique JASPAR matrix ID and the TF name. The following example shows a jaspar formatted file containing the three motifs Arnt, RUNX1 and MEF2A: +

    >MA0004.1 Arnt
     A  [ 4 19  0  0  0  0 ]
     C  [16  0 20  0  0  0 ]
     G  [ 0  1  0 20  0 20 ]
    @@ -7388,10 +7632,10 @@
     C  [50  0  1  1  0  0  0  0  0  0 ]
     G  [ 0  0  0  0  0  0  0  0  2 50 ]
     T  [ 7 58  0 55 49 52 21 56  0  2 ]
    -

    The motifs are read as follows: -

    >>> fh = open("jaspar_motifs.txt")
    +

    The motifs are read as follows: +

    >>> fh = open("jaspar_motifs.txt")
     >>> for m in motifs.parse(fh, "jaspar"))
    -...     print m
    +...     print(m)
     TF name  Arnt
     Matrix ID MA0004.1
     Matrix:
    @@ -7422,9 +7666,9 @@
     C:  50.00   0.00   1.00   1.00   0.00   0.00   0.00   0.00   0.00   0.00
     G:   0.00   0.00   0.00   0.00   0.00   0.00   0.00   0.00   2.00  50.00
     T:   7.00  58.00   0.00  55.00  49.00  52.00  21.00  56.00   0.00   2.00
    -

    Note that printing a JASPAR motif yields both the counts data and the available meta-information.

    -

    Accessing the JASPAR database

    In addition to parsing these flat file formats, we can also retrieve motifs from a JASPAR SQL database. Unlike the flat file formats, a JASPAR database allows storing of all possible meta information defined in the JASPAR Motif class. It is beyond the scope of this document to describe how to set up a JASPAR database (please see the main JASPAR website). Motifs are read from a JASPAR database using the Bio.motifs.jaspar.db module. First connect to the JASPAR database using the JASPAR5 class which models the the latest JASPAR schema: -

    >>> from Bio.motifs.jaspar.db import JASPAR5
    +

    Note that printing a JASPAR motif yields both the counts data and the available meta-information.

    +

    Accessing the JASPAR database

    In addition to parsing these flat file formats, we can also retrieve motifs from a JASPAR SQL database. Unlike the flat file formats, a JASPAR database allows storing of all possible meta information defined in the JASPAR Motif class. It is beyond the scope of this document to describe how to set up a JASPAR database (please see the main JASPAR website). Motifs are read from a JASPAR database using the Bio.motifs.jaspar.db module. First connect to the JASPAR database using the JASPAR5 class which models the the latest JASPAR schema: +

    >>> from Bio.motifs.jaspar.db import JASPAR5
     >>> 
     >>> JASPAR_DB_HOST = <hostname>
     >>> JASPAR_DB_NAME = <db_name>
    @@ -7437,10 +7681,10 @@
     ...     user=JASPAR_DB_USER,
     ...     password=JASPAR_DB_PASS
     ... )
    -

    Now we can fetch a single motif by its unique JASPAR ID with the fetch_motif_by_id method. Note that a JASPAR ID conists of a base ID and a version number seperated by a decimal point, e.g. ’MA0004.1’. The fetch_motif_by_id method allows you to use either the fully specified ID or just the base ID. If only the base ID is provided, the latest version of the motif is returned. -

    >>> arnt = jdb.fetch_motif_by_id("MA0004")
    -

    Printing the motif reveals that the JASPAR SQL database stores much more meeta-information than the flat files: -

    >>> print arnt
    +

    Now we can fetch a single motif by its unique JASPAR ID with the fetch_motif_by_id method. Note that a JASPAR ID conists of a base ID and a version number seperated by a decimal point, e.g. ’MA0004.1’. The fetch_motif_by_id method allows you to use either the fully specified ID or just the base ID. If only the base ID is provided, the latest version of the motif is returned. +

    >>> arnt = jdb.fetch_motif_by_id("MA0004")
    +

    Printing the motif reveals that the JASPAR SQL database stores much more meeta-information than the flat files: +

    >>> print(arnt)
     TF name Arnt
     Matrix ID MA0004.1
     Collection CORE
    @@ -7461,9 +7705,9 @@
     T:   0.00   0.00   0.00   0.00  20.00   0.00
     
     
    -

    We can also fetch motifs by name. The name must be an exact match (partial matches or database wildcards are not currently supported). Note that as the name is not guaranteed to be unique, the fetch_motifs_by_name method actually returns a list. -

    >>> motifs = jdb.fetch_motifs_by_name("Arnt")
    ->>> print motifs[0]
    +

    We can also fetch motifs by name. The name must be an exact match (partial matches or database wildcards are not currently supported). Note that as the name is not guaranteed to be unique, the fetch_motifs_by_name method actually returns a list. +

    >>> motifs = jdb.fetch_motifs_by_name("Arnt")
    +>>> print(motifs[0])
     TF name Arnt
     Matrix ID MA0004.1
     Collection CORE
    @@ -7484,8 +7728,8 @@
     T:   0.00   0.00   0.00   0.00  20.00   0.00
     
     
    -

    The fetch_motifs method allows you to fetch motifs which match a specified set of criteria. These criteria include any of the above described meta information as well as certain matrix properties such as the minimum information content (min_ic in the example below), the minimum length of the matrix or the minimum number of sites used to construct the matrix. Only motifs which pass ALL the specified criteria are returned. Note that selection criteria which correspond to meta information which allow for multiple values may be specified as either a single value or a list of values, e.g. tax_group and tf_family in the example below. -

    >>> motifs = jdb.fetch_motifs(
    +

    The fetch_motifs method allows you to fetch motifs which match a specified set of criteria. These criteria include any of the above described meta information as well as certain matrix properties such as the minimum information content (min_ic in the example below), the minimum length of the matrix or the minimum number of sites used to construct the matrix. Only motifs which pass ALL the specified criteria are returned. Note that selection criteria which correspond to meta information which allow for multiple values may be specified as either a single value or a list of values, e.g. tax_group and tf_family in the example below. +

    >>> motifs = jdb.fetch_motifs(
     ...     collection = 'CORE',
     ...     tax_group = ['vertebrates', 'insects'],
     ...     tf_class = 'Winged Helix-Turn-Helix',
    @@ -7494,23 +7738,23 @@
     ... )
     >>> for motif in motifs:
     ...     pass # do something with the motif
    -
    -

    Compatibility with Perl TFBS modules

    An important thing to note is that the JASPAR Motif class was designed to be compatible with the popular Perl TFBS modules. Therefore some specifics about the choice of defaults for background and pseudocounts as well as how information content is computed and sequences searched for instances is based on this compatibility criteria. These choices are noted in the specific subsections below.

    • -Choice of background:
      -The Perl TFBS modules appear to allow a choice of custom background probabilities (although the documentation states that uniform background is assumed). However the default is to use a uniform background. Therefore it is recommended that you use a uniform background for computing the position-specific scoring matrix (PSSM). This is the default when using the Biopython motifs module. -
    • Choice of pseudocounts:
      -By default, the Perl TFBS modules use a pseudocount equal to √N * bg[nucleotide], where N represents the total number of sequences used to construct the matrix. To apply this same pseudocount formula, set the motif pseudocounts attribute using the jaspar.calculate\_pseudcounts() funtion: -
      >>> motif.pseudocounts = motifs.jaspar.calculate_pseudocounts(motif)
      -
      Note that it is possible for the counts matrix to have an unequal number of sequences making up the columns. The pseudocount computation uses the average number of sequences making up the matrix. However, when normalize is called on the counts matrix, each count value in a column is divided by the total number of sequences making up that specific column, not by the average number of sequences. This differs from the Perl TFBS modules because the normalization is not done as a separate step and so the average number of sequences is used throughout the computation of the pssm. Therefore, for matrices with unequal column counts, the pssm computed by the motifs module will differ somewhat from the pssm computed by the Perl TFBS modules. -
    • Computation of matrix information content:
      -The information content (IC) or specificity of a matrix is computed using the mean method of the PositionSpecificScoringMatrix class. However of note, in the Perl TFBS modules the default behaviour is to compute the IC without first applying pseudocounts, even though by default the PSSMs are computed using pseudocounts as described above. -
    • Searching for instances:
      -Searching for instances with the Perl TFBS motifs was usually performed using a relative score threshold, i.e. a score in the range 0 to 1. In order to compute the absolute PSSM score corresponding to a relative score one can use the equation: -
      >>> abs_score =  (pssm.max - pssm.min) * rel_score + pssm.min
      -
      To convert the absolute score of an instance back to a relative score, one can use the equation: -
      >>> rel_score = (abs_score - pssm.min) / (pssm.max - pssm.min)
      -
      For example, using the Arnt motif before, let’s search a sequence with a relative score threshold of 0.8. -
      >>> test_seq=Seq("TAAGCGTGCACGCGCAACACGTGCATTA", unambiguous_dna)
      +
      +

      Compatibility with Perl TFBS modules

      An important thing to note is that the JASPAR Motif class was designed to be compatible with the popular Perl TFBS modules. Therefore some specifics about the choice of defaults for background and pseudocounts as well as how information content is computed and sequences searched for instances is based on this compatibility criteria. These choices are noted in the specific subsections below.

      • +Choice of background:
        +The Perl TFBS modules appear to allow a choice of custom background probabilities (although the documentation states that uniform background is assumed). However the default is to use a uniform background. Therefore it is recommended that you use a uniform background for computing the position-specific scoring matrix (PSSM). This is the default when using the Biopython motifs module. +
      • Choice of pseudocounts:
        +By default, the Perl TFBS modules use a pseudocount equal to √N * bg[nucleotide], where N represents the total number of sequences used to construct the matrix. To apply this same pseudocount formula, set the motif pseudocounts attribute using the jaspar.calculate\_pseudcounts() funtion: +
        >>> motif.pseudocounts = motifs.jaspar.calculate_pseudocounts(motif)
        +
        Note that it is possible for the counts matrix to have an unequal number of sequences making up the columns. The pseudocount computation uses the average number of sequences making up the matrix. However, when normalize is called on the counts matrix, each count value in a column is divided by the total number of sequences making up that specific column, not by the average number of sequences. This differs from the Perl TFBS modules because the normalization is not done as a separate step and so the average number of sequences is used throughout the computation of the pssm. Therefore, for matrices with unequal column counts, the pssm computed by the motifs module will differ somewhat from the pssm computed by the Perl TFBS modules. +
      • Computation of matrix information content:
        +The information content (IC) or specificity of a matrix is computed using the mean method of the PositionSpecificScoringMatrix class. However of note, in the Perl TFBS modules the default behaviour is to compute the IC without first applying pseudocounts, even though by default the PSSMs are computed using pseudocounts as described above. +
      • Searching for instances:
        +Searching for instances with the Perl TFBS motifs was usually performed using a relative score threshold, i.e. a score in the range 0 to 1. In order to compute the absolute PSSM score corresponding to a relative score one can use the equation: +
        >>> abs_score =  (pssm.max - pssm.min) * rel_score + pssm.min
        +
        To convert the absolute score of an instance back to a relative score, one can use the equation: +
        >>> rel_score = (abs_score - pssm.min) / (pssm.max - pssm.min)
        +
        For example, using the Arnt motif before, let’s search a sequence with a relative score threshold of 0.8. +
        >>> test_seq=Seq("TAAGCGTGCACGCGCAACACGTGCATTA", unambiguous_dna)
         >>> arnt.pseudocounts = motifs.jaspar.calculate_pseudocounts(arnt) 
         >>> pssm = arnt.pssm()
         >>> max_score = pssm.max()
        @@ -7519,27 +7763,28 @@
         >>> for position, score in pssm.search(test_seq,
                                                threshold=abs_score_threshold):
         ...     rel_score = (score - min_score) / (max_score - min_score)
        -...     print "Position %d: score = %5.3f, rel. score = %5.3f" % (
        -            position, score, rel_score)
        +...     print("Position %d: score = %5.3f, rel. score = %5.3f" % (
        +            position, score, rel_score))
         ... 
         Position 2: score = 5.362, rel. score = 0.801
         Position 8: score = 6.112, rel. score = 0.831
         Position -20: score = 7.103, rel. score = 0.870
         Position 17: score = 10.351, rel. score = 1.000
         Position -11: score = 10.351, rel. score = 1.000
        -
      -

      14.2.2  MEME

      MEME [12] is a tool for discovering motifs in a group of related +

    + +

    14.2.2  MEME

    MEME [12] is a tool for discovering motifs in a group of related DNA or protein sequences. It takes as input a group of DNA or protein sequences and outputs as many motifs as requested. Therefore, in contrast to JASPAR -files, MEME output files typically contain multiple motifs. This is an example.

    At the top of an output file generated by MEME shows some background information +files, MEME output files typically contain multiple motifs. This is an example.

    At the top of an output file generated by MEME shows some background information about the MEME and the version of MEME used: -

    ********************************************************************************
    +

    ********************************************************************************
     MEME - Motif discovery tool
     ********************************************************************************
     MEME version 3.0 (Release date: 2004/08/18 09:07:01)
     ...
    -

    Further down, the input set of training sequences is recapitulated: -

    ********************************************************************************
    +

    Further down, the input set of training sequences is recapitulated: +

    ********************************************************************************
     TRAINING SET
     ********************************************************************************
     DATAFILE= INO_up800.s
    @@ -7551,8 +7796,8 @@
     ACC1                     1.0000    800  INO1                     1.0000    800
     OPI3                     1.0000    800
     ********************************************************************************
    -

    and the exact command line that was used: -

    ********************************************************************************
    +

    and the exact command line that was used: +

    ********************************************************************************
     COMMAND LINE SUMMARY
     ********************************************************************************
     This information can also be useful in the event you wish to report a
    @@ -7560,8 +7805,8 @@
     
     command: meme -mod oops -dna -revcomp -nmotifs 2 -bfile yeast.nc.6.freq INO_up800.s
     ...
    -

    Next is detailed information on each motif that was found: -

    ********************************************************************************
    +

    Next is detailed information on each motif that was found: +

    ********************************************************************************
     MOTIF  1        width =   12   sites =   7   llr = 95   E-value = 2.0e-001
     ********************************************************************************
     --------------------------------------------------------------------------------
    @@ -7571,14 +7816,14 @@
     pos.-specific     C  ::a:9:11691a
     probability       G  ::::1::94:4:
     matrix            T  aa:1::9::11:
    -

    To parse this file (stored as meme.dna.oops.txt), use -

    >>> handle = open("meme.dna.oops.txt")
    +

    To parse this file (stored as meme.dna.oops.txt), use +

    >>> handle = open("meme.dna.oops.txt")
     >>> record = motifs.parse(handle, "meme")
     >>> handle.close()
    -

    The motifs.parse command reads the complete file directly, so you can -close the file after calling motifs.parse. +

    The motifs.parse command reads the complete file directly, so you can +close the file after calling motifs.parse. The header information is stored in attributes: -

    >>> record.version
    +

    >>> record.version
     '3.0'
     >>> record.datafile
     'INO_up800.s'
    @@ -7588,32 +7833,32 @@
     IUPACUnambiguousDNA()
     >>> record.sequences
     ['CHO1', 'CHO2', 'FAS1', 'FAS2', 'ACC1', 'INO1', 'OPI3']
    -

    The record is an object of the Bio.motifs.meme.Record class. -The class inherits from list, and you can think of record as a list of Motif objects: -

    >>> len(record)
    +

    The record is an object of the Bio.motifs.meme.Record class. +The class inherits from list, and you can think of record as a list of Motif objects: +

    >>> len(record)
     2
     >>> motif = record[0]
    ->>> print motif.consensus
    +>>> print(motif.consensus)
     TTCACATGCCGC
    ->>> print motif.degenerate_consensus
    +>>> print(motif.degenerate_consensus)
     TTCACATGSCNC
    -

    In addition to these generic motif attributes, each motif also stores its +

    In addition to these generic motif attributes, each motif also stores its specific information as calculated by MEME. For example, -

    >>> motif.num_occurrences
    +

    >>> motif.num_occurrences
     7
     >>> motif.length
     12
     >>> evalue = motif.evalue
    ->>> print "%3.1g" % evalue
    +>>> print("%3.1g" % evalue)
     0.2
     >>> motif.name
     'Motif 1'
    -

    In addition to using an index into the record, as we did above, +

    In addition to using an index into the record, as we did above, you can also find it by its name: -

    >>> motif = record['Motif 1']
    -

    Each motif has an attribute .instances with the sequence instances +

    >>> motif = record['Motif 1']
    +

    Each motif has an attribute .instances with the sequence instances in which the motif was found, providing some information on each instance: -

    >>> len(motif.instances)
    +

    >>> len(motif.instances)
     7
     >>> motif.instances[0]
     Instance('TTCACATGCCGC', IUPACUnambiguousDNA())
    @@ -7628,15 +7873,16 @@
     >>> motif.instances[0].length
     12
     >>> pvalue = motif.instances[0].pvalue
    -
    >>> print "%5.3g" % pvalue
    +>>> print("%5.3g" % pvalue)
     1.85e-08
    -
    -

    MAST

    -

    14.2.3  TRANSFAC

    TRANSFAC is a manually curated database of transcription factors, together -with their genomic binding sites and DNA binding profiles [27]. +

    +

    MAST

    + +

    14.2.3  TRANSFAC

    TRANSFAC is a manually curated database of transcription factors, together +with their genomic binding sites and DNA binding profiles [27]. While the file format used in the TRANSFAC database is nowadays also used -by others, we will refer to it as the TRANSFAC file format.

    A minimal file in the TRANSFAC format looks as follows: -

    ID  motif1
    +by others, we will refer to it as the TRANSFAC file format.

    A minimal file in the TRANSFAC format looks as follows: +

    ID  motif1
     P0      A      C      G      T
     01      1      2      2      0      S
     02      2      1      2      0      R
    @@ -7651,10 +7897,10 @@
     11      0      2      0      3      Y
     12      1      0      3      1      G
     //
    -

    This file shows the frequency matrix of motif motif1 of 12 nucleotides. +

    This file shows the frequency matrix of motif motif1 of 12 nucleotides. In general, one file in the TRANSFAC format can contain multiple motifs. For -example, this is the contents of the example TRANSFAC file transfac.dat: -

    VV  EXAMPLE January 15, 2013
    +example, this is the contents of the example TRANSFAC file transfac.dat:
    +

    VV  EXAMPLE January 15, 2013
     XX
     //
     ID  motif1
    @@ -7674,66 +7920,66 @@
     09      0      0      0      5      T
     10      0      2      0      3      Y
     //
    -

    To parse a TRANSFAC file, use -

    >>> handle = open("transfac.dat")
    +

    To parse a TRANSFAC file, use +

    >>> handle = open("transfac.dat")
     >>> record = motifs.parse(handle, "TRANSFAC")
     >>> handle.close()
    -

    The overall version number, if available, is stored as record.version: -

    >>> record.version
    +

    The overall version number, if available, is stored as record.version: +

    >>> record.version
     'EXAMPLE January 15, 2013'
    -

    Each motif in record is in instance of the Bio.motifs.transfac.Motif -class, which inherits both from the Bio.motifs.Motif class and +

    Each motif in record is in instance of the Bio.motifs.transfac.Motif +class, which inherits both from the Bio.motifs.Motif class and from a Python dictionary. The dictionary uses the two-letter keys to store any additional information about the motif: -

    >>> motif = record[0]
    +

    >>> motif = record[0]
     >>> motif.degenerate_consensus # Using the Bio.motifs.Motif method
     Seq('SRACAGGTGKYG', IUPACAmbiguousDNA())
     >>> motif['ID'] # Using motif as a dictionary
     'motif1'
    -

    TRANSFAC files are typically much more elaborate than this example, containing -lots of additional information about the motif. Table 14.2.3 +

    TRANSFAC files are typically much more elaborate than this example, containing +lots of additional information about the motif. Table 14.2.3 lists the two-letter field codes that are commonly found in TRANSFAC files: -


    - -
    -
    -
    Table 14.1: Fields commonly found in TRANSFAC files
    - - - - - - - - - - - - - - - - - - - - -
    ACAccession number
    ASAccession numbers, secondary
    BAStatistical basis
    BFBinding factors
    BSFactor binding sites underlying the matrix
    CCComments
    COCopyright notice
    DEShort factor description
    DRExternal databases
    DTDate created/updated
    HCSubfamilies
    HPSuperfamilies
    IDIdentifier
    NAName of the binding factor
    OCTaxonomic classification
    OSSpecies/Taxon
    OVOlder version
    PVPreferred version
    TYType
    XXEmpty line; these are not stored in the Record.
    -
    -

    Each motif also has an attribute .references containing the -references associated with the motif, using these two-letter keys:


    -
    -
    -
    Table 14.2: Fields used to store references in TRANSFAC files
    - - - - - -
    RNReference number
    RAReference authors
    RLReference data
    RTReference title
    RXPubMed ID
    -
    -

    Printing the motifs writes them out in their native TRANSFAC format: -

    >>> print record
    +


    + +
    +
    +
    Table 14.1: Fields commonly found in TRANSFAC files
    + + + + + + + + + + + + + + + + + + + + +
    ACAccession number
    ASAccession numbers, secondary
    BAStatistical basis
    BFBinding factors
    BSFactor binding sites underlying the matrix
    CCComments
    COCopyright notice
    DEShort factor description
    DRExternal databases
    DTDate created/updated
    HCSubfamilies
    HPSuperfamilies
    IDIdentifier
    NAName of the binding factor
    OCTaxonomic classification
    OSSpecies/Taxon
    OVOlder version
    PVPreferred version
    TYType
    XXEmpty line; these are not stored in the Record.
    +
    +

    Each motif also has an attribute .references containing the +references associated with the motif, using these two-letter keys:


    +
    +
    +
    Table 14.2: Fields used to store references in TRANSFAC files
    + + + + + +
    RNReference number
    RAReference authors
    RLReference data
    RTReference title
    RXPubMed ID
    +
    +

    Printing the motifs writes them out in their native TRANSFAC format: +

    >>> print(record)
     VV  EXAMPLE January 15, 2013
     XX
     //
    @@ -7770,29 +8016,30 @@
     XX
     //
     <BLANKLINE>
    -

    You can export the motifs in the TRANSFAC format by capturing this output +

    You can export the motifs in the TRANSFAC format by capturing this output in a string and saving it in a file: -

    >>> text = str(record)
    +

    >>> text = str(record)
     >>> handle = open("mytransfacfile.dat", 'w')
     >>> handle.write(text)
     >>> handle.close()
    -
    -

    14.3  Writing motifs

    Speaking of exporting, let’s look at export functions in general. -We can use the format method to write the motif in the simple JASPAR pfm format: -

    >>> print arnt.format("pfm")
    +
    + +

    14.3  Writing motifs

    Speaking of exporting, let’s look at export functions in general. +We can use the format method to write the motif in the simple JASPAR pfm format: +

    >>> print(arnt.format("pfm"))
       4.00  19.00   0.00   0.00   0.00   0.00
      16.00   0.00  20.00   0.00   0.00   0.00
       0.00   1.00   0.00  20.00   0.00  20.00
       0.00   0.00   0.00   0.00  20.00   0.00
    -

    Similarly, we can use format to write the motif in the JASPAR jaspar format: -

    >>> print arnt.format("jaspar")
    +

    Similarly, we can use format to write the motif in the JASPAR jaspar format: +

    >>> print(arnt.format("jaspar"))
     >MA0004.1  Arnt
     A [  4.00  19.00   0.00   0.00   0.00   0.00]
     C [ 16.00   0.00  20.00   0.00   0.00   0.00]
     G [  0.00   1.00   0.00  20.00   0.00  20.00]
     T [  0.00   0.00   0.00   0.00  20.00   0.00]
    -

    To write the motif in a TRANSFAC-like matrix format, use -

    >>> print m.format("transfac")
    +

    To write the motif in a TRANSFAC-like matrix format, use +

    >>> print(m.format("transfac"))
     P0      A      C      G      T
     01      3      0      0      4      W
     02      7      0      0      0      A
    @@ -7802,10 +8049,10 @@
     XX
     //
     <BLANKLINE>
    -

    To write out multiple motifs, you can use motifs.write. +

    To write out multiple motifs, you can use motifs.write. This function can be used regardless of whether the motifs originated from a TRANSFAC file. For example, -

    >>> two_motifs = [arnt, srf]
    ->>> print motifs.write(two_motifs, 'transfac')
    +

    >>> two_motifs = [arnt, srf]
    +>>> print(motifs.write(two_motifs, 'transfac'))
     P0      A      C      G      T
     01      4     16      0      0      C
     02     19      0      1      0      A
    @@ -7831,9 +8078,9 @@
     XX
     //
     <BLANKLINE>
    -

    Or, to write multiple motifs in the jaspar format: -

    >>> two_motifs = [arnt, mef2a]
    ->>> print motifs.write(two_motifs, "jaspar")
    +

    Or, to write multiple motifs in the jaspar format: +

    >>> two_motifs = [arnt, mef2a]
    +>>> print(motifs.write(two_motifs, "jaspar"))
     >MA0004.1  Arnt
     A [  4.00  19.00   0.00   0.00   0.00   0.00]
     C [ 16.00   0.00  20.00   0.00   0.00   0.00]
    @@ -7844,163 +8091,168 @@
     C [ 50.00   0.00   1.00   1.00   0.00   0.00   0.00   0.00   0.00   0.00]
     G [  0.00   0.00   0.00   0.00   0.00   0.00   0.00   0.00   2.00  50.00]
     T [  7.00  58.00   0.00  55.00  49.00  52.00  21.00  56.00   0.00   2.00]
    -
    -

    14.4  Position-Weight Matrices

    The .counts attribute of a Motif object shows how often each +

    + +

    14.4  Position-Weight Matrices

    The .counts attribute of a Motif object shows how often each nucleotide appeared at each position along the alignment. We can normalize this matrix by dividing by the number of instances in the alignment, resulting in the probability of each nucleotide at each position along the alignment. We refer to these probabilities as the position-weight matrix. However, beware that in the literature this term may also be used to refer to the position-specific scoring -matrix, which we discuss below.

    Usually, pseudocounts are added to each position before normalizing. +matrix, which we discuss below.

    Usually, pseudocounts are added to each position before normalizing. This avoids overfitting of the position-weight matrix to the limited number of motif instances in the alignment, and can also prevent probabilities from becoming zero. To add a fixed pseudocount to all nucleotides at all positions, specify a number for the -pseudocounts argument: -

    >>> pwm = m.counts.normalize(pseudocounts=0.5)
    ->>> print pwm
    +pseudocounts argument:
    +

    >>> pwm = m.counts.normalize(pseudocounts=0.5)
    +>>> print(pwm)
             0      1      2      3      4
     A:   0.39   0.83   0.06   0.28   0.17
     C:   0.06   0.06   0.61   0.28   0.72
     G:   0.06   0.06   0.06   0.39   0.06
     T:   0.50   0.06   0.28   0.06   0.06
     <BLANKLINE>
    -

    Alternatively, pseudocounts can be a dictionary specifying the +

    Alternatively, pseudocounts can be a dictionary specifying the pseudocounts for each nucleotide. For example, as the GC content of the human genome is about 40%, you may want to choose the pseudocounts accordingly: -

    >>> pwm = m.counts.normalize(pseudocounts={'A':0.6, 'C': 0.4, 'G': 0.4, 'T': 0.6})
    ->>> print pwm
    +

    >>> pwm = m.counts.normalize(pseudocounts={'A':0.6, 'C': 0.4, 'G': 0.4, 'T': 0.6})
    +>>> print(pwm)
             0      1      2      3      4
     A:   0.40   0.84   0.07   0.29   0.18
     C:   0.04   0.04   0.60   0.27   0.71
     G:   0.04   0.04   0.04   0.38   0.04
     T:   0.51   0.07   0.29   0.07   0.07
     <BLANKLINE>
    -

    The position-weight matrix has its own methods to calculate the +

    The position-weight matrix has its own methods to calculate the consensus, anticonsensus, and degenerate consensus sequences: -

    >>> pwm.consensus
    +

    >>> pwm.consensus
     Seq('TACGC', IUPACUnambiguousDNA())
     >>> pwm.anticonsensus
     Seq('GGGTG', IUPACUnambiguousDNA())
     >>> pwm.degenerate_consensus
     Seq('WACNC', IUPACAmbiguousDNA())
    -

    Note that due to the pseudocounts, the degenerate consensus sequence +

    Note that due to the pseudocounts, the degenerate consensus sequence calculated from the position-weight matrix is slightly different from the degenerate consensus sequence calculated from the instances in the motif: -

    >>> m.degenerate_consensus
    +

    >>> m.degenerate_consensus
     Seq('WACVC', IUPACAmbiguousDNA())
    -

    The reverse complement of the position-weight matrix can be calculated directly from the pwm: -

    >>> rpwm = pwm.reverse_complement()
    ->>> print rpwm
    +

    The reverse complement of the position-weight matrix can be calculated directly from the pwm: +

    >>> rpwm = pwm.reverse_complement()
    +>>> print(rpwm)
             0      1      2      3      4
     A:   0.07   0.07   0.29   0.07   0.51
     C:   0.04   0.38   0.04   0.04   0.04
     G:   0.71   0.27   0.60   0.04   0.04
     T:   0.18   0.29   0.07   0.84   0.40
     <BLANKLINE>
    -
    -

    14.5  Position-Specific Scoring Matrices

    Using the background distribution and PWM with pseudo-counts added, +

    + +

    14.5  Position-Specific Scoring Matrices

    Using the background distribution and PWM with pseudo-counts added, it’s easy to compute the log-odds ratios, telling us what are the log odds of a particular symbol to be coming from a motif against the -background. We can use the .log_odds() method on the position-weight +background. We can use the .log_odds() method on the position-weight matrix: -

    >>> pssm = pwm.log_odds()
    ->>> print pssm
    +

    >>> pssm = pwm.log_odds()
    +>>> print(pssm)
             0      1      2      3      4
     A:   0.68   1.76  -1.91   0.21  -0.49
     C:  -2.49  -2.49   1.26   0.09   1.51
     G:  -2.49  -2.49  -2.49   0.60  -2.49
     T:   1.03  -1.91   0.21  -1.91  -1.91
     <BLANKLINE>
    -

    Here we can see positive values for symbols more frequent in the motif +

    Here we can see positive values for symbols more frequent in the motif than in the background and negative for symbols more frequent in the background. 0.0 means that it’s equally likely to see a symbol in the -background and in the motif.

    This assumes that A, C, G, and T are equally likely in the background. To +background and in the motif.

    This assumes that A, C, G, and T are equally likely in the background. To calculate the position-specific scoring matrix against a background with -unequal probabilities for A, C, G, T, use the background argument. +unequal probabilities for A, C, G, T, use the background argument. For example, against a background with a 40% GC content, use -

    >>> background = {'A':0.3,'C':0.2,'G':0.2,'T':0.3}
    +

    >>> background = {'A':0.3,'C':0.2,'G':0.2,'T':0.3}
     >>> pssm = pwm.log_odds(background)
    ->>> print pssm
    +>>> print(pssm)
             0      1      2      3      4
     A:   0.42   1.49  -2.17  -0.05  -0.75
     C:  -2.17  -2.17   1.58   0.42   1.83
     G:  -2.17  -2.17  -2.17   0.92  -2.17
     T:   0.77  -2.17  -0.05  -2.17  -2.17
     <BLANKLINE>
    -

    The maximum and minimum score obtainable from the PSSM are stored in the -.max and .min properties: -

    >>> print "%4.2f" % pssm.max
    +

    The maximum and minimum score obtainable from the PSSM are stored in the +.max and .min properties: +

    >>> print("%4.2f" % pssm.max)
     6.59
    ->>> print "%4.2f" % pssm.min
    +>>> print("%4.2f" % pssm.min)
     -10.85
    -

    The mean and standard deviation of the PSSM scores with respect to a specific -background are calculated by the .mean and .std methods. -

    >>> mean = pssm.mean(background)
    +

    The mean and standard deviation of the PSSM scores with respect to a specific +background are calculated by the .mean and .std methods. +

    >>> mean = pssm.mean(background)
     >>> std = pssm.std(background)
    ->>> print "mean = %0.2f, standard deviation = %0.2f" % (mean, std)
    +>>> print("mean = %0.2f, standard deviation = %0.2f" % (mean, std))
     mean = 3.21, standard deviation = 2.59
    -

    A uniform background is used if background is not specified. +

    A uniform background is used if background is not specified. The mean is particularly important, as its value is equal to the Kullback-Leibler divergence or relative entropy, and is a measure for the information content of the motif compared to the background. As in Biopython the base-2 logarithm is used in the calculation of the log-odds scores, the -information content has units of bits.

    The .reverse_complement, .consensus, .anticonsensus, and -.degenerate_consensus methods can be applied directly to PSSM objects.

    -

    14.6  Searching for instances

    -

    The most frequent use for a motif is to find its instances in some -sequence. For the sake of this section, we will use an artificial sequence like this:

    >>> test_seq=Seq("TACACTGCATTACAACCCAAGCATTA",m.alphabet)
    +information content has units of bits.

    The .reverse_complement, .consensus, .anticonsensus, and +.degenerate_consensus methods can be applied directly to PSSM objects.

    + +

    14.6  Searching for instances

    +

    The most frequent use for a motif is to find its instances in some +sequence. For the sake of this section, we will use an artificial sequence like this:

    >>> test_seq=Seq("TACACTGCATTACAACCCAAGCATTA", m.alphabet)
     >>> len(test_seq)
     26
    -
    -

    14.6.1  Searching for exact matches

    The simplest way to find instances, is to look for exact matches of +

    + +

    14.6.1  Searching for exact matches

    The simplest way to find instances, is to look for exact matches of the true instances of the motif: -

    >>> for pos,seq in m.instances.search(test_seq):
    -...     print pos, seq
    +

    >>> for pos, seq in m.instances.search(test_seq):
    +...     print("%i %s" % (pos, seq))
     ... 
     0 TACAC
     10 TACAA
     13 AACCC
    -

    We can do the same with the reverse complement (to find instances on the complementary strand): -

    >>> for pos,seq in r.instances.search(test_seq):
    -...     print pos, seq
    +

    We can do the same with the reverse complement (to find instances on the complementary strand): +

    >>> for pos, seq in r.instances.search(test_seq):
    +...     print("%i %s" % (pos, seq))
     ... 
     6 GCATT
     20 GCATT
    -
    -

    14.6.2  Searching for matches using the PSSM score

    It’s just as easy to look for positions, giving rise to high log-odds scores against our motif: -

    >>> for position, score in pssm.search(test_seq, threshold=3.0):
    -...     print "Position %d: score = %5.3f" % (position, score)
    +
    + +

    14.6.2  Searching for matches using the PSSM score

    It’s just as easy to look for positions, giving rise to high log-odds scores against our motif: +

    >>> for position, score in pssm.search(test_seq, threshold=3.0):
    +...     print("Position %d: score = %5.3f" % (position, score))
     ... 
     Position 0: score = 5.622
     Position -20: score = 4.601
     Position 10: score = 3.037
     Position 13: score = 5.738
     Position -6: score = 4.601
    -

    The negative positions refer to instances of the motif found on the +

    The negative positions refer to instances of the motif found on the reverse strand of the test sequence, and follow the Python convention -on negative indices. Therefore, the instance of the motif at pos -is located at test_seq[pos:pos+len(m)] both for positive and for -negative values of pos.

    You may notice the threshold parameter, here set arbitrarily to -3.0. This is in log2, so we are now looking only for words, which +on negative indices. Therefore, the instance of the motif at pos +is located at test_seq[pos:pos+len(m)] both for positive and for +negative values of pos.

    You may notice the threshold parameter, here set arbitrarily to +3.0. This is in log2, so we are now looking only for words, which are eight times more likely to occur under the motif model than in the background. The default threshold is 0.0, which selects everything -that looks more like the motif than the background.

    You can also calculate the scores at all positions along the sequence: -

    >>> pssm.calculate(test_seq)
    +that looks more like the motif than the background.

    You can also calculate the scores at all positions along the sequence: +

    >>> pssm.calculate(test_seq)
     array([  5.62230396,  -5.6796999 ,  -3.43177247,   0.93827754,
             -6.84962511,  -2.04066086, -10.84962463,  -3.65614533,
             -0.03370807,  -3.91102552,   3.03734159,  -2.14918518,
             -0.6016975 ,   5.7381525 ,  -0.50977498,  -3.56422281,
             -8.73414803,  -0.09919716,  -0.6016975 ,  -2.39429784,
            -10.84962463,  -3.65614533], dtype=float32)
    -

    In general, this is the fastest way to calculate PSSM scores. -The scores returned by pssm.calculate are for the forward strand +

    In general, this is the fastest way to calculate PSSM scores. +The scores returned by pssm.calculate are for the forward strand only. To obtain the scores on the reverse strand, you can take the reverse complement of the PSSM: -

    >>> rpssm = pssm.reverse_complement()
    +

    >>> rpssm = pssm.reverse_complement()
     >>> rpssm.calculate(test_seq)
     array([ -9.43458748,  -3.06172252,  -7.18665981,  -7.76216221,
             -2.04066086,  -4.26466274,   4.60124254,  -4.2480607 ,
    @@ -8008,224 +8260,229 @@
             -8.73414803, -10.84962463,  -4.82356262,  -4.82356262,
             -5.64668512,  -8.73414803,  -4.15613794,  -5.6796999 ,
              4.60124254,  -4.2480607 ], dtype=float32)
    -
    -

    14.6.3  Selecting a score threshold

    If you want to use a less arbitrary way of selecting thresholds, you +

    + +

    14.6.3  Selecting a score threshold

    If you want to use a less arbitrary way of selecting thresholds, you can explore the distribution of PSSM scores. Since the space for a score distribution grows exponentially with motif length, we are using an approximation with a given precision to keep computation cost manageable: -

    >>> distribution = pssm.distribution(background=background, precision=10**4)
    -

    The distribution object can be used to determine a number of different thresholds. +

    >>> distribution = pssm.distribution(background=background, precision=10**4)
    +

    The distribution object can be used to determine a number of different thresholds. We can specify the requested false-positive rate (probability of “finding” a motif instance in background generated sequence): -

    >>> threshold = distribution.threshold_fpr(0.01)
    ->>> print "%5.3f" % threshold
    +

    >>> threshold = distribution.threshold_fpr(0.01)
    +>>> print("%5.3f" % threshold)
     4.009
    -

    or the false-negative rate (probability of “not finding” an instance generated from the motif): -

    >>> threshold = distribution.threshold_fnr(0.1)
    ->>> print "%5.3f" % threshold
    +

    or the false-negative rate (probability of “not finding” an instance generated from the motif): +

    >>> threshold = distribution.threshold_fnr(0.1)
    +>>> print("%5.3f" % threshold)
     -0.510
    -

    or a threshold (approximately) satisfying some relation between the false-positive rate and the false-negative rate (fnr/fpr≃ t): -

    >>> threshold = distribution.threshold_balanced(1000)
    ->>> print "%5.3f" % threshold
    +

    or a threshold (approximately) satisfying some relation between the false-positive rate and the false-negative rate (fnr/fpr≃ t): +

    >>> threshold = distribution.threshold_balanced(1000)
    +>>> print("%5.3f" % threshold)
     6.241
    -

    or a threshold satisfying (roughly) the equality between the -false-positive rate and the −log of the information content (as used +

    or a threshold satisfying (roughly) the equality between the +false-positive rate and the −log of the information content (as used in patser software by Hertz and Stormo): -

    >>> threshold = distribution.threshold_patser()
    ->>> print "%5.3f" % threshold
    +

    >>> threshold = distribution.threshold_patser()
    +>>> print("%5.3f" % threshold)
     0.346
    -

    For example, in case of our motif, you can get the threshold giving +

    For example, in case of our motif, you can get the threshold giving you exactly the same results (for this sequence) as searching for instances with balanced threshold with rate of 1000. -

    >>> threshold = distribution.threshold_fpr(0.01)
    ->>> print "%5.3f" % threshold
    +

    >>> threshold = distribution.threshold_fpr(0.01)
    +>>> print("%5.3f" % threshold)
     4.009
    ->>> for position, score in pssm.search(test_seq,threshold=threshold):
    -...     print "Position %d: score = %5.3f" % (position, score)
    +>>> for position, score in pssm.search(test_seq, threshold=threshold):
    +...     print("Position %d: score = %5.3f" % (position, score))
     ... 
     Position 0: score = 5.622
     Position -20: score = 4.601
     Position 13: score = 5.738
     Position -6: score = 4.601
    -
    -

    14.7  Each motif object has an associated Position-Specific Scoring Matrix

    To facilitate searching for potential TFBSs using PSSMs, both the position-weight matrix and the position-specific scoring matrix are associated with each motif. Using the Arnt motif as an example: -

    >>> from Bio import motifs
    +
    + +

    14.7  Each motif object has an associated Position-Specific Scoring Matrix

    To facilitate searching for potential TFBSs using PSSMs, both the position-weight matrix and the position-specific scoring matrix are associated with each motif. Using the Arnt motif as an example: +

    >>> from Bio import motifs
     >>> handle = open("Arnt.sites")
     >>> motif = motifs.read(handle, 'sites')
    ->>> print motif.counts
    +>>> print(motif.counts)
             0      1      2      3      4      5
     A:   4.00  19.00   0.00   0.00   0.00   0.00
     C:  16.00   0.00  20.00   0.00   0.00   0.00
     G:   0.00   1.00   0.00  20.00   0.00  20.00
     T:   0.00   0.00   0.00   0.00  20.00   0.00
     <BLANKLINE>
    ->>> print motif.pwm
    +>>> print(motif.pwm)
             0      1      2      3      4      5
     A:   0.20   0.95   0.00   0.00   0.00   0.00
     C:   0.80   0.00   1.00   0.00   0.00   0.00
     G:   0.00   0.05   0.00   1.00   0.00   1.00
     T:   0.00   0.00   0.00   0.00   1.00   0.00
     <BLANKLINE>
    -
    >>> print motif.pssm
    +
    >>> print(motif.pssm)
             0      1      2      3      4      5
     A:  -0.32   1.93   -inf   -inf   -inf   -inf
     C:   1.68   -inf   2.00   -inf   -inf   -inf
     G:   -inf  -2.32   -inf   2.00   -inf   2.00
     T:   -inf   -inf   -inf   -inf   2.00   -inf
     <BLANKLINE>
    -

    The negative infinities appear here because the corresponding entry in the frequency matrix is 0, and we are using zero pseudocounts by default: -

    >>> for letter in "ACGT":
    -...     print "%s: %4.2f" % (letter, motif.pseudocounts[letter])
    -...
    +

    The negative infinities appear here because the corresponding entry in the frequency matrix is 0, and we are using zero pseudocounts by default: +

    >>> for letter in "ACGT":
    +...     print("%s: %4.2f" % (letter, motif.pseudocounts[letter]))
    +... 
     A: 0.00
     C: 0.00
     G: 0.00
     T: 0.00
    -

    If you change the .pseudocounts attribute, the position-frequency matrix and the position-specific scoring matrix are recalculated automatically: -

    >>> motif.pseudocounts = 3.0
    +

    If you change the .pseudocounts attribute, the position-frequency matrix and the position-specific scoring matrix are recalculated automatically: +

    >>> motif.pseudocounts = 3.0
     >>> for letter in "ACGT":
    -...     print "%s: %4.2f" % (letter, motif.pseudocounts[letter])
    -...
    +...     print("%s: %4.2f" % (letter, motif.pseudocounts[letter]))
    +... 
     A: 3.00
     C: 3.00
     G: 3.00
     T: 3.00
    -
    >>> print motif.pwm
    +
    >>> print(motif.pwm)
             0      1      2      3      4      5
     A:   0.22   0.69   0.09   0.09   0.09   0.09
     C:   0.59   0.09   0.72   0.09   0.09   0.09
     G:   0.09   0.12   0.09   0.72   0.09   0.72
     T:   0.09   0.09   0.09   0.09   0.72   0.09
     <BLANKLINE>
    -
    >>> print motif.pssm
    +
    >>> print(motif.pssm)
             0      1      2      3      4      5
     A:  -0.19   1.46  -1.42  -1.42  -1.42  -1.42
     C:   1.25  -1.42   1.52  -1.42  -1.42  -1.42
     G:  -1.42  -1.00  -1.42   1.52  -1.42   1.52
     T:  -1.42  -1.42  -1.42  -1.42   1.52  -1.42
     <BLANKLINE>
    -

    You can also set the .pseudocounts to a dictionary over the four nucleotides if you want to use different pseudocounts for them. Setting motif.pseudocounts to None resets it to its default value of zero.

    The position-specific scoring matrix depends on the background distribution, which is uniform by default: -

    >>> for letter in "ACGT":
    -...     print "%s: %4.2f" % (letter, motif.background[letter])
    -...
    +

    You can also set the .pseudocounts to a dictionary over the four nucleotides if you want to use different pseudocounts for them. Setting motif.pseudocounts to None resets it to its default value of zero.

    The position-specific scoring matrix depends on the background distribution, which is uniform by default: +

    >>> for letter in "ACGT":
    +...     print("%s: %4.2f" % (letter, motif.background[letter]))
    +... 
     A: 0.25
     C: 0.25
     G: 0.25
     T: 0.25
    -

    Again, if you modify the background distribution, the position-specific scoring matrix is recalculated: -

    >>> motif.background = {'A': 0.2, 'C': 0.3, 'G': 0.3, 'T': 0.2}
    ->>> print motif.pssm
    +

    Again, if you modify the background distribution, the position-specific scoring matrix is recalculated: +

    >>> motif.background = {'A': 0.2, 'C': 0.3, 'G': 0.3, 'T': 0.2}
    +>>> print(motif.pssm)
             0      1      2      3      4      5
     A:   0.13   1.78  -1.09  -1.09  -1.09  -1.09
     C:   0.98  -1.68   1.26  -1.68  -1.68  -1.68
     G:  -1.68  -1.26  -1.68   1.26  -1.68   1.26
     T:  -1.09  -1.09  -1.09  -1.09   1.85  -1.09
     <BLANKLINE>
    -

    Setting motif.background to None resets it to a uniform distribution: -

    >>> motif.background = None
    +

    Setting motif.background to None resets it to a uniform distribution: +

    >>> motif.background = None
     >>> for letter in "ACGT":
    -...     print "%s: %4.2f" % (letter, motif.background[letter])
    -...
    +...     print("%s: %4.2f" % (letter, motif.background[letter]))
    +... 
     A: 0.25
     C: 0.25
     G: 0.25
     T: 0.25
    -

    If you set motif.background equal to a single value, it will be interpreted as the GC content: -

    >>> motif.background = 0.8
    +

    If you set motif.background equal to a single value, it will be interpreted as the GC content: +

    >>> motif.background = 0.8
     >>> for letter in "ACGT":
    -...     print "%s: %4.2f" % (letter, motif.background[letter])
    -...
    +...     print("%s: %4.2f" % (letter, motif.background[letter]))
    +... 
     A: 0.10
     C: 0.40
     G: 0.40
     T: 0.10
    -

    Note that you can now calculate the mean of the PSSM scores over the background against which it was computed: -

    >>> print "%f" % motif.pssm.mean(motif.background)
    +

    Note that you can now calculate the mean of the PSSM scores over the background against which it was computed: +

    >>> print("%f" % motif.pssm.mean(motif.background))
     4.703928
    -

    as well as its standard deviation: -

    >>> print "%f" % motif.pssm.std(motif.background)
    +

    as well as its standard deviation: +

    >>> print("%f" % motif.pssm.std(motif.background))
     3.290900
    -

    and its distribution: -

    >>> distribution = motif.pssm.distribution(background=motif.background)
    +

    and its distribution: +

    >>> distribution = motif.pssm.distribution(background=motif.background)
     >>> threshold = distribution.threshold_fpr(0.01)
    ->>> print "%f" % threshold
    +>>> print("%f" % threshold)
     3.854375
    -

    Note that the position-weight matrix and the position-specific scoring matrix are recalculated each time you call motif.pwm or motif.pssm, respectively. If speed is an issue and you want to use the PWM or PSSM repeatedly, you can save them as a variable, as in -

    >>> pssm = motif.pssm
    -
    -

    14.8  Comparing motifs

    - -Once we have more than one motif, we might want to compare them.

    Before we start comparing motifs, I should point out that motif +

    Note that the position-weight matrix and the position-specific scoring matrix are recalculated each time you call motif.pwm or motif.pssm, respectively. If speed is an issue and you want to use the PWM or PSSM repeatedly, you can save them as a variable, as in +

    >>> pssm = motif.pssm
    +
    + +

    14.8  Comparing motifs

    + +Once we have more than one motif, we might want to compare them.

    Before we start comparing motifs, I should point out that motif boundaries are usually quite arbitrary. This means we often need to compare motifs of different lengths, so comparison needs to involve some kind of alignment. This means we have to take into account two things: -

    • +

      • alignment of motifs -
      • some function to compare aligned motifs -

      +

    • some function to compare aligned motifs +

    To align the motifs, we use ungapped alignment of PSSMs and substitute zeros for any missing columns at the beginning and end of the matrices. This means that effectively we are using the background distribution for columns missing from the PSSM. The distance function then returns the minimal distance between motifs, as -well as the corresponding offset in their alignment.

    To give an exmaple, let us first load another motif, -which is similar to our test motif m: -

    >>> m_reb1 = motifs.read(open("REB1.pfm"), "pfm")
    +well as the corresponding offset in their alignment.

    To give an exmaple, let us first load another motif, +which is similar to our test motif m: +

    >>> m_reb1 = motifs.read(open("REB1.pfm"), "pfm")
     >>> m_reb1.consensus
     Seq('GTTACCCGG', IUPACUnambiguousDNA())
    ->>> print m_reb1.counts
    +>>> print(m_reb1.counts)
             0      1      2      3      4      5      6      7      8
     A:  30.00   0.00   0.00 100.00   0.00   0.00   0.00   0.00  15.00
     C:  10.00   0.00   0.00   0.00 100.00 100.00 100.00   0.00  15.00
     G:  50.00   0.00   0.00   0.00   0.00   0.00   0.00  60.00  55.00
     T:  10.00 100.00 100.00   0.00   0.00   0.00   0.00  40.00  15.00
     <BLANKLINE>
    -

    To make the motifs comparable, we choose the same values for the pseudocounts and the background distribution as our motif m: -

    >>> m_reb1.pseudocounts = {'A':0.6, 'C': 0.4, 'G': 0.4, 'T': 0.6}
    +

    To make the motifs comparable, we choose the same values for the pseudocounts and the background distribution as our motif m: +

    >>> m_reb1.pseudocounts = {'A':0.6, 'C': 0.4, 'G': 0.4, 'T': 0.6}
     >>> m_reb1.background = {'A':0.3,'C':0.2,'G':0.2,'T':0.3}
     >>> pssm_reb1 = m_reb1.pssm
    ->>> print pssm_reb1
    +>>> print(pssm_reb1)
             0      1      2      3      4      5      6      7      8
     A:   0.00  -5.67  -5.67   1.72  -5.67  -5.67  -5.67  -5.67  -0.97
     C:  -0.97  -5.67  -5.67  -5.67   2.30   2.30   2.30  -5.67  -0.41
     G:   1.30  -5.67  -5.67  -5.67  -5.67  -5.67  -5.67   1.57   1.44
     T:  -1.53   1.72   1.72  -5.67  -5.67  -5.67  -5.67   0.41  -0.97
     <BLANKLINE>
    -

    We’ll compare these motifs using the Pearson correlation. +

    We’ll compare these motifs using the Pearson correlation. Since we want it to resemble a distance measure, we actually take -1−r, where r is the Pearson correlation coefficient (PCC): -

    >>> distance, offset = pssm.dist_pearson(pssm_reb1)
    ->>> print "distance = %5.3g" % distance
    +1−r, where r is the Pearson correlation coefficient (PCC):
    +

    >>> distance, offset = pssm.dist_pearson(pssm_reb1)
    +>>> print("distance = %5.3g" % distance)
     distance = 0.239
    ->>> print offset
    +>>> print(offset)
     -2
    -

    This means that the best PCC between motif m and m_reb1 is obtained with the following alignment: -

    m:      bbTACGCbb
    +

    This means that the best PCC between motif m and m_reb1 is obtained with the following alignment: +

    m:      bbTACGCbb
     m_reb1: GTTACCCGG
    -

    where b stands for background distribution. The PCC itself is -roughly 1−0.239=0.761.

    -

    14.9  De novo motif finding

    -

    Currently, Biopython has only limited support for de novo motif +

    where b stands for background distribution. The PCC itself is +roughly 1−0.239=0.761.

    + +

    14.9  De novo motif finding

    +

    Currently, Biopython has only limited support for de novo motif finding. Namely, we support running and parsing of AlignAce and MEME. Since the number of motif finding tools is growing rapidly, -contributions of new parsers are welcome.

    -

    14.9.1  MEME

    -

    Let’s assume, you have run MEME on sequences of your choice with your +contributions of new parsers are welcome.

    + +

    14.9.1  MEME

    +

    Let’s assume, you have run MEME on sequences of your choice with your favorite parameters and saved the output in the file -meme.out. You can retrieve the motifs reported by MEME by -running the following piece of code:

    >>> from Bio import motifs
    +meme.out. You can retrieve the motifs reported by MEME by
    +running the following piece of code:

    >>> from Bio import motifs
     >>> motifsM = motifs.parse(open("meme.out"), "meme")
    -
    >>> motifsM
    +
    >>> motifsM
     [<Bio.motifs.meme.Motif object at 0xc356b0>]
    -

    Besides the most wanted list of motifs, the result object contains more useful information, accessible through properties with self-explanatory names: -

    • -.alphabet -
    • .datafile -
    • .sequence_names -
    • .version -
    • .command -

    The motifs returned by the MEME Parser can be treated exactly like regular +

    Besides the most wanted list of motifs, the result object contains more useful information, accessible through properties with self-explanatory names: +

    • +.alphabet +
    • .datafile +
    • .sequence_names +
    • .version +
    • .command +

    The motifs returned by the MEME Parser can be treated exactly like regular Motif objects (with instances), they also provide some extra -functionality, by adding additional information about the instances.

    >>> motifsM[0].consensus
    +functionality, by adding additional information about the instances. 

    >>> motifsM[0].consensus
     Seq('CTCAATCGTA', IUPACUnambiguousDNA())
     >>> motifsM[0].instances[0].sequence_name
     'SEQ10;'
    @@ -8233,107 +8490,111 @@
     3
     >>> motifsM[0].instances[0].strand
     '+'
    -
    >>> motifsM[0].instances[0].pvalue
    +
    >>> motifsM[0].instances[0].pvalue
     8.71e-07
    -
    -

    14.9.2  AlignAce

    -

    We can do very similar things with the AlignACE program. Assume, you have -your output in the file alignace.out. You can parse your output -with the following code:

    >>> from Bio import motifs
    ->>> motifsA = motifs.parse(open("alignace.out"),"alignace")
    -

    Again, your motifs behave as they should: -

    >>> motifsA[0].consensus
    +
    + +

    14.9.2  AlignAce

    +

    We can do very similar things with the AlignACE program. Assume, you have +your output in the file alignace.out. You can parse your output +with the following code:

    >>> from Bio import motifs
    +>>> motifsA = motifs.parse(open("alignace.out"), "alignace")
    +

    Again, your motifs behave as they should: +

    >>> motifsA[0].consensus
     Seq('TCTACGATTGAG', IUPACUnambiguousDNA())
    -

    In fact you can even see, that AlignAce found a very similar motif as +

    In fact you can even see, that AlignAce found a very similar motif as MEME. It is just a longer version of a reverse complement of the MEME motif: -

    >>> motifsM[0].reverse_complement().consensus
    +

    >>> motifsM[0].reverse_complement().consensus
     Seq('TACGATTGAG', IUPACUnambiguousDNA())
    -

    If you have AlignAce installed on the same machine, you can also run +

    If you have AlignAce installed on the same machine, you can also run it directly from Biopython. A short example of how this can be done is -shown below (other parameters can be specified as keyword parameters):

    >>> command="/opt/bin/AlignACE"
    +shown below (other parameters can be specified as keyword parameters):

    >>> command="/opt/bin/AlignACE"
     >>> input_file="test.fa"
     >>> from Bio.motifs.applications import AlignAceCommandline
    ->>> cmd = AlignAceCommandline(cmd=command,input=input_file,gcback=0.6,numcols=10)
    ->>> stdout,stderr= cmd()
    -

    Since AlignAce prints all of its output to standard output, you can get +>>> cmd = AlignAceCommandline(cmd=command, input=input_file, gcback=0.6, numcols=10) +>>> stdout, stderr= cmd() +

    Since AlignAce prints all of its output to standard output, you can get to your motifs by parsing the first part of the result: -

    >>> motifs = motifs.parse(stdout,"alignace")
    -
    -

    14.10  Useful links

    -

    -

    14.11  Obsolete Bio.Motif module

    The rest of this chapter above describes the Bio.motifs package included -in Biopython 1.61 onwards, which is replacing the older Bio.Motif package +

    >>> motifs = motifs.parse(stdout, "alignace")
    +
    + +

    14.10  Useful links

    +

    + +

    14.11  Obsolete Bio.Motif module

    The rest of this chapter above describes the Bio.motifs package included +in Biopython 1.61 onwards, which is replacing the older Bio.Motif package introduced with Biopython 1.50, which was in turn based on two older former -Biopython modules, Bio.AlignAce and Bio.MEME.

    To allow for a smooth transition, the older Bio.Motif package will be -maintained in parallel with its replacement Bio.motifs at least two more -releases, and at least one year.

    -

    14.11.1  Motif objects

    Since we are interested in motif analysis, we need to take a look at -Motif objects in the first place. For that we need to import +Biopython modules, Bio.AlignAce and Bio.MEME.

    To allow for a smooth transition, the older Bio.Motif package will be +maintained in parallel with its replacement Bio.motifs at least two more +releases, and at least one year.

    + +

    14.11.1  Motif objects

    Since we are interested in motif analysis, we need to take a look at +Motif objects in the first place. For that we need to import the Motif library: -

    >>> from Bio import Motif
    -

    and we can start creating our first motif objects. Let’s create a DNA motif: -

    >>> from Bio.Alphabet import IUPAC
    +

    >>> from Bio import Motif
    +

    and we can start creating our first motif objects. Let’s create a DNA motif: +

    >>> from Bio.Alphabet import IUPAC
     >>> m = Motif.Motif(alphabet=IUPAC.unambiguous_dna)
    -

    This is for now just an empty container, so let’s add some sequences to our newly created motif: -

    >>> from Bio.Seq import Seq
    ->>> m.add_instance(Seq("TATAA",m.alphabet))
    ->>> m.add_instance(Seq("TATTA",m.alphabet))
    ->>> m.add_instance(Seq("TATAA",m.alphabet))
    ->>> m.add_instance(Seq("TATAA",m.alphabet))
    -

    Now we have a full Motif instance, so we can try to get some +

    This is for now just an empty container, so let’s add some sequences to our newly created motif: +

    >>> from Bio.Seq import Seq
    +>>> m.add_instance(Seq("TATAA", m.alphabet))
    +>>> m.add_instance(Seq("TATTA", m.alphabet))
    +>>> m.add_instance(Seq("TATAA", m.alphabet))
    +>>> m.add_instance(Seq("TATAA", m.alphabet))
    +

    Now we have a full Motif instance, so we can try to get some basic information about it. Let’s start with length and consensus sequence: -

    >>> len(m)
    +

    >>> len(m)
     5
     >>> m.consensus()
     Seq('TATAA', IUPACUnambiguousDNA())
    -

    In case of DNA motifs, we can also get a reverse complement of a motif: -

    >>> m.reverse_complement().consensus()
    +

    In case of DNA motifs, we can also get a reverse complement of a motif: +

    >>> m.reverse_complement().consensus()
     Seq('TTATA', IUPACUnambiguousDNA())
     >>> for i in m.reverse_complement().instances:
    -...     print i
    +...     print(i)
     TTATA
     TAATA
     TTATA
     TTATA
    -

    We can also calculate the information content of a motif with a simple call: -

    >>> print "%0.2f" % m.ic()
    +

    We can also calculate the information content of a motif with a simple call: +

    >>> print("%0.2f" % m.ic())
     5.27
    -

    This gives us a number of bits of information provided by the motif, -which tells us how much differs from background.

    The most common representation of a motif is a PWM (Position Weight +

    This gives us a number of bits of information provided by the motif, +which tells us how much differs from background.

    The most common representation of a motif is a PWM (Position Weight Matrix). It summarizes the probabilities of finding any symbol (in -this case nucleotide) in any position of a motif. It can be computed by calling the .pwm() method: -

    >>> m.pwm()
    +this case nucleotide) in any position of a motif. It can be computed by calling the .pwm() method:
    +

    >>> m.pwm()
     [{'A': 0.05, 'C': 0.05, 'T': 0.85, 'G': 0.05}, 
      {'A': 0.85, 'C': 0.05, 'T': 0.05, 'G': 0.05}, 
      {'A': 0.05, 'C': 0.05, 'T': 0.85, 'G': 0.05}, 
      {'A': 0.65, 'C': 0.05, 'T': 0.25, 'G': 0.05}, 
      {'A': 0.85, 'C': 0.05, 'T': 0.05, 'G': 0.05}]
    -

    The probabilities in the motif’s PWM are based on the counts in the +

    The probabilities in the motif’s PWM are based on the counts in the instances, but we can see, that even though there were no Gs and no Cs in the instances, we still have non-zero probabilities assigned to them. These come from pseudo-counts which are, roughly speaking, a commonly used way to acknowledge the incompleteness of our knowledge -and avoid technical problems with calculating logarithms of 0.

    We can control the way that pseudo-counts are added with two -properties of Motif objects .background is the probability +and avoid technical problems with calculating logarithms of 0.

    We can control the way that pseudo-counts are added with two +properties of Motif objects .background is the probability distribution over all symbols in the alphabet that we assume represents background, non-motif sequences (usually based on the GC content of the respective genome). It is by default set to a uniform distribution upon creation of a motif: -

    >>> m.background  
    +

    >>> m.background  
     {'A': 0.25, 'C': 0.25, 'T': 0.25, 'G': 0.25}
    -

    The other parameter is .beta, which states the amount of +

    The other parameter is .beta, which states the amount of pseudo-counts we should add to the PWM. By default it is set to 1.0, -

    >>> m.beta
    +

    >>> m.beta
     1.0
    -

    so that the total input of pseudo-counts is equal to that of one instance.

    Using the background distribution and pwm with pseudo-counts added, +

    so that the total input of pseudo-counts is equal to that of one instance.

    Using the background distribution and pwm with pseudo-counts added, it’s easy to compute the log-odds ratios, telling us what are the log odds of a particular symbol to be coming from a motif against the -background. We can use the .log_odds() method:

     >>> m.log_odds() 
    +background. We can use the .log_odds() method:

     >>> m.log_odds() 
     [{'A': -2.3219280948873622, 
       'C': -2.3219280948873622, 
       'T': 1.7655347463629771, 
    @@ -8355,41 +8616,42 @@
       'T': -2.3219280948873622, 
       'G': -2.3219280948873622}
     ]
    -

    Here we can see positive values for symbols more frequent in the motif +

    Here we can see positive values for symbols more frequent in the motif than in the background and negative for symbols more frequent in the background. 0.0 means that it’s equally likely to see a symbol in -background and in the motif (e.g. ‘T’ in the second-last position).

    -

    14.11.1.1  Reading and writing

    Creating motifs from instances by hand is a bit boring, so it’s +background and in the motif (e.g. ‘T’ in the second-last position).

    + +

    14.11.1.1  Reading and writing

    Creating motifs from instances by hand is a bit boring, so it’s useful to have some I/O functions for reading and writing motifs. There are no really well established standards for storing motifs, but there’s a couple of formats which are more used than others. The most important distinction is whether the motif representation is based on instances or on some version of PWM matrix. -On of the most popular motif databases JASPAR +On of the most popular motif databases JASPAR stores motifs in both formats, so let’s look at how we can import JASPAR motifs from instances: -

    >>> from Bio import Motif
    ->>> arnt = Motif.read(open("Arnt.sites"),"jaspar-sites")
    -

    and from a count matrix: -

    >>> srf = Motif.read(open("SRF.pfm"),"jaspar-pfm")
    -

    The arnt and srf motifs can both do the same things for +

    >>> from Bio import Motif
    +>>> arnt = Motif.read(open("Arnt.sites"), "jaspar-sites")
    +

    and from a count matrix: +

    >>> srf = Motif.read(open("SRF.pfm"), "jaspar-pfm")
    +

    The arnt and srf motifs can both do the same things for us, but they use different internal representations of the motif. We -can tell that by inspecting the has_counts and -has_instances properties: -

    >>> arnt.has_instances
    +can tell that by inspecting the has_counts and
    +has_instances properties:
    +

    >>> arnt.has_instances
     True
     >>> srf.has_instances
     False
     >>> srf.has_counts
     True
    -
    >>> srf.counts
    +
    >>> srf.counts
     {'A': [2, 9, 0, 1, 32, 3, 46, 1, 43, 15, 2, 2],
      'C': [1, 33, 45, 45, 1, 1, 0, 0, 0, 1, 0, 1],
      'G': [39, 2, 1, 0, 0, 0, 0, 0, 0, 0, 44, 43],
      'T': [4, 2, 0, 0, 13, 42, 0, 45, 3, 30, 0, 0]}
    -

    There are conversion functions, which can help us convert between +

    There are conversion functions, which can help us convert between different representations: -

    >>> arnt.make_counts_from_instances()
    +

    >>> arnt.make_counts_from_instances()
     {'A': [8, 38, 0, 0, 0, 0],
      'C': [32, 0, 40, 0, 0, 0],
      'G': [0, 2, 0, 40, 0, 40],
    @@ -8400,14 +8662,14 @@
      Seq('GGCCAAATAAGG', IUPACUnambiguousDNA()),
      Seq('GACCAAATAAGG', IUPACUnambiguousDNA()),
     ....
    -

    The important thing to remember here is that the method -make_instances_from_counts() creates fake instances, because +

    The important thing to remember here is that the method +make_instances_from_counts() creates fake instances, because usually there are very many possible sets of instances which give rise to the same pwm, and if we have only the count matrix, we cannot reconstruct the original one. This does not make any difference if we are using the PWM as the representation of the motif, but one should -be careful with exporting instances from count-based motifs.

    Speaking of exporting, let’s look at export functions. We can export to fasta: -

    >>> print m.format("fasta")
    +be careful with exporting instances from count-based motifs.

    Speaking of exporting, let’s look at export functions. We can export to fasta: +

    >>> print(m.format("fasta"))
     >instance0
     TATAA
     >instance1
    @@ -8416,8 +8678,8 @@
     TATAA
     >instance3
     TATAA
    -

    or to TRANSFAC-like matrix format (used by some motif processing software) -

    >>> print m.format("transfac")
    +

    or to TRANSFAC-like matrix format (used by some motif processing software) +

    >>> print(m.format("transfac"))
     XX
     TY Motif
     ID 
    @@ -8429,136 +8691,140 @@
     04 0 3 1 0
     05 0 4 0 0
     XX
    -

    Finally, if we have internet access, we can create a weblogo: -

    >>> arnt.weblogo("Arnt.png")
    -

    We should get our logo saved as a png in the specified file.

    -

    14.11.2  Searching for instances

    The most frequent use for a motif is to find its instances in some -sequence. For the sake of this section, we will use an artificial sequence like this:

    test_seq=Seq("TATGATGTAGTATAATATAATTATAA",m.alphabet)
    -

    The simplest way to find instances, is to look for exact matches of +

    Finally, if we have internet access, we can create a weblogo: +

    >>> arnt.weblogo("Arnt.png")
    +

    We should get our logo saved as a png in the specified file.

    + +

    14.11.2  Searching for instances

    The most frequent use for a motif is to find its instances in some +sequence. For the sake of this section, we will use an artificial sequence like this:

    test_seq=Seq("TATGATGTAGTATAATATAATTATAA",m.alphabet)
    +

    The simplest way to find instances, is to look for exact matches of the true instances of the motif: -

    >>> for pos,seq in m.search_instances(test_seq):
    -...     print pos,seq.tostring()
    +

    >>> for pos, seq in m.search_instances(test_seq):
    +...     print(pos, seq.tostring())
     ... 
     10 TATAA
     15 TATAA
     21 TATAA
    -

    We can do the same with the reverse complement (to find instances on the complementary strand): -

    >>> for pos,seq in m.reverse_complement().search_instances(test_seq):
    -...     print pos,seq.tostring()
    +

    We can do the same with the reverse complement (to find instances on the complementary strand): +

    >>> for pos, seq in m.reverse_complement().search_instances(test_seq):
    +...     print(pos, seq.tostring())
     ... 
     12 TAATA
     20 TTATA
    -

    It’s just as easy to look for positions, giving rise to high log-odds scores against our motif: -

    >>> for pos,score in m.search_pwm(test_seq,threshold=5.0):
    -...     print pos,score
    +

    It’s just as easy to look for positions, giving rise to high log-odds scores against our motif: +

    >>> for pos, score in m.search_pwm(test_seq, threshold=5.0):
    +...     print(pos, score)
     ... 
     10 8.44065060871
     -12 7.06213898545
     15 8.44065060871
     -20 8.44065060871
     21 8.44065060871
    -

    You may notice the threshold parameter, here set arbitrarily to -5.0. This is in log2, so we are now looking only for words, which +

    You may notice the threshold parameter, here set arbitrarily to +5.0. This is in log2, so we are now looking only for words, which are 32 times more likely to occur under the motif model than in the background. The default threshold is 0.0, which selects everything -that looks more like the motif than the background.

    If you want to use a less arbitrary way of selecting thresholds, you -can explore the Motif.score_distribution class implementing an +that looks more like the motif than the background.

    If you want to use a less arbitrary way of selecting thresholds, you +can explore the Motif.score_distribution class implementing an distribution of scores for a given motif. Since the space for a score distribution grows exponentially with motif length, we are using an approximation with a given precision to keep computation cost manageable: -

    >>> sd = Motif.score_distribution(m,precision=10**4)
    -

    The sd object can be used to determine a number of different thresholds.

    We can specify the requested false-positive rate (probability of “finding” a motif instance in background generated sequence): -

    >>> sd.threshold_fpr(0.01)
    +

    >>> sd = Motif.score_distribution(m, precision=10**4)
    +

    The sd object can be used to determine a number of different thresholds.

    We can specify the requested false-positive rate (probability of “finding” a motif instance in background generated sequence): +

    >>> sd.threshold_fpr(0.01)
     4.3535838726139886
    -

    or the false-negative rate (probability of “not finding” an instance generated from the motif): -

    >>> sd.threshold_fnr(0.1)
    +

    or the false-negative rate (probability of “not finding” an instance generated from the motif): +

    >>> sd.threshold_fnr(0.1)
     0.26651713652234044
    -

    or a threshold (approximately) satisfying some relation between fpr -and fnr fnr/fprt: -

    >>> sd.threshold_balanced(1000)
    +

    or a threshold (approximately) satisfying some relation between fpr +and fnr fnr/fprt: +

    >>> sd.threshold_balanced(1000)
     8.4406506087056368
    -

    or a threshold satisfying (roughly) the equality between the -false-positive rate and the −log of the information content (as used -in patser software by Hertz and Stormo).

    For example, in case of our motif, you can get the threshold giving +

    or a threshold satisfying (roughly) the equality between the +false-positive rate and the −log of the information content (as used +in patser software by Hertz and Stormo).

    For example, in case of our motif, you can get the threshold giving you exactly the same results (for this sequence) as searching for instances with balanced threshold with rate of 1000. -

    >>> for pos,score in m.search_pwm(test_seq,threshold=sd.threshold_balanced(1000)):
    -...     print pos,score
    +

    >>> for pos, score in m.search_pwm(test_seq, threshold=sd.threshold_balanced(1000)):
    +...     print(pos, score)
     ... 
     10 8.44065060871
     15 8.44065060871
     -20 8.44065060871
     21 8.44065060871
    -
    -

    14.11.3  Comparing motifs

    +

    + +

    14.11.3  Comparing motifs

    Once we have more than one motif, we might want to compare them. For -that, we have currently three different methods of Bio.Motif -objects.

    Before we start comparing motifs, I should point out that motif +that, we have currently three different methods of Bio.Motif +objects.

    Before we start comparing motifs, I should point out that motif boundaries are usually quite arbitrary. This means, that we often need to compare motifs of different lengths, so comparison needs to involve some kind of alignment. This means, that we have to take into account two things: -

    • +

      • alignment of motifs -
      • some function to compare aligned motifs -

      -In Bio.Motif we have 3 different functions for motif +

    • some function to compare aligned motifs +

    +In Bio.Motif we have 3 different functions for motif comparison, which are based on the same idea behind motif alignment, but use different functions to compare aligned motifs. Briefly speaking, we are using ungapped alignment of PWMs and substitute the missing columns at the beginning and end of the matrices with background distribution. All three comparison functions are written in such a way, that they can be interpreted as distance measures, however -only one (dist_dpq) satisfies the triangle inequality. All of +only one (dist_dpq) satisfies the triangle inequality. All of them return the minimal distance and the corresponding offset between -motifs.

    To show how these functions work, let us first load another motif, -which is similar to our test motif m: -

    >>> ubx=Motif.read(open("Ubx.pfm"),"jaspar-pfm")
    +motifs.

    To show how these functions work, let us first load another motif, +which is similar to our test motif m: +

    >>> ubx=Motif.read(open("Ubx.pfm"), "jaspar-pfm")
     <Bio.Motif.Motif.Motif object at 0xc29b90>
     >>> ubx.consensus()
     Seq('TAAT', IUPACUnambiguousDNA())
    -

    The first function we’ll use to compare these motifs is based on +

    The first function we’ll use to compare these motifs is based on Pearson correlation. Since we want it to resemble a distance -measure, we actually take 1−r, where r is the Pearson correlation +measure, we actually take 1−r, where r is the Pearson correlation coefficient (PCC): -

    >>> m.dist_pearson(ubx)
    +

    >>> m.dist_pearson(ubx)
     (0.41740393308237722, 2)
    -

    This means, that the best PCC between motif m and Ubx is obtained with the following alignment: -

    bbTAAT
    +

    This means, that the best PCC between motif m and Ubx is obtained with the following alignment: +

    bbTAAT
     TATAAb
    -

    where b stands for background distribution. The PCC itself is -roughly 1−0.42=0.58. If we try the reverse complement of the Ubx motif:

    >>> m.dist_pearson(ubx.reverse_complement())
    +

    where b stands for background distribution. The PCC itself is +roughly 1−0.42=0.58. If we try the reverse complement of the Ubx motif:

    >>> m.dist_pearson(ubx.reverse_complement())
     (0.25784180151584823, 1)
    -

    We can see that the PCC is better (almost 0.75), and the alignment is also different: -

    bATTA
    +

    We can see that the PCC is better (almost 0.75), and the alignment is also different: +

    bATTA
     TATAA
    -

    There are two other functions: dist_dpq, which is a true metric (satisfying traingle inequality) based on the Kullback-Leibler divergence -

    >>> m.dist_dpq(ubx.reverse_complement())
    +

    There are two other functions: dist_dpq, which is a true metric (satisfying traingle inequality) based on the Kullback-Leibler divergence +

    >>> m.dist_dpq(ubx.reverse_complement())
     (0.49292358382899853, 1)
    -

    and the dist_product method, which is based on the product of +

    and the dist_product method, which is based on the product of probabilities which can be interpreted as the probability of -independently generating the same instance by both motifs.

    >>> m.dist_product(ubx.reverse_complement())
    +independently generating the same instance by both motifs.

    >>> m.dist_product(ubx.reverse_complement())
     (0.16224587301064275, 1)
    -
    -

    14.11.4  De novo motif finding

    Currently, Biopython has only limited support for de novo motif +

    + +

    14.11.4  De novo motif finding

    Currently, Biopython has only limited support for de novo motif finding. Namely, we support running and parsing of AlignAce and MEME. Since the number of motif finding tools is growing rapidly, -contributions of new parsers are welcome.

    -

    14.11.4.1  MEME

    Let’s assume, you have run MEME on sequences of your choice with your +contributions of new parsers are welcome.

    + +

    14.11.4.1  MEME

    Let’s assume, you have run MEME on sequences of your choice with your favorite parameters and saved the output in the file -meme.out. You can retrieve the motifs reported by MEME by -running the following piece of code:

    >>> motifsM = list(Motif.parse(open("meme.out"),"MEME"))
    +meme.out. You can retrieve the motifs reported by MEME by
    +running the following piece of code:

    >>> motifsM = list(Motif.parse(open("meme.out"), "MEME"))
     >>> motifsM
     [<Bio.Motif.MEMEMotif.MEMEMotif object at 0xc356b0>]
    -

    Besides the most wanted list of motifs, the result object contains more useful information, accessible through properties with self-explanatory names: -

    • -.alphabet -
    • .datafile -
    • .sequence_names -
    • .version -
    • .command -

    The motifs returned by MEMEParser can be treated exactly like regular +

    Besides the most wanted list of motifs, the result object contains more useful information, accessible through properties with self-explanatory names: +

    • +.alphabet +
    • .datafile +
    • .sequence_names +
    • .version +
    • .command +

    The motifs returned by MEMEParser can be treated exactly like regular Motif objects (with instances), they also provide some extra -functionality, by adding additional information about the instances.

    >>> motifsM[0].consensus()
    +functionality, by adding additional information about the instances. 

    >>> motifsM[0].consensus()
     Seq('CTCAATCGTA', IUPACUnambiguousDNA())
     
     >>> motifsM[0].instances[0].pvalue
    @@ -8569,473 +8835,478 @@
     3
     >>> motifsM[0].instances[0].strand
     '+'
    -
    -

    14.11.4.2  AlignAce

    We can do very similar things with AlignACE program. Assume, you have -your output in the file alignace.out. You can parse your output -with the following code:

    >>> motifsA=list(Motif.parse(open("alignace.out"),"AlignAce"))
    -

    Again, your motifs behave as they should: -

    >>> motifsA[0].consensus()
    +
    + +

    14.11.4.2  AlignAce

    We can do very similar things with AlignACE program. Assume, you have +your output in the file alignace.out. You can parse your output +with the following code:

    >>> motifsA=list(Motif.parse(open("alignace.out"), "AlignAce"))
    +

    Again, your motifs behave as they should: +

    >>> motifsA[0].consensus()
     Seq('TCTACGATTGAG', IUPACUnambiguousDNA())
    -

    In fact you can even see, that AlignAce found a very similar motif as +

    In fact you can even see, that AlignAce found a very similar motif as MEME, it is just a longer version of a reverse complement of MEME motif: -

    >>> motifsM[0].reverse_complement().consensus()
    +

    >>> motifsM[0].reverse_complement().consensus()
     Seq('TACGATTGAG', IUPACUnambiguousDNA())
    -

    If you have AlignAce installed on the same machine, you can also run +

    If you have AlignAce installed on the same machine, you can also run it directly from Biopython. Short example of how this can be done is -shown below (other parameters can be specified as keyword parameters):

    >>> command="/opt/bin/AlignACE"
    +shown below (other parameters can be specified as keyword parameters):

    >>> command="/opt/bin/AlignACE"
     >>> input_file="test.fa"
     >>> from Bio.Motif.Applications import AlignAceCommandline
    ->>> cmd = AlignAceCommandline(cmd=command,input=input_file,gcback=0.6,numcols=10)
    ->>> stdout,stderr= cmd()
    -

    Since AlignAce prints all its output to standard output, you can get +>>> cmd = AlignAceCommandline(cmd=command, input=input_file, gcback=0.6, numcols=10) +>>> stdout, stderr= cmd() +

    Since AlignAce prints all its output to standard output, you can get to your motifs by parsing the first part of the result: -

    motifs=list(Motif.parse(stdout,"AlignAce"))
    -
    -

    Chapter 15  Cluster analysis

    Cluster analysis is the grouping of items into clusters based on the similarity of the items to each other. In bioinformatics, clustering is widely used in gene expression data analysis to find groups of genes with similar gene expression profiles. This may identify functionally related genes, as well as suggest the function of presently unknown genes.

    The Biopython module Bio.Cluster provides commonly used clustering algorithms and was designed with the application to gene expression data in mind. However, this module can also be used for cluster analysis of other types of data. Bio.Cluster and the underlying C Clustering Library is described by De Hoon et al. [14].

    The following four clustering approaches are implemented in Bio.Cluster: -

    • +

      motifs=list(Motif.parse(stdout,"AlignAce"))
      +
      + +

      Chapter 15  Cluster analysis

      Cluster analysis is the grouping of items into clusters based on the similarity of the items to each other. In bioinformatics, clustering is widely used in gene expression data analysis to find groups of genes with similar gene expression profiles. This may identify functionally related genes, as well as suggest the function of presently unknown genes.

      The Biopython module Bio.Cluster provides commonly used clustering algorithms and was designed with the application to gene expression data in mind. However, this module can also be used for cluster analysis of other types of data. Bio.Cluster and the underlying C Clustering Library is described by De Hoon et al. [14].

      The following four clustering approaches are implemented in Bio.Cluster: +

      • Hierarchical clustering (pairwise centroid-, single-, complete-, and average-linkage); -
      • k-means, k-medians, and k-medoids clustering; -
      • Self-Organizing Maps; -
      • Principal Component Analysis. -
      -

      Data representation

      The data to be clustered are represented by a n × m Numerical Python array data. Within the context of gene expression data clustering, typically the rows correspond to different genes whereas the columns correspond to different experimental conditions. The clustering algorithms in Bio.Cluster can be applied both to rows (genes) and to columns (experiments).

      -

      Missing values

      Often in microarray experiments, some of the data values are missing, which is indicated by an additional n × m Numerical Python integer array mask. If mask[i,j]==0, then data[i,j] is missing and is ignored in the analysis.

      -

      Random number generator

      The k-means/medians/medoids clustering algorithms and Self-Organizing Maps (SOMs) include the use of a random number generator. The uniform random number generator in Bio.Cluster is based on the algorithm by L’Ecuyer [25], while random numbers following the binomial distribution are generated using the BTPE algorithm by Kachitvichyanukul and Schmeiser [23]. The random number generator is initialized automatically during its first call. As this random number generator uses a combination of two multiplicative linear congruential generators, two (integer) seeds are needed for initialization, for which we use the system-supplied random number generator rand (in the C standard library). We initialize this generator by calling srand with the epoch time in seconds, and use the first two random numbers generated by rand as seeds for the uniform random number generator in Bio.Cluster.

      -

      15.1  Distance functions

      -

      In order to cluster items into groups based on their similarity, we should first define what exactly we mean by similar. Bio.Cluster provides eight distance functions, indicated by a single character, to measure similarity, or conversely, distance: -

      • -'e': +
      • k-means, k-medians, and k-medoids clustering; +
      • Self-Organizing Maps; +
      • Principal Component Analysis. +
      +

      Data representation

      The data to be clustered are represented by a n × m Numerical Python array data. Within the context of gene expression data clustering, typically the rows correspond to different genes whereas the columns correspond to different experimental conditions. The clustering algorithms in Bio.Cluster can be applied both to rows (genes) and to columns (experiments).

      +

      Missing values

      Often in microarray experiments, some of the data values are missing, which is indicated by an additional n × m Numerical Python integer array mask. If mask[i,j]==0, then data[i,j] is missing and is ignored in the analysis.

      +

      Random number generator

      The k-means/medians/medoids clustering algorithms and Self-Organizing Maps (SOMs) include the use of a random number generator. The uniform random number generator in Bio.Cluster is based on the algorithm by L’Ecuyer [25], while random numbers following the binomial distribution are generated using the BTPE algorithm by Kachitvichyanukul and Schmeiser [23]. The random number generator is initialized automatically during its first call. As this random number generator uses a combination of two multiplicative linear congruential generators, two (integer) seeds are needed for initialization, for which we use the system-supplied random number generator rand (in the C standard library). We initialize this generator by calling srand with the epoch time in seconds, and use the first two random numbers generated by rand as seeds for the uniform random number generator in Bio.Cluster.

      + +

      15.1  Distance functions

      +

      In order to cluster items into groups based on their similarity, we should first define what exactly we mean by similar. Bio.Cluster provides eight distance functions, indicated by a single character, to measure similarity, or conversely, distance: +

      • +'e': Euclidean distance; -
      • 'b': +
      • 'b': City-block distance. -
      • 'c': +
      • 'c': Pearson correlation coefficient; -
      • 'a': +
      • 'a': Absolute value of the Pearson correlation coefficient; -
      • 'u': +
      • 'u': Uncentered Pearson correlation (equivalent to the cosine of the angle between two data vectors); -
      • 'x': +
      • 'x': Absolute uncentered Pearson correlation; -
      • 's': +
      • 's': Spearman’s rank correlation; -
      • 'k': +
      • 'k': Kendall’s τ. -

      +

    The first two are true distance functions that satisfy the triangle inequality: -

    -
    d
    -⎜
    -⎝
    - -
    u
    , - -
    v

    -⎟
    -⎠
    ≤ d
    -⎜
    -⎝
    - -
    u
    , - -
    w

    -⎟
    -⎠
    d
    -⎜
    -⎝
    - -
    w
    , - -
    v

    -⎟
    -⎠
    for all   - -
    u
    - -
    v
    - -
    w
    ,

    -and are therefore refered to as metrics. In everyday language, this means that the shortest distance between two points is a straight line.

    The remaining six distance measures are related to the correlation coefficient, where the distance d is defined in terms of the correlation r by d=1−r. Note that these distance functions are semi-metrics that do not satisfy the triangle inequality. For example, for -

    -
    - -
    u
    =
    -⎝
    1,0,−1
    -⎠
    ;
    -
    - -
    v
    =
    -⎝
    1,1,0
    -⎠
    ;
    -
    - -
    w
    =
    -⎝
    0,1,1
    -⎠
    ;

    +

    +
    d
    +⎜
    +⎝
    + +
    u
    , + +
    v

    +⎟
    +⎠
    ≤ d
    +⎜
    +⎝
    + +
    u
    , + +
    w

    +⎟
    +⎠
    d
    +⎜
    +⎝
    + +
    w
    , + +
    v

    +⎟
    +⎠
    for all   + +
    u
    + +
    v
    + +
    w
    ,

    +and are therefore refered to as metrics. In everyday language, this means that the shortest distance between two points is a straight line.

    The remaining six distance measures are related to the correlation coefficient, where the distance d is defined in terms of the correlation r by d=1−r. Note that these distance functions are semi-metrics that do not satisfy the triangle inequality. For example, for +

    +
    + +
    u
    =
    +⎝
    1,0,−1
    +⎠
    ;
    +
    + +
    v
    =
    +⎝
    1,1,0
    +⎠
    ;
    +
    + +
    w
    =
    +⎝
    0,1,1
    +⎠
    ;

    we find a Pearson distance -d(u,w) = 1.8660, while -d(u,v)+d(v,w) = 1.6340.

    -

    Euclidean distance

    In Bio.Cluster, we define the Euclidean distance as -

    -
    d =  - - -
    n
      - - -
    n
    i=1
     
    -⎝
    xiyi
    -⎠
    2.

    +d(u,w) = 1.8660, while +d(u,v)+d(v,w) = 1.6340.

    +

    Euclidean distance

    In Bio.Cluster, we define the Euclidean distance as +

    +
    d =  + + +
    n
      + + +
    n
    i=1
     
    +⎝
    xiyi
    +⎠
    2.

    Only those terms are included in the summation for which both -xi and yi are present, and the denominator n is chosen accordingly. -As the expression data xi and yi are subtracted directly from each other, we should make sure that the expression data are properly normalized when using the Euclidean distance.

    -

    City-block distance

    The city-block distance, alternatively known as the Manhattan distance, is related to the Euclidean distance. Whereas the Euclidean distance corresponds to the length of the shortest path between two points, the city-block distance is the sum of distances along each dimension. As gene expression data tend to have missing values, in Bio.Cluster we define the city-block distance as the sum of distances divided by the number of dimensions: -

    -
    d =  - - -
    n
      - - -
    n
    i=1
     
    -⎪
    xiyi
    -⎪
    .

    +xi and yi are present, and the denominator n is chosen accordingly. +As the expression data xi and yi are subtracted directly from each other, we should make sure that the expression data are properly normalized when using the Euclidean distance.

    +

    City-block distance

    The city-block distance, alternatively known as the Manhattan distance, is related to the Euclidean distance. Whereas the Euclidean distance corresponds to the length of the shortest path between two points, the city-block distance is the sum of distances along each dimension. As gene expression data tend to have missing values, in Bio.Cluster we define the city-block distance as the sum of distances divided by the number of dimensions: +

    +
    d =  + + +
    n
      + + +
    n
    i=1
     
    +⎪
    xiyi
    +⎪
    .

    This is equal to the distance you would have to walk between two points in a city, where you have to walk along city blocks. As for the Euclidean distance, -the expression data are subtracted directly from each other, and we should therefore make sure that they are properly normalized.

    -

    The Pearson correlation coefficient

    The Pearson correlation coefficient is defined as -

    -
    r =  - - -
    1
    n
      - - -
    n
    i=1
     
    -⎜
    -⎜
    -⎝
    - - -
    xi −x
    σx
     
    -⎟
    -⎟
    -⎠

    -⎜
    -⎜
    -⎝
    - - -
    yi −ȳ
    σy
     
    -⎟
    -⎟
    -⎠
    ,

    +the expression data are subtracted directly from each other, and we should therefore make sure that they are properly normalized.

    +

    The Pearson correlation coefficient

    The Pearson correlation coefficient is defined as +

    +
    r =  + + +
    1
    n
      + + +
    n
    i=1
     
    +⎜
    +⎜
    +⎝
    + + +
    xi −x
    σx
     
    +⎟
    +⎟
    +⎠

    +⎜
    +⎜
    +⎝
    + + +
    yi −ȳ
    σy
     
    +⎟
    +⎟
    +⎠
    ,

    in which -x, ȳ -are the sample mean of x and y respectively, and -σx, σy -are the sample standard deviation of x and y. -The Pearson correlation coefficient is a measure for how well a straight line can be fitted to a scatterplot of x and y. -If all the points in the scatterplot lie on a straight line, the Pearson correlation coefficient is either +1 or -1, depending on whether the slope of line is positive or negative. If the Pearson correlation coefficient is equal to zero, there is no correlation between x and y.

    The Pearson distance is then defined as -

    -
    dP ≡ 1 − r.

    -As the Pearson correlation coefficient lies between -1 and 1, the Pearson distance lies between 0 and 2.

    -

    Absolute Pearson correlation

    By taking the absolute value of the Pearson correlation, we find a number between 0 and 1. If the absolute value is 1, all the points in the scatter plot lie on a straight line with either a positive or a negative slope. If the absolute value is equal to zero, there is no correlation between x and y.

    The corresponding distance is defined as -

    -
    dA ≡ 1 − 
    -⎪
    r
    -⎪
    ,

    -where r is the Pearson correlation coefficient. As the absolute value of the Pearson correlation coefficient lies between 0 and 1, the corresponding distance lies between 0 and 1 as well.

    In the context of gene expression experiments, the absolute correlation is equal to 1 if the gene expression profiles of two genes are either exactly the same or exactly opposite. The absolute correlation coefficient should therefore be used with care.

    -

    Uncentered correlation (cosine of the angle)

    In some cases, it may be preferable to use the uncentered correlation instead of the regular Pearson correlation coefficient. The uncentered correlation is defined as -

    -
    rU =  - - -
    1
    n
      - - -
    n
    i=1
     
    -⎜
    -⎜
    -⎝
    - - -
    xi
    σx(0)
     
    -⎟
    -⎟
    -⎠

    -⎜
    -⎜
    -⎝
    - - -
    yi
    σy(0)
     
    -⎟
    -⎟
    -⎠
    ,

    +x, ȳ +are the sample mean of x and y respectively, and +σx, σy +are the sample standard deviation of x and y. +The Pearson correlation coefficient is a measure for how well a straight line can be fitted to a scatterplot of x and y. +If all the points in the scatterplot lie on a straight line, the Pearson correlation coefficient is either +1 or -1, depending on whether the slope of line is positive or negative. If the Pearson correlation coefficient is equal to zero, there is no correlation between x and y.

    The Pearson distance is then defined as +

    +
    dP ≡ 1 − r.

    +As the Pearson correlation coefficient lies between -1 and 1, the Pearson distance lies between 0 and 2.

    +

    Absolute Pearson correlation

    By taking the absolute value of the Pearson correlation, we find a number between 0 and 1. If the absolute value is 1, all the points in the scatter plot lie on a straight line with either a positive or a negative slope. If the absolute value is equal to zero, there is no correlation between x and y.

    The corresponding distance is defined as +

    +
    dA ≡ 1 − 
    +⎪
    r
    +⎪
    ,

    +where r is the Pearson correlation coefficient. As the absolute value of the Pearson correlation coefficient lies between 0 and 1, the corresponding distance lies between 0 and 1 as well.

    In the context of gene expression experiments, the absolute correlation is equal to 1 if the gene expression profiles of two genes are either exactly the same or exactly opposite. The absolute correlation coefficient should therefore be used with care.

    +

    Uncentered correlation (cosine of the angle)

    In some cases, it may be preferable to use the uncentered correlation instead of the regular Pearson correlation coefficient. The uncentered correlation is defined as +

    +
    rU =  + + +
    1
    n
      + + +
    n
    i=1
     
    +⎜
    +⎜
    +⎝
    + + +
    xi
    σx(0)
     
    +⎟
    +⎟
    +⎠

    +⎜
    +⎜
    +⎝
    + + +
    yi
    σy(0)
     
    +⎟
    +⎟
    +⎠
    ,

    where -

    +
    +

    -
          - - -
    σx(0) = -
      - -
    - -
    -
    - - -
    1
    n
      - - -
    n
    i=1
    xi2
    ;  
     
    σy(0) = -
      - -
    - -
    -
    - - -
    1
    n
      - - -
    n
    i=1
    yi2
    .   -
     

    +

    + +
    σx(0) = +
      + +
    + +
    +
    + + +
    1
    n
      + + +
    n
    i=1
    xi2
    ;  
     
    σy(0) = +
      + +
    + +
    +
    + + +
    1
    n
      + + +
    n
    i=1
    yi2
    .   +
     

    This is the same expression as for the regular Pearson correlation coefficient, except that the sample means -x, ȳ -are set equal to zero. The uncentered correlation may be appropriate if there is a zero reference state. For instance, in the case of gene expression data given in terms of log-ratios, a log-ratio equal to zero corresponds to the green and red signal being equal, which means that the experimental manipulation did not affect the gene expression.

    The distance corresponding to the uncentered correlation coefficient is defined as -

    -
    dU ≡ 1 − rU,

    +x, ȳ +are set equal to zero. The uncentered correlation may be appropriate if there is a zero reference state. For instance, in the case of gene expression data given in terms of log-ratios, a log-ratio equal to zero corresponds to the green and red signal being equal, which means that the experimental manipulation did not affect the gene expression.

    The distance corresponding to the uncentered correlation coefficient is defined as +

    +
    dU ≡ 1 − rU,

    where -rU +rU is the uncentered correlation. -As the uncentered correlation coefficient lies between -1 and 1, the corresponding distance lies between 0 and 2.

    The uncentered correlation is equal to the cosine of the angle of the two data vectors in n-dimensional space, and is often referred to as such.

    -

    Absolute uncentered correlation

    As for the regular Pearson correlation, we can define a distance measure using the absolute value of the uncentered correlation: -

    -
    dAU ≡ 1 − 
    -⎪
    rU
    -⎪
    ,

    +As the uncentered correlation coefficient lies between -1 and 1, the corresponding distance lies between 0 and 2.

    The uncentered correlation is equal to the cosine of the angle of the two data vectors in n-dimensional space, and is often referred to as such.

    +

    Absolute uncentered correlation

    As for the regular Pearson correlation, we can define a distance measure using the absolute value of the uncentered correlation: +

    +
    dAU ≡ 1 − 
    +⎪
    rU
    +⎪
    ,

    where -rU -is the uncentered correlation coefficient. As the absolute value of the uncentered correlation coefficient lies between 0 and 1, the corresponding distance lies between 0 and 1 as well.

    Geometrically, the absolute value of the uncentered correlation is equal to the cosine between the supporting lines of the two data vectors (i.e., the angle without taking the direction of the vectors into consideration).

    -

    Spearman rank correlation

    The Spearman rank correlation is an example of a non-parametric similarity measure, and tends to be more robust against outliers than the Pearson correlation.

    To calculate the Spearman rank correlation, we replace each data value by their rank if we would order the data in each vector by their value. We then calculate the Pearson correlation between the two rank vectors instead of the data vectors.

    As in the case of the Pearson correlation, we can define a distance measure corresponding to the Spearman rank correlation as -

    -
    dS ≡ 1 − rS,

    +rU +is the uncentered correlation coefficient. As the absolute value of the uncentered correlation coefficient lies between 0 and 1, the corresponding distance lies between 0 and 1 as well.

    Geometrically, the absolute value of the uncentered correlation is equal to the cosine between the supporting lines of the two data vectors (i.e., the angle without taking the direction of the vectors into consideration).

    +

    Spearman rank correlation

    The Spearman rank correlation is an example of a non-parametric similarity measure, and tends to be more robust against outliers than the Pearson correlation.

    To calculate the Spearman rank correlation, we replace each data value by their rank if we would order the data in each vector by their value. We then calculate the Pearson correlation between the two rank vectors instead of the data vectors.

    As in the case of the Pearson correlation, we can define a distance measure corresponding to the Spearman rank correlation as +

    +
    dS ≡ 1 − rS,

    where -rS -is the Spearman rank correlation.

    -

    Kendall’s τ

    Kendall’s τ -is another example of a non-parametric similarity measure. It is similar to the Spearman rank correlation, but instead of the ranks themselves only the relative ranks are used to calculate τ (see Snedecor & Cochran [29]).

    We can define a distance measure corresponding to Kendall’s τ -as

    -
    dK ≡ 1 − τ.

    -As Kendall’s τ is always between -1 and 1, the corresponding distance will be between 0 and 2.

    -

    Weighting

    For most of the distance functions available in Bio.Cluster, a weight vector can be applied. The weight vector contains weights for the items in the data vector. If the weight for item i is wi, then that item is treated as if it occurred wi times in the data. The weight do not have to be integers. +rS +is the Spearman rank correlation.

    +

    Kendall’s τ

    Kendall’s τ +is another example of a non-parametric similarity measure. It is similar to the Spearman rank correlation, but instead of the ranks themselves only the relative ranks are used to calculate τ (see Snedecor & Cochran [29]).

    We can define a distance measure corresponding to Kendall’s τ +as

    +
    dK ≡ 1 − τ.

    +As Kendall’s τ is always between -1 and 1, the corresponding distance will be between 0 and 2.

    +

    Weighting

    For most of the distance functions available in Bio.Cluster, a weight vector can be applied. The weight vector contains weights for the items in the data vector. If the weight for item i is wi, then that item is treated as if it occurred wi times in the data. The weight do not have to be integers. For the Spearman rank correlation and Kendall’s τ, -weights do not have a well-defined meaning and are therefore not implemented.

    -

    Calculating the distance matrix

    -

    The distance matrix is a square matrix with all pairwise distances between the items in data, and can be calculated by the function distancematrix in the Bio.Cluster module: -

    >>> from Bio.Cluster import distancematrix
    +weights do not have a well-defined meaning and are therefore not implemented.

    +

    Calculating the distance matrix

    The distance matrix is a square matrix with all pairwise distances between the items in data, and can be calculated by the function distancematrix in the Bio.Cluster module: +

    >>> from Bio.Cluster import distancematrix
     >>> matrix = distancematrix(data)
    -

    where the following arguments are defined: -

    • -data (required)
      +

    where the following arguments are defined: +

    • +data (required)
      Array containing the data for the items. -
    • mask (default: None)
      -Array of integers showing which data are missing. If mask[i,j]==0, then data[i,j] is missing. If mask==None, then all data are present. -
    • weight (default: None)
      -The weights to be used when calculating distances. If weight==None, then equal weights are assumed. -
    • transpose (default: 0)
      -Determines if the distances between the rows of data are to be calculated (transpose==0), or between the columns of data (transpose==1). -
    • dist (default: 'e', Euclidean distance)
      -Defines the distance function to be used (see 15.1). -

    To save memory, the distance matrix is returned as a list of 1D arrays. +

  • mask (default: None)
    +Array of integers showing which data are missing. If mask[i,j]==0, then data[i,j] is missing. If mask==None, then all data are present. +
  • weight (default: None)
    +The weights to be used when calculating distances. If weight==None, then equal weights are assumed. +
  • transpose (default: 0)
    +Determines if the distances between the rows of data are to be calculated (transpose==0), or between the columns of data (transpose==1). +
  • dist (default: 'e', Euclidean distance)
    +Defines the distance function to be used (see 15.1). +
  • To save memory, the distance matrix is returned as a list of 1D arrays. The number of columns in each row is equal to the row number. Hence, the first row has zero elements. An example of the return value is -

    [array([]),
    +

    [array([]),
      array([1.]),
      array([7., 3.]),
      array([4., 2., 6.])]
    -

    This corresponds to the distance matrix -

    -

    -⎜
    -⎜
    -⎜
    -⎝
    - - - - -
    0174  
    1032  
    7306  
    4260
    -
    -⎟
    -⎟
    -⎟
    -⎠
    . -
    -

    15.2  Calculating cluster properties

    -

    Calculating the cluster centroids

    -

    The centroid of a cluster can be defined either as the mean or as the median of each dimension over all cluster items. The function clustercentroids in Bio.Cluster can be used to calculate either:

    >>> from Bio.Cluster import clustercentroids
    +

    This corresponds to the distance matrix +

    +

    +⎜
    +⎜
    +⎜
    +⎝
    + + + + +
    0174  
    1032  
    7306  
    4260 +
    +
    +⎟
    +⎟
    +⎟
    +⎠
    . +
    + +

    15.2  Calculating cluster properties

    +

    Calculating the cluster centroids

    The centroid of a cluster can be defined either as the mean or as the median of each dimension over all cluster items. The function clustercentroids in Bio.Cluster can be used to calculate either:

    >>> from Bio.Cluster import clustercentroids
     >>> cdata, cmask = clustercentroids(data)
    -

    where the following arguments are defined: -

    • -data (required)
      +

    where the following arguments are defined: +

    • +data (required)
      Array containing the data for the items. -
    • mask (default: None)
      -Array of integers showing which data are missing. If mask[i,j]==0, then data[i,j] is missing. If mask==None, then all data are present. -
    • clusterid (default: None)
      -Vector of integers showing to which cluster each item belongs. If clusterid is None, then all items are assumed to belong to the same cluster. -
    • method (default: 'a')
      -Specifies whether the arithmetic mean (method=='a') or the median (method=='m') is used to calculate the cluster center. -
    • transpose (default: 0)
      -Determines if the centroids of the rows of data are to be calculated (transpose==0), or the centroids of the columns of data (transpose==1). -

    This function returns the tuple (cdata, cmask). The centroid data are stored in the 2D Numerical Python array cdata, with missing data indicated by the 2D Numerical Python integer array cmask. The dimensions of these arrays are (number of clusters, number of columns) if transpose is 0, or (number of rows, number of clusters) if transpose is 1. Each row (if transpose is 0) or column (if transpose is 1) contains the averaged data corresponding to the centroid of each cluster.

    -

    Calculating the distance between clusters

    Given a distance function between items, we can define the distance between two clusters in several ways. The distance between the arithmetic means of the two clusters is used in pairwise centroid-linkage clustering and in k-means clustering. In k-medoids clustering, the distance between the medians of the two clusters is used instead. The shortest pairwise distance between items of the two clusters is used in pairwise single-linkage clustering, while the longest pairwise distance is used in pairwise maximum-linkage clustering. In pairwise average-linkage clustering, the distance between two clusters is defined as the average over the pairwise distances.

    To calculate the distance between two clusters, use -

    >>> from Bio.Cluster import clusterdistance
    +
  • mask (default: None)
    +Array of integers showing which data are missing. If mask[i,j]==0, then data[i,j] is missing. If mask==None, then all data are present. +
  • clusterid (default: None)
    +Vector of integers showing to which cluster each item belongs. If clusterid is None, then all items are assumed to belong to the same cluster. +
  • method (default: 'a')
    +Specifies whether the arithmetic mean (method=='a') or the median (method=='m') is used to calculate the cluster center. +
  • transpose (default: 0)
    +Determines if the centroids of the rows of data are to be calculated (transpose==0), or the centroids of the columns of data (transpose==1). +
  • This function returns the tuple (cdata, cmask). The centroid data are stored in the 2D Numerical Python array cdata, with missing data indicated by the 2D Numerical Python integer array cmask. The dimensions of these arrays are (number of clusters, number of columns) if transpose is 0, or (number of rows, number of clusters) if transpose is 1. Each row (if transpose is 0) or column (if transpose is 1) contains the averaged data corresponding to the centroid of each cluster.

    +

    Calculating the distance between clusters

    Given a distance function between items, we can define the distance between two clusters in several ways. The distance between the arithmetic means of the two clusters is used in pairwise centroid-linkage clustering and in k-means clustering. In k-medoids clustering, the distance between the medians of the two clusters is used instead. The shortest pairwise distance between items of the two clusters is used in pairwise single-linkage clustering, while the longest pairwise distance is used in pairwise maximum-linkage clustering. In pairwise average-linkage clustering, the distance between two clusters is defined as the average over the pairwise distances.

    To calculate the distance between two clusters, use +

    >>> from Bio.Cluster import clusterdistance
     >>> distance = clusterdistance(data)
    -

    where the following arguments are defined: -

    • -data (required)
      +

    where the following arguments are defined: +

    • +data (required)
      Array containing the data for the items. -
    • mask (default: None)
      -Array of integers showing which data are missing. If mask[i,j]==0, then data[i,j] is missing. If mask==None, then all data are present. -
    • weight (default: None)
      -The weights to be used when calculating distances. If weight==None, then equal weights are assumed. -
    • index1 (default: 0)
      -A list containing the indices of the items belonging to the first cluster. A cluster containing only one item i can be represented either as a list [i], or as an integer i. -
    • index2 (default: 0)
      -A list containing the indices of the items belonging to the second cluster. A cluster containing only one items i can be represented either as a list [i], or as an integer i. -
    • method (default: 'a')
      +
    • mask (default: None)
      +Array of integers showing which data are missing. If mask[i,j]==0, then data[i,j] is missing. If mask==None, then all data are present. +
    • weight (default: None)
      +The weights to be used when calculating distances. If weight==None, then equal weights are assumed. +
    • index1 (default: 0)
      +A list containing the indices of the items belonging to the first cluster. A cluster containing only one item i can be represented either as a list [i], or as an integer i. +
    • index2 (default: 0)
      +A list containing the indices of the items belonging to the second cluster. A cluster containing only one items i can be represented either as a list [i], or as an integer i. +
    • method (default: 'a')
      Specifies how the distance between clusters is defined: -
      • -'a': Distance between the two cluster centroids (arithmetic mean); -
      • 'm': Distance between the two cluster centroids (median); -
      • 's': Shortest pairwise distance between items in the two clusters; -
      • 'x': Longest pairwise distance between items in the two clusters; -
      • 'v': Average over the pairwise distances between items in the two clusters. -
      -
    • dist (default: 'e', Euclidean distance)
      -Defines the distance function to be used (see 15.1). -
    • transpose (default: 0)
      -If transpose==0, calculate the distance between the rows of data. If transpose==1, calculate the distance between the columns of data. -
    -

    15.3  Partitioning algorithms

    Partitioning algorithms divide items into k clusters such that the sum of distances over the items to their cluster centers is minimal. -The number of clusters k is specified by the user. -Three partitioning algorithms are available in Bio.Cluster: -

    • -k-means clustering -
    • k-medians clustering -
    • k-medoids clustering -

    -These algorithms differ in how the cluster center is defined. In k-means clustering, the cluster center is defined as the mean data vector averaged over all items in the cluster. Instead of the mean, in k-medians clustering the median is calculated for each dimension in the data vector. Finally, in k-medoids clustering the cluster center is defined as the item which has the smallest sum of distances to the other items in the cluster. This clustering algorithm is suitable for cases in which the distance matrix is known but the original data matrix is not available, for example when clustering proteins based on their structural similarity.

    The expectation-maximization (EM) algorithm is used to find this partitioning into k groups. -In the initialization of the EM algorithm, we randomly assign items to clusters. To ensure that no empty clusters are produced, we use the binomial distribution to randomly choose the number of items in each cluster to be one or more. We then randomly permute the cluster assignments to items such that each item has an equal probability to be in any cluster. Each cluster is thus guaranteed to contain at least one item.

    We then iterate: -

    • +
      • +'a': Distance between the two cluster centroids (arithmetic mean); +
      • 'm': Distance between the two cluster centroids (median); +
      • 's': Shortest pairwise distance between items in the two clusters; +
      • 'x': Longest pairwise distance between items in the two clusters; +
      • 'v': Average over the pairwise distances between items in the two clusters. +
      +
    • dist (default: 'e', Euclidean distance)
      +Defines the distance function to be used (see 15.1). +
    • transpose (default: 0)
      +If transpose==0, calculate the distance between the rows of data. If transpose==1, calculate the distance between the columns of data. +
    + +

    15.3  Partitioning algorithms

    Partitioning algorithms divide items into k clusters such that the sum of distances over the items to their cluster centers is minimal. +The number of clusters k is specified by the user. +Three partitioning algorithms are available in Bio.Cluster: +

    • +k-means clustering +
    • k-medians clustering +
    • k-medoids clustering +

    +These algorithms differ in how the cluster center is defined. In k-means clustering, the cluster center is defined as the mean data vector averaged over all items in the cluster. Instead of the mean, in k-medians clustering the median is calculated for each dimension in the data vector. Finally, in k-medoids clustering the cluster center is defined as the item which has the smallest sum of distances to the other items in the cluster. This clustering algorithm is suitable for cases in which the distance matrix is known but the original data matrix is not available, for example when clustering proteins based on their structural similarity.

    The expectation-maximization (EM) algorithm is used to find this partitioning into k groups. +In the initialization of the EM algorithm, we randomly assign items to clusters. To ensure that no empty clusters are produced, we use the binomial distribution to randomly choose the number of items in each cluster to be one or more. We then randomly permute the cluster assignments to items such that each item has an equal probability to be in any cluster. Each cluster is thus guaranteed to contain at least one item.

    We then iterate: +

    • Calculate the centroid of each cluster, defined as either the mean, the median, or the medoid of the cluster; -
    • Calculate the distances of each item to the cluster centers; -
    • For each item, determine which cluster centroid is closest; -
    • Reassign each item to its closest cluster, or stop the iteration if no further item reassignments take place. -

    To avoid clusters becoming empty during the iteration, in k-means and k-medians clustering the algorithm keeps track of the number of items in each cluster, and prohibits the last remaining item in a cluster from being reassigned to a different cluster. For k-medoids clustering, such a check is not needed, as the item that functions as the cluster centroid has a zero distance to itself, and will therefore never be closer to a different cluster.

    As the initial assignment of items to clusters is done randomly, usually a different clustering solution is found each time the EM algorithm is executed. -To find the optimal clustering solution, the k-means algorithm is repeated many times, each time starting from a different initial random clustering. The sum of distances of the items to their cluster center is saved for each run, and the solution with the smallest value of this sum will be returned as the overall clustering solution.

    How often the EM algorithm should be run depends on the number of items being clustered. As a rule of thumb, we can consider how often the optimal solution was found; this number is returned by the partitioning algorithms as implemented in this library. If the optimal solution was found many times, it is unlikely that better solutions exist than the one that was found. However, if the optimal solution was found only once, there may well be other solutions with a smaller within-cluster sum of distances. If the number of items is large (more than several hundreds), it may be difficult to find the globally optimal solution.

    The EM algorithm terminates when no further reassignments take place. We noticed that for some sets of initial cluster assignments, the EM algorithm fails to converge due to the same clustering solution reappearing periodically after a small number of iteration steps. We therefore check for the occurrence of such periodic solutions during the iteration. After a given number of iteration steps, the current clustering result is saved as a reference. By comparing the clustering result after each subsequent iteration step to the reference state, we can determine if a previously encountered clustering result is found. In such a case, the iteration is halted. If after a given number of iterations the reference state has not yet been encountered, the current clustering solution is saved to be used as the new reference state. Initially, ten iteration steps are executed before resaving the reference state. This number of iteration steps is doubled each time, to ensure that periodic behavior with longer periods can also be detected.

    -

    k-means and k-medians

    The k-means and k-medians algorithms are implemented as the function kcluster in Bio.Cluster:

    >>> from Bio.Cluster import kcluster
    +
  • Calculate the distances of each item to the cluster centers; +
  • For each item, determine which cluster centroid is closest; +
  • Reassign each item to its closest cluster, or stop the iteration if no further item reassignments take place. +
  • To avoid clusters becoming empty during the iteration, in k-means and k-medians clustering the algorithm keeps track of the number of items in each cluster, and prohibits the last remaining item in a cluster from being reassigned to a different cluster. For k-medoids clustering, such a check is not needed, as the item that functions as the cluster centroid has a zero distance to itself, and will therefore never be closer to a different cluster.

    As the initial assignment of items to clusters is done randomly, usually a different clustering solution is found each time the EM algorithm is executed. +To find the optimal clustering solution, the k-means algorithm is repeated many times, each time starting from a different initial random clustering. The sum of distances of the items to their cluster center is saved for each run, and the solution with the smallest value of this sum will be returned as the overall clustering solution.

    How often the EM algorithm should be run depends on the number of items being clustered. As a rule of thumb, we can consider how often the optimal solution was found; this number is returned by the partitioning algorithms as implemented in this library. If the optimal solution was found many times, it is unlikely that better solutions exist than the one that was found. However, if the optimal solution was found only once, there may well be other solutions with a smaller within-cluster sum of distances. If the number of items is large (more than several hundreds), it may be difficult to find the globally optimal solution.

    The EM algorithm terminates when no further reassignments take place. We noticed that for some sets of initial cluster assignments, the EM algorithm fails to converge due to the same clustering solution reappearing periodically after a small number of iteration steps. We therefore check for the occurrence of such periodic solutions during the iteration. After a given number of iteration steps, the current clustering result is saved as a reference. By comparing the clustering result after each subsequent iteration step to the reference state, we can determine if a previously encountered clustering result is found. In such a case, the iteration is halted. If after a given number of iterations the reference state has not yet been encountered, the current clustering solution is saved to be used as the new reference state. Initially, ten iteration steps are executed before resaving the reference state. This number of iteration steps is doubled each time, to ensure that periodic behavior with longer periods can also be detected.

    +

    k-means and k-medians

    The k-means and k-medians algorithms are implemented as the function kcluster in Bio.Cluster:

    >>> from Bio.Cluster import kcluster
     >>> clusterid, error, nfound = kcluster(data)
    -

    where the following arguments are defined: -

    • -data (required)
      +

    where the following arguments are defined: +

    • +data (required)
      Array containing the data for the items. -
    • nclusters (default: 2)
      -The number of clusters k. -
    • mask (default: None)
      -Array of integers showing which data are missing. If mask[i,j]==0, then data[i,j] is missing. If mask==None, then all data are present. -
    • weight (default: None)
      -The weights to be used when calculating distances. If weight==None, then equal weights are assumed. -
    • transpose (default: 0)
      -Determines if rows (transpose is 0) or columns (transpose is 1) are to be clustered. -
    • npass (default: 1)
      -The number of times the k-means/-medians clustering algorithm is performed, each time with a different (random) initial condition. If initialid is given, the value of npass is ignored and the clustering algorithm is run only once, as it behaves deterministically in that case. -
    • method (default: a)
      +
    • nclusters (default: 2)
      +The number of clusters k. +
    • mask (default: None)
      +Array of integers showing which data are missing. If mask[i,j]==0, then data[i,j] is missing. If mask==None, then all data are present. +
    • weight (default: None)
      +The weights to be used when calculating distances. If weight==None, then equal weights are assumed. +
    • transpose (default: 0)
      +Determines if rows (transpose is 0) or columns (transpose is 1) are to be clustered. +
    • npass (default: 1)
      +The number of times the k-means/-medians clustering algorithm is performed, each time with a different (random) initial condition. If initialid is given, the value of npass is ignored and the clustering algorithm is run only once, as it behaves deterministically in that case. +
    • method (default: a)
      describes how the center of a cluster is found: -
      • -method=='a': arithmetic mean (k-means clustering); -
      • method=='m': median (k-medians clustering). -
      -For other values of method, the arithmetic mean is used. -
    • dist (default: 'e', Euclidean distance)
      -Defines the distance function to be used (see 15.1). -Whereas all eight distance measures are accepted by kcluster, from a theoretical viewpoint it is best to use the Euclidean distance for the k-means algorithm, and the city-block distance for k-medians. -
    • initialid (default: None)
      -Specifies the initial clustering to be used for the EM algorithm. If initialid==None, then a different random initial clustering is used for each of the npass runs of the EM algorithm. If initialid is not None, then it should be equal to a 1D array containing the cluster number (between 0 and nclusters-1) for each item. Each cluster should contain at least one item. With the initial clustering specified, the EM algorithm is deterministic. -

    This function returns a tuple (clusterid, error, nfound), where clusterid is an integer array containing the number of the cluster to which each row or cluster was assigned, error is the within-cluster sum of distances for the optimal clustering solution, and nfound is the number of times this optimal solution was found.

    -

    k-medoids clustering

    The kmedoids routine performs k-medoids clustering on a given set of items, using the distance matrix and the number of clusters passed by the user: -

    >>> from Bio.Cluster import kmedoids
    +
    • +method=='a': arithmetic mean (k-means clustering); +
    • method=='m': median (k-medians clustering). +
    +For other values of method, the arithmetic mean is used. +
  • dist (default: 'e', Euclidean distance)
    +Defines the distance function to be used (see 15.1). +Whereas all eight distance measures are accepted by kcluster, from a theoretical viewpoint it is best to use the Euclidean distance for the k-means algorithm, and the city-block distance for k-medians. +
  • initialid (default: None)
    +Specifies the initial clustering to be used for the EM algorithm. If initialid==None, then a different random initial clustering is used for each of the npass runs of the EM algorithm. If initialid is not None, then it should be equal to a 1D array containing the cluster number (between 0 and nclusters-1) for each item. Each cluster should contain at least one item. With the initial clustering specified, the EM algorithm is deterministic. +
  • This function returns a tuple (clusterid, error, nfound), where clusterid is an integer array containing the number of the cluster to which each row or cluster was assigned, error is the within-cluster sum of distances for the optimal clustering solution, and nfound is the number of times this optimal solution was found.

    +

    k-medoids clustering

    The kmedoids routine performs k-medoids clustering on a given set of items, using the distance matrix and the number of clusters passed by the user: +

    >>> from Bio.Cluster import kmedoids
     >>> clusterid, error, nfound = kmedoids(distance)
    -

    where the following arguments are defined: -, nclusters=2, npass=1, initialid=None)|

    • -distance (required)
      +

    where the following arguments are defined: +, nclusters=2, npass=1, initialid=None)|

    • +distance (required)
      The matrix containing the distances between the items; this matrix can be specified in three ways: -
      • +
        • as a 2D Numerical Python array (in which only the left-lower part of the array will be accessed): -
          distance = array([[0.0, 1.1, 2.3],
          +
          distance = array([[0.0, 1.1, 2.3],
                             [1.1, 0.0, 4.5],
                             [2.3, 4.5, 0.0]])
          -
        • as a 1D Numerical Python array containing consecutively the distances in the left-lower part of the distance matrix: -
          distance = array([1.1, 2.3, 4.5])
          -
        • as a list containing the rows of the left-lower part of the distance matrix: -
          distance = [array([]|,
          +
        • as a 1D Numerical Python array containing consecutively the distances in the left-lower part of the distance matrix: +
          distance = array([1.1, 2.3, 4.5])
          +
        • as a list containing the rows of the left-lower part of the distance matrix: +
          distance = [array([]|,
                       array([1.1]),
                       array([2.3, 4.5])
                      ]
          -
        +
      These three expressions correspond to the same distance matrix. -
    • nclusters (default: 2)
      -The number of clusters k. -
    • npass (default: 1)
      -The number of times the k-medoids clustering algorithm is performed, each time with a different (random) initial condition. If initialid is given, the value of npass is ignored, as the clustering algorithm behaves deterministically in that case. -
    • initialid (default: None)
      -Specifies the initial clustering to be used for the EM algorithm. If initialid==None, then a different random initial clustering is used for each of the npass runs of the EM algorithm. If initialid is not None, then it should be equal to a 1D array containing the cluster number (between 0 and nclusters-1) for each item. Each cluster should contain at least one item. With the initial clustering specified, the EM algorithm is deterministic. -

    This function returns a tuple (clusterid, error, nfound), where clusterid is an array containing the number of the cluster to which each item was assigned, error is the within-cluster sum of distances for the optimal k-medoids clustering solution, and nfound is the number of times the optimal solution was found. Note that the cluster number in clusterid is defined as the item number of the item representing the cluster centroid.

    -

    15.4  Hierarchical clustering

    Hierarchical clustering methods are inherently different from the k-means clustering method. In hierarchical clustering, the similarity in the expression profile between genes or experimental conditions are represented in the form of a tree structure. This tree structure can be shown graphically by programs such as Treeview and Java Treeview, which has contributed to the popularity of hierarchical clustering in the analysis of gene expression data.

    The first step in hierarchical clustering is to calculate the distance matrix, specifying all the distances between the items to be clustered. Next, we create a node by joining the two closest items. Subsequent nodes are created by pairwise joining of items or nodes based on the distance between them, until all items belong to the same node. A tree structure can then be created by retracing which items and nodes were merged. Unlike the EM algorithm, which is used in k-means clustering, the complete process of hierarchical clustering is deterministic.

    Several flavors of hierarchical clustering exist, which differ in how the distance between subnodes is defined in terms of their members. In Bio.Cluster, pairwise single, maximum, average, and centroid linkage are available.

    • +
    • nclusters (default: 2)
      +The number of clusters k. +
    • npass (default: 1)
      +The number of times the k-medoids clustering algorithm is performed, each time with a different (random) initial condition. If initialid is given, the value of npass is ignored, as the clustering algorithm behaves deterministically in that case. +
    • initialid (default: None)
      +Specifies the initial clustering to be used for the EM algorithm. If initialid==None, then a different random initial clustering is used for each of the npass runs of the EM algorithm. If initialid is not None, then it should be equal to a 1D array containing the cluster number (between 0 and nclusters-1) for each item. Each cluster should contain at least one item. With the initial clustering specified, the EM algorithm is deterministic. +

    This function returns a tuple (clusterid, error, nfound), where clusterid is an array containing the number of the cluster to which each item was assigned, error is the within-cluster sum of distances for the optimal k-medoids clustering solution, and nfound is the number of times the optimal solution was found. Note that the cluster number in clusterid is defined as the item number of the item representing the cluster centroid.

    + +

    15.4  Hierarchical clustering

    Hierarchical clustering methods are inherently different from the k-means clustering method. In hierarchical clustering, the similarity in the expression profile between genes or experimental conditions are represented in the form of a tree structure. This tree structure can be shown graphically by programs such as Treeview and Java Treeview, which has contributed to the popularity of hierarchical clustering in the analysis of gene expression data.

    The first step in hierarchical clustering is to calculate the distance matrix, specifying all the distances between the items to be clustered. Next, we create a node by joining the two closest items. Subsequent nodes are created by pairwise joining of items or nodes based on the distance between them, until all items belong to the same node. A tree structure can then be created by retracing which items and nodes were merged. Unlike the EM algorithm, which is used in k-means clustering, the complete process of hierarchical clustering is deterministic.

    Several flavors of hierarchical clustering exist, which differ in how the distance between subnodes is defined in terms of their members. In Bio.Cluster, pairwise single, maximum, average, and centroid linkage are available.

    • In pairwise single-linkage clustering, the distance between two nodes is defined as the shortest distance among the pairwise distances between the members of the two nodes. -
    • In pairwise maximum-linkage clustering, alternatively known as pairwise complete-linkage clustering, the distance between two nodes is defined as the longest distance among the pairwise distances between the members of the two nodes. -
    • In pairwise average-linkage clustering, the distance between two nodes is defined as the average over all pairwise distances between the items of the two nodes. -
    • In pairwise centroid-linkage clustering, the distance between two nodes is defined as the distance between their centroids. The centroids are calculated by taking the mean over all the items in a cluster. As the distance from each newly formed node to existing nodes and items need to be calculated at each step, the computing time of pairwise centroid-linkage clustering may be significantly longer than for the other hierarchical clustering methods. Another peculiarity is that (for a distance measure based on the Pearson correlation), the distances do not necessarily increase when going up in the clustering tree, and may even decrease. This is caused by an inconsistency between the centroid calculation and the distance calculation when using the Pearson correlation: Whereas the Pearson correlation effectively normalizes the data for the distance calculation, no such normalization occurs for the centroid calculation. -

    For pairwise single-, complete-, and average-linkage clustering, the distance between two nodes can be found directly from the distances between the individual items. Therefore, the clustering algorithm does not need access to the original gene expression data, once the distance matrix is known. For pairwise centroid-linkage clustering, however, the centroids of newly formed subnodes can only be calculated from the original data and not from the distance matrix.

    The implementation of pairwise single-linkage hierarchical clustering is based on the SLINK algorithm (R. Sibson, 1973), which is much faster and more memory-efficient than a straightforward implementation of pairwise single-linkage clustering. The clustering result produced by this algorithm is identical to the clustering solution found by the conventional single-linkage algorithm. The single-linkage hierarchical clustering algorithm implemented in this library can be used to cluster large gene expression data sets, for which conventional hierarchical clustering algorithms fail due to excessive memory requirements and running time.

    -

    Representing a hierarchical clustering solution

    The result of hierarchical clustering consists of a tree of nodes, in which each node joins two items or subnodes. Usually, we are not only interested in which items or subnodes are joined at each node, but also in their similarity (or distance) as they are joined. To store one node in the hierarchical clustering tree, we make use of the class Node, which defined in Bio.Cluster. An instance of Node has three attributes: -

    • -left -
    • right -
    • distance -

    -Here, left and right are integers referring to the two items or subnodes that are joined at this node, and distance is the distance between them. The items being clustered are numbered from 0 to (number of items − 1), while clusters are numbered from -1 to −(number of items−1). Note that the number of nodes is one less than the number of items.

    To create a new Node object, we need to specify left and right; distance is optional.

    >>> from Bio.Cluster import Node
    ->>> Node(2,3)
    +
  • In pairwise maximum-linkage clustering, alternatively known as pairwise complete-linkage clustering, the distance between two nodes is defined as the longest distance among the pairwise distances between the members of the two nodes. +
  • In pairwise average-linkage clustering, the distance between two nodes is defined as the average over all pairwise distances between the items of the two nodes. +
  • In pairwise centroid-linkage clustering, the distance between two nodes is defined as the distance between their centroids. The centroids are calculated by taking the mean over all the items in a cluster. As the distance from each newly formed node to existing nodes and items need to be calculated at each step, the computing time of pairwise centroid-linkage clustering may be significantly longer than for the other hierarchical clustering methods. Another peculiarity is that (for a distance measure based on the Pearson correlation), the distances do not necessarily increase when going up in the clustering tree, and may even decrease. This is caused by an inconsistency between the centroid calculation and the distance calculation when using the Pearson correlation: Whereas the Pearson correlation effectively normalizes the data for the distance calculation, no such normalization occurs for the centroid calculation. +
  • For pairwise single-, complete-, and average-linkage clustering, the distance between two nodes can be found directly from the distances between the individual items. Therefore, the clustering algorithm does not need access to the original gene expression data, once the distance matrix is known. For pairwise centroid-linkage clustering, however, the centroids of newly formed subnodes can only be calculated from the original data and not from the distance matrix.

    The implementation of pairwise single-linkage hierarchical clustering is based on the SLINK algorithm (R. Sibson, 1973), which is much faster and more memory-efficient than a straightforward implementation of pairwise single-linkage clustering. The clustering result produced by this algorithm is identical to the clustering solution found by the conventional single-linkage algorithm. The single-linkage hierarchical clustering algorithm implemented in this library can be used to cluster large gene expression data sets, for which conventional hierarchical clustering algorithms fail due to excessive memory requirements and running time.

    +

    Representing a hierarchical clustering solution

    The result of hierarchical clustering consists of a tree of nodes, in which each node joins two items or subnodes. Usually, we are not only interested in which items or subnodes are joined at each node, but also in their similarity (or distance) as they are joined. To store one node in the hierarchical clustering tree, we make use of the class Node, which defined in Bio.Cluster. An instance of Node has three attributes: +

    • +left +
    • right +
    • distance +

    +Here, left and right are integers referring to the two items or subnodes that are joined at this node, and distance is the distance between them. The items being clustered are numbered from 0 to (number of items − 1), while clusters are numbered from -1 to −(number of items−1). Note that the number of nodes is one less than the number of items.

    To create a new Node object, we need to specify left and right; distance is optional.

    >>> from Bio.Cluster import Node
    +>>> Node(2, 3)
     (2, 3): 0
    ->>> Node(2,3,0.91)
    +>>> Node(2, 3, 0.91)
     (2, 3): 0.91
    -

    The attributes left, right, and distance of an existing Node object can be modified directly:

    >>> node = Node(4,5)
    +

    The attributes left, right, and distance of an existing Node object can be modified directly:

    >>> node = Node(4, 5)
     >>> node.left = 6
     >>> node.right = 2
     >>> node.distance = 0.73
     >>> node
     (6, 2): 0.73
    -

    An error is raised if left and right are not integers, or if distance cannot be converted to a floating-point value.

    The Python class Tree represents a full hierarchical clustering solution. A Tree object can be created from a list of Node objects:

    >>> from Bio.Cluster import Node, Tree
    ->>> nodes = [Node(1,2,0.2), Node(0,3,0.5), Node(-2,4,0.6), Node(-1,-3,0.9)]
    +

    An error is raised if left and right are not integers, or if distance cannot be converted to a floating-point value.

    The Python class Tree represents a full hierarchical clustering solution. A Tree object can be created from a list of Node objects:

    >>> from Bio.Cluster import Node, Tree
    +>>> nodes = [Node(1, 2, 0.2), Node(0, 3, 0.5), Node(-2, 4, 0.6), Node(-1, -3, 0.9)]
     >>> tree = Tree(nodes)
    ->>> print tree
    +>>> print(tree)
     (1, 2): 0.2
     (0, 3): 0.5
     (-2, 4): 0.6
     (-1, -3): 0.9
    -

    The Tree initializer checks if the list of nodes is a valid hierarchical clustering result:

    >>> nodes = [Node(1,2,0.2), Node(0,2,0.5)]
    +

    The Tree initializer checks if the list of nodes is a valid hierarchical clustering result:

    >>> nodes = [Node(1, 2, 0.2), Node(0, 2, 0.5)]
     >>> Tree(nodes)
     Traceback (most recent call last):
       File "<stdin>", line 1, in ?
     ValueError: Inconsistent tree
    -

    Individual nodes in a Tree object can be accessed using square brackets:

    >>> nodes = [Node(1,2,0.2), Node(0,-1,0.5)]
    +

    Individual nodes in a Tree object can be accessed using square brackets:

    >>> nodes = [Node(1, 2, 0.2), Node(0, -1, 0.5)]
     >>> tree = Tree(nodes)
     >>> tree[0]
     (1, 2): 0.2
    @@ -9043,306 +9314,310 @@
     (0, -1): 0.5
     >>> tree[-1]
     (0, -1): 0.5
    -

    As a Tree object is read-only, we cannot change individual nodes in a Tree object. However, we can convert the tree to a list of nodes, modify this list, and create a new tree from this list:

    >>> tree = Tree([Node(1,2,0.1), Node(0,-1,0.5), Node(-2,3,0.9)])
    ->>> print tree
    +

    As a Tree object is read-only, we cannot change individual nodes in a Tree object. However, we can convert the tree to a list of nodes, modify this list, and create a new tree from this list:

    >>> tree = Tree([Node(1, 2, 0.1), Node(0, -1, 0.5), Node(-2, 3, 0.9)])
    +>>> print(tree)
     (1, 2): 0.1
     (0, -1): 0.5
     (-2, 3): 0.9
     >>> nodes = tree[:]
    ->>> nodes[0] = Node(0,1,0.2)
    +>>> nodes[0] = Node(0, 1, 0.2)
     >>> nodes[1].left = 2
     >>> tree = Tree(nodes)
    ->>> print tree
    +>>> print(tree)
     (0, 1): 0.2
     (2, -1): 0.5
     (-2, 3): 0.9
    -

    This guarantees that any Tree object is always well-formed.

    To display a hierarchical clustering solution with visualization programs such as Java Treeview, it is better to scale all node distances such that they are between zero and one. This can be accomplished by calling the scale method on an existing Tree object: -

    >>> tree.scale()
    -

    This method takes no arguments, and returns None.

    After hierarchical clustering, the items can be grouped into k clusters based on the tree structure stored in the Tree object by cutting the tree: -

    >>> clusterid = tree.cut(nclusters=1)
    -

    where nclusters (defaulting to 1) is the desired number of clusters k. -This method ignores the top k−1 linking events in the tree structure, resulting in k separated clusters of items. The number of clusters k should be positive, and less than or equal to the number of items. -This method returns an array clusterid containing the number of the cluster to which each item is assigned.

    -

    Performing hierarchical clustering

    To perform hierarchical clustering, use the treecluster function in Bio.Cluster. -

    >>> from Bio.Cluster import treecluster
    +

    This guarantees that any Tree object is always well-formed.

    To display a hierarchical clustering solution with visualization programs such as Java Treeview, it is better to scale all node distances such that they are between zero and one. This can be accomplished by calling the scale method on an existing Tree object: +

    >>> tree.scale()
    +

    This method takes no arguments, and returns None.

    After hierarchical clustering, the items can be grouped into k clusters based on the tree structure stored in the Tree object by cutting the tree: +

    >>> clusterid = tree.cut(nclusters=1)
    +

    where nclusters (defaulting to 1) is the desired number of clusters k. +This method ignores the top k−1 linking events in the tree structure, resulting in k separated clusters of items. The number of clusters k should be positive, and less than or equal to the number of items. +This method returns an array clusterid containing the number of the cluster to which each item is assigned.

    +

    Performing hierarchical clustering

    To perform hierarchical clustering, use the treecluster function in Bio.Cluster. +

    >>> from Bio.Cluster import treecluster
     >>> tree = treecluster(data)
    -

    where the following arguments are defined:

    • -data
      +

    where the following arguments are defined:

    • +data
      Array containing the data for the items. -
    • mask (default: None)
      -Array of integers showing which data are missing. If mask[i,j]==0, then data[i,j] is missing. If mask==None, then all data are present. -
    • weight (default: None)
      -The weights to be used when calculating distances. If weight==None, then equal weights are assumed. -
    • transpose (default: 0)
      -Determines if rows (transpose==0) or columns (transpose==1) are to be clustered. -
    • method (default: 'm')
      +
    • mask (default: None)
      +Array of integers showing which data are missing. If mask[i,j]==0, then data[i,j] is missing. If mask==None, then all data are present. +
    • weight (default: None)
      +The weights to be used when calculating distances. If weight==None, then equal weights are assumed. +
    • transpose (default: 0)
      +Determines if rows (transpose==0) or columns (transpose==1) are to be clustered. +
    • method (default: 'm')
      defines the linkage method to be used: -
      • -method=='s': pairwise single-linkage clustering -
      • method=='m': pairwise maximum- (or complete-) linkage clustering -
      • method=='c': pairwise centroid-linkage clustering -
      • method=='a': pairwise average-linkage clustering -
      -
    • dist (default: 'e', Euclidean distance)
      -Defines the distance function to be used (see 15.1). -

    To apply hierarchical clustering on a precalculated distance matrix, specify the distancematrix argument when calling treecluster function instead of the data argument: -

    >>> from Bio.Cluster import treecluster
    +
    • +method=='s': pairwise single-linkage clustering +
    • method=='m': pairwise maximum- (or complete-) linkage clustering +
    • method=='c': pairwise centroid-linkage clustering +
    • method=='a': pairwise average-linkage clustering +
    +
  • dist (default: 'e', Euclidean distance)
    +Defines the distance function to be used (see 15.1). +
  • To apply hierarchical clustering on a precalculated distance matrix, specify the distancematrix argument when calling treecluster function instead of the data argument: +

    >>> from Bio.Cluster import treecluster
     >>> tree = treecluster(distancematrix=distance)
    -

    In this case, the following arguments are defined: -

    • -distancematrix
      +

    In this case, the following arguments are defined: +

    • +distancematrix
      The distance matrix, which can be specified in three ways: -
      • +
        • as a 2D Numerical Python array (in which only the left-lower part of the array will be accessed): -
          distance = array([[0.0, 1.1, 2.3], 
          +
          distance = array([[0.0, 1.1, 2.3], 
                             [1.1, 0.0, 4.5],
                             [2.3, 4.5, 0.0]])
          -
        • as a 1D Numerical Python array containing consecutively the distances in the left-lower part of the distance matrix: -
          distance = array([1.1, 2.3, 4.5])
          -
        • as a list containing the rows of the left-lower part of the distance matrix: -
          distance = [array([]),
          +
        • as a 1D Numerical Python array containing consecutively the distances in the left-lower part of the distance matrix: +
          distance = array([1.1, 2.3, 4.5])
          +
        • as a list containing the rows of the left-lower part of the distance matrix: +
          distance = [array([]),
                       array([1.1]),
                       array([2.3, 4.5])
          -
        +
      These three expressions correspond to the same distance matrix. -As treecluster may shuffle the values in the distance matrix as part of the clustering algorithm, be sure to save this array in a different variable before calling treecluster if you need it later. -
    • method
      +As treecluster may shuffle the values in the distance matrix as part of the clustering algorithm, be sure to save this array in a different variable before calling treecluster if you need it later. +
    • method
      The linkage method to be used: -
      • -method=='s': pairwise single-linkage clustering -
      • method=='m': pairwise maximum- (or complete-) linkage clustering -
      • method=='a': pairwise average-linkage clustering -
      +
      • +method=='s': pairwise single-linkage clustering +
      • method=='m': pairwise maximum- (or complete-) linkage clustering +
      • method=='a': pairwise average-linkage clustering +
      While pairwise single-, maximum-, and average-linkage clustering can be calculated from the distance matrix alone, pairwise centroid-linkage cannot. -

    When calling treecluster, either data or distancematrix should be None.

    This function returns a Tree object. This object contains (number of items − 1) nodes, where the number of items is the number of rows if rows were clustered, or the number of columns if columns were clustered. Each node describes a pairwise linking event, where the node attributes left and right each contain the number of one item or subnode, and distance the distance between them. Items are numbered from 0 to (number of items − 1), while clusters are numbered -1 to −(number of items−1).

    -

    15.5  Self-Organizing Maps

    Self-Organizing Maps (SOMs) were invented by Kohonen to describe neural networks (see for instance Kohonen, 1997 [24]). Tamayo (1999) first applied Self-Organizing Maps to gene expression data [30].

    SOMs organize items into clusters that are situated in some topology. Usually a rectangular topology is chosen. The clusters generated by SOMs are such that neighboring clusters in the topology are more similar to each other than clusters far from each other in the topology.

    The first step to calculate a SOM is to randomly assign a data vector to each cluster in the topology. If rows are being clustered, then the number of elements in each data vector is equal to the number of columns.

    An SOM is then generated by taking rows one at a time, and finding which cluster in the topology has the closest data vector. The data vector of that cluster, as well as those of the neighboring clusters, are adjusted using the data vector of the row under consideration. The adjustment is given by -

    -
    Δ  - -
    x
    cell = τ · 
    -⎜
    -⎝
    - -
    x
    row −  - -
    x
    cell 
    -⎟
    -⎠
    .

    +

    When calling treecluster, either data or distancematrix should be None.

    This function returns a Tree object. This object contains (number of items − 1) nodes, where the number of items is the number of rows if rows were clustered, or the number of columns if columns were clustered. Each node describes a pairwise linking event, where the node attributes left and right each contain the number of one item or subnode, and distance the distance between them. Items are numbered from 0 to (number of items − 1), while clusters are numbered -1 to −(number of items−1).

    + +

    15.5  Self-Organizing Maps

    Self-Organizing Maps (SOMs) were invented by Kohonen to describe neural networks (see for instance Kohonen, 1997 [24]). Tamayo (1999) first applied Self-Organizing Maps to gene expression data [30].

    SOMs organize items into clusters that are situated in some topology. Usually a rectangular topology is chosen. The clusters generated by SOMs are such that neighboring clusters in the topology are more similar to each other than clusters far from each other in the topology.

    The first step to calculate a SOM is to randomly assign a data vector to each cluster in the topology. If rows are being clustered, then the number of elements in each data vector is equal to the number of columns.

    An SOM is then generated by taking rows one at a time, and finding which cluster in the topology has the closest data vector. The data vector of that cluster, as well as those of the neighboring clusters, are adjusted using the data vector of the row under consideration. The adjustment is given by +

    +
    Δ  + +
    x
    cell = τ · 
    +⎜
    +⎝
    + +
    x
    row −  + +
    x
    cell 
    +⎟
    +⎠
    .

    The parameter τ is a parameter that decreases at each iteration step. We have used a simple linear function of the iteration step: -

    -
    τ = τinit · 
    -⎜
    -⎜
    -⎝
    1 −  - - -
    i 
    n

    -⎟
    -⎟
    -⎠
    ,

    init -is the initial value of τ as specified by the user, i is the number of the current iteration step, and n is the total number of iteration steps to be performed. While changes are made rapidly in the beginning of the iteration, at the end of iteration only small changes are made.

    All clusters within a radius R are adjusted to the gene under consideration. This radius decreases as the calculation progresses as -

    -
    R = Rmax · 
    -⎜
    -⎜
    -⎝
    1 −  - - -
    i 
    n

    -⎟
    -⎟
    -⎠
    ,

    +

    +
    τ = τinit · 
    +⎜
    +⎜
    +⎝
    1 −  + + +
    i 
    n

    +⎟
    +⎟
    +⎠
    ,

    init +is the initial value of τ as specified by the user, i is the number of the current iteration step, and n is the total number of iteration steps to be performed. While changes are made rapidly in the beginning of the iteration, at the end of iteration only small changes are made.

    All clusters within a radius R are adjusted to the gene under consideration. This radius decreases as the calculation progresses as +

    +
    R = Rmax · 
    +⎜
    +⎜
    +⎝
    1 −  + + +
    i 
    n

    +⎟
    +⎟
    +⎠
    ,

    in which the maximum radius is defined as -

    -
    Rmax =  - -
    Nx2 + Ny2
    ,

    +

    +
    Rmax =  + +
    Nx2 + Ny2
    ,

    where -(Nx, Ny) -are the dimensions of the rectangle defining the topology.

    The function somcluster implements the complete algorithm to calculate a Self-Organizing Map on a rectangular grid. First it initializes the random number generator. The node data are then initialized using the random number generator. The order in which genes or microarrays are used to modify the SOM is also randomized. The total number of iterations in the SOM algorithm is specified by the user.

    To run somcluster, use -

    >>> from Bio.Cluster import somcluster
    +(Nx, Ny)
    +are the dimensions of the rectangle defining the topology.

    The function somcluster implements the complete algorithm to calculate a Self-Organizing Map on a rectangular grid. First it initializes the random number generator. The node data are then initialized using the random number generator. The order in which genes or microarrays are used to modify the SOM is also randomized. The total number of iterations in the SOM algorithm is specified by the user.

    To run somcluster, use +

    >>> from Bio.Cluster import somcluster
     >>> clusterid, celldata = somcluster(data)
    -

    where the following arguments are defined: -

    • -data (required)
      +

    where the following arguments are defined: +

    • +data (required)
      Array containing the data for the items. -
    • mask (default: None)
      -Array of integers showing which data are missing. If mask[i,j]==0, then data[i,j] is missing. If mask==None, then all data are present. -
    • weight (default: None)
      -contains the weights to be used when calculating distances. If weight==None, then equal weights are assumed. -
    • transpose (default: 0)
      -Determines if rows (transpose is 0) or columns (transpose is 1) are to be clustered. -
    • nxgrid, nygrid (default: 2, 1)
      +
    • mask (default: None)
      +Array of integers showing which data are missing. If mask[i,j]==0, then data[i,j] is missing. If mask==None, then all data are present. +
    • weight (default: None)
      +contains the weights to be used when calculating distances. If weight==None, then equal weights are assumed. +
    • transpose (default: 0)
      +Determines if rows (transpose is 0) or columns (transpose is 1) are to be clustered. +
    • nxgrid, nygrid (default: 2, 1)
      The number of cells horizontally and vertically in the rectangular grid on which the Self-Organizing Map is calculated. -
    • inittau (default: 0.02)
      -The initial value for the parameter τ that is used in the SOM algorithm. The default value for inittau is 0.02, which was used in Michael Eisen’s Cluster/TreeView program. -
    • niter (default: 1)
      +
    • inittau (default: 0.02)
      +The initial value for the parameter τ that is used in the SOM algorithm. The default value for inittau is 0.02, which was used in Michael Eisen’s Cluster/TreeView program. +
    • niter (default: 1)
      The number of iterations to be performed. -
    • dist (default: 'e', Euclidean distance)
      -Defines the distance function to be used (see 15.1). -

    This function returns the tuple (clusterid, celldata): -

    • -clusterid:
      -An array with two columns, where the number of rows is equal to the number of items that were clustered. Each row contains the x and y coordinates of the cell in the rectangular SOM grid to which the item was assigned. -
    • celldata:
      -An array with dimensions (nxgrid, nygrid, number of columns) if rows are being clustered, or (nxgrid, nygrid, number of rows) if columns are being clustered. Each element [ix][iy] of this array is a 1D vector containing the gene expression data for the centroid of the cluster in the grid cell with coordinates [ix][iy]. -
    -

    15.6  Principal Component Analysis

    Principal Component Analysis (PCA) is a widely used technique for analyzing multivariate data. A practical example of applying Principal Component Analysis to gene expression data is presented by Yeung and Ruzzo (2001) [33].

    In essence, PCA is a coordinate transformation in which each row in the data matrix is written as a linear sum over basis vectors called principal components, which are ordered and chosen such that each maximally explains the remaining variance in the data vectors. For example, an n × 3 data matrix can be represented as an ellipsoidal cloud of n points in three dimensional space. The first principal component is the longest axis of the ellipsoid, the second principal component the second longest axis of the ellipsoid, and the third principal component is the shortest axis. Each row in the data matrix can be reconstructed as a suitable linear combination of the principal components. However, in order to reduce the dimensionality of the data, usually only the most important principal components are retained. The remaining variance present in the data is then regarded as unexplained variance.

    The principal components can be found by calculating the eigenvectors of the covariance matrix of the data. The corresponding eigenvalues determine how much of the variance present in the data is explained by each principal component.

    Before applying principal component analysis, typically the mean is subtracted from each column in the data matrix. In the example above, this effectively centers the ellipsoidal cloud around its centroid in 3D space, with the principal components describing the variation of points in the ellipsoidal cloud with respect to their centroid.

    The function pca below first uses the singular value decomposition to calculate the eigenvalues and eigenvectors of the data matrix. The singular value decomposition is implemented as a translation in C of the Algol procedure svd [16], which uses Householder bidiagonalization and a variant of the QR algorithm. The principal components, the coordinates of each data vector along the principal components, and the eigenvalues corresponding to the principal components are then evaluated and returned in decreasing order of the magnitude of the eigenvalue. If data centering is desired, the mean should be subtracted from each column in the data matrix before calling the pca routine.

    To apply Principal Component Analysis to a rectangular matrix data, use -

    >>> from Bio.Cluster import pca
    +
  • dist (default: 'e', Euclidean distance)
    +Defines the distance function to be used (see 15.1). +
  • This function returns the tuple (clusterid, celldata): +

    • +clusterid:
      +An array with two columns, where the number of rows is equal to the number of items that were clustered. Each row contains the x and y coordinates of the cell in the rectangular SOM grid to which the item was assigned. +
    • celldata:
      +An array with dimensions (nxgrid, nygrid, number of columns) if rows are being clustered, or (nxgrid, nygrid, number of rows) if columns are being clustered. Each element [ix][iy] of this array is a 1D vector containing the gene expression data for the centroid of the cluster in the grid cell with coordinates [ix][iy]. +
    + +

    15.6  Principal Component Analysis

    Principal Component Analysis (PCA) is a widely used technique for analyzing multivariate data. A practical example of applying Principal Component Analysis to gene expression data is presented by Yeung and Ruzzo (2001) [33].

    In essence, PCA is a coordinate transformation in which each row in the data matrix is written as a linear sum over basis vectors called principal components, which are ordered and chosen such that each maximally explains the remaining variance in the data vectors. For example, an n × 3 data matrix can be represented as an ellipsoidal cloud of n points in three dimensional space. The first principal component is the longest axis of the ellipsoid, the second principal component the second longest axis of the ellipsoid, and the third principal component is the shortest axis. Each row in the data matrix can be reconstructed as a suitable linear combination of the principal components. However, in order to reduce the dimensionality of the data, usually only the most important principal components are retained. The remaining variance present in the data is then regarded as unexplained variance.

    The principal components can be found by calculating the eigenvectors of the covariance matrix of the data. The corresponding eigenvalues determine how much of the variance present in the data is explained by each principal component.

    Before applying principal component analysis, typically the mean is subtracted from each column in the data matrix. In the example above, this effectively centers the ellipsoidal cloud around its centroid in 3D space, with the principal components describing the variation of points in the ellipsoidal cloud with respect to their centroid.

    The function pca below first uses the singular value decomposition to calculate the eigenvalues and eigenvectors of the data matrix. The singular value decomposition is implemented as a translation in C of the Algol procedure svd [16], which uses Householder bidiagonalization and a variant of the QR algorithm. The principal components, the coordinates of each data vector along the principal components, and the eigenvalues corresponding to the principal components are then evaluated and returned in decreasing order of the magnitude of the eigenvalue. If data centering is desired, the mean should be subtracted from each column in the data matrix before calling the pca routine.

    To apply Principal Component Analysis to a rectangular matrix data, use +

    >>> from Bio.Cluster import pca
     >>> columnmean, coordinates, components, eigenvalues = pca(data)
    -

    This function returns a tuple columnmean, coordinates, components, eigenvalues: -

    • -columnmean
      -Array containing the mean over each column in data. -
    • coordinates
      -The coordinates of each row in data with respect to the principal components. -
    • components
      +

    This function returns a tuple columnmean, coordinates, components, eigenvalues: +

    • +columnmean
      +Array containing the mean over each column in data. +
    • coordinates
      +The coordinates of each row in data with respect to the principal components. +
    • components
      The principal components. -
    • eigenvalues
      +
    • eigenvalues
      The eigenvalues corresponding to each of the principal components. -

    -The original matrix data can be recreated by calculating columnmean + dot(coordinates, components).

    -

    15.7  Handling Cluster/TreeView-type files

    Cluster/TreeView are GUI-based codes for clustering gene expression data. They were originally written by Michael Eisen while at Stanford University. Bio.Cluster contains functions for reading and writing data files that correspond to the format specified for Cluster/TreeView. In particular, by saving a clustering result in that format, TreeView can be used to visualize the clustering results. We recommend using Alok Saldanha’s http://jtreeview.sourceforge.net/Java TreeView program, which can display hierarchical as well as k-means clustering results.

    An object of the class Record contains all information stored in a Cluster/TreeView-type data file. To store the information contained in the data file in a Record object, we first open the file and then read it:

    >>> from Bio import Cluster
    +

    +The original matrix data can be recreated by calculating columnmean + dot(coordinates, components).

    + +

    15.7  Handling Cluster/TreeView-type files

    Cluster/TreeView are GUI-based codes for clustering gene expression data. They were originally written by Michael Eisen while at Stanford University. Bio.Cluster contains functions for reading and writing data files that correspond to the format specified for Cluster/TreeView. In particular, by saving a clustering result in that format, TreeView can be used to visualize the clustering results. We recommend using Alok Saldanha’s http://jtreeview.sourceforge.net/Java TreeView program, which can display hierarchical as well as k-means clustering results.

    An object of the class Record contains all information stored in a Cluster/TreeView-type data file. To store the information contained in the data file in a Record object, we first open the file and then read it:

    >>> from Bio import Cluster
     >>> handle = open("mydatafile.txt")
     >>> record = Cluster.read(handle)
     >>> handle.close()
    -

    This two-step process gives you some flexibility in the source of the data. -For example, you can use

    >>> import gzip # Python standard library
    +

    This two-step process gives you some flexibility in the source of the data. +For example, you can use

    >>> import gzip # Python standard library
     >>> handle = gzip.open("mydatafile.txt.gz")
    -

    to open a gzipped file, or -

    >>> import urllib # Python standard library
    +

    to open a gzipped file, or +

    >>> import urllib # Python standard library
     >>> handle = urllib.urlopen("http://somewhere.org/mydatafile.txt")
    -

    to open a file stored on the Internet before calling read.

    The read command reads the tab-delimited text file mydatafile.txt containing gene expression data in the format specified for Michael Eisen’s Cluster/TreeView program. For a description of this file format, see the manual to Cluster/TreeView. It is available at Michael Eisen’s lab website and at our website.

    A Record object has the following attributes:

    • -data
      -The data array containing the gene expression data. Genes are stored row-wise, while microarrays are stored column-wise.
    • mask
      -This array shows which elements in the data array, if any, are missing. If mask[i,j]==0, then data[i,j] is missing. If no data were found to be missing, mask is set to None.
    • geneid
      -This is a list containing a unique description for each gene (i.e., ORF numbers).
    • genename
      -This is a list containing a description for each gene (i.e., gene name). If not present in the data file, genename is set to None.
    • gweight
      -The weights that are to be used to calculate the distance in expression profile between genes. If not present in the data file, gweight is set to None.
    • gorder
      -The preferred order in which genes should be stored in an output file. If not present in the data file, gorder is set to None.
    • expid
      -This is a list containing a description of each microarray, e.g. experimental condition.
    • eweight
      -The weights that are to be used to calculate the distance in expression profile between microarrays. If not present in the data file, eweight is set to None.
    • eorder
      -The preferred order in which microarrays should be stored in an output file. If not present in the data file, eorder is set to None.
    • uniqid
      +

    to open a file stored on the Internet before calling read.

    The read command reads the tab-delimited text file mydatafile.txt containing gene expression data in the format specified for Michael Eisen’s Cluster/TreeView program. For a description of this file format, see the manual to Cluster/TreeView. It is available at Michael Eisen’s lab website and at our website.

    A Record object has the following attributes:

    • +data
      +The data array containing the gene expression data. Genes are stored row-wise, while microarrays are stored column-wise.
    • mask
      +This array shows which elements in the data array, if any, are missing. If mask[i,j]==0, then data[i,j] is missing. If no data were found to be missing, mask is set to None.
    • geneid
      +This is a list containing a unique description for each gene (i.e., ORF numbers).
    • genename
      +This is a list containing a description for each gene (i.e., gene name). If not present in the data file, genename is set to None.
    • gweight
      +The weights that are to be used to calculate the distance in expression profile between genes. If not present in the data file, gweight is set to None.
    • gorder
      +The preferred order in which genes should be stored in an output file. If not present in the data file, gorder is set to None.
    • expid
      +This is a list containing a description of each microarray, e.g. experimental condition.
    • eweight
      +The weights that are to be used to calculate the distance in expression profile between microarrays. If not present in the data file, eweight is set to None.
    • eorder
      +The preferred order in which microarrays should be stored in an output file. If not present in the data file, eorder is set to None.
    • uniqid
      The string that was used instead of UNIQID in the data file. -

    After loading a Record object, each of these attributes can be accessed and modified directly. For example, the data can be log-transformed by taking the logarithm of record.data.

    -

    Calculating the distance matrix

    To calculate the distance matrix between the items stored in the record, use -

    >>> matrix = record.distancematrix()
    -

    where the following arguments are defined: -

    • -transpose (default: 0)
      -Determines if the distances between the rows of data are to be calculated (transpose==0), or between the columns of data (transpose==1). -
    • dist (default: 'e', Euclidean distance)
      -Defines the distance function to be used (see 15.1). -

    This function returns the distance matrix as a list of rows, where the number of columns of each row is equal to the row number (see section 15.1).

    -

    Calculating the cluster centroids

    To calculate the centroids of clusters of items stored in the record, use -

    >>> cdata, cmask = record.clustercentroids()
    -
    • -clusterid (default: None)
      -Vector of integers showing to which cluster each item belongs. If clusterid is not given, then all items are assumed to belong to the same cluster. -
    • method (default: 'a')
      -Specifies whether the arithmetic mean (method=='a') or the median (method=='m') is used to calculate the cluster center. -
    • transpose (default: 0)
      -Determines if the centroids of the rows of data are to be calculated (transpose==0), or the centroids of the columns of data (transpose==1). -

    This function returns the tuple cdata, cmask; see section 15.2 for a description.

    -

    Calculating the distance between clusters

    +

    After loading a Record object, each of these attributes can be accessed and modified directly. For example, the data can be log-transformed by taking the logarithm of record.data.

    +

    Calculating the distance matrix

    To calculate the distance matrix between the items stored in the record, use +

    >>> matrix = record.distancematrix()
    +

    where the following arguments are defined: +

    • +transpose (default: 0)
      +Determines if the distances between the rows of data are to be calculated (transpose==0), or between the columns of data (transpose==1). +
    • dist (default: 'e', Euclidean distance)
      +Defines the distance function to be used (see 15.1). +

    This function returns the distance matrix as a list of rows, where the number of columns of each row is equal to the row number (see section 15.1).

    +

    Calculating the cluster centroids

    To calculate the centroids of clusters of items stored in the record, use +

    >>> cdata, cmask = record.clustercentroids()
    +
    • +clusterid (default: None)
      +Vector of integers showing to which cluster each item belongs. If clusterid is not given, then all items are assumed to belong to the same cluster. +
    • method (default: 'a')
      +Specifies whether the arithmetic mean (method=='a') or the median (method=='m') is used to calculate the cluster center. +
    • transpose (default: 0)
      +Determines if the centroids of the rows of data are to be calculated (transpose==0), or the centroids of the columns of data (transpose==1). +

    This function returns the tuple cdata, cmask; see section 15.2 for a description.

    +

    Calculating the distance between clusters

    To calculate the distance between clusters of items stored in the record, use -

    >>> distance = record.clusterdistance()
    -

    where the following arguments are defined: -

    • -index1 (default: 0)
      -A list containing the indices of the items belonging to the first cluster. A cluster containing only one item i can be represented either as a list [i], or as an integer i. -
    • index2 (default: 0)
      -A list containing the indices of the items belonging to the second cluster. A cluster containing only one item i can be represented either as a list [i], or as an integer i. -
    • method (default: 'a')
      +

      >>> distance = record.clusterdistance()
      +

      where the following arguments are defined: +

      • +index1 (default: 0)
        +A list containing the indices of the items belonging to the first cluster. A cluster containing only one item i can be represented either as a list [i], or as an integer i. +
      • index2 (default: 0)
        +A list containing the indices of the items belonging to the second cluster. A cluster containing only one item i can be represented either as a list [i], or as an integer i. +
      • method (default: 'a')
        Specifies how the distance between clusters is defined: -
        • -'a': Distance between the two cluster centroids (arithmetic mean); -
        • 'm': Distance between the two cluster centroids (median); -
        • 's': Shortest pairwise distance between items in the two clusters; -
        • 'x': Longest pairwise distance between items in the two clusters; -
        • 'v': Average over the pairwise distances between items in the two clusters. -
        -
      • dist (default: 'e', Euclidean distance)
        -Defines the distance function to be used (see 15.1). -
      • transpose (default: 0)
        -If transpose==0, calculate the distance between the rows of data. If transpose==1, calculate the distance between the columns of data. -
      -

      Performing hierarchical clustering

      To perform hierarchical clustering on the items stored in the record, use -

      >>> tree = record.treecluster()
      -

      where the following arguments are defined: -

      • -transpose (default: 0)
        -Determines if rows (transpose==0) or columns (transpose==1) are to be clustered. -
      • method (default: 'm')
        +
        • +'a': Distance between the two cluster centroids (arithmetic mean); +
        • 'm': Distance between the two cluster centroids (median); +
        • 's': Shortest pairwise distance between items in the two clusters; +
        • 'x': Longest pairwise distance between items in the two clusters; +
        • 'v': Average over the pairwise distances between items in the two clusters. +
        +
      • dist (default: 'e', Euclidean distance)
        +Defines the distance function to be used (see 15.1). +
      • transpose (default: 0)
        +If transpose==0, calculate the distance between the rows of data. If transpose==1, calculate the distance between the columns of data. +
      +

      Performing hierarchical clustering

      To perform hierarchical clustering on the items stored in the record, use +

      >>> tree = record.treecluster()
      +

      where the following arguments are defined: +

      • +transpose (default: 0)
        +Determines if rows (transpose==0) or columns (transpose==1) are to be clustered. +
      • method (default: 'm')
        defines the linkage method to be used: -
        • -method=='s': pairwise single-linkage clustering -
        • method=='m': pairwise maximum- (or complete-) linkage clustering -
        • method=='c': pairwise centroid-linkage clustering -
        • method=='a': pairwise average-linkage clustering -
        -
      • dist (default: 'e', Euclidean distance)
        -Defines the distance function to be used (see 15.1). -
      • transpose
        -Determines if genes or microarrays are being clustered. If transpose==0, genes (rows) are being clustered. If transpose==1, microarrays (columns) are clustered. -

      This function returns a Tree object. This object contains (number of items − 1) nodes, where the number of items is the number of rows if rows were clustered, or the number of columns if columns were clustered. Each node describes a pairwise linking event, where the node attributes left and right each contain the number of one item or subnode, and distance the distance between them. Items are numbered from 0 to (number of items − 1), while clusters are numbered -1 to −(number of items−1).

      -

      Performing k-means or k-medians clustering

      To perform k-means or k-medians clustering on the items stored in the record, use -

      >>> clusterid, error, nfound = record.kcluster()
      -

      where the following arguments are defined: -

      • -nclusters (default: 2)
        -The number of clusters k. -
      • transpose (default: 0)
        -Determines if rows (transpose is 0) or columns (transpose is 1) are to be clustered. -
      • npass (default: 1)
        -The number of times the k-means/-medians clustering algorithm is performed, each time with a different (random) initial condition. If initialid is given, the value of npass is ignored and the clustering algorithm is run only once, as it behaves deterministically in that case. -
      • method (default: a)
        +
        • +method=='s': pairwise single-linkage clustering +
        • method=='m': pairwise maximum- (or complete-) linkage clustering +
        • method=='c': pairwise centroid-linkage clustering +
        • method=='a': pairwise average-linkage clustering +
        +
      • dist (default: 'e', Euclidean distance)
        +Defines the distance function to be used (see 15.1). +
      • transpose
        +Determines if genes or microarrays are being clustered. If transpose==0, genes (rows) are being clustered. If transpose==1, microarrays (columns) are clustered. +

      This function returns a Tree object. This object contains (number of items − 1) nodes, where the number of items is the number of rows if rows were clustered, or the number of columns if columns were clustered. Each node describes a pairwise linking event, where the node attributes left and right each contain the number of one item or subnode, and distance the distance between them. Items are numbered from 0 to (number of items − 1), while clusters are numbered -1 to −(number of items−1).

      +

      Performing k-means or k-medians clustering

      To perform k-means or k-medians clustering on the items stored in the record, use +

      >>> clusterid, error, nfound = record.kcluster()
      +

      where the following arguments are defined: +

      • +nclusters (default: 2)
        +The number of clusters k. +
      • transpose (default: 0)
        +Determines if rows (transpose is 0) or columns (transpose is 1) are to be clustered. +
      • npass (default: 1)
        +The number of times the k-means/-medians clustering algorithm is performed, each time with a different (random) initial condition. If initialid is given, the value of npass is ignored and the clustering algorithm is run only once, as it behaves deterministically in that case. +
      • method (default: a)
        describes how the center of a cluster is found: -
        • -method=='a': arithmetic mean (k-means clustering); -
        • method=='m': median (k-medians clustering). -
        -For other values of method, the arithmetic mean is used. -
      • dist (default: 'e', Euclidean distance)
        -Defines the distance function to be used (see 15.1). -

      This function returns a tuple (clusterid, error, nfound), where clusterid is an integer array containing the number of the cluster to which each row or cluster was assigned, error is the within-cluster sum of distances for the optimal clustering solution, and nfound is the number of times this optimal solution was found.

      -

      Calculating a Self-Organizing Map

      To calculate a Self-Organizing Map of the items stored in the record, use -

      >>> clusterid, celldata = record.somcluster()
      -

      where the following arguments are defined: -

      • -transpose (default: 0)
        -Determines if rows (transpose is 0) or columns (transpose is 1) are to be clustered. -
      • nxgrid, nygrid (default: 2, 1)
        +
        • +method=='a': arithmetic mean (k-means clustering); +
        • method=='m': median (k-medians clustering). +
        +For other values of method, the arithmetic mean is used. +
      • dist (default: 'e', Euclidean distance)
        +Defines the distance function to be used (see 15.1). +

      This function returns a tuple (clusterid, error, nfound), where clusterid is an integer array containing the number of the cluster to which each row or cluster was assigned, error is the within-cluster sum of distances for the optimal clustering solution, and nfound is the number of times this optimal solution was found.

      +

      Calculating a Self-Organizing Map

      To calculate a Self-Organizing Map of the items stored in the record, use +

      >>> clusterid, celldata = record.somcluster()
      +

      where the following arguments are defined: +

      • +transpose (default: 0)
        +Determines if rows (transpose is 0) or columns (transpose is 1) are to be clustered. +
      • nxgrid, nygrid (default: 2, 1)
        The number of cells horizontally and vertically in the rectangular grid on which the Self-Organizing Map is calculated. -
      • inittau (default: 0.02)
        -The initial value for the parameter τ that is used in the SOM algorithm. The default value for inittau is 0.02, which was used in Michael Eisen’s Cluster/TreeView program. -
      • niter (default: 1)
        +
      • inittau (default: 0.02)
        +The initial value for the parameter τ that is used in the SOM algorithm. The default value for inittau is 0.02, which was used in Michael Eisen’s Cluster/TreeView program. +
      • niter (default: 1)
        The number of iterations to be performed. -
      • dist (default: 'e', Euclidean distance)
        -Defines the distance function to be used (see 15.1). -

      This function returns the tuple (clusterid, celldata): -

      • -clusterid:
        -An array with two columns, where the number of rows is equal to the number of items that were clustered. Each row contains the x and y coordinates of the cell in the rectangular SOM grid to which the item was assigned. -
      • celldata:
        -An array with dimensions (nxgrid, nygrid, number of columns) if rows are being clustered, or (nxgrid, nygrid, number of rows) if columns are being clustered. Each element [ix][iy] of this array is a 1D vector containing the gene expression data for the centroid of the cluster in the grid cell with coordinates [ix][iy]. -
      -

      Saving the clustering result

      To save the clustering result, use -

      >>> record.save(jobname, geneclusters, expclusters)
      -

      where the following arguments are defined: -

      • -jobname
        -The string jobname is used as the base name for names of the files that are to be saved. -
      • geneclusters
        -This argument describes the gene (row-wise) clustering result. In case of k-means clustering, this is a 1D array containing the number of the cluster each gene belongs to. It can be calculated using kcluster. In case of hierarchical clustering, geneclusters is a Tree object. -
      • expclusters
        -This argument describes the (column-wise) clustering result for the experimental conditions. In case of k-means clustering, this is a 1D array containing the number of the cluster each experimental condition belongs to. It can be calculated using kcluster. In case of hierarchical clustering, expclusters is a Tree object. -

      This method writes the text file jobname.cdt, jobname.gtr, jobname.atr, jobname*.kgg, and/or jobname*.kag for subsequent reading by the Java TreeView program. If geneclusters and expclusters are both None, this method only writes the text file jobname.cdt; this file can subsequently be read into a new Record object. -

      -

      15.8  Example calculation

      This is an example of a hierarchical clustering calculation, using single linkage clustering for genes and maximum linkage clustering for experimental conditions. As the Euclidean distance is being used for gene clustering, it is necessary to scale the node distances genetree such that they are all between zero and one. This is needed for the Java TreeView code to display the tree diagram correctly. To cluster the experimental conditions, the uncentered correlation is being used. No scaling is needed in this case, as the distances in exptree are already between zero and two. The example data cyano.txt can be found in the data subdirectory.

      >>> from Bio import Cluster
      +
    • dist (default: 'e', Euclidean distance)
      +Defines the distance function to be used (see 15.1). +

    This function returns the tuple (clusterid, celldata): +

    • +clusterid:
      +An array with two columns, where the number of rows is equal to the number of items that were clustered. Each row contains the x and y coordinates of the cell in the rectangular SOM grid to which the item was assigned. +
    • celldata:
      +An array with dimensions (nxgrid, nygrid, number of columns) if rows are being clustered, or (nxgrid, nygrid, number of rows) if columns are being clustered. Each element [ix][iy] of this array is a 1D vector containing the gene expression data for the centroid of the cluster in the grid cell with coordinates [ix][iy]. +
    +

    Saving the clustering result

    To save the clustering result, use +

    >>> record.save(jobname, geneclusters, expclusters)
    +

    where the following arguments are defined: +

    • +jobname
      +The string jobname is used as the base name for names of the files that are to be saved. +
    • geneclusters
      +This argument describes the gene (row-wise) clustering result. In case of k-means clustering, this is a 1D array containing the number of the cluster each gene belongs to. It can be calculated using kcluster. In case of hierarchical clustering, geneclusters is a Tree object. +
    • expclusters
      +This argument describes the (column-wise) clustering result for the experimental conditions. In case of k-means clustering, this is a 1D array containing the number of the cluster each experimental condition belongs to. It can be calculated using kcluster. In case of hierarchical clustering, expclusters is a Tree object. +

    This method writes the text file jobname.cdt, jobname.gtr, jobname.atr, jobname*.kgg, and/or jobname*.kag for subsequent reading by the Java TreeView program. If geneclusters and expclusters are both None, this method only writes the text file jobname.cdt; this file can subsequently be read into a new Record object. +

    + +

    15.8  Example calculation

    This is an example of a hierarchical clustering calculation, using single linkage clustering for genes and maximum linkage clustering for experimental conditions. As the Euclidean distance is being used for gene clustering, it is necessary to scale the node distances genetree such that they are all between zero and one. This is needed for the Java TreeView code to display the tree diagram correctly. To cluster the experimental conditions, the uncentered correlation is being used. No scaling is needed in this case, as the distances in exptree are already between zero and two. The example data cyano.txt can be found in the data subdirectory.

    >>> from Bio import Cluster
     >>> handle = open("cyano.txt")
     >>> record = Cluster.read(handle)
     >>> handle.close()
    @@ -9350,82 +9625,87 @@
     >>> genetree.scale()
     >>> exptree = record.treecluster(dist='u', transpose=1)
     >>> record.save("cyano_result", genetree, exptree)
    -

    This will create the files cyano_result.cdt, cyano_result.gtr, and cyano_result.atr.

    Similarly, we can save a k-means clustering solution:

    >>> from Bio import Cluster
    +

    This will create the files cyano_result.cdt, cyano_result.gtr, and cyano_result.atr.

    Similarly, we can save a k-means clustering solution:

    >>> from Bio import Cluster
     >>> handle = open("cyano.txt")
     >>> record = Cluster.read(handle)
     >>> handle.close()
     >>> (geneclusters, error, ifound) = record.kcluster(nclusters=5, npass=1000)
     >>> (expclusters, error, ifound) = record.kcluster(nclusters=2, npass=100, transpose=1)
     >>> record.save("cyano_result", geneclusters, expclusters)
    -

    This will create the files cyano_result_K_G2_A2.cdt, cyano_result_K_G2.kgg, and cyano_result_K_A2.kag.

    -

    15.9  Auxiliary functions

    median(data) -returns the median of the 1D array data.

    mean(data) -returns the mean of the 1D array data.

    version() -returns the version number of the underlying C Clustering Library as a string.

    -

    Chapter 16  Supervised learning methods

    Note the supervised learning methods described in this chapter all require Numerical Python (numpy) to be installed.

    -

    16.1  The Logistic Regression Model

    -

    -

    16.1.1  Background and Purpose

    Logistic regression is a supervised learning approach that attempts to distinguish K classes from each other using a weighted sum of some predictor variables xi. The logistic regression model is used to calculate the weights βi of the predictor variables. In Biopython, the logistic regression model is currently implemented for two classes only (K = 2); the number of predictor variables has no predefined limit.

    As an example, let’s try to predict the operon structure in bacteria. An operon is a set of adjacent genes on the same strand of DNA that are transcribed into a single mRNA molecule. Translation of the single mRNA molecule then yields the individual proteins. For Bacillus subtilis, whose data we will be using, the average number of genes in an operon is about 2.4.

    As a first step in understanding gene regulation in bacteria, we need to know the operon structure. For about 10% of the genes in Bacillus subtilis, the operon structure is known from experiments. A supervised learning method can be used to predict the operon structure for the remaining 90% of the genes.

    For such a supervised learning approach, we need to choose some predictor variables xi that can be measured easily and are somehow related to the operon structure. One predictor variable might be the distance in base pairs between genes. Adjacent genes belonging to the same operon tend to be separated by a relatively short distance, whereas adjacent genes in different operons tend to have a larger space between them to allow for promoter and terminator sequences. Another predictor variable is based on gene expression measurements. By definition, genes belonging to the same operon have equal gene expression profiles, while genes in different operons are expected to have different expression profiles. In practice, the measured expression profiles of genes in the same operon are not quite identical due to the presence of measurement errors. To assess the similarity in the gene expression profiles, we assume that the measurement errors follow a normal distribution and calculate the corresponding log-likelihood score.

    We now have two predictor variables that we can use to predict if two adjacent genes on the same strand of DNA belong to the same operon: -

    • -x1: the number of base pairs between them; -
    • x2: their similarity in expression profile. -

    In a logistic regression model, we use a weighted sum of these two predictors to calculate a joint score S: -

    -
    -S = β0 + β1 x1 + β2 x2. -    (16.1)

    -The logistic regression model gives us appropriate values for the parameters β0, β1, β2 using two sets of example genes: -

    • +

      This will create the files cyano_result_K_G2_A2.cdt, cyano_result_K_G2.kgg, and cyano_result_K_A2.kag.

      + +

      15.9  Auxiliary functions

      median(data) +returns the median of the 1D array data.

      mean(data) +returns the mean of the 1D array data.

      version() +returns the version number of the underlying C Clustering Library as a string.

      + +

      Chapter 16  Supervised learning methods

      Note the supervised learning methods described in this chapter all require Numerical Python (numpy) to be installed.

      + +

      16.1  The Logistic Regression Model

      +

      + +

      16.1.1  Background and Purpose

      Logistic regression is a supervised learning approach that attempts to distinguish K classes from each other using a weighted sum of some predictor variables xi. The logistic regression model is used to calculate the weights βi of the predictor variables. In Biopython, the logistic regression model is currently implemented for two classes only (K = 2); the number of predictor variables has no predefined limit.

      As an example, let’s try to predict the operon structure in bacteria. An operon is a set of adjacent genes on the same strand of DNA that are transcribed into a single mRNA molecule. Translation of the single mRNA molecule then yields the individual proteins. For Bacillus subtilis, whose data we will be using, the average number of genes in an operon is about 2.4.

      As a first step in understanding gene regulation in bacteria, we need to know the operon structure. For about 10% of the genes in Bacillus subtilis, the operon structure is known from experiments. A supervised learning method can be used to predict the operon structure for the remaining 90% of the genes.

      For such a supervised learning approach, we need to choose some predictor variables xi that can be measured easily and are somehow related to the operon structure. One predictor variable might be the distance in base pairs between genes. Adjacent genes belonging to the same operon tend to be separated by a relatively short distance, whereas adjacent genes in different operons tend to have a larger space between them to allow for promoter and terminator sequences. Another predictor variable is based on gene expression measurements. By definition, genes belonging to the same operon have equal gene expression profiles, while genes in different operons are expected to have different expression profiles. In practice, the measured expression profiles of genes in the same operon are not quite identical due to the presence of measurement errors. To assess the similarity in the gene expression profiles, we assume that the measurement errors follow a normal distribution and calculate the corresponding log-likelihood score.

      We now have two predictor variables that we can use to predict if two adjacent genes on the same strand of DNA belong to the same operon: +

      • +x1: the number of base pairs between them; +
      • x2: their similarity in expression profile. +

      In a logistic regression model, we use a weighted sum of these two predictors to calculate a joint score S: +

      +
      +S = β0 + β1 x1 + β2 x2. +    (16.1)

      +The logistic regression model gives us appropriate values for the parameters β0, β1, β2 using two sets of example genes: +

      • OP: Adjacent genes, on the same strand of DNA, known to belong to the same operon; -
      • NOP: Adjacent genes, on the same strand of DNA, known to belong to different operons. -

      In the logistic regression model, the probability of belonging to a class depends on the score via the logistic function. For the two classes OP and NOP, we can write this as -

      +
      +
    • NOP: Adjacent genes, on the same strand of DNA, known to belong to different operons. +
    • In the logistic regression model, the probability of belonging to a class depends on the score via the logistic function. For the two classes OP and NOP, we can write this as +

      -
            - - -
      Pr(OP|x1x2) = -
        - - -
      exp(β0 + β1 x1 + β2 x2)
      1+exp(β0 + β1 x1 + β2 x2)
         
          (16.2)
      Pr(NOP|x1x2) = -
        - - -
      1
      1+exp(β0 + β1 x1 + β2 x2)
          -
          (16.3)

      -Using a set of gene pairs for which it is known whether they belong to the same operon (class OP) or to different operons (class NOP), we can calculate the weights β0, β1, β2 by maximizing the log-likelihood corresponding to the probability functions (16.2) and (16.3).

      -

      16.1.2  Training the logistic regression model

      -


      -
      -
      -
      Table 16.1: Adjacent gene pairs known to belong to the same operon (class OP) or to different operons (class NOP). Intergene distances are negative if the two genes overlap.
      - - - - - - - - - - - - - - - - - - -
      Gene pairIntergene distance (x1)Gene expression score (x2)Class
      cotJAcotJB-53-200.78OP
      yesKyesL117-267.14OP
      lplAlplB57-163.47OP
      lplBlplC16-190.30OP
      lplClplD11-220.94OP
      lplDyetF85-193.94OP
      yfmTyfmS16-182.71OP
      yfmFyfmE15-180.41OP
      citScitT-26-181.73OP
      citMyflN58-259.87OP
      yfiIyfiJ126-414.53NOP
      lipByfiQ191-249.57NOP
      yfiUyfiV113-265.28NOP
      yfhHyfhI145-312.99NOP
      cotYcotX154-213.83NOP
      yjoBrapA147-380.85NOP
      ptsIsplA93-291.13NOP
      - -
      -

      Table 16.1 lists some of the Bacillus subtilis gene pairs for which the operon structure is known. -Let’s calculate the logistic regression model from these data:

      >>> from Bio import LogisticRegression
      +
      + +
      Pr(OP|x1x2) = +
        + + +
      exp(β0 + β1 x1 + β2 x2)
      1+exp(β0 + β1 x1 + β2 x2)
         
          (16.2)
      Pr(NOP|x1x2) = +
        + + +
      1
      1+exp(β0 + β1 x1 + β2 x2)
          +
          (16.3)

      +Using a set of gene pairs for which it is known whether they belong to the same operon (class OP) or to different operons (class NOP), we can calculate the weights β0, β1, β2 by maximizing the log-likelihood corresponding to the probability functions (16.2) and (16.3).

      + +

      16.1.2  Training the logistic regression model

      +


      +
      +
      +
      Table 16.1: Adjacent gene pairs known to belong to the same operon (class OP) or to different operons (class NOP). Intergene distances are negative if the two genes overlap.
      + + + + + + + + + + + + + + + + + + +
      Gene pairIntergene distance (x1)Gene expression score (x2)Class
      cotJAcotJB-53-200.78OP
      yesKyesL117-267.14OP
      lplAlplB57-163.47OP
      lplBlplC16-190.30OP
      lplClplD11-220.94OP
      lplDyetF85-193.94OP
      yfmTyfmS16-182.71OP
      yfmFyfmE15-180.41OP
      citScitT-26-181.73OP
      citMyflN58-259.87OP
      yfiIyfiJ126-414.53NOP
      lipByfiQ191-249.57NOP
      yfiUyfiV113-265.28NOP
      yfhHyfhI145-312.99NOP
      cotYcotX154-213.83NOP
      yjoBrapA147-380.85NOP
      ptsIsplA93-291.13NOP
      + +
      +

      Table 16.1 lists some of the Bacillus subtilis gene pairs for which the operon structure is known. +Let’s calculate the logistic regression model from these data:

      >>> from Bio import LogisticRegression
       >>> xs = [[-53, -200.78],
                 [117, -267.14],
                 [57, -163.47],
      @@ -9461,11 +9741,11 @@
                 0,
                 0]
       >>> model = LogisticRegression.train(xs, ys)
      -

      Here, xs and ys are the training data: xs contains the predictor variables for each gene pair, and ys specifies if the gene pair belongs to the same operon (1, class OP) or different operons (0, class NOP). The resulting logistic regression model is stored in model, which contains the weights β0, β1, and β2:

      >>> model.beta
      +

      Here, xs and ys are the training data: xs contains the predictor variables for each gene pair, and ys specifies if the gene pair belongs to the same operon (1, class OP) or different operons (0, class NOP). The resulting logistic regression model is stored in model, which contains the weights β0, β1, and β2:

      >>> model.beta
       [8.9830290157144681, -0.035968960444850887, 0.02181395662983519]
      -

      Note that β1 is negative, as gene pairs with a shorter intergene distance have a higher probability of belonging to the same operon (class OP). On the other hand, β2 is positive, as gene pairs belonging to the same operon typically have a higher similarity score of their gene expression profiles. -The parameter β0 is positive due to the higher prevalence of operon gene pairs than non-operon gene pairs in the training data.

      The function train has two optional arguments: update_fn and typecode. The update_fn can be used to specify a callback function, taking as arguments the iteration number and the log-likelihood. With the callback function, we can for example track the progress of the model calculation (which uses a Newton-Raphson iteration to maximize the log-likelihood function of the logistic regression model):

      >>> def show_progress(iteration, loglikelihood):
      -        print "Iteration:", iteration, "Log-likelihood function:", loglikelihood
      +

      Note that β1 is negative, as gene pairs with a shorter intergene distance have a higher probability of belonging to the same operon (class OP). On the other hand, β2 is positive, as gene pairs belonging to the same operon typically have a higher similarity score of their gene expression profiles. +The parameter β0 is positive due to the higher prevalence of operon gene pairs than non-operon gene pairs in the training data.

      The function train has two optional arguments: update_fn and typecode. The update_fn can be used to specify a callback function, taking as arguments the iteration number and the log-likelihood. With the callback function, we can for example track the progress of the model calculation (which uses a Newton-Raphson iteration to maximize the log-likelihood function of the logistic regression model):

      >>> def show_progress(iteration, loglikelihood):
      +        print("Iteration:", iteration, "Log-likelihood function:", loglikelihood)
       >>>
       >>> model = LogisticRegression.train(xs, ys, update_fn=show_progress)
       Iteration: 0 Log-likelihood function: -11.7835020695
      @@ -9510,32 +9790,33 @@
       Iteration: 39 Log-likelihood function: -3.00441242601
       Iteration: 40 Log-likelihood function: -2.99406722296
       Iteration: 41 Log-likelihood function: -2.98413867259
      -

      The iteration stops once the increase in the log-likelihood function is less than 0.01. If no convergence is reached after 500 iterations, the train function returns with an AssertionError.

      The optional keyword typecode can almost always be ignored. This keyword allows the user to choose the type of Numeric matrix to use. In particular, to avoid memory problems for very large problems, it may be necessary to use single-precision floats (Float8, Float16, etc.) rather than double, which is used by default.

      -

      16.1.3  Using the logistic regression model for classification

      Classification is performed by calling the classify function. Given a logistic regression model and the values for x1 and x2 (e.g. for a gene pair of unknown operon structure), the classify function returns 1 or 0, corresponding to class OP and class NOP, respectively. For example, let’s consider the gene pairs yxcE, yxcD and yxiB, yxiA:


      -
      -
      -
      Table 16.2: Adjacent gene pairs of unknown operon status.
      - - - -
      Gene pairIntergene distance x1Gene expression score x2
      yxcEyxcD6-173.143442352
      yxiByxiA309-271.005880394
      -
      -

      The logistic regression model classifies yxcE, yxcD as belonging to the same operon (class OP), while yxiB, yxiA are predicted to belong to different operons: -

      >>> print "yxcE, yxcD:", LogisticRegression.classify(model, [6,-173.143442352])
      +

      The iteration stops once the increase in the log-likelihood function is less than 0.01. If no convergence is reached after 500 iterations, the train function returns with an AssertionError.

      The optional keyword typecode can almost always be ignored. This keyword allows the user to choose the type of Numeric matrix to use. In particular, to avoid memory problems for very large problems, it may be necessary to use single-precision floats (Float8, Float16, etc.) rather than double, which is used by default.

      + +

      16.1.3  Using the logistic regression model for classification

      Classification is performed by calling the classify function. Given a logistic regression model and the values for x1 and x2 (e.g. for a gene pair of unknown operon structure), the classify function returns 1 or 0, corresponding to class OP and class NOP, respectively. For example, let’s consider the gene pairs yxcE, yxcD and yxiB, yxiA:


      +
      +
      +
      Table 16.2: Adjacent gene pairs of unknown operon status.
      + + + +
      Gene pairIntergene distance x1Gene expression score x2
      yxcEyxcD6-173.143442352
      yxiByxiA309-271.005880394
      +
      +

      The logistic regression model classifies yxcE, yxcD as belonging to the same operon (class OP), while yxiB, yxiA are predicted to belong to different operons: +

      >>> print("yxcE, yxcD:", LogisticRegression.classify(model, [6, -173.143442352]))
       yxcE, yxcD: 1
      ->>> print "yxiB, yxiA:", LogisticRegression.classify(model, [309, -271.005880394])
      +>>> print("yxiB, yxiA:", LogisticRegression.classify(model, [309, -271.005880394]))
       yxiB, yxiA: 0
      -

      (which, by the way, agrees with the biological literature).

      To find out how confident we can be in these predictions, we can call the calculate function to obtain the probabilities (equations (16.2) and 16.3) for class OP and NOP. For yxcE, yxcD we find -

      >>> q, p = LogisticRegression.calculate(model, [6,-173.143442352])
      ->>> print "class OP: probability =", p, "class NOP: probability =", q
      +

      (which, by the way, agrees with the biological literature).

      To find out how confident we can be in these predictions, we can call the calculate function to obtain the probabilities (equations (16.2) and 16.3) for class OP and NOP. For yxcE, yxcD we find +

      >>> q, p = LogisticRegression.calculate(model, [6, -173.143442352])
      +>>> print("class OP: probability =", p, "class NOP: probability =", q)
       class OP: probability = 0.993242163503 class NOP: probability = 0.00675783649744
      -

      and for yxiB, yxiA -

      >>> q, p = LogisticRegression.calculate(model, [309, -271.005880394])
      ->>> print "class OP: probability =", p, "class NOP: probability =", q
      +

      and for yxiB, yxiA +

      >>> q, p = LogisticRegression.calculate(model, [309, -271.005880394])
      +>>> print("class OP: probability =", p, "class NOP: probability =", q)
       class OP: probability = 0.000321211251817 class NOP: probability = 0.999678788748
      -

      To get some idea of the prediction accuracy of the logistic regression model, we can apply it to the training data: -

      >>> for i in range(len(ys)):
      -        print "True:", ys[i], "Predicted:", LogisticRegression.classify(model, xs[i])
      +

      To get some idea of the prediction accuracy of the logistic regression model, we can apply it to the training data: +

      >>> for i in range(len(ys)):
      +        print("True:", ys[i], "Predicted:", LogisticRegression.classify(model, xs[i]))
       True: 1 Predicted: 1
       True: 1 Predicted: 0
       True: 1 Predicted: 1
      @@ -9553,10 +9834,10 @@
       True: 0 Predicted: 0
       True: 0 Predicted: 0
       True: 0 Predicted: 0
      -

      showing that the prediction is correct for all but one of the gene pairs. A more reliable estimate of the prediction accuracy can be found from a leave-one-out analysis, in which the model is recalculated from the training data after removing the gene to be predicted: -

      >>> for i in range(len(ys)):
      +

      showing that the prediction is correct for all but one of the gene pairs. A more reliable estimate of the prediction accuracy can be found from a leave-one-out analysis, in which the model is recalculated from the training data after removing the gene to be predicted: +

      >>> for i in range(len(ys)):
               model = LogisticRegression.train(xs[:i]+xs[i+1:], ys[:i]+ys[i+1:])
      -        print "True:", ys[i], "Predicted:", LogisticRegression.classify(model, xs[i])
      +        print("True:", ys[i], "Predicted:", LogisticRegression.classify(model, xs[i]))
       True: 1 Predicted: 1
       True: 1 Predicted: 0
       True: 1 Predicted: 1
      @@ -9574,50 +9855,55 @@
       True: 0 Predicted: 1
       True: 0 Predicted: 0
       True: 0 Predicted: 0
      -

      The leave-one-out analysis shows that the prediction of the logistic regression model is incorrect for only two of the gene pairs, which corresponds to a prediction accuracy of 88%.

      -

      16.1.4  Logistic Regression, Linear Discriminant Analysis, and Support Vector Machines

      The logistic regression model is similar to linear discriminant analysis. In linear discriminant analysis, the class probabilities also follow equations (16.2) and (16.3). However, instead of estimating the coefficients β directly, we first fit a normal distribution to the predictor variables x. The coefficients β are then calculated from the means and covariances of the normal distribution. If the distribution of x is indeed normal, then we expect linear discriminant analysis to perform better than the logistic regression model. The logistic regression model, on the other hand, is more robust to deviations from normality.

      Another similar approach is a support vector machine with a linear kernel. Such an SVM also uses a linear combination of the predictors, but estimates the coefficients β from the predictor variables x near the boundary region between the classes. If the logistic regression model (equations (16.2) and (16.3)) is a good description for x away from the boundary region, we expect the logistic regression model to perform better than an SVM with a linear kernel, as it relies on more data. If not, an SVM with a linear kernel may perform better.

      Trevor Hastie, Robert Tibshirani, and Jerome Friedman: The Elements of Statistical Learning. Data Mining, Inference, and Prediction. Springer Series in Statistics, 2001. Chapter 4.4.

      -

      16.2  k-Nearest Neighbors

      -

      16.2.1  Background and purpose

      The k-nearest neighbors method is a supervised learning approach that does not need to fit a model to the data. Instead, data points are classified based on the categories of the k nearest neighbors in the training data set.

      In Biopython, the k-nearest neighbors method is available in Bio.kNN. To illustrate the use of the k-nearest neighbor method in Biopython, we will use the same operon data set as in section 16.1.

      -

      16.2.2  Initializing a k-nearest neighbors model

      Using the data in Table 16.1, we create and initialize a k-nearest neighbors model as follows:

      >>> from Bio import kNN
      +

      The leave-one-out analysis shows that the prediction of the logistic regression model is incorrect for only two of the gene pairs, which corresponds to a prediction accuracy of 88%.

      + +

      16.1.4  Logistic Regression, Linear Discriminant Analysis, and Support Vector Machines

      The logistic regression model is similar to linear discriminant analysis. In linear discriminant analysis, the class probabilities also follow equations (16.2) and (16.3). However, instead of estimating the coefficients β directly, we first fit a normal distribution to the predictor variables x. The coefficients β are then calculated from the means and covariances of the normal distribution. If the distribution of x is indeed normal, then we expect linear discriminant analysis to perform better than the logistic regression model. The logistic regression model, on the other hand, is more robust to deviations from normality.

      Another similar approach is a support vector machine with a linear kernel. Such an SVM also uses a linear combination of the predictors, but estimates the coefficients β from the predictor variables x near the boundary region between the classes. If the logistic regression model (equations (16.2) and (16.3)) is a good description for x away from the boundary region, we expect the logistic regression model to perform better than an SVM with a linear kernel, as it relies on more data. If not, an SVM with a linear kernel may perform better.

      Trevor Hastie, Robert Tibshirani, and Jerome Friedman: The Elements of Statistical Learning. Data Mining, Inference, and Prediction. Springer Series in Statistics, 2001. Chapter 4.4.

      + +

      16.2  k-Nearest Neighbors

      + +

      16.2.1  Background and purpose

      The k-nearest neighbors method is a supervised learning approach that does not need to fit a model to the data. Instead, data points are classified based on the categories of the k nearest neighbors in the training data set.

      In Biopython, the k-nearest neighbors method is available in Bio.kNN. To illustrate the use of the k-nearest neighbor method in Biopython, we will use the same operon data set as in section 16.1.

      + +

      16.2.2  Initializing a k-nearest neighbors model

      Using the data in Table 16.1, we create and initialize a k-nearest neighbors model as follows:

      >>> from Bio import kNN
       >>> k = 3
       >>> model = kNN.train(xs, ys, k)
      -

      where xs and ys are the same as in Section 16.1.2. Here, k is the number of neighbors k that will be considered for the classification. For classification into two classes, choosing an odd number for k lets you avoid tied votes. The function name train is a bit of a misnomer, since no model training is done: this function simply stores xs, ys, and k in model.

      -

      16.2.3  Using a k-nearest neighbors model for classification

      To classify new data using the k-nearest neighbors model, we use the classify function. This function takes a data point (x1,x2) and finds the k-nearest neighbors in the training data set xs. The data point (x1, x2) is then classified based on which category (ys) occurs most among the k neighbors.

      For the example of the gene pairs yxcE, yxcD and yxiB, yxiA, we find: -

      >>> x = [6, -173.143442352]
      ->>> print "yxcE, yxcD:", kNN.classify(model, x)
      +

      where xs and ys are the same as in Section 16.1.2. Here, k is the number of neighbors k that will be considered for the classification. For classification into two classes, choosing an odd number for k lets you avoid tied votes. The function name train is a bit of a misnomer, since no model training is done: this function simply stores xs, ys, and k in model.

      + +

      16.2.3  Using a k-nearest neighbors model for classification

      To classify new data using the k-nearest neighbors model, we use the classify function. This function takes a data point (x1,x2) and finds the k-nearest neighbors in the training data set xs. The data point (x1, x2) is then classified based on which category (ys) occurs most among the k neighbors.

      For the example of the gene pairs yxcE, yxcD and yxiB, yxiA, we find: +

      >>> x = [6, -173.143442352]
      +>>> print("yxcE, yxcD:", kNN.classify(model, x))
       yxcE, yxcD: 1
       >>> x = [309, -271.005880394]
      ->>> print "yxiB, yxiA:", kNN.classify(model, x)
      +>>> print("yxiB, yxiA:", kNN.classify(model, x))
       yxiB, yxiA: 0
      -

      In agreement with the logistic regression model, yxcE, yxcD are classified as belonging to the same operon (class OP), while yxiB, yxiA are predicted to belong to different operons.

      The classify function lets us specify both a distance function and a weight function as optional arguments. The distance function affects which k neighbors are chosen as the nearest neighbors, as these are defined as the neighbors with the smallest distance to the query point (x, y). By default, the Euclidean distance is used. Instead, we could for example use the city-block (Manhattan) distance:

      >>> def cityblock(x1, x2):
      +

      In agreement with the logistic regression model, yxcE, yxcD are classified as belonging to the same operon (class OP), while yxiB, yxiA are predicted to belong to different operons.

      The classify function lets us specify both a distance function and a weight function as optional arguments. The distance function affects which k neighbors are chosen as the nearest neighbors, as these are defined as the neighbors with the smallest distance to the query point (x, y). By default, the Euclidean distance is used. Instead, we could for example use the city-block (Manhattan) distance:

      >>> def cityblock(x1, x2):
       ...    assert len(x1)==2
       ...    assert len(x2)==2
       ...    distance = abs(x1[0]-x2[0]) + abs(x1[1]-x2[1])
       ...    return distance
      -...
      +... 
       >>> x = [6, -173.143442352]
      ->>> print "yxcE, yxcD:", kNN.classify(model, x, distance_fn = cityblock)
      +>>> print("yxcE, yxcD:", kNN.classify(model, x, distance_fn = cityblock))
       yxcE, yxcD: 1
      -

      The weight function can be used for weighted voting. For example, we may want to give closer neighbors a higher weight than neighbors that are further away:

      >>> def weight(x1, x2):
      +

      The weight function can be used for weighted voting. For example, we may want to give closer neighbors a higher weight than neighbors that are further away:

      >>> def weight(x1, x2):
       ...    assert len(x1)==2
       ...    assert len(x2)==2
       ...    return exp(-abs(x1[0]-x2[0]) - abs(x1[1]-x2[1]))
      -...
      +... 
       >>> x = [6, -173.143442352]
      ->>> print "yxcE, yxcD:", kNN.classify(model, x, weight_fn = weight)
      +>>> print("yxcE, yxcD:", kNN.classify(model, x, weight_fn = weight))
       yxcE, yxcD: 1
      -

      By default, all neighbors are given an equal weight.

      To find out how confident we can be in these predictions, we can call the calculate function, which will calculate the total weight assigned to the classes OP and NOP. For the default weighting scheme, this reduces to the number of neighbors in each category. For yxcE, yxcD, we find -

      >>> x = [6, -173.143442352]
      +

      By default, all neighbors are given an equal weight.

      To find out how confident we can be in these predictions, we can call the calculate function, which will calculate the total weight assigned to the classes OP and NOP. For the default weighting scheme, this reduces to the number of neighbors in each category. For yxcE, yxcD, we find +

      >>> x = [6, -173.143442352]
       >>> weight = kNN.calculate(model, x)
      ->>> print "class OP: weight =", weight[0], "class NOP: weight =", weight[1]
      +>>> print("class OP: weight =", weight[0], "class NOP: weight =", weight[1])
       class OP: weight = 0.0 class NOP: weight = 3.0
      -

      which means that all three neighbors of x1, x2 are in the NOP class. As another example, for yesK, yesL we find

      >>> x = [117, -267.14]
      +

      which means that all three neighbors of x1, x2 are in the NOP class. As another example, for yesK, yesL we find

      >>> x = [117, -267.14]
       >>> weight = kNN.calculate(model, x)
      ->>> print "class OP: weight =", weight[0], "class NOP: weight =", weight[1]
      +>>> print("class OP: weight =", weight[0], "class NOP: weight =", weight[1])
       class OP: weight = 2.0 class NOP: weight = 1.0
      -

      which means that two neighbors are operon pairs and one neighbor is a non-operon pair.

      To get some idea of the prediction accuracy of the k-nearest neighbors approach, we can apply it to the training data: -

      >>> for i in range(len(ys)):
      -        print "True:", ys[i], "Predicted:", kNN.classify(model, xs[i])
      +

      which means that two neighbors are operon pairs and one neighbor is a non-operon pair.

      To get some idea of the prediction accuracy of the k-nearest neighbors approach, we can apply it to the training data: +

      >>> for i in range(len(ys)):
      +        print("True:", ys[i], "Predicted:", kNN.classify(model, xs[i]))
       True: 1 Predicted: 1
       True: 1 Predicted: 0
       True: 1 Predicted: 1
      @@ -9635,10 +9921,10 @@
       True: 0 Predicted: 0
       True: 0 Predicted: 0
       True: 0 Predicted: 0
      -

      showing that the prediction is correct for all but two of the gene pairs. A more reliable estimate of the prediction accuracy can be found from a leave-one-out analysis, in which the model is recalculated from the training data after removing the gene to be predicted: -

      >>> for i in range(len(ys)):
      +

      showing that the prediction is correct for all but two of the gene pairs. A more reliable estimate of the prediction accuracy can be found from a leave-one-out analysis, in which the model is recalculated from the training data after removing the gene to be predicted: +

      >>> for i in range(len(ys)):
               model = kNN.train(xs[:i]+xs[i+1:], ys[:i]+ys[i+1:])
      -        print "True:", ys[i], "Predicted:", kNN.classify(model, xs[i])
      +        print("True:", ys[i], "Predicted:", kNN.classify(model, xs[i]))
       True: 1 Predicted: 1
       True: 1 Predicted: 0
       True: 1 Predicted: 1
      @@ -9656,71 +9942,79 @@
       True: 0 Predicted: 0
       True: 0 Predicted: 0
       True: 0 Predicted: 1
      -

      The leave-one-out analysis shows that k-nearest neighbors model is correct for 13 out of 17 gene pairs, which corresponds to a prediction accuracy of 76%.

      -

      16.3  Naïve Bayes

      This section will describe the Bio.NaiveBayes module.

      -

      16.4  Maximum Entropy

      This section will describe the Bio.MaximumEntropy module.

      -

      16.5  Markov Models

      This section will describe the Bio.MarkovModel and/or Bio.HMM.MarkovModel modules.

      -

      Chapter 17  Graphics including GenomeDiagram

      -

      The Bio.Graphics module depends on the third party Python library -ReportLab. Although focused on producing PDF files, +

      The leave-one-out analysis shows that k-nearest neighbors model is correct for 13 out of 17 gene pairs, which corresponds to a prediction accuracy of 76%.

      + +

      16.3  Naïve Bayes

      This section will describe the Bio.NaiveBayes module.

      + +

      16.4  Maximum Entropy

      This section will describe the Bio.MaximumEntropy module.

      + +

      16.5  Markov Models

      This section will describe the Bio.MarkovModel and/or Bio.HMM.MarkovModel modules.

      + +

      Chapter 17  Graphics including GenomeDiagram

      +

      The Bio.Graphics module depends on the third party Python library +ReportLab. Although focused on producing PDF files, ReportLab can also create encapsulated postscript (EPS) and (SVG) files. In addition to these vector based images, provided certain further dependencies such as the -Python Imaging Library (PIL) are +Python Imaging Library (PIL) are installed, ReportLab can also output bitmap images (including JPEG, PNG, GIF, BMP -and PICT formats).

      -

      17.1  GenomeDiagram

      - -

      -

      17.1.1  Introduction

      The Bio.Graphics.GenomeDiagram module was added to Biopython 1.50, +and PICT formats).

      + +

      17.1  GenomeDiagram

      + +

      + +

      17.1.1  Introduction

      The Bio.Graphics.GenomeDiagram module was added to Biopython 1.50, having previously been available as a separate Python module dependent on Biopython. -GenomeDiagram is described in the Bioinformatics journal publication by Pritchard et al. (2006) [2], +GenomeDiagram is described in the Bioinformatics journal publication by Pritchard et al. (2006) [2], which includes some examples images. There is a PDF copy of the old manual here, -http://biopython.org/DIST/docs/GenomeDiagram/userguide.pdf which has some +http://biopython.org/DIST/docs/GenomeDiagram/userguide.pdf which has some more examples. -

      As the name might suggest, GenomeDiagram was designed for drawing whole genomes, in +

      As the name might suggest, GenomeDiagram was designed for drawing whole genomes, in particular prokaryotic genomes, either as linear diagrams (optionally broken up into fragments to fit better) or as circular wheel diagrams. Have a look at Figure 2 in -Toth et al. (2006) [3] +Toth et al. (2006) [3] for a good example. It proved also well suited to drawing quite detailed figures for smaller genomes such as phage, plasmids or mitochrondia, for example see Figures 1 -and 2 in Van der Auwera et al. (2009) [4] -(shown with additional manual editing).

      This module is easiest to use if you have your genome loaded as a SeqRecord -object containing lots of SeqFeature objects - for example as loaded from a -GenBank file (see Chapters 4 and 5).

      -

      17.1.2  Diagrams, tracks, feature-sets and features

      GenomeDiagram uses a nested set of objects. At the top level, you have a diagram +and 2 in Van der Auwera et al. (2009) [4] +(shown with additional manual editing).

      This module is easiest to use if you have your genome loaded as a SeqRecord +object containing lots of SeqFeature objects - for example as loaded from a +GenBank file (see Chapters 4 and 5).

      + +

      17.1.2  Diagrams, tracks, feature-sets and features

      GenomeDiagram uses a nested set of objects. At the top level, you have a diagram object representing a sequence (or sequence region) along the horizontal axis (or circle). A diagram can contain one or more tracks, shown stacked vertically (or radially on circular diagrams). These will typically all have the same length and represent the same sequence region. You might use one track to show the gene locations, another to show regulatory regions, and a third track to show the GC -percentage.

      The most commonly used type of track will contain features, bundled together in +percentage.

      The most commonly used type of track will contain features, bundled together in feature-sets. You might choose to use one feature-set for all your CDS features, and another for tRNA features. This isn’t required - they can all go in the same feature-set, but it makes it easier to update the properties of just selected -features (e.g. make all the tRNA features red).

      There are two main ways to build up a complete diagram. Firstly, the top down +features (e.g. make all the tRNA features red).

      There are two main ways to build up a complete diagram. Firstly, the top down approach where you create a diagram object, and then using its methods add track(s), and use the track methods to add feature-set(s), and use their methods to add the features. Secondly, you can create the individual objects -separately (in whatever order suits your code), and then combine them.

      -

      17.1.3  A top down example

      -

      We’re going to draw a whole genome from a SeqRecord object read in from -a GenBank file (see Chapter 5). This example uses the -pPCP1 plasmid from Yersinia pestis biovar Microtus, the file is +separately (in whatever order suits your code), and then combine them.

      + +

      17.1.3  A top down example

      +

      We’re going to draw a whole genome from a SeqRecord object read in from +a GenBank file (see Chapter 5). This example uses the +pPCP1 plasmid from Yersinia pestis biovar Microtus, the file is included with the Biopython unit tests under the GenBank folder, or online -NC_005816.gb from our website.

      from reportlab.lib import colors
      +NC_005816.gb from our website.

      from reportlab.lib import colors
       from reportlab.lib.units import cm
       from Bio.Graphics import GenomeDiagram
       from Bio import SeqIO
       record = SeqIO.read("NC_005816.gb", "genbank")
      -

      We’re using a top down approach, so after loading in our sequence we next +

      We’re using a top down approach, so after loading in our sequence we next create an empty diagram, then add an (empty) track, and to that add an -(empty) feature set:

      gd_diagram = GenomeDiagram.Diagram("Yersinia pestis biovar Microtus plasmid pPCP1")
      +(empty) feature set:

      gd_diagram = GenomeDiagram.Diagram("Yersinia pestis biovar Microtus plasmid pPCP1")
       gd_track_for_features = gd_diagram.new_track(1, name="Annotated Features")
       gd_feature_set = gd_track_for_features.new_set()
      -

      Now the fun part - we take each gene SeqFeature object in our -SeqRecord, and use it to generate a feature on the diagram. We’re +

      Now the fun part - we take each gene SeqFeature object in our +SeqRecord, and use it to generate a feature on the diagram. We’re going to color them blue, alternating between a dark blue and a light blue. -

      for feature in record.features:
      +

      for feature in record.features:
           if feature.type != "gene":
               #Exclude this feature
               continue
      @@ -9729,31 +10023,32 @@
           else:
               color = colors.lightblue
           gd_feature_set.add_feature(feature, color=color, label=True)
      -

      Now we come to actually making the output file. This happens in two steps, -first we call the draw method, which creates all the shapes using -ReportLab objects. Then we call the write method which renders these -to the requested file format. Note you can output in multiple file formats:

      gd_diagram.draw(format="linear", orientation="landscape", pagesize='A4',
      +

      Now we come to actually making the output file. This happens in two steps, +first we call the draw method, which creates all the shapes using +ReportLab objects. Then we call the write method which renders these +to the requested file format. Note you can output in multiple file formats:

      gd_diagram.draw(format="linear", orientation="landscape", pagesize='A4',
                       fragments=4, start=0, end=len(record))
       gd_diagram.write("plasmid_linear.pdf", "PDF")
       gd_diagram.write("plasmid_linear.eps", "EPS")
       gd_diagram.write("plasmid_linear.svg", "SVG")
      -

      Also, provided you have the dependencies installed, you can also do bitmaps, -for example:

      gd_diagram.write("plasmid_linear.png", "PNG")
      -

      -

      +

      Also, provided you have the dependencies installed, you can also do bitmaps, +for example:

      gd_diagram.write("plasmid_linear.png", "PNG")
      +

      +

      -Notice that the fragments argument which we set to four controls how -many pieces the genome gets broken up into.

      If you want to do a circular figure, then try this:

      gd_diagram.draw(format="circular", circular=True, pagesize=(20*cm,20*cm),
      +Notice that the fragments argument which we set to four controls how
      +many pieces the genome gets broken up into.

      If you want to do a circular figure, then try this:

      gd_diagram.draw(format="circular", circular=True, pagesize=(20*cm,20*cm),
                       start=0, end=len(record), circle_core=0.7)
       gd_diagram.write("plasmid_circular.pdf", "PDF")
      -

      -

      +

      +

      -These figures are not very exciting, but we’ve only just got started.

      -

      17.1.4  A bottom up example

      +These figures are not very exciting, but we’ve only just got started.

      + +

      17.1.4  A bottom up example

      Now let’s produce exactly the same figures, but using the bottom up approach. This means we create the different objects directly (and this can be done in -almost any order) and then combine them.

      from reportlab.lib import colors
      +almost any order) and then combine them.

      from reportlab.lib import colors
       from reportlab.lib.units import cm
       from Bio.Graphics import GenomeDiagram
       from Bio import SeqIO
      @@ -9779,19 +10074,20 @@
       #Now have to glue the bits together...
       gd_track_for_features.add_set(gd_feature_set)
       gd_diagram.add_track(gd_track_for_features, 1)
      -

      You can now call the draw and write methods as before to produce +

      You can now call the draw and write methods as before to produce a linear or circular diagram, using the code at the end of the top-down example -above. The figures should be identical.

      -

      17.1.5  Features without a SeqFeature

      -

      In the above example we used a SeqRecord’s SeqFeature objects -to build our diagram (see also Section 4.3). -Sometimes you won’t have SeqFeature objects, +above. The figures should be identical.

      + +

      17.1.5  Features without a SeqFeature

      +

      In the above example we used a SeqRecord’s SeqFeature objects +to build our diagram (see also Section 4.3). +Sometimes you won’t have SeqFeature objects, but just the coordinates for a feature you want to draw. You have to create -minimal SeqFeature object, but this is easy:

      from Bio.SeqFeature import SeqFeature, FeatureLocation
      +minimal SeqFeature object, but this is easy:

      from Bio.SeqFeature import SeqFeature, FeatureLocation
       my_seq_feature = SeqFeature(FeatureLocation(50,100),strand=+1)
      -

      For strand, use +1 for the forward strand, -1 for the -reverse strand, and None for both. Here is a short self contained -example:

      from Bio.SeqFeature import SeqFeature, FeatureLocation
      +

      For strand, use +1 for the forward strand, -1 for the +reverse strand, and None for both. Here is a short self contained +example:

      from Bio.SeqFeature import SeqFeature, FeatureLocation
       from Bio.Graphics import GenomeDiagram
       from reportlab.lib.units import cm
       
      @@ -9810,24 +10106,25 @@
       gdd.draw(format='linear', pagesize=(15*cm,4*cm), fragments=1,
                start=0, end=400)
       gdd.write("GD_labels_default.pdf", "pdf")
      -

      +

      The top part of the image in the next subsection shows the output -(in the default feature color, pale green).

      Notice that we have used the name argument here to specify the -caption text for these features. This is discussed in more detail next.

      -

      17.1.6  Feature captions

      -

      Recall we used the following (where feature was a -SeqFeature object) to add a feature to the diagram:

      gd_feature_set.add_feature(feature, color=color, label=True)
      -

      In the example above the SeqFeature annotation was used to pick a +(in the default feature color, pale green).

      Notice that we have used the name argument here to specify the +caption text for these features. This is discussed in more detail next.

      + +

      17.1.6  Feature captions

      +

      Recall we used the following (where feature was a +SeqFeature object) to add a feature to the diagram:

      gd_feature_set.add_feature(feature, color=color, label=True)
      +

      In the example above the SeqFeature annotation was used to pick a sensible caption for the features. By default the following possible entries -under the SeqFeature object’s qualifiers dictionary are used: -gene, label, name, locus_tag, and -product. More simply, you can specify a name directly:

      gd_feature_set.add_feature(feature, color=color, label=True, name="My Gene")
      -

      In addition to the caption text for each feature’s label, you can also choose +under the SeqFeature object’s qualifiers dictionary are used: +gene, label, name, locus_tag, and +product. More simply, you can specify a name directly:

      gd_feature_set.add_feature(feature, color=color, label=True, name="My Gene")
      +

      In addition to the caption text for each feature’s label, you can also choose the font, position (this defaults to the start of the sigil, you can also choose the middle or at the end) and orientation (for linear diagrams only, -where this defaults to rotated by 45 degrees):

      #Large font, parallel with the track
      +where this defaults to rotated by 45 degrees):

      #Large font, parallel with the track
       gd_feature_set.add_feature(feature, label=True, color="green",
                                  label_size=25, label_angle=0)
       
      @@ -9840,18 +10137,19 @@
       gd_feature_set.add_feature(feature, label=True, color="blue",
                                  label_position="middle",
                                  label_size=6, label_angle=-90)
      -

      Combining each of these three fragments with the complete example +

      Combining each of these three fragments with the complete example in the previous section should give something like -this:

      -

      We’ve not shown it here, but you can also set label_color to -control the label’s color (used in Section 17.1.9).

      You’ll notice the default font is quite small - this makes sense because +this:

      +

      We’ve not shown it here, but you can also set label_color to +control the label’s color (used in Section 17.1.9).

      You’ll notice the default font is quite small - this makes sense because you will usually be drawing many (small) features on a page, not just a -few large ones as shown here.

      -

      17.1.7  Feature sigils

      -

      The examples above have all just used the default sigil for the feature, a +few large ones as shown here.

      + +

      17.1.7  Feature sigils

      +

      The examples above have all just used the default sigil for the feature, a plain box, which was all that was available in the last publicly released standalone version of GenomeDiagram. Arrow sigils were included when -GenomeDiagram was added to Biopython 1.50:

      #Default uses a BOX sigil
      +GenomeDiagram was added to Biopython 1.50:

      #Default uses a BOX sigil
       gd_feature_set.add_feature(feature)
       
       #You can make this explicit:
      @@ -9859,7 +10157,7 @@
       
       #Or opt for an arrow:
       gd_feature_set.add_feature(feature, sigil="ARROW")
      -

      Biopython 1.61 added three more sigils,

      #Box with corners cut off (making it an octagon)
      +

      Biopython 1.61 added three more sigils,

      #Box with corners cut off (making it an octagon)
       gd_feature_set.add_feature(feature, sigil="OCTO")
       
       #Box with jagged edges (useful for showing breaks in contains)
      @@ -9867,7 +10165,7 @@
       
       #Arrow which spans the axis with strand used only for direction
       gd_feature_set.add_feature(feature, sigil="BIGARROW")
      -

      These are shown +

      These are shown below. @@ -9876,15 +10174,16 @@ either above or below the axis for the forward or reverse strand, or straddling it (double the height) for strand-less features. The BIGARROW sigil is different, always straddling the axis with the -direction taken from the feature’s stand.

      - +direction taken from the feature’s stand.

      + -

      -

      17.1.8  Arrow sigils

      -

      We introduced the arrow sigils in the previous section. +

      + +

      17.1.8  Arrow sigils

      +

      We introduced the arrow sigils in the previous section. There are two additional options to adjust the shapes of the arrows, firstly the thickness of the arrow shaft, given as a proportion of the height of the -bounding box:

      #Full height shafts, giving pointed boxes:
      +bounding box:

      #Full height shafts, giving pointed boxes:
       gd_feature_set.add_feature(feature, sigil="ARROW", color="brown",
                                  arrowshaft_height=1.0)
       #Or, thin shafts:                      
      @@ -9893,9 +10192,9 @@
       #Or, very thin shafts:
       gd_feature_set.add_feature(feature, sigil="ARROW", color="darkgreen",
                                  arrowshaft_height=0.1)
      -

      -The results are shown below:

      Secondly, the length of the arrow head - given as a proportion of the height -of the bounding box (defaulting to 0.5, or 50%):

      #Short arrow heads:
      +

      +The results are shown below:

      Secondly, the length of the arrow head - given as a proportion of the height +of the bounding box (defaulting to 0.5, or 50%):

      #Short arrow heads:
       gd_feature_set.add_feature(feature, sigil="ARROW", color="blue",
                                  arrowhead_length=0.25)
       #Or, longer arrow heads:
      @@ -9904,18 +10203,19 @@
       #Or, very very long arrow heads (i.e. all head, no shaft, so triangles):
       gd_feature_set.add_feature(feature, sigil="ARROW", color="red",
                                  arrowhead_length=10000)
      -

      -The results are shown below:

      Biopython 1.61 adds a new BIGARROW sigil which always stradles -the axis, pointing left for the reverse strand or right otherwise:

      #A large arrow straddling the axis:
      +

      +The results are shown below:

      Biopython 1.61 adds a new BIGARROW sigil which always stradles +the axis, pointing left for the reverse strand or right otherwise:

      #A large arrow straddling the axis:
       gd_feature_set.add_feature(feature, sigil="BIGARROW")
      -

      All the shaft and arrow head options shown above for the -ARROW sigil can be used for the BIGARROW sigil too.

      -

      17.1.9  A nice example

      -

      Now let’s return to the pPCP1 plasmid from Yersinia pestis biovar -Microtus, and the top down approach used in Section 17.1.3, +

      All the shaft and arrow head options shown above for the +ARROW sigil can be used for the BIGARROW sigil too.

      + +

      17.1.9  A nice example

      +

      Now let’s return to the pPCP1 plasmid from Yersinia pestis biovar +Microtus, and the top down approach used in Section 17.1.3, but take advantage of the sigil options we’ve now discussed. This time we’ll use arrows for the genes, and overlay them with strand-less features -(as plain boxes) showing the position of some restriction digest sites.

      from reportlab.lib import colors
      +(as plain boxes) showing the position of some restriction digest sites.

      from reportlab.lib import colors
       from reportlab.lib.units import cm
       from Bio.Graphics import GenomeDiagram
       from Bio import SeqIO
      @@ -9966,34 +10266,35 @@
       gd_diagram.write("plasmid_circular_nice.pdf", "PDF")
       gd_diagram.write("plasmid_circular_nice.eps", "EPS")
       gd_diagram.write("plasmid_circular_nice.svg", "SVG")
      -

      -And the output:

      -

      17.1.10  Multiple tracks

      -

      All the examples so far have used a single track, but you can have more than +

      +And the output:

      + +

      17.1.10  Multiple tracks

      +

      All the examples so far have used a single track, but you can have more than one track – for example show the genes on one, and repeat regions on another. In this example we’re going to show three phage genomes side by side to scale, -inspired by Figure 6 in Proux et al. (2002) [5]. +inspired by Figure 6 in Proux et al. (2002) [5]. We’ll need the GenBank files for the following three phage: -

      • -NC_002703 – Lactococcus phage Tuc2009, complete genome (38347 bp) -
      • AF323668 – Bacteriophage bIL285, complete genome (35538 bp) -
      • NC_003212Listeria innocua Clip11262, complete genome, +

        • +NC_002703 – Lactococcus phage Tuc2009, complete genome (38347 bp) +
        • AF323668 – Bacteriophage bIL285, complete genome (35538 bp) +
        • NC_003212Listeria innocua Clip11262, complete genome, of which we are focussing only on integrated prophage 5 (similar length). -

        You can download these using Entrez if you like, see Section 9.6 +

      You can download these using Entrez if you like, see Section 9.6 for more details. For the third record we’ve worked out where the phage is integrated into the genome, and slice the record to extract it (with the -features preserved, see Section 4.6), and must also +features preserved, see Section 4.6), and must also reverse complement to match the orientation of the first two phage (again -preserving the features, see Section 4.8):

      from Bio import SeqIO
      +preserving the features, see Section 4.8):

      from Bio import SeqIO
       
       A_rec = SeqIO.read("NC_002703.gbk", "gb")
       B_rec = SeqIO.read("AF323668.gbk", "gb")
       C_rec = SeqIO.read("NC_003212.gbk", "gb")[2587879:2625807].reverse_complement(name=True)
      -

      The figure we are imitating used different colors for different gene functions. +

      The figure we are imitating used different colors for different gene functions. One way to do this is to edit the GenBank file to record color preferences for -each feature - something Sanger’s Artemis editor does, and which GenomeDiagram should understand. Here -however, we’ll just hard code three lists of colors.

      Note that the annotation in the GenBank files doesn’t exactly match that shown -in Proux et al., they have drawn some unannotated genes.

      from reportlab.lib.colors import red, grey, orange, green, brown, blue, lightblue, purple
      +each feature - something Sanger’s Artemis editor does, and which GenomeDiagram should understand. Here
      +however, we’ll just hard code three lists of colors.

      Note that the annotation in the GenBank files doesn’t exactly match that shown +in Proux et al., they have drawn some unannotated genes.

      from reportlab.lib.colors import red, grey, orange, green, brown, blue, lightblue, purple
       
       A_colors = [red]*5 + [grey]*7 + [orange]*2 + [grey]*2 + [orange] + [grey]*11 + [green]*4 \
                + [grey] + [green]*2 + [grey, green] + [brown]*5 + [blue]*4 + [lightblue]*5 \
      @@ -10002,9 +10303,9 @@
                + [grey] + [brown]*4 + [blue]*3 + [lightblue]*3 + [grey]*5 + [purple]*2
       C_colors = [grey]*30 + [green]*5 + [brown]*4 + [blue]*2 + [grey, blue] + [lightblue]*2 \
                + [grey]*5
      -

      Now to draw them – this time we add three tracks to the diagram, and also notice they +

      Now to draw them – this time we add three tracks to the diagram, and also notice they are given different start/end values to reflect their different lengths (this requires -Biopython 1.59 or later).

      from Bio.Graphics import GenomeDiagram
      +Biopython 1.59 or later).

      from Bio.Graphics import GenomeDiagram
       
       name = "Proux Fig 6"
       gd_diagram = GenomeDiagram.Diagram(name)
      @@ -10034,24 +10335,25 @@
       gd_diagram.write(name + ".pdf", "PDF")
       gd_diagram.write(name + ".eps", "EPS")
       gd_diagram.write(name + ".svg", "SVG")
      -

      -The result:

      +

      +The result:

      I did wonder why in the original manuscript there were no red or orange genes marked in the bottom phage. Another important point is here the phage are shown with different lengths - this is because they are all drawn to the same -scale (they are different lengths).

      The key difference from the published figure is they have color-coded links -between similar proteins – which is what we will do in the next section.

      -

      17.1.11  Cross-Links between tracks

      -

      Biopython 1.59 added the ability to draw cross links between tracks - both +scale (they are different lengths).

      The key difference from the published figure is they have color-coded links +between similar proteins – which is what we will do in the next section.

      + +

      17.1.11  Cross-Links between tracks

      +

      Biopython 1.59 added the ability to draw cross links between tracks - both simple linear diagrams as we will show here, but also linear diagrams split -into fragments and circular diagrams.

      Continuing the example from the previous section inspired by Figure 6 from -Proux et al. 2002 [5], +into fragments and circular diagrams.

      Continuing the example from the previous section inspired by Figure 6 from +Proux et al. 2002 [5], we would need a list of cross links between pairs of genes, along with a score or color to use. Realistically you might extract this from a BLAST file -computationally, but here I have manually typed them in.

      My naming convention continues to refer to the three phage as A, B and C. +computationally, but here I have manually typed them in.

      My naming convention continues to refer to the three phage as A, B and C. Here are the links we want to show between A and B, given as a list of -tuples (percentage similarity score, gene in A, gene in B).

      #Tuc2009 (NC_002703) vs bIL285 (AF323668)
      +tuples (percentage similarity score, gene in A, gene in B).

      #Tuc2009 (NC_002703) vs bIL285 (AF323668)
       A_vs_B = [
           (99, "Tuc2009_01", "int"),
           (33, "Tuc2009_03", "orf4"),
      @@ -10079,7 +10381,7 @@
           (91, "Tuc2009_49", "orf55"),
           (95, "Tuc2009_52", "orf60"), 
       ]
      -

      Likewise for B and C:

      #bIL285 (AF323668) vs Listeria innocua prophage 5 (in NC_003212)
      +

      Likewise for B and C:

      #bIL285 (AF323668) vs Listeria innocua prophage 5 (in NC_003212)
       B_vs_C = [
           (42, "orf39", "lin2581"),
           (31, "orf40", "lin2580"),
      @@ -10097,10 +10399,10 @@
           (30, "orf53", "lin2567"),
           (28, "orf54", "lin2566"),
       ]
      -

      For the first and last phage these identifiers are locus tags, for the middle +

      For the first and last phage these identifiers are locus tags, for the middle phage there are no locus tags so I’ve used gene names instead. The following little helper function lets us lookup a feature using either a locus tag or -gene name:

      def get_feature(features, id, tags=["locus_tag", "gene"]):
      +gene name:

      def get_feature(features, id, tags=["locus_tag", "gene"]):
           """Search list of SeqFeature objects for an identifier under the given tags."""
           for f in features:
               for key in tags:
      @@ -10109,13 +10411,13 @@
                       if x == id:
                            return f
           raise KeyError(id)
      -

      We can now turn those list of identifier pairs into SeqFeature pairs, and thus +

      We can now turn those list of identifier pairs into SeqFeature pairs, and thus find their location co-ordinates. We can now add all that code and the following -snippet to the previous example (just before the gd_diagram.draw(...) +snippet to the previous example (just before the gd_diagram.draw(...) line – see the finished example script -Proux_et_al_2002_Figure_6.py -included in the Doc/examples folder of the Biopython source code) -to add cross links to the figure:

      from Bio.Graphics.GenomeDiagram import CrossLink
      +Proux_et_al_2002_Figure_6.py
      +included in the Doc/examples folder of the Biopython source code)
      +to add cross links to the figure:

      from Bio.Graphics.GenomeDiagram import CrossLink
       from reportlab.lib import colors
       #Note it might have been clearer to assign the track numbers explicitly...                                                          
       for rec_X, tn_X, rec_Y, tn_Y, X_vs_Y in [(A_rec, 3, B_rec, 2, A_vs_B),
      @@ -10130,19 +10432,19 @@
                                   (track_Y, feature_Y.location.start, feature_Y.location.end),
                                   color, colors.lightgrey)
               gd_diagram.cross_track_links.append(link_xy)
      -

      There are several important pieces to this code. First the GenomeDiagram object -has a cross_track_links attribute which is just a list of CrossLink objects. -Each CrossLink object takes two sets of track-specific co-ordinates (here given -as tuples, you can alternatively use a GenomeDiagram.Feature object instead). +

      There are several important pieces to this code. First the GenomeDiagram object +has a cross_track_links attribute which is just a list of CrossLink objects. +Each CrossLink object takes two sets of track-specific co-ordinates (here given +as tuples, you can alternatively use a GenomeDiagram.Feature object instead). You can optionally supply a colour, border color, and say if this link should be drawn -flipped (useful for showing inversions).

      You can also see how we turn the BLAST percentage identity score into a colour, +flipped (useful for showing inversions).

      You can also see how we turn the BLAST percentage identity score into a colour, interpolating between white (0%) and a dark red (100%). In this example we don’t have any problems with overlapping cross-links. One way to tackle that is to use transparency in ReportLab, by using colors with their alpha channel set. However, this kind of shaded color scheme combined with overlap transparency would be difficult to interpret. -The result:

      There is still a lot more that can be done within Biopython to help +The result:

      There is still a lot more that can be done within Biopython to help improve this figure. First of all, the cross links in this case are between proteins which are drawn in a strand specific manor. It can help to add a background region (a feature using the ‘BOX’ sigil) on the @@ -10150,61 +10452,65 @@ height of the feature tracks to allocate more to the links instead – one way to do that is to allocate space for empty tracks. Furthermore, in cases like this where there are no large gene overlaps, we can use -the axis-straddling BIGARROW sigil, which allows us to further +the axis-straddling BIGARROW sigil, which allows us to further reduce the vertical space needed for the track. These improvements are demonstrated in the example script -Proux_et_al_2002_Figure_6.py -included in the Doc/examples folder of the Biopython source code. +Proux_et_al_2002_Figure_6.py +included in the Doc/examples folder of the Biopython source code. -The result:

      Beyond that, finishing touches you might want to do manually in a vector +The result:

      Beyond that, finishing touches you might want to do manually in a vector image editor include fine tuning the placement of gene labels, and adding -other custom annotation such as highlighting particular regions.

      Although not really necessary in this example since none of the cross-links +other custom annotation such as highlighting particular regions.

      Although not really necessary in this example since none of the cross-links overlap, using a transparent color in ReportLab is a very useful technique for superimposing multiple links. However, in this case a shaded color -scheme should be avoided.

      -

      17.1.12  Further options

      You can control the tick marks to show the scale – after all every graph -should show its units, and the number of the grey-track labels.

      Also, we have only used the FeatureSet so far. GenomeDiagram also has -a GraphSet which can be used for show line graphs, bar charts and heat -plots (e.g. to show plots of GC% on a track parallel to the features).

      These options are not covered here yet, so for now we refer you to the -User Guide (PDF) included with the standalone version of GenomeDiagram (but -please read the next section first), and the docstrings.

      -

      17.1.13  Converting old code

      If you have old code written using the standalone version of GenomeDiagram, and +scheme should be avoided.

      + +

      17.1.12  Further options

      You can control the tick marks to show the scale – after all every graph +should show its units, and the number of the grey-track labels.

      Also, we have only used the FeatureSet so far. GenomeDiagram also has +a GraphSet which can be used for show line graphs, bar charts and heat +plots (e.g. to show plots of GC% on a track parallel to the features).

      These options are not covered here yet, so for now we refer you to the +User Guide (PDF) included with the standalone version of GenomeDiagram (but +please read the next section first), and the docstrings.

      + +

      17.1.13  Converting old code

      If you have old code written using the standalone version of GenomeDiagram, and you want to switch it over to using the new version included with Biopython then -you will have to make a few changes - most importantly to your import statements.

      Also, the older version of GenomeDiagram used only the UK spellings of color and +you will have to make a few changes - most importantly to your import statements.

      Also, the older version of GenomeDiagram used only the UK spellings of color and center (colour and centre). You will need to change to the American spellings, -although for several years the Biopython version of GenomeDiagram supported both.

      For example, if you used to have: -

      from GenomeDiagram import GDFeatureSet, GDDiagram
      +although for several years the Biopython version of GenomeDiagram supported both.

      For example, if you used to have: +

      from GenomeDiagram import GDFeatureSet, GDDiagram
       gdd = GDDiagram("An example")
       ...
      -

      you could just switch the import statements like this: -

      from Bio.Graphics.GenomeDiagram import FeatureSet as GDFeatureSet, Diagram as GDDiagram
      +

      you could just switch the import statements like this: +

      from Bio.Graphics.GenomeDiagram import FeatureSet as GDFeatureSet, Diagram as GDDiagram
       gdd = GDDiagram("An example")
       ...
      -

      and hopefully that should be enough. In the long term you might want to +

      and hopefully that should be enough. In the long term you might want to switch to the new names, but you would have to change more of your code: -

      from Bio.Graphics.GenomeDiagram import FeatureSet, Diagram
      +

      from Bio.Graphics.GenomeDiagram import FeatureSet, Diagram
       gdd = Diagram("An example")
       ...
      -

      or: -

      from Bio.Graphics import GenomeDiagram
      +

      or: +

      from Bio.Graphics import GenomeDiagram
       gdd = GenomeDiagram.Diagram("An example")
       ...
      -

      If you run into difficulties, please ask on the Biopython mailing list for +

      If you run into difficulties, please ask on the Biopython mailing list for advice. One catch is that we have not included the old module -GenomeDiagram.GDUtilities yet. This included a number of +GenomeDiagram.GDUtilities yet. This included a number of GC% related functions, which will probably be merged under -Bio.SeqUtils later on. -

      -

      17.2  Chromosomes

      The Bio.Graphics.BasicChromosome module allows drawing of chromosomes. -There is an example in Jupe et al. (2012) [6] -(open access) using colors to highlight different gene families.

      -

      17.2.1  Simple Chromosomes

      -Here is a very simple example - for which we’ll use Arabidopsis thaliana.

      You can skip this bit, but first I downloaded the five sequenced chromosomes +Bio.SeqUtils later on. +

      + +

      17.2  Chromosomes

      The Bio.Graphics.BasicChromosome module allows drawing of chromosomes. +There is an example in Jupe et al. (2012) [6] +(open access) using colors to highlight different gene families.

      + +

      17.2.1  Simple Chromosomes

      +Here is a very simple example - for which we’ll use Arabidopsis thaliana.

      You can skip this bit, but first I downloaded the five sequenced chromosomes from the NCBI’s FTP site -ftp://ftp.ncbi.nlm.nih.gov/genomes/Arabidopsis_thaliana and then parsed -them with Bio.SeqIO to find out their lengths. You could use the +ftp://ftp.ncbi.nlm.nih.gov/genomes/Arabidopsis_thaliana and then parsed +them with Bio.SeqIO to find out their lengths. You could use the GenBank files for this, but it is faster to use the FASTA files for the -whole chromosomes:

      from Bio import SeqIO
      +whole chromosomes:

      from Bio import SeqIO
       entries = [("Chr I", "CHR_I/NC_003070.fna"),
                  ("Chr II", "CHR_II/NC_003071.fna"),
                  ("Chr III", "CHR_III/NC_003074.fna"),
      @@ -10212,9 +10518,9 @@
                  ("Chr V", "CHR_V/NC_003076.fna")]
       for (name, filename) in entries:
          record = SeqIO.read(filename,"fasta")
      -   print name, len(record)
      -

      This gave the lengths of the five chromosomes, which we’ll now use in -the following short demonstration of the BasicChromosome module:

      from reportlab.lib.units import cm
      +   print(name, len(record))
      +

      This gave the lengths of the five chromosomes, which we’ll now use in +the following short demonstration of the BasicChromosome module:

      from reportlab.lib.units import cm
       from Bio.Graphics import BasicChromosome
       
       entries = [("Chr I", 30432563),
      @@ -10255,18 +10561,19 @@
           chr_diagram.add(cur_chromosome)
       
       chr_diagram.draw("simple_chrom.pdf", "Arabidopsis thaliana")
      -

      This should create a very simple PDF file, shown +

      This should create a very simple PDF file, shown -here:

      +here:

      This example is deliberately short and sweet. The next example shows the -location of features of interest.

      -

      17.2.2  Annotated Chromosomes

      Continuing from the previous example, let’s also show the tRNA genes. +location of features of interest.

      + +

      17.2.2  Annotated Chromosomes

      Continuing from the previous example, let’s also show the tRNA genes. We’ll get their locations by parsing the GenBank files for the five -Arabidopsis thaliana chromosomes. You’ll need to download these +Arabidopsis thaliana chromosomes. You’ll need to download these files from the NCBI FTP site -ftp://ftp.ncbi.nlm.nih.gov/genomes/Arabidopsis_thaliana, -and preserve the subdirectory names or edit the paths below:

      from reportlab.lib.units import cm
      +ftp://ftp.ncbi.nlm.nih.gov/genomes/Arabidopsis_thaliana,
      +and preserve the subdirectory names or edit the paths below:

      from reportlab.lib.units import cm
       from Bio import SeqIO
       from Bio.Graphics import BasicChromosome
       
      @@ -10315,73 +10622,77 @@
           chr_diagram.add(cur_chromosome)
       
       chr_diagram.draw("tRNA_chrom.pdf", "Arabidopsis thaliana")
      -

      It might warn you about the labels being too close together - have a look +

      It might warn you about the labels being too close together - have a look at the forward strand (right hand side) of Chr I, but it should create a colorful PDF file, shown -here:

      -

      Chapter 18  Cookbook – Cool things to do with it

      -

      Biopython now has two collections of “cookbook” examples – this chapter +here:

      + +

      Chapter 18  Cookbook – Cool things to do with it

      +

      Biopython now has two collections of “cookbook” examples – this chapter (which has been included in this tutorial for many years and has gradually -grown), and http://biopython.org/wiki/Category:Cookbook which is a -user contributed collection on our wiki.

      We’re trying to encourage Biopython users to contribute their own examples +grown), and http://biopython.org/wiki/Category:Cookbook which is a +user contributed collection on our wiki.

      We’re trying to encourage Biopython users to contribute their own examples to the wiki. In addition to helping the community, one direct benefit of sharing an example like this is that you could also get some feedback on the code from other Biopython users and developers - which could help you -improve all your Python code.

      In the long term, we may end up moving all of the examples in this chapter -to the wiki, or elsewhere within the tutorial.

      -

      18.1  Working with sequence files

      -

      This section shows some more examples of sequence input/output, using the -Bio.SeqIO module described in Chapter 5.

      -

      18.1.1  Filtering a sequence file

      Often you’ll have a large file with many sequences in it (e.g. FASTA file +improve all your Python code.

      In the long term, we may end up moving all of the examples in this chapter +to the wiki, or elsewhere within the tutorial.

      + +

      18.1  Working with sequence files

      +

      This section shows some more examples of sequence input/output, using the +Bio.SeqIO module described in Chapter 5.

      + +

      18.1.1  Filtering a sequence file

      Often you’ll have a large file with many sequences in it (e.g. FASTA file or genes, or a FASTQ or SFF file of reads), a separate shorter list of the IDs for a subset of sequences of interest, and want to make a new -sequence file for this subset.

      Let’s say the list of IDs is in a simple text file, as the first word on +sequence file for this subset.

      Let’s say the list of IDs is in a simple text file, as the first word on each line. This could be a tabular file where the first column is the ID. -Try something like this:

      from Bio import SeqIO
      +Try something like this:

      from Bio import SeqIO
       input_file = "big_file.sff"
       id_file = "short_list.txt"
       output_file = "short_list.sff"
       wanted = set(line.rstrip("\n").split(None,1)[0] for line in open(id_file))
      -print "Found %i unique identifiers in %s" % (len(wanted), id_file)
      +print("Found %i unique identifiers in %s" % (len(wanted), id_file))
       records = (r for r in SeqIO.parse(input_file, "sff") if r.id in wanted)
       count = SeqIO.write(records, output_file, "sff")
      -print "Saved %i records from %s to %s" % (count, input_file, output_file)
      +print("Saved %i records from %s to %s" % (count, input_file, output_file))
       if count < len(wanted):
      -    print "Warning %i IDs not found in %s" % (len(wanted)-count, input_file)
      -

      Note that we use a Python set rather than a list, this makes -testing membership faster.

      -

      18.1.2  Producing randomised genomes

      Let’s suppose you are looking at genome sequence, hunting for some sequence + print("Warning %i IDs not found in %s" % (len(wanted)-count, input_file)) +

      Note that we use a Python set rather than a list, this makes +testing membership faster.

      + +

      18.1.2  Producing randomised genomes

      Let’s suppose you are looking at genome sequence, hunting for some sequence feature – maybe extreme local GC% bias, or possible restriction digest sites. Once you’ve got your Python code working on the real genome it may be sensible to try running the same search on randomised versions of the same genome for statistical analysis (after all, any “features” you’ve found could just be -there just by chance).

      For this discussion, we’ll use the GenBank file for the pPCP1 plasmid from -Yersinia pestis biovar Microtus. The file is included with the +there just by chance).

      For this discussion, we’ll use the GenBank file for the pPCP1 plasmid from +Yersinia pestis biovar Microtus. The file is included with the Biopython unit tests under the GenBank folder, or you can get it from our -website, NC_005816.gb. +website, NC_005816.gb. This file contains one and only one record, so we can read it in as a -SeqRecord using the Bio.SeqIO.read() function:

      >>> from Bio import SeqIO
      ->>> original_rec = SeqIO.read("NC_005816.gb","genbank")
      -

      So, how can we generate a shuffled versions of the original sequence? I would -use the built in Python random module for this, in particular the function -random.shuffle – but this works on a Python list. Our sequence is a -Seq object, so in order to shuffle it we need to turn it into a list:

      >>> import random
      +SeqRecord using the Bio.SeqIO.read() function:

      >>> from Bio import SeqIO
      +>>> original_rec = SeqIO.read("NC_005816.gb", "genbank")
      +

      So, how can we generate a shuffled versions of the original sequence? I would +use the built in Python random module for this, in particular the function +random.shuffle – but this works on a Python list. Our sequence is a +Seq object, so in order to shuffle it we need to turn it into a list:

      >>> import random
       >>> nuc_list = list(original_rec.seq)
       >>> random.shuffle(nuc_list) #acts in situ!
      -

      Now, in order to use Bio.SeqIO to output the shuffled sequence, we need -to construct a new SeqRecord with a new Seq object using this +

      Now, in order to use Bio.SeqIO to output the shuffled sequence, we need +to construct a new SeqRecord with a new Seq object using this shuffled list. In order to do this, we need to turn the list of nucleotides (single letter strings) into a long string – the standard Python way to do -this is with the string object’s join method.

      >>> from Bio.Seq import Seq
      +this is with the string object’s join method.

      >>> from Bio.Seq import Seq
       >>> from Bio.SeqRecord import SeqRecord
       >>> shuffled_rec = SeqRecord(Seq("".join(nuc_list), original_rec.seq.alphabet),
       ...                          id="Shuffled", description="Based on %s" % original_rec.id)
      -

      Let’s put all these pieces together to make a complete Python script which +

      Let’s put all these pieces together to make a complete Python script which generates a single FASTA file containing 30 randomly shuffled versions of -the original sequence.

      This first version just uses a big for loop and writes out the records one by one -(using the SeqRecord’s format method described in -Section 5.5.4):

      import random
      +the original sequence.

      This first version just uses a big for loop and writes out the records one by one +(using the SeqRecord’s format method described in +Section 5.5.4):

      import random
       from Bio.Seq import Seq
       from Bio.SeqRecord import SeqRecord
       from Bio import SeqIO
      @@ -10397,8 +10708,8 @@
                                    description="Based on %s" % original_rec.id)
           handle.write(shuffled_rec.format("fasta"))
       handle.close()
      -

      Personally I prefer the following version using a function to shuffle the record -and a generator expression instead of the for loop:

      import random
      +

      Personally I prefer the following version using a function to shuffle the record +and a generator expression instead of the for loop:

      import random
       from Bio.Seq import Seq
       from Bio.SeqRecord import SeqRecord
       from Bio import SeqIO
      @@ -10415,73 +10726,76 @@
       handle = open("shuffled.fasta", "w")
       SeqIO.write(shuffled_recs, handle, "fasta")
       handle.close()
      -
      -

      18.1.3  Translating a FASTA file of CDS entries

      - +

      + +

      18.1.3  Translating a FASTA file of CDS entries

      + Suppose you’ve got an input file of CDS entries for some organism, and you want to generate a new FASTA file containing their protein sequences. i.e. Take each nucleotide sequence from the original file, and translate it. -Back in Section 3.9 we saw how to use the Seq -object’s translate method, and the optional cds argument -which enables correct translation of alternative start codons.

      We can combine this with Bio.SeqIO as -shown in the reverse complement example in Section 5.5.3. -The key point is that for each nucleotide SeqRecord, we need to create -a protein SeqRecord - and take care of naming it.

      You can write you own function to do this, choosing suitable protein identifiers +Back in Section 3.9 we saw how to use the Seq +object’s translate method, and the optional cds argument +which enables correct translation of alternative start codons.

      We can combine this with Bio.SeqIO as +shown in the reverse complement example in Section 5.5.3. +The key point is that for each nucleotide SeqRecord, we need to create +a protein SeqRecord - and take care of naming it.

      You can write you own function to do this, choosing suitable protein identifiers for your sequences, and the appropriate genetic code. In this example we just -use the default table and add a prefix to the identifier:

      from Bio.SeqRecord import SeqRecord
      +use the default table and add a prefix to the identifier:

      from Bio.SeqRecord import SeqRecord
       def make_protein_record(nuc_record):
           """Returns a new SeqRecord with the translated sequence (default table)."""
           return SeqRecord(seq = nuc_record.seq.translate(cds=True), \
                            id = "trans_" + nuc_record.id, \
                            description = "translation of CDS, using default table")
      -

      We can then use this function to turn the input nucleotide records into protein +

      We can then use this function to turn the input nucleotide records into protein records ready for output. An elegant way and memory efficient way to do this -is with a generator expression:

      from Bio import SeqIO
      +is with a generator expression:

      from Bio import SeqIO
       proteins = (make_protein_record(nuc_rec) for nuc_rec in \
                   SeqIO.parse("coding_sequences.fasta", "fasta"))
       SeqIO.write(proteins, "translations.fasta", "fasta")
      -

      This should work on any FASTA file of complete coding sequences. +

      This should work on any FASTA file of complete coding sequences. If you are working on partial coding sequences, you may prefer to use -nuc_record.seq.translate(to_stop=True) in the example above, as -this wouldn’t check for a valid start codon etc.

      -

      18.1.4  Making the sequences in a FASTA file upper case

      Often you’ll get data from collaborators as FASTA files, and sometimes the +nuc_record.seq.translate(to_stop=True) in the example above, as +this wouldn’t check for a valid start codon etc.

      + +

      18.1.4  Making the sequences in a FASTA file upper case

      Often you’ll get data from collaborators as FASTA files, and sometimes the sequences can be in a mixture of upper and lower case. In some cases this is deliberate (e.g. lower case for poor quality regions), but usually it is not important. You may want to edit the file to make everything consistent (e.g. -all upper case), and you can do this easily using the upper() method -of the SeqRecord object (added in Biopython 1.55):

      from Bio import SeqIO
      +all upper case), and you can do this easily using the upper() method
      +of the SeqRecord object (added in Biopython 1.55):

      from Bio import SeqIO
       records = (rec.upper() for rec in SeqIO.parse("mixed.fas", "fasta"))
       count = SeqIO.write(records, "upper.fas", "fasta")
      -print "Converted %i records to upper case" % count
      -

      How does this work? The first line is just importing the Bio.SeqIO +print("Converted %i records to upper case" % count) +

      How does this work? The first line is just importing the Bio.SeqIO module. The second line is the interesting bit – this is a Python generator expression which gives an upper case version of each record -parsed from the input file (mixed.fas). In the third line we give -this generator expression to the Bio.SeqIO.write() function and it -saves the new upper cases records to our output file (upper.fas).

      The reason we use a generator expression (rather than a list or list +parsed from the input file (mixed.fas). In the third line we give +this generator expression to the Bio.SeqIO.write() function and it +saves the new upper cases records to our output file (upper.fas).

      The reason we use a generator expression (rather than a list or list comprehension) is this means only one record is kept in memory at a time. This can be really important if you are dealing with large files with -millions of entries.

      -

      18.1.5  Sorting a sequence file

      -

      Suppose you wanted to sort a sequence file by length (e.g. a set of +millions of entries.

      + +

      18.1.5  Sorting a sequence file

      +

      Suppose you wanted to sort a sequence file by length (e.g. a set of contigs from an assembly), and you are working with a file format like -FASTA or FASTQ which Bio.SeqIO can read, write (and index).

      If the file is small enough, you can load it all into memory at once -as a list of SeqRecord objects, sort the list, and save it:

      from Bio import SeqIO
      +FASTA or FASTQ which Bio.SeqIO can read, write (and index).

      If the file is small enough, you can load it all into memory at once +as a list of SeqRecord objects, sort the list, and save it:

      from Bio import SeqIO
       records = list(SeqIO.parse("ls_orchid.fasta","fasta"))
       records.sort(cmp=lambda x,y: cmp(len(x),len(y)))
       SeqIO.write(records, "sorted_orchids.fasta", "fasta")
      -

      The only clever bit is specifying a comparison function for how to +

      The only clever bit is specifying a comparison function for how to sort the records (here we sort them by length). If you wanted the longest records first, you could flip the comparison or use the -reverse argument:

      from Bio import SeqIO
      +reverse argument:

      from Bio import SeqIO
       records = list(SeqIO.parse("ls_orchid.fasta","fasta"))
       records.sort(cmp=lambda x,y: cmp(len(y),len(x)))
       SeqIO.write(records, "sorted_orchids.fasta", "fasta")
      -

      Now that’s pretty straight forward - but what happens if you have a +

      Now that’s pretty straight forward - but what happens if you have a very large file and you can’t load it all into memory like this? For example, you might have some next-generation sequencing reads to sort by length. This can be solved using the -Bio.SeqIO.index() function.

      from Bio import SeqIO
      +Bio.SeqIO.index() function.

      from Bio import SeqIO
       #Get the lengths and ids, and sort on length         
       len_and_ids = sorted((len(rec), rec.id) for rec in \
                            SeqIO.parse("ls_orchid.fasta","fasta"))
      @@ -10490,17 +10804,17 @@
       record_index = SeqIO.index("ls_orchid.fasta", "fasta")
       records = (record_index[id] for id in ids)
       SeqIO.write(records, "sorted.fasta", "fasta")
      -

      First we scan through the file once using Bio.SeqIO.parse(), +

      First we scan through the file once using Bio.SeqIO.parse(), recording the record identifiers and their lengths in a list of tuples. We then sort this list to get them in length order, and discard the lengths. -Using this sorted list of identifiers Bio.SeqIO.index() allows us to -retrieve the records one by one, and we pass them to Bio.SeqIO.write() -for output.

      These examples all use Bio.SeqIO to parse the records into -SeqRecord objects which are output using Bio.SeqIO.write(). -What if you want to sort a file format which Bio.SeqIO.write() doesn’t +Using this sorted list of identifiers Bio.SeqIO.index() allows us to +retrieve the records one by one, and we pass them to Bio.SeqIO.write() +for output.

      These examples all use Bio.SeqIO to parse the records into +SeqRecord objects which are output using Bio.SeqIO.write(). +What if you want to sort a file format which Bio.SeqIO.write() doesn’t support, like the plain text SwissProt format? Here is an alternative -solution using the get_raw() method added to Bio.SeqIO.index() -in Biopython 1.54 (see Section 5.4.2.2).

      from Bio import SeqIO
      +solution using the get_raw() method added to Bio.SeqIO.index()
      +in Biopython 1.54 (see Section 5.4.2.2).

      from Bio import SeqIO
       #Get the lengths and ids, and sort on length         
       len_and_ids = sorted((len(rec), rec.id) for rec in \
                            SeqIO.parse("ls_orchid.fasta","fasta"))
      @@ -10511,71 +10825,73 @@
       for id in ids:
           handle.write(record_index.get_raw(id))
       handle.close()
      -

      As a bonus, because it doesn’t parse the data into SeqRecord objects -a second time it should be faster.

      -

      18.1.6  Simple quality filtering for FASTQ files

      -

      The FASTQ file format was introduced at Sanger and is now widely used for +

      As a bonus, because it doesn’t parse the data into SeqRecord objects +a second time it should be faster.

      + +

      18.1.6  Simple quality filtering for FASTQ files

      +

      The FASTQ file format was introduced at Sanger and is now widely used for holding nucleotide sequencing reads together with their quality scores. FASTQ files (and the related QUAL files) are an excellent example of per-letter-annotation, because for each nucleotide in the sequence there is an associated quality score. Any per-letter-annotation is held in a -SeqRecord in the letter_annotations dictionary as a list, -tuple or string (with the same number of elements as the sequence length).

      One common task is taking a large set of sequencing reads and filtering them +SeqRecord in the letter_annotations dictionary as a list, +tuple or string (with the same number of elements as the sequence length).

      One common task is taking a large set of sequencing reads and filtering them (or cropping them) based on their quality scores. The following example is very simplistic, but should illustrate the basics of -working with quality data in a SeqRecord object. All we are going to +working with quality data in a SeqRecord object. All we are going to do here is read in a file of FASTQ data, and filter it to pick out only those -records whose PHRED quality scores are all above some threshold (here 20).

      For this example we’ll use some real data downloaded from the ENA sequence +records whose PHRED quality scores are all above some threshold (here 20).

      For this example we’ll use some real data downloaded from the ENA sequence read archive, -ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR020/SRR020192/SRR020192.fastq.gz -(2MB) which unzips to a 19MB file SRR020192.fastq. This is some +ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR020/SRR020192/SRR020192.fastq.gz +(2MB) which unzips to a 19MB file SRR020192.fastq. This is some Roche 454 GS FLX single end data from virus infected California sea lions -(see http://www.ebi.ac.uk/ena/data/view/SRS004476 for details).

      First, let’s count the reads:

      from Bio import SeqIO
      +(see http://www.ebi.ac.uk/ena/data/view/SRS004476 for details).

      First, let’s count the reads:

      from Bio import SeqIO
       count = 0
       for rec in SeqIO.parse("SRR020192.fastq", "fastq"):
           count += 1
      -print "%i reads" % count
      -

      Now let’s do a simple filtering for a minimum PHRED quality of 20:

      from Bio import SeqIO
      +print("%i reads" % count)
      +

      Now let’s do a simple filtering for a minimum PHRED quality of 20:

      from Bio import SeqIO
       good_reads = (rec for rec in \
                     SeqIO.parse("SRR020192.fastq", "fastq") \
                     if min(rec.letter_annotations["phred_quality"]) >= 20)
       count = SeqIO.write(good_reads, "good_quality.fastq", "fastq")
      -print "Saved %i reads" % count
      -

      This pulled out only 14580 reads out of the 41892 present. +print("Saved %i reads" % count) +

      This pulled out only 14580 reads out of the 41892 present. A more sensible thing to do would be to quality trim the reads, but this -is intended as an example only.

      FASTQ files can contain millions of entries, so it is best to avoid loading +is intended as an example only.

      FASTQ files can contain millions of entries, so it is best to avoid loading them all into memory at once. This example uses a generator expression, which -means only one SeqRecord is created at a time - avoiding any memory -limitations.

      -

      18.1.7  Trimming off primer sequences

      -

      For this example we’re going to pretend that GATGACGGTGT is a 5’ primer +means only one SeqRecord is created at a time - avoiding any memory +limitations.

      + +

      18.1.7  Trimming off primer sequences

      +

      For this example we’re going to pretend that GATGACGGTGT is a 5’ primer sequence we want to look for in some FASTQ formatted read data. As in the example -above, we’ll use the SRR020192.fastq file downloaded from the ENA -(ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR020/SRR020192/SRR020192.fastq.gz). -The same approach would work with any other supported file format (e.g. FASTA files).

      This code uses Bio.SeqIO with a generator expression (to avoid loading -all the sequences into memory at once), and the Seq object’s -startswith method to see if the read starts with the primer sequence:

      from Bio import SeqIO
      +above, we’ll use the SRR020192.fastq file downloaded from the ENA
      +(ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR020/SRR020192/SRR020192.fastq.gz).
      +The same approach would work with any other supported file format (e.g. FASTA files).

      This code uses Bio.SeqIO with a generator expression (to avoid loading +all the sequences into memory at once), and the Seq object’s +startswith method to see if the read starts with the primer sequence:

      from Bio import SeqIO
       primer_reads = (rec for rec in \
                       SeqIO.parse("SRR020192.fastq", "fastq") \
                       if rec.seq.startswith("GATGACGGTGT"))
       count = SeqIO.write(primer_reads, "with_primer.fastq", "fastq")
      -print "Saved %i reads" % count
      -

      That should find 13819 reads from SRR014849.fastq and save them to -a new FASTQ file, with_primer.fastq.

      Now suppose that instead you wanted to make a FASTQ file containing these reads +print("Saved %i reads" % count) +

      That should find 13819 reads from SRR014849.fastq and save them to +a new FASTQ file, with_primer.fastq.

      Now suppose that instead you wanted to make a FASTQ file containing these reads but with the primer sequence removed? That’s just a small change as we can slice the -SeqRecord (see Section 4.6) to remove the first eleven -letters (the length of our primer):

      from Bio import SeqIO
      +SeqRecord (see Section 4.6) to remove the first eleven
      +letters (the length of our primer):

      from Bio import SeqIO
       trimmed_primer_reads = (rec[11:] for rec in \
                               SeqIO.parse("SRR020192.fastq", "fastq") \
                               if rec.seq.startswith("GATGACGGTGT"))
       count = SeqIO.write(trimmed_primer_reads, "with_primer_trimmed.fastq", "fastq")
      -print "Saved %i reads" % count
      -

      Again, that should pull out the 13819 reads from SRR020192.fastq, +print("Saved %i reads" % count) +

      Again, that should pull out the 13819 reads from SRR020192.fastq, but this time strip off the first ten characters, and save them to another new -FASTQ file, with_primer_trimmed.fastq.

      Finally, suppose you want to create a new FASTQ file where these reads have +FASTQ file, with_primer_trimmed.fastq.

      Finally, suppose you want to create a new FASTQ file where these reads have their primer removed, but all the other reads are kept as they were? If we want to still use a generator expression, it is probably clearest to -define our own trim function:

      from Bio import SeqIO
      +define our own trim function:

      from Bio import SeqIO
       def trim_primer(record, primer):
           if record.seq.startswith(primer):
               return record[len(primer):]
      @@ -10585,11 +10901,11 @@
       trimmed_reads = (trim_primer(record, "GATGACGGTGT") for record in \
                        SeqIO.parse("SRR020192.fastq", "fastq"))
       count = SeqIO.write(trimmed_reads, "trimmed.fastq", "fastq")
      -print "Saved %i reads" % count
      -

      This takes longer, as this time the output file contains all 41892 reads. +print("Saved %i reads" % count) +

      This takes longer, as this time the output file contains all 41892 reads. Again, we’re used a generator expression to avoid any memory problems. You could alternatively use a generator function rather than a generator -expression.

      from Bio import SeqIO
      +expression.

      from Bio import SeqIO
       def trim_primers(records, primer):
           """Removes perfect primer sequences at start of reads.
           
      @@ -10606,15 +10922,16 @@
       original_reads = SeqIO.parse("SRR020192.fastq", "fastq")
       trimmed_reads = trim_primers(original_reads, "GATGACGGTGT")
       count = SeqIO.write(trimmed_reads, "trimmed.fastq", "fastq") 
      -print "Saved %i reads" % count
      -

      This form is more flexible if you want to do something more complicated -where only some of the records are retained – as shown in the next example.

      -

      18.1.8  Trimming off adaptor sequences

      -

      This is essentially a simple extension to the previous example. We are going -to going to pretend GATGACGGTGT is an adaptor sequence in some FASTQ -formatted read data, again the SRR020192.fastq file from the NCBI -(ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR020/SRR020192/SRR020192.fastq.gz).

      This time however, we will look for the sequence anywhere in the reads, -not just at the very beginning:

      from Bio import SeqIO
      +print("Saved %i reads" % count)
      +

      This form is more flexible if you want to do something more complicated +where only some of the records are retained – as shown in the next example.

      + +

      18.1.8  Trimming off adaptor sequences

      +

      This is essentially a simple extension to the previous example. We are going +to going to pretend GATGACGGTGT is an adaptor sequence in some FASTQ +formatted read data, again the SRR020192.fastq file from the NCBI +(ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR020/SRR020192/SRR020192.fastq.gz).

      This time however, we will look for the sequence anywhere in the reads, +not just at the very beginning:

      from Bio import SeqIO
       
       def trim_adaptors(records, adaptor):
           """Trims perfect adaptor sequences.
      @@ -10635,15 +10952,15 @@
       original_reads = SeqIO.parse("SRR020192.fastq", "fastq")
       trimmed_reads = trim_adaptors(original_reads, "GATGACGGTGT")
       count = SeqIO.write(trimmed_reads, "trimmed.fastq", "fastq") 
      -print "Saved %i reads" % count
      -

      Because we are using a FASTQ input file in this example, the SeqRecord +print("Saved %i reads" % count) +

      Because we are using a FASTQ input file in this example, the SeqRecord objects have per-letter-annotation for the quality scores. By slicing the -SeqRecord object the appropriate scores are used on the trimmed -records, so we can output them as a FASTQ file too.

      Compared to the output of the previous example where we only looked for +SeqRecord object the appropriate scores are used on the trimmed +records, so we can output them as a FASTQ file too.

      Compared to the output of the previous example where we only looked for a primer/adaptor at the start of each read, you may find some of the trimmed reads are quite short after trimming (e.g. if the adaptor was found in the middle rather than near the start). So, let’s add a minimum -length requirement as well:

      from Bio import SeqIO
      +length requirement as well:

      from Bio import SeqIO
       
       def trim_adaptors(records, adaptor, min_len):
           """Trims perfect adaptor sequences, checks read length.
      @@ -10668,119 +10985,122 @@
       original_reads = SeqIO.parse("SRR020192.fastq", "fastq")
       trimmed_reads = trim_adaptors(original_reads, "GATGACGGTGT", 100)
       count = SeqIO.write(trimmed_reads, "trimmed.fastq", "fastq") 
      -print "Saved %i reads" % count
      -

      By changing the format names, you could apply this to FASTA files instead. +print("Saved %i reads" % count) +

      By changing the format names, you could apply this to FASTA files instead. This code also could be extended to do a fuzzy match instead of an exact match (maybe using a pairwise alignment, or taking into account the read -quality scores), but that will be much slower.

      -

      18.1.9  Converting FASTQ files

      -

      Back in Section 5.5.2 we showed how to use -Bio.SeqIO to convert between two file formats. Here we’ll go into a +quality scores), but that will be much slower.

      + +

      18.1.9  Converting FASTQ files

      +

      Back in Section 5.5.2 we showed how to use +Bio.SeqIO to convert between two file formats. Here we’ll go into a little more detail regarding FASTQ files which are used in second generation -DNA sequencing. Please refer to Cock et al. (2009) [7] +DNA sequencing. Please refer to Cock et al. (2009) [7] for a longer description. FASTQ files store both the DNA sequence (as a string) -and the associated read qualities.

      PHRED scores (used in most FASTQ files, and also in QUAL files, ACE files -and SFF files) have become a de facto standard for representing -the probability of a sequencing error (here denoted by Pe) at a given -base using a simple base ten log transformation:

      -
      -QPHRED = − 10 × log10 ( Pe ) -    (18.1)

      This means a wrong read (Pe = 1) gets a PHRED quality of 0, while a very -good read like Pe = 0.00001 gets a PHRED quality of 50. While for raw +and the associated read qualities.

      PHRED scores (used in most FASTQ files, and also in QUAL files, ACE files +and SFF files) have become a de facto standard for representing +the probability of a sequencing error (here denoted by Pe) at a given +base using a simple base ten log transformation:

      +
      +QPHRED = − 10 × log10 ( Pe ) +    (18.1)

      This means a wrong read (Pe = 1) gets a PHRED quality of 0, while a very +good read like Pe = 0.00001 gets a PHRED quality of 50. While for raw sequencing data qualities higher than this are rare, with post processing such as read mapping or assembly, qualities of up to about 90 are possible -(indeed, the MAQ tool allows for PHRED scores in the range 0 to 93 inclusive).

      The FASTQ format has the potential to become a de facto standard for +(indeed, the MAQ tool allows for PHRED scores in the range 0 to 93 inclusive).

      The FASTQ format has the potential to become a de facto standard for storing the letters and quality scores for a sequencing read in a single plain text file. The only fly in the ointment is that there are at least three versions of the FASTQ format which are incompatible and difficult to -distinguish...

      1. +distinguish...

        1. The original Sanger FASTQ format uses PHRED qualities encoded with an ASCII offset of 33. The NCBI are using this format in their Short Read -Archive. We call this the fastq (or fastq-sanger) format -in Bio.SeqIO. -
        2. Solexa (later bought by Illumina) introduced their own version using +Archive. We call this the fastq (or fastq-sanger) format +in Bio.SeqIO. +
        3. Solexa (later bought by Illumina) introduced their own version using Solexa qualities encoded with an ASCII offset of 64. We call this the -fastq-solexa format. -
        4. Illumina pipeline 1.3 onwards produces FASTQ files with PHRED qualities +fastq-solexa format. +
        5. Illumina pipeline 1.3 onwards produces FASTQ files with PHRED qualities (which is more consistent), but encoded with an ASCII offset of 64. We call -this the fastq-illumina format. -

        The Solexa quality scores are defined using a different log transformation:

        -
        -QSolexa = − 10 × log10 
        -⎜
        -⎜
        -⎝
        - - -
        Pe
        1−Pe
         
        -⎟
        -⎟
        -⎠
        -    (18.2)

        Given Solexa/Illumina have now moved to using PHRED scores in version 1.3 of +this the fastq-illumina format. +

      The Solexa quality scores are defined using a different log transformation:

      +
      +QSolexa = − 10 × log10 
      +⎜
      +⎜
      +⎝
      + + +
      Pe
      1−Pe
       
      +⎟
      +⎟
      +⎠
      +    (18.2)

      Given Solexa/Illumina have now moved to using PHRED scores in version 1.3 of their pipeline, the Solexa quality scores will gradually fall out of use. -If you equate the error estimates (Pe) these two equations allow conversion +If you equate the error estimates (Pe) these two equations allow conversion between the two scoring systems - and Biopython includes functions to do this -in the Bio.SeqIO.QualityIO module, which are called if you use -Bio.SeqIO to convert an old Solexa/Illumina file into a standard Sanger -FASTQ file:

      from Bio import SeqIO
      +in the Bio.SeqIO.QualityIO module, which are called if you use
      +Bio.SeqIO to convert an old Solexa/Illumina file into a standard Sanger
      +FASTQ file:

      from Bio import SeqIO
       SeqIO.convert("solexa.fastq", "fastq-solexa", "standard.fastq", "fastq")
      -

      If you want to convert a new Illumina 1.3+ FASTQ file, all that gets changed +

      If you want to convert a new Illumina 1.3+ FASTQ file, all that gets changed is the ASCII offset because although encoded differently the scores are all -PHRED qualities:

      from Bio import SeqIO
      +PHRED qualities:

      from Bio import SeqIO
       SeqIO.convert("illumina.fastq", "fastq-illumina", "standard.fastq", "fastq")
      -

      Note that using Bio.SeqIO.convert() like this is much faster -than combining Bio.SeqIO.parse() and Bio.SeqIO.write() +

      Note that using Bio.SeqIO.convert() like this is much faster +than combining Bio.SeqIO.parse() and Bio.SeqIO.write() because optimised code is used for converting between FASTQ variants -(and also for FASTQ to FASTA conversion).

      For good quality reads, PHRED and Solexa scores are approximately equal, -which means since both the fasta-solexa and fastq-illumina +(and also for FASTQ to FASTA conversion).

      For good quality reads, PHRED and Solexa scores are approximately equal, +which means since both the fasta-solexa and fastq-illumina formats use an ASCII offset of 64 the files are almost the same. This was a deliberate design choice by Illumina, meaning applications expecting the old -fasta-solexa style files will probably be OK using the newer -fastq-illumina files (on good data). Of course, both variants are +fasta-solexa style files will probably be OK using the newer +fastq-illumina files (on good data). Of course, both variants are very different from the original FASTQ standard as used by Sanger, -the NCBI, and elsewhere (format name fastq or fastq-sanger).

      For more details, see the built in help (also online):

      >>> from Bio.SeqIO import QualityIO
      +the NCBI, and elsewhere (format name fastq or fastq-sanger).

      For more details, see the built in help (also online):

      >>> from Bio.SeqIO import QualityIO
       >>> help(QualityIO)
       ...
      -
      -

      18.1.10  Converting FASTA and QUAL files into FASTQ files

      -

      FASTQ files hold both sequences and their quality strings. -FASTA files hold just sequences, while QUAL files hold just +

      + +

      18.1.10  Converting FASTA and QUAL files into FASTQ files

      +

      FASTQ files hold both sequences and their quality strings. +FASTA files hold just sequences, while QUAL files hold just the qualities. Therefore a single FASTQ file can be converted to or from -paired FASTA and QUAL files.

      Going from FASTQ to FASTA is easy:

      from Bio import SeqIO
      +paired FASTA and QUAL files.

      Going from FASTQ to FASTA is easy:

      from Bio import SeqIO
       SeqIO.convert("example.fastq", "fastq", "example.fasta", "fasta")
      -

      Going from FASTQ to QUAL is also easy:

      from Bio import SeqIO
      +

      Going from FASTQ to QUAL is also easy:

      from Bio import SeqIO
       SeqIO.convert("example.fastq", "fastq", "example.qual", "qual")
      -

      However, the reverse is a little more tricky. You can use Bio.SeqIO.parse() -to iterate over the records in a single file, but in this case we have +

      However, the reverse is a little more tricky. You can use Bio.SeqIO.parse() +to iterate over the records in a single file, but in this case we have two input files. There are several strategies possible, but assuming that the two files are really paired the most memory efficient way is to loop over both together. The code is a little fiddly, so we provide a function called -PairedFastaQualIterator in the Bio.SeqIO.QualityIO module to do +PairedFastaQualIterator in the Bio.SeqIO.QualityIO module to do this. This takes two handles (the FASTA file and the QUAL file) and returns -a SeqRecord iterator:

      from Bio.SeqIO.QualityIO import PairedFastaQualIterator
      +a SeqRecord iterator:

      from Bio.SeqIO.QualityIO import PairedFastaQualIterator
       for record in PairedFastaQualIterator(open("example.fasta"), open("example.qual")):
      -   print record
      -

      This function will check that the FASTA and QUAL files are consistent (e.g. + print(record) +

      This function will check that the FASTA and QUAL files are consistent (e.g. the records are in the same order, and have the same sequence length). -You can combine this with the Bio.SeqIO.write() function to convert a -pair of FASTA and QUAL files into a single FASTQ files:

      from Bio import SeqIO
      +You can combine this with the Bio.SeqIO.write() function to convert a
      +pair of FASTA and QUAL files into a single FASTQ files:

      from Bio import SeqIO
       from Bio.SeqIO.QualityIO import PairedFastaQualIterator
       handle = open("temp.fastq", "w") #w=write
       records = PairedFastaQualIterator(open("example.fasta"), open("example.qual"))
       count = SeqIO.write(records, handle, "fastq")
       handle.close()
      -print "Converted %i records" % count
      -
      -

      18.1.11  Indexing a FASTQ file

      -

      FASTQ files are often very large, with millions of reads in them. Due to the +print("Converted %i records" % count) +

      + +

      18.1.11  Indexing a FASTQ file

      +

      FASTQ files are often very large, with millions of reads in them. Due to the sheer amount of data, you can’t load all the records into memory at once. This is why the examples above (filtering and trimming) iterate over the file -looking at just one SeqRecord at a time.

      However, sometimes you can’t use a big loop or an iterator - you may need -random access to the reads. Here the Bio.SeqIO.index() function +looking at just one SeqRecord at a time.

      However, sometimes you can’t use a big loop or an iterator - you may need +random access to the reads. Here the Bio.SeqIO.index() function may prove very helpful, as it allows you to access any read in the FASTQ file -by its name (see Section 5.4.2).

      Again we’ll use the SRR020192.fastq file from the ENA -(ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR020/SRR020192/SRR020192.fastq.gz), -although this is actually quite a small FASTQ file with less than 50,000 reads:

      >>> from Bio import SeqIO
      +by its name (see Section 5.4.2).

      Again we’ll use the SRR020192.fastq file from the ENA +(ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR020/SRR020192/SRR020192.fastq.gz), +although this is actually quite a small FASTQ file with less than 50,000 reads:

      >>> from Bio import SeqIO
       >>> fq_dict = SeqIO.index("SRR020192.fastq", "fastq")
       >>> len(fq_dict)
       41892
      @@ -10788,67 +11108,69 @@
       ['SRR020192.38240', 'SRR020192.23181', 'SRR020192.40568', 'SRR020192.23186']
       >>> fq_dict["SRR020192.23186"].seq
       Seq('GTCCCAGTATTCGGATTTGTCTGCCAAAACAATGAAATTGACACAGTTTACAAC...CCG', SingleLetterAlphabet())
      -

      When testing this on a FASTQ file with seven million reads, -indexing took about a minute, but record access was almost instant.

      The example in Section 18.1.5 show how you can use the -Bio.SeqIO.index() function to sort a large FASTA file – this -could also be used on FASTQ files.

      -

      18.1.12  Converting SFF files

      -

      If you work with 454 (Roche) sequence data, you will probably have access +

      When testing this on a FASTQ file with seven million reads, +indexing took about a minute, but record access was almost instant.

      The example in Section 18.1.5 show how you can use the +Bio.SeqIO.index() function to sort a large FASTA file – this +could also be used on FASTQ files.

      + +

      18.1.12  Converting SFF files

      +

      If you work with 454 (Roche) sequence data, you will probably have access to the raw data as a Standard Flowgram Format (SFF) file. This contains the sequence reads (called bases) with quality scores and the original -flow information.

      A common task is to convert from SFF to a pair of FASTA and QUAL files, +flow information.

      A common task is to convert from SFF to a pair of FASTA and QUAL files, or to a single FASTQ file. These operations are trivial using the -Bio.SeqIO.convert() function (see Section 5.5.2):

      >>> from Bio import SeqIO
      +Bio.SeqIO.convert() function (see Section 5.5.2):

      >>> from Bio import SeqIO
       >>> SeqIO.convert("E3MFGYR02_random_10_reads.sff", "sff", "reads.fasta", "fasta")
       10
       >>> SeqIO.convert("E3MFGYR02_random_10_reads.sff", "sff", "reads.qual", "qual")
       10
       >>> SeqIO.convert("E3MFGYR02_random_10_reads.sff", "sff", "reads.fastq", "fastq")
       10
      -

      Remember the convert function returns the number of records, in -this example just ten. This will give you the untrimmed reads, where +

      Remember the convert function returns the number of records, in +this example just ten. This will give you the untrimmed reads, where the leading and trailing poor quality sequence or adaptor will be in lower -case. If you want the trimmed reads (using the clipping information -recorded within the SFF file) use this:

      >>> from Bio import SeqIO
      +case. If you want the trimmed reads (using the clipping information
      +recorded within the SFF file) use this:

      >>> from Bio import SeqIO
       >>> SeqIO.convert("E3MFGYR02_random_10_reads.sff", "sff-trim", "trimmed.fasta", "fasta")
       10
       >>> SeqIO.convert("E3MFGYR02_random_10_reads.sff", "sff-trim", "trimmed.qual", "qual")
       10
       >>> SeqIO.convert("E3MFGYR02_random_10_reads.sff", "sff-trim", "trimmed.fastq", "fastq")
       10
      -

      If you run Linux, you could ask Roche for a copy of their “off instrument” +

      If you run Linux, you could ask Roche for a copy of their “off instrument” tools (often referred to as the Newbler tools). This offers an alternative way to do SFF to FASTA or QUAL conversion at the command line (but currently FASTQ output -is not supported), e.g.

      $ sffinfo -seq -notrim E3MFGYR02_random_10_reads.sff > reads.fasta
      +is not supported), e.g.

      $ sffinfo -seq -notrim E3MFGYR02_random_10_reads.sff > reads.fasta
       $ sffinfo -qual -notrim E3MFGYR02_random_10_reads.sff > reads.qual
       $ sffinfo -seq -trim E3MFGYR02_random_10_reads.sff > trimmed.fasta
       $ sffinfo -qual -trim E3MFGYR02_random_10_reads.sff > trimmed.qual
      -

      The way Biopython uses mixed case sequence strings to represent -the trimming points deliberately mimics what the Roche tools do.

      For more information on the Biopython SFF support, consult the built in help:

      >>> from Bio.SeqIO import SffIO
      +

      The way Biopython uses mixed case sequence strings to represent +the trimming points deliberately mimics what the Roche tools do.

      For more information on the Biopython SFF support, consult the built in help:

      >>> from Bio.SeqIO import SffIO
       >>> help(SffIO)
       ...
      -
      -

      18.1.13  Identifying open reading frames

      A very simplistic first step at identifying possible genes is to look for +

      + +

      18.1.13  Identifying open reading frames

      A very simplistic first step at identifying possible genes is to look for open reading frames (ORFs). By this we mean look in all six frames for long regions without stop codons – an ORF is just a region of nucleotides with -no in frame stop codons.

      Of course, to find a gene you would also need to worry about locating a start +no in frame stop codons.

      Of course, to find a gene you would also need to worry about locating a start codon, possible promoters – and in Eukaryotes there are introns to worry about -too. However, this approach is still useful in viruses and Prokaryotes.

      To show how you might approach this with Biopython, we’ll need a sequence to +too. However, this approach is still useful in viruses and Prokaryotes.

      To show how you might approach this with Biopython, we’ll need a sequence to search, and as an example we’ll again use the bacterial plasmid – although this time we’ll start with a plain FASTA file with no pre-marked genes: -NC_005816.fna. This is a bacterial sequence, so we’ll want to use -NCBI codon table 11 (see Section 3.9 about translation).

      >>> from Bio import SeqIO 
      ->>> record = SeqIO.read("NC_005816.fna","fasta")
      +NC_005816.fna. This is a bacterial sequence, so we’ll want to use
      +NCBI codon table 11 (see Section 3.9 about translation).

      >>> from Bio import SeqIO 
      +>>> record = SeqIO.read("NC_005816.fna", "fasta")
       >>> table = 11
       >>> min_pro_len = 100
      -

      Here is a neat trick using the Seq object’s split method to -get a list of all the possible ORF translations in the six reading frames:

      >>> for strand, nuc in [(+1, record.seq), (-1, record.seq.reverse_complement())]:
      +

      Here is a neat trick using the Seq object’s split method to +get a list of all the possible ORF translations in the six reading frames:

      >>> for strand, nuc in [(+1, record.seq), (-1, record.seq.reverse_complement())]:
       ...     for frame in range(3):
       ...         length = 3 * ((len(record)-frame) // 3) #Multiple of three
       ...         for pro in nuc[frame:frame+length].translate(table).split("*"):
       ...             if len(pro) >= min_pro_len:
      -...                 print "%s...%s - length %i, strand %i, frame %i" \
      -...                       % (pro[:30], pro[-3:], len(pro), strand, frame)
      +...                 print("%s...%s - length %i, strand %i, frame %i" \
      +...                       % (pro[:30], pro[-3:], len(pro), strand, frame))
       GCLMKKSSIVATIITILSGSANAASSQLIP...YRF - length 315, strand 1, frame 0
       KSGELRQTPPASSTLHLRLILQRSGVMMEL...NPE - length 285, strand 1, frame 1
       GLNCSFFSICNWKFIDYINRLFQIIYLCKN...YYH - length 176, strand 1, frame 1
      @@ -10863,14 +11185,14 @@
       WDVKTVTGVLHHPFHLTFSLCPEGATQSGR...VKR - length 111, strand -1, frame 1
       LSHTVTDFTDQMAQVGLCQCVNVFLDEVTG...KAA - length 107, strand -1, frame 2
       RALTGLSAPGIRSQTSCDRLRELRYVPVSL...PLQ - length 119, strand -1, frame 2
      -

      Note that here we are counting the frames from the 5’ end (start) of -each strand. It is sometimes easier to always count from the 5’ end -(start) of the forward strand.

      You could easily edit the above loop based code to build up a list of the +

      Note that here we are counting the frames from the 5’ end (start) of +each strand. It is sometimes easier to always count from the 5’ end +(start) of the forward strand.

      You could easily edit the above loop based code to build up a list of the candidate proteins, or convert this to a list comprehension. Now, one thing -this code doesn’t do is keep track of where the proteins are.

      You could tackle this in several ways. For example, the following code tracks +this code doesn’t do is keep track of where the proteins are.

      You could tackle this in several ways. For example, the following code tracks the locations in terms of the protein counting, and converts back to the parent sequence by multiplying by three, then adjusting for the frame and -strand:

      from Bio import SeqIO 
      +strand:

      from Bio import SeqIO 
       record = SeqIO.read("NC_005816.gb","genbank")
       table = 11
       min_pro_len = 100
      @@ -10903,9 +11225,9 @@
       
       orf_list = find_orfs_with_trans(record.seq, table, min_pro_len)
       for start, end, strand, pro in orf_list:
      -    print "%s...%s - length %i, strand %i, %i:%i" \
      -          % (pro[:30], pro[-3:], len(pro), strand, start, end)
      -

      And the output:

      NQIQGVICSPDSGEFMVTFETVMEIKILHK...GVA - length 355, strand 1, 41:1109
      +    print("%s...%s - length %i, strand %i, %i:%i" \
      +          % (pro[:30], pro[-3:], len(pro), strand, start, end))
      +

      And the output:

      NQIQGVICSPDSGEFMVTFETVMEIKILHK...GVA - length 355, strand 1, 41:1109
       WDVKTVTGVLHHPFHLTFSLCPEGATQSGR...VKR - length 111, strand -1, 491:827
       KSGELRQTPPASSTLHLRLILQRSGVMMEL...NPE - length 285, strand 1, 1030:1888
       RALTGLSAPGIRSQTSCDRLRELRYVPVSL...PLQ - length 119, strand -1, 2830:3190
      @@ -10919,34 +11241,36 @@
       WGKLQVIGLSMWMVLFSQRFDDWLNEQEDA...ESK - length 125, strand -1, 8087:8465
       TGKQNSCQMSAIWQLRQNTATKTRQNRARI...AIK - length 100, strand 1, 8741:9044
       QGSGYAFPHASILSGIAMSHFYFLVLHAVK...CSD - length 114, strand -1, 9264:9609
      -

      If you comment out the sort statement, then the protein sequences will be +

      If you comment out the sort statement, then the protein sequences will be shown in the same order as before, so you can check this is doing the same thing. Here we have sorted them by location to make it easier to compare to the actual annotation in the GenBank file (as visualised in -Section 17.1.9).

      If however all you want to find are the locations of the open reading frames, +Section 17.1.9).

      If however all you want to find are the locations of the open reading frames, then it is a waste of time to translate every possible codon, including doing the reverse complement to search the reverse strand too. All you need to do is search for the possible stop codons (and their reverse complements). Using regular expressions is an obvious approach here (see the Python module -re). These are an extremely powerful (but rather complex) way of +re). These are an extremely powerful (but rather complex) way of describing search strings, which are supported in lots of programming -languages and also command line tools like grep as well). You can -find whole books about this topic!

      -

      18.2  Sequence parsing plus simple plots

      -

      This section shows some more examples of sequence parsing, using the Bio.SeqIO -module described in Chapter 5, plus the Python library matplotlib’s pylab plotting interface (see the matplotlib website for a tutorial). Note that to follow these examples you will need matplotlib installed - but without it you can still try the data parsing bits.

      -

      18.2.1  Histogram of sequence lengths

      There are lots of times when you might want to visualise the distribution of sequence +languages and also command line tools like grep as well). You can +find whole books about this topic!

      + +

      18.2  Sequence parsing plus simple plots

      +

      This section shows some more examples of sequence parsing, using the Bio.SeqIO +module described in Chapter 5, plus the Python library matplotlib’s pylab plotting interface (see the matplotlib website for a tutorial). Note that to follow these examples you will need matplotlib installed - but without it you can still try the data parsing bits.

      + +

      18.2.1  Histogram of sequence lengths

      There are lots of times when you might want to visualise the distribution of sequence lengths in a dataset – for example the range of contig sizes in a genome assembly -project. In this example we’ll reuse our orchid FASTA file ls_orchid.fasta which has only 94 sequences.

      First of all, we will use Bio.SeqIO to parse the FASTA file and compile a list +project. In this example we’ll reuse our orchid FASTA file ls_orchid.fasta which has only 94 sequences.

      First of all, we will use Bio.SeqIO to parse the FASTA file and compile a list of all the sequence lengths. You could do this with a for loop, but I find a list -comprehension more pleasing:

      >>> from Bio import SeqIO
      +comprehension more pleasing:

      >>> from Bio import SeqIO
       >>> sizes = [len(rec) for rec in SeqIO.parse("ls_orchid.fasta", "fasta")]
       >>> len(sizes), min(sizes), max(sizes)
       (94, 572, 789)
       >>> sizes
       [740, 753, 748, 744, 733, 718, 730, 704, 740, 709, 700, 726, ..., 592]
      -

      Now that we have the lengths of all the genes (as a list of integers), we can use the -matplotlib histogram function to display it.

      from Bio import SeqIO
      +

      Now that we have the lengths of all the genes (as a list of integers), we can use the +matplotlib histogram function to display it.

      from Bio import SeqIO
       sizes = [len(rec) for rec in SeqIO.parse("ls_orchid.fasta", "fasta")]
       
       import pylab
      @@ -10956,33 +11280,35 @@
       pylab.xlabel("Sequence length (bp)")
       pylab.ylabel("Count")
       pylab.show()
      -

      -That should pop up a new window containing the following graph:

      +

      +That should pop up a new window containing the following graph:

      Notice that most of these orchid sequences are about 740 bp long, and there could be -two distinct classes of sequence here with a subset of shorter sequences.

      Tip: Rather than using pylab.show() to show the plot in a window, you can also use pylab.savefig(...) to save the figure to a file (e.g. as a PNG or PDF).

      -

      18.2.2  Plot of sequence GC%

      Another easily calculated quantity of a nucleotide sequence is the GC%. You might +two distinct classes of sequence here with a subset of shorter sequences.

      Tip: Rather than using pylab.show() to show the plot in a window, you can also use pylab.savefig(...) to save the figure to a file (e.g. as a PNG or PDF).

      + +

      18.2.2  Plot of sequence GC%

      Another easily calculated quantity of a nucleotide sequence is the GC%. You might want to look at the GC% of all the genes in a bacterial genome for example, and investigate any outliers which could have been recently acquired by horizontal gene -transfer. Again, for this example we’ll reuse our orchid FASTA file ls_orchid.fasta.

      First of all, we will use Bio.SeqIO to parse the FASTA file and compile a list -of all the GC percentages. Again, you could do this with a for loop, but I prefer this:

      from Bio import SeqIO
      +transfer. Again, for this example we’ll reuse our orchid FASTA file ls_orchid.fasta.

      First of all, we will use Bio.SeqIO to parse the FASTA file and compile a list +of all the GC percentages. Again, you could do this with a for loop, but I prefer this:

      from Bio import SeqIO
       from Bio.SeqUtils import GC
       
       gc_values = sorted(GC(rec.seq) for rec in SeqIO.parse("ls_orchid.fasta", "fasta"))
      -

      Having read in each sequence and calculated the GC%, we then sorted them into ascending -order. Now we’ll take this list of floating point values and plot them with matplotlib:

      import pylab
      +

      Having read in each sequence and calculated the GC%, we then sorted them into ascending +order. Now we’ll take this list of floating point values and plot them with matplotlib:

      import pylab
       pylab.plot(gc_values)
       pylab.title("%i orchid sequences\nGC%% %0.1f to %0.1f" \
                   % (len(gc_values),min(gc_values),max(gc_values)))
       pylab.xlabel("Genes")
       pylab.ylabel("GC%")
       pylab.show()
      -

      -As in the previous example, that should pop up a new window containing a graph:

      +

      +As in the previous example, that should pop up a new window containing a graph:

      If you tried this on the full set of genes from one organism, you’d probably get a much -smoother plot than this.

      -

      18.2.3  Nucleotide dot plots

      +smoother plot than this.

      + +

      18.2.3  Nucleotide dot plots

      A dot plot is a way of visually comparing two nucleotide sequences for similarity to each other. A sliding window is used to compare short sub-sequences to each other, often with a mis-match threshold. Here for simplicity we’ll only look for perfect @@ -10990,49 +11316,49 @@ in the plot below). -

      To start off, we’ll need two sequences. For the sake of argument, we’ll just take -the first two from our orchid FASTA file ls_orchid.fasta:

      from Bio import SeqIO
      +

      To start off, we’ll need two sequences. For the sake of argument, we’ll just take +the first two from our orchid FASTA file ls_orchid.fasta:

      from Bio import SeqIO
       handle = open("ls_orchid.fasta")
       record_iterator = SeqIO.parse(handle, "fasta")
      -rec_one = record_iterator.next()
      -rec_two = record_iterator.next()
      +rec_one = next(record_iterator)
      +rec_two = next(record_iterator)
       handle.close()
      -

      We’re going to show two approaches. Firstly, a simple naive implementation +

      We’re going to show two approaches. Firstly, a simple naive implementation which compares all the window sized sub-sequences to each other to compiles a similarity matrix. You could construct a matrix or array object, but here we just use a list of lists of booleans created with a nested list -comprehension:

      window = 7
      +comprehension:

      window = 7
       seq_one = str(rec_one.seq).upper()
       seq_two = str(rec_two.seq).upper()
       data = [[(seq_one[i:i+window] <> seq_two[j:j+window]) \
               for j in range(len(seq_one)-window)] \
              for i in range(len(seq_two)-window)]
      -

      Note that we have not checked for reverse complement matches here. -Now we’ll use the matplotlib’s pylab.imshow() function to display this +

      Note that we have not checked for reverse complement matches here. +Now we’ll use the matplotlib’s pylab.imshow() function to display this data, first requesting the gray color scheme so this is done in black and -white:

      import pylab
      +white:

      import pylab
       pylab.gray()
       pylab.imshow(data)
       pylab.xlabel("%s (length %i bp)" % (rec_one.id, len(rec_one)))
       pylab.ylabel("%s (length %i bp)" % (rec_two.id, len(rec_two)))
       pylab.title("Dot plot using window size %i\n(allowing no mis-matches)" % window)
       pylab.show()
      -

      -That should pop up a new window containing a graph like this:

      +

      +That should pop up a new window containing a graph like this:

      As you might have expected, these two sequences are very similar with a partial line of window sized matches along the diagonal. There are no off diagonal matches which would be indicative of inversions or other interesting -events.

      The above code works fine on small examples, but there are two problems +events.

      The above code works fine on small examples, but there are two problems applying this to larger sequences, which we will address below. First off all, this brute force approach to the all against all comparisons is very slow. Instead, we’ll compile dictionaries mapping the window sized sub-sequences to their locations, and then take the set intersection to find those sub-sequences found in both sequences. This uses more memory, but is -much faster. Secondly, the pylab.imshow() function is limited +much faster. Secondly, the pylab.imshow() function is limited in the size of matrix it can display. As an alternative, we’ll use the -pylab.scatter() function.

      We start by creating dictionaries mapping the window-sized sub-sequences to locations: -

      window = 7
      +pylab.scatter() function.

      We start by creating dictionaries mapping the window-sized sub-sequences to locations: +

      window = 7
       dict_one = {}
       dict_two = {}
       for (seq, section_dict) in [(str(rec_one.seq).upper(), dict_one),
      @@ -11046,9 +11372,9 @@
       #Now find any sub-sequences found in both sequences
       #(Python 2.3 would require slightly different code here)
       matches = set(dict_one).intersection(dict_two)
      -print "%i unique matches" % len(matches)
      -

      In order to use the pylab.scatter() we need separate lists for the x and y co-ordinates: -

      #Create lists of x and y co-ordinates for scatter plot
      +print("%i unique matches" % len(matches))
      +

      In order to use the pylab.scatter() we need separate lists for the x and y co-ordinates: +

      #Create lists of x and y co-ordinates for scatter plot
       x = []
       y = []
       for section in matches:
      @@ -11056,8 +11382,8 @@
               for j in dict_two[section]:
                   x.append(i)
                   y.append(j)
      -

      We are now ready to draw the revised dot plot as a scatter plot: -

      import pylab
      +

      We are now ready to draw the revised dot plot as a scatter plot: +

      import pylab
       pylab.cla() #clear any prior graph
       pylab.gray()
       pylab.scatter(x,y)
      @@ -11067,24 +11393,25 @@
       pylab.ylabel("%s (length %i bp)" % (rec_two.id, len(rec_two)))
       pylab.title("Dot plot using window size %i\n(allowing no mis-matches)" % window)
       pylab.show()
      -

      -That should pop up a new window containing a graph like this:

      +

      +That should pop up a new window containing a graph like this:

      Personally I find this second plot much easier to read! -Again note that we have not checked for reverse complement matches here +Again note that we have not checked for reverse complement matches here – you could extend this example to do this, and perhaps plot the forward -matches in one color and the reverse matches in another.

      -

      18.2.4  Plotting the quality scores of sequencing read data

      If you are working with second generation sequencing data, you may want to try plotting +matches in one color and the reverse matches in another.

      + +

      18.2.4  Plotting the quality scores of sequencing read data

      If you are working with second generation sequencing data, you may want to try plotting the quality data. Here is an example using two FASTQ files containing paired end reads, -SRR001666_1.fastq for the forward reads, and SRR001666_2.fastq for +SRR001666_1.fastq for the forward reads, and SRR001666_2.fastq for the reverse reads. These were downloaded from the ENA sequence read archive FTP site -(ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR001/SRR001666/SRR001666_1.fastq.gz and -ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR001/SRR001666/SRR001666_2.fastq.gz), and -are from E. coli – see http://www.ebi.ac.uk/ena/data/view/SRR001666 +(ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR001/SRR001666/SRR001666_1.fastq.gz and +ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR001/SRR001666/SRR001666_2.fastq.gz), and +are from E. coli – see http://www.ebi.ac.uk/ena/data/view/SRR001666 for details. -

      In the following code the pylab.subplot(...) function is used in order to show +

      In the following code the pylab.subplot(...) function is used in order to show the forward and reverse qualities on two subplots, side by side. There is also a little -bit of code to only plot the first fifty reads.

      import pylab
      +bit of code to only plot the first fifty reads.

      import pylab
       from Bio import SeqIO
       for subfigure in [1,2]:
           filename = "SRR001666_%i.fastq" % subfigure
      @@ -11096,52 +11423,58 @@
           pylab.ylabel("PHRED quality score")
           pylab.xlabel("Position")
       pylab.savefig("SRR001666.png")
      -print "Done"
      -

      You should note that we are using the Bio.SeqIO format name fastq +print("Done") +

      You should note that we are using the Bio.SeqIO format name fastq here because the NCBI has saved these reads using the standard Sanger FASTQ format with PHRED scores. However, as you might guess from the read lengths, this data was from an Illumina Genome Analyzer and was probably originally in one of the two -Solexa/Illumina FASTQ variant file formats instead.

      This example uses the pylab.savefig(...) function instead of -pylab.show(...), but as mentioned before both are useful. +Solexa/Illumina FASTQ variant file formats instead.

      This example uses the pylab.savefig(...) function instead of +pylab.show(...), but as mentioned before both are useful. -Here is the result:

      -

      18.3  Dealing with alignments

      This section can been seen as a follow on to Chapter 6.

      -

      18.3.1  Calculating summary information

      -

      Once you have an alignment, you are very likely going to want to find out information about it. Instead of trying to have all of the functions that can generate information about an alignment in the alignment object itself, we’ve tried to separate out the functionality into separate classes, which act on the alignment.

      Getting ready to calculate summary information about an object is quick to do. Let’s say we’ve got an alignment object called alignment, for example read in using Bio.AlignIO.read(...) as described in Chapter 6. All we need to do to get an object that will calculate summary information is:

      from Bio.Align import AlignInfo
      +Here is the result:

      + +

      18.3  Dealing with alignments

      This section can been seen as a follow on to Chapter 6.

      + +

      18.3.1  Calculating summary information

      +

      Once you have an alignment, you are very likely going to want to find out information about it. Instead of trying to have all of the functions that can generate information about an alignment in the alignment object itself, we’ve tried to separate out the functionality into separate classes, which act on the alignment.

      Getting ready to calculate summary information about an object is quick to do. Let’s say we’ve got an alignment object called alignment, for example read in using Bio.AlignIO.read(...) as described in Chapter 6. All we need to do to get an object that will calculate summary information is:

      from Bio.Align import AlignInfo
       summary_align = AlignInfo.SummaryInfo(alignment)
      -

      The summary_align object is very useful, and will do the following neat things for you:

      1. -Calculate a quick consensus sequence – see section 18.3.2 -
      2. Get a position specific score matrix for the alignment – see section 18.3.3 -
      3. Calculate the information content for the alignment – see section 18.3.4 -
      4. Generate information on substitutions in the alignment – section 18.4 details using this to generate a substitution matrix. -
      -

      18.3.2  Calculating a quick consensus sequence

      -

      The SummaryInfo object, described in section 18.3.1, provides functionality to calculate a quick consensus of an alignment. Assuming we’ve got a SummaryInfo object called summary_align we can calculate a consensus by doing:

      consensus = summary_align.dumb_consensus()
      -

      As the name suggests, this is a really simple consensus calculator, and will just add up all of the residues at each point in the consensus, and if the most common value is higher than some threshold value will add the common residue to the consensus. If it doesn’t reach the threshold, it adds an ambiguity character to the consensus. The returned consensus object is Seq object whose alphabet is inferred from the alphabets of the sequences making up the consensus. So doing a print consensus would give:

      consensus Seq('TATACATNAAAGNAGGGGGATGCGGATAAATGGAAAGGCGAAAGAAAGAAAAAAATGAAT
      +

      The summary_align object is very useful, and will do the following neat things for you:

      1. +Calculate a quick consensus sequence – see section 18.3.2 +
      2. Get a position specific score matrix for the alignment – see section 18.3.3 +
      3. Calculate the information content for the alignment – see section 18.3.4 +
      4. Generate information on substitutions in the alignment – section 18.4 details using this to generate a substitution matrix. +
      + +

      18.3.2  Calculating a quick consensus sequence

      +

      The SummaryInfo object, described in section 18.3.1, provides functionality to calculate a quick consensus of an alignment. Assuming we’ve got a SummaryInfo object called summary_align we can calculate a consensus by doing:

      consensus = summary_align.dumb_consensus()
      +

      As the name suggests, this is a really simple consensus calculator, and will just add up all of the residues at each point in the consensus, and if the most common value is higher than some threshold value will add the common residue to the consensus. If it doesn’t reach the threshold, it adds an ambiguity character to the consensus. The returned consensus object is Seq object whose alphabet is inferred from the alphabets of the sequences making up the consensus. So doing a print consensus would give:

      consensus Seq('TATACATNAAAGNAGGGGGATGCGGATAAATGGAAAGGCGAAAGAAAGAAAAAAATGAAT
       ...', IUPACAmbiguousDNA())
      -

      You can adjust how dumb_consensus works by passing optional parameters:

      -the threshold
      This is the threshold specifying how common a particular residue has to be at a position before it is added. The default is 0.7 (meaning 70%).
      the ambiguous character
      This is the ambiguity character to use. The default is ’N’.
      the consensus alphabet
      This is the alphabet to use for the consensus sequence. If an alphabet is not specified than we will try to guess the alphabet based on the alphabets of the sequences in the alignment. -
      -

      18.3.3  Position Specific Score Matrices

      -

      Position specific score matrices (PSSMs) summarize the alignment information in a different way than a consensus, and may be useful for different tasks. Basically, a PSSM is a count matrix. For each column in the alignment, the number of each alphabet letters is counted and totaled. The totals are displayed relative to some representative sequence along the left axis. This sequence may be the consesus sequence, but can also be any sequence in the alignment. For instance for the alignment,

      GTATC
      +

      You can adjust how dumb_consensus works by passing optional parameters:

      +the threshold
      This is the threshold specifying how common a particular residue has to be at a position before it is added. The default is 0.7 (meaning 70%).
      the ambiguous character
      This is the ambiguity character to use. The default is ’N’.
      the consensus alphabet
      This is the alphabet to use for the consensus sequence. If an alphabet is not specified than we will try to guess the alphabet based on the alphabets of the sequences in the alignment. +
      + +

      18.3.3  Position Specific Score Matrices

      +

      Position specific score matrices (PSSMs) summarize the alignment information in a different way than a consensus, and may be useful for different tasks. Basically, a PSSM is a count matrix. For each column in the alignment, the number of each alphabet letters is counted and totaled. The totals are displayed relative to some representative sequence along the left axis. This sequence may be the consesus sequence, but can also be any sequence in the alignment. For instance for the alignment,

      GTATC
       AT--C
       CTGTC
      -

      the PSSM is:

            G A T C
      +

      the PSSM is:

            G A T C
           G 1 1 0 1
           T 0 0 3 0
           A 1 1 0 0
           T 0 0 2 0
           C 0 0 0 3
      -

      Let’s assume we’ve got an alignment object called c_align. To get a PSSM with the consensus sequence along the side we first get a summary object and calculate the consensus sequence:

      summary_align = AlignInfo.SummaryInfo(c_align)
      +

      Let’s assume we’ve got an alignment object called c_align. To get a PSSM with the consensus sequence along the side we first get a summary object and calculate the consensus sequence:

      summary_align = AlignInfo.SummaryInfo(c_align)
       consensus = summary_align.dumb_consensus()
      -

      Now, we want to make the PSSM, but ignore any N ambiguity residues when calculating this:

      my_pssm = summary_align.pos_specific_score_matrix(consensus,
      +

      Now, we want to make the PSSM, but ignore any N ambiguity residues when calculating this:

      my_pssm = summary_align.pos_specific_score_matrix(consensus,
                                                         chars_to_ignore = ['N'])
      -

      Two notes should be made about this:

      1. -To maintain strictness with the alphabets, you can only include characters along the top of the PSSM that are in the alphabet of the alignment object. Gaps are not included along the top axis of the PSSM.
      2. The sequence passed to be displayed along the left side of the axis does not need to be the consensus. For instance, if you wanted to display the second sequence in the alignment along this axis, you would need to do:
        second_seq = alignment.get_seq_by_num(1)
        +

        Two notes should be made about this:

        1. +To maintain strictness with the alphabets, you can only include characters along the top of the PSSM that are in the alphabet of the alignment object. Gaps are not included along the top axis of the PSSM.
        2. The sequence passed to be displayed along the left side of the axis does not need to be the consensus. For instance, if you wanted to display the second sequence in the alignment along this axis, you would need to do:
          second_seq = alignment.get_seq_by_num(1)
           my_pssm = summary_align.pos_specific_score_matrix(second_seq
                                                             chars_to_ignore = ['N'])
          -

        The command above returns a PSSM object. To print out the PSSM as we showed above, we simply need to do a print my_pssm, which gives:

            A   C   G   T
        +

      The command above returns a PSSM object. +To print out the PSSM as shown above, +we simply need to do a print(my_pssm), which gives:

          A   C   G   T
       T  0.0 0.0 0.0 7.0
       A  7.0 0.0 0.0 0.0
       T  0.0 0.0 0.0 7.0
      @@ -11151,65 +11484,69 @@
       T  0.0 0.0 0.0 7.0
       T  1.0 0.0 0.0 6.0
       ...
      -

      You can access any element of the PSSM by subscripting like your_pssm[sequence_number][residue_count_name]. For instance, to get the counts for the ’A’ residue in the second element of the above PSSM you would do:

      >>> print my_pssm[1]["A"]
      +

      You can access any element of the PSSM by subscripting like your_pssm[sequence_number][residue_count_name]. For instance, to get the counts for the ’A’ residue in the second element of the above PSSM you would do:

      >>> print(my_pssm[1]["A"])
       7.0
      -

      The structure of the PSSM class hopefully makes it easy both to access elements and to pretty print the matrix.

      -

      18.3.4  Information Content

      -

      A potentially useful measure of evolutionary conservation is the information content of a sequence.

      A useful introduction to information theory targeted towards molecular biologists can be found at http://www.lecb.ncifcrf.gov/~toms/paper/primer/. For our purposes, we will be looking at the information content of a consesus sequence, or a portion of a consensus sequence. We calculate information content at a particular column in a multiple sequence alignment using the following formula:

      -
      ICj =  - - -
      Na
      i=1
       Pij log
      -⎜
      -⎜
      -⎝
      - - -
      Pij
      Qi

      -⎟
      -⎟
      -⎠

      where:

      • -ICj – The information content for the j-th column in an alignment. -
      • Na – The number of letters in the alphabet. -
      • Pij – The frequency of a particular letter i in the j-th column (i. e. if G occurred 3 out of 6 times in an aligment column, this would be 0.5) -
      • Qi – The expected frequency of a letter i. This is an +

      The structure of the PSSM class hopefully makes it easy both to access elements and to pretty print the matrix.

      + +

      18.3.4  Information Content

      +

      A potentially useful measure of evolutionary conservation is the information content of a sequence.

      A useful introduction to information theory targeted towards molecular biologists can be found at http://www.lecb.ncifcrf.gov/~toms/paper/primer/. For our purposes, we will be looking at the information content of a consesus sequence, or a portion of a consensus sequence. We calculate information content at a particular column in a multiple sequence alignment using the following formula:

      +
      ICj =  + + +
      Na
      i=1
       Pij log
      +⎜
      +⎜
      +⎝
      + + +
      Pij
      Qi

      +⎟
      +⎟
      +⎠

      where:

      • +ICj – The information content for the j-th column in an alignment. +
      • Na – The number of letters in the alphabet. +
      • Pij – The frequency of a particular letter i in the j-th column (i. e. if G occurred 3 out of 6 times in an aligment column, this would be 0.5) +
      • Qi – The expected frequency of a letter i. This is an optional argument, usage of which is left at the user’s discretion. By default, it is automatically assigned to 0.05 = 1/20 for a protein alphabet, and 0.25 = 1/4 for a nucleic acid alphabet. This is for geting the information content without any assumption of prior distributions. When assuming priors, or when using a non-standard -alphabet, you should supply the values for Qi. -

      Well, now that we have an idea what information content is being calculated in Biopython, let’s look at how to get it for a particular region of the alignment.

      First, we need to use our alignment to get an alignment summary object, which we’ll assume is called summary_align (see section 18.3.1) for instructions on how to get this. Once we’ve got this object, calculating the information content for a region is as easy as:

      info_content = summary_align.information_content(5, 30,
      +alphabet, you should supply the values for Qi.
      +

    Well, now that we have an idea what information content is being calculated in Biopython, let’s look at how to get it for a particular region of the alignment.

    First, we need to use our alignment to get an alignment summary object, which we’ll assume is called summary_align (see section 18.3.1) for instructions on how to get this. Once we’ve got this object, calculating the information content for a region is as easy as:

    info_content = summary_align.information_content(5, 30,
                                                      chars_to_ignore = ['N'])
    -

    Wow, that was much easier then the formula above made it look! The variable info_content now contains a float value specifying the information content over the specified region (from 5 to 30 of the alignment). We specifically ignore the ambiguity residue ’N’ when calculating the information content, since this value is not included in our alphabet (so we shouldn’t be interested in looking at it!).

    As mentioned above, we can also calculate relative information content by supplying the expected frequencies:

    expect_freq = {
    +

    Wow, that was much easier then the formula above made it look! The variable info_content now contains a float value specifying the information content over the specified region (from 5 to 30 of the alignment). We specifically ignore the ambiguity residue ’N’ when calculating the information content, since this value is not included in our alphabet (so we shouldn’t be interested in looking at it!).

    As mentioned above, we can also calculate relative information content by supplying the expected frequencies:

    expect_freq = {
         'A' : .3,
         'G' : .2,
         'T' : .3,
         'C' : .2}
    -

    The expected should not be passed as a raw dictionary, but instead by passed as a SubsMat.FreqTable object (see section 20.2.2 for more information about FreqTables). The FreqTable object provides a standard for associating the dictionary with an Alphabet, similar to how the Biopython Seq class works.

    To create a FreqTable object, from the frequency dictionary you just need to do:

    from Bio.Alphabet import IUPAC
    +

    The expected should not be passed as a raw dictionary, but instead by passed as a SubsMat.FreqTable object (see section 20.2.2 for more information about FreqTables). The FreqTable object provides a standard for associating the dictionary with an Alphabet, similar to how the Biopython Seq class works.

    To create a FreqTable object, from the frequency dictionary you just need to do:

    from Bio.Alphabet import IUPAC
     from Bio.SubsMat import FreqTable
     
     e_freq_table = FreqTable.FreqTable(expect_freq, FreqTable.FREQ,
                                        IUPAC.unambiguous_dna)
    -

    Now that we’ve got that, calculating the relative information content for our region of the alignment is as simple as:

    info_content = summary_align.information_content(5, 30,
    +

    Now that we’ve got that, calculating the relative information content for our region of the alignment is as simple as:

    info_content = summary_align.information_content(5, 30,
                                                      e_freq_table = e_freq_table,
                                                      chars_to_ignore = ['N'])
    -

    Now, info_content will contain the relative information content over the region in relation to the expected frequencies.

    The value return is calculated using base 2 as the logarithm base in the formula above. You can modify this by passing the parameter log_base as the base you want:

    info_content = summary_align.information_content(5, 30, log_base = 10,
    +

    Now, info_content will contain the relative information content over the region in relation to the expected frequencies.

    The value return is calculated using base 2 as the logarithm base in the formula above. You can modify this by passing the parameter log_base as the base you want:

    info_content = summary_align.information_content(5, 30, log_base = 10,
                                                      chars_to_ignore = ['N'])
    -

    Well, now you are ready to calculate information content. If you want to try applying this to some real life problems, it would probably be best to dig into the literature on information content to get an idea of how it is used. Hopefully your digging won’t reveal any mistakes made in coding this function!

    -

    18.4  Substitution Matrices

    -

    Substitution matrices are an extremely important part of everyday bioinformatics work. They provide the scoring terms for classifying how likely two different residues are to substitute for each other. This is essential in doing sequence comparisons. The book “Biological Sequence Analysis” by Durbin et al. provides a really nice introduction to Substitution Matrices and their uses. Some famous substitution matrices are the PAM and BLOSUM series of matrices.

    Biopython provides a ton of common substitution matrices, and also provides functionality for creating your own substitution matrices.

    -

    18.4.1  Using common substitution matrices

    -

    18.4.2  Creating your own substitution matrix from an alignment

    -

    A very cool thing that you can do easily with the substitution matrix +

    Well, now you are ready to calculate information content. If you want to try applying this to some real life problems, it would probably be best to dig into the literature on information content to get an idea of how it is used. Hopefully your digging won’t reveal any mistakes made in coding this function!

    + +

    18.4  Substitution Matrices

    +

    Substitution matrices are an extremely important part of everyday bioinformatics work. They provide the scoring terms for classifying how likely two different residues are to substitute for each other. This is essential in doing sequence comparisons. The book “Biological Sequence Analysis” by Durbin et al. provides a really nice introduction to Substitution Matrices and their uses. Some famous substitution matrices are the PAM and BLOSUM series of matrices.

    Biopython provides a ton of common substitution matrices, and also provides functionality for creating your own substitution matrices.

    + +

    18.4.1  Using common substitution matrices

    + +

    18.4.2  Creating your own substitution matrix from an alignment

    +

    A very cool thing that you can do easily with the substitution matrix classes is to create your own substitution matrix from an alignment. In practice, this is normally done with protein alignments. In this example, we’ll first get a Biopython alignment object and then get a summary object to calculate info about the -alignment. The file containing protein.aln +alignment. The file containing protein.aln (also available online -here) -contains the Clustalw alignment output.

    >>> from Bio import AlignIO
    +here)
    +contains the Clustalw alignment output.

    >>> from Bio import AlignIO
     >>> from Bio import Alphabet
     >>> from Bio.Alphabet import IUPAC
     >>> from Bio.Align import AlignInfo
    @@ -11217,66 +11554,68 @@
     >>> alpha = Alphabet.Gapped(IUPAC.protein)
     >>> c_align = AlignIO.read(filename, "clustal", alphabet=alpha)
     >>> summary_align = AlignInfo.SummaryInfo(c_align)
    -

    Sections 6.4.1 and 18.3.1 contain -more information on doing this.

    Now that we’ve got our summary_align object, we want to use it +

    Sections 6.4.1 and 18.3.1 contain +more information on doing this.

    Now that we’ve got our summary_align object, we want to use it to find out the number of times different residues substitute for each other. To make the example more readable, we’ll focus on only amino acids with polar charged side chains. Luckily, this can be done easily when generating a replacement dictionary, by passing in all of the characters that should be ignored. Thus we’ll create a dictionary of -replacements for only charged polar amino acids using:

    >>> replace_info = summary_align.replacement_dictionary(["G", "A", "V", "L", "I",
    +replacements for only charged polar amino acids using:

    >>> replace_info = summary_align.replacement_dictionary(["G", "A", "V", "L", "I",
     ...                                                      "M", "P", "F", "W", "S",
     ...                                                      "T", "N", "Q", "Y", "C"])
    -

    This information about amino acid replacements is represented as a -python dictionary which will look something like (the order can vary):

    {('R', 'R'): 2079.0, ('R', 'H'): 17.0, ('R', 'K'): 103.0, ('R', 'E'): 2.0,
    +

    This information about amino acid replacements is represented as a +python dictionary which will look something like (the order can vary):

    {('R', 'R'): 2079.0, ('R', 'H'): 17.0, ('R', 'K'): 103.0, ('R', 'E'): 2.0,
     ('R', 'D'): 2.0, ('H', 'R'): 0, ('D', 'H'): 15.0, ('K', 'K'): 3218.0,
     ('K', 'H'): 24.0, ('H', 'K'): 8.0, ('E', 'H'): 15.0, ('H', 'H'): 1235.0,
     ('H', 'E'): 18.0, ('H', 'D'): 0, ('K', 'D'): 0, ('K', 'E'): 9.0,
     ('D', 'R'): 48.0, ('E', 'R'): 2.0, ('D', 'K'): 1.0, ('E', 'K'): 45.0,
     ('K', 'R'): 130.0, ('E', 'D'): 241.0, ('E', 'E'): 3305.0,
     ('D', 'E'): 270.0, ('D', 'D'): 2360.0}
    -

    This information gives us our accepted number of replacements, or how +

    This information gives us our accepted number of replacements, or how often we expect different things to substitute for each other. It turns out, amazingly enough, that this is all of the information we need to go ahead and create a substitution matrix. First, we use the replacement dictionary information to create an Accepted Replacement -Matrix (ARM):

    >>> from Bio import SubsMat
    +Matrix (ARM):

    >>> from Bio import SubsMat
     >>> my_arm = SubsMat.SeqMat(replace_info)
    -

    With this accepted replacement matrix, we can go right ahead and -create our log odds matrix (i. e. a standard type Substitution Matrix):

    >>> my_lom = SubsMat.make_log_odds_matrix(my_arm)
    -

    The log odds matrix you create is customizable with the following -optional arguments:

    • -exp_freq_table – You can pass a table of expected +

    With this accepted replacement matrix, we can go right ahead and +create our log odds matrix (i. e. a standard type Substitution Matrix):

    >>> my_lom = SubsMat.make_log_odds_matrix(my_arm)
    +

    The log odds matrix you create is customizable with the following +optional arguments:

    • +exp_freq_table – You can pass a table of expected frequencies for each alphabet. If supplied, this will be used instead of the passed accepted replacement matrix when calculate -expected replacments.
    • logbase - The base of the logarithm taken to create the -log odd matrix. Defaults to base 10.
    • factor - The factor to multiply each matrix entry +expected replacments.
    • logbase - The base of the logarithm taken to create the +log odd matrix. Defaults to base 10.
    • factor - The factor to multiply each matrix entry by. This defaults to 10, which normally makes the matrix numbers -easy to work with.
    • round_digit - The digit to round to in the matrix. This -defaults to 0 (i. e. no digits).

    Once you’ve got your log odds matrix, you can display it prettily -using the function print_mat. Doing this on our created matrix -gives:

    >>> my_lom.print_mat()
    +easy to work with.
  • round_digit - The digit to round to in the matrix. This +defaults to 0 (i. e. no digits).
  • Once you’ve got your log odds matrix, you can display it prettily +using the function print_mat. Doing this on our created matrix +gives:

    >>> my_lom.print_mat()
     D   2
     E  -1   1
     H  -5  -4   3
     K -10  -5  -4   1
     R  -4  -8  -4  -2   2
        D   E   H   K   R
    -

    Very nice. Now we’ve got our very own substitution matrix to play with!

    -

    18.5  BioSQL – storing sequences in a relational database

    - -BioSQL is a joint effort between the -OBF projects (BioPerl, BioJava etc) to support a +

    Very nice. Now we’ve got our very own substitution matrix to play with!

    + +

    18.5  BioSQL – storing sequences in a relational database

    + +BioSQL is a joint effort between the +OBF projects (BioPerl, BioJava etc) to support a shared database schema for storing sequence data. In theory, you could load a GenBank file into the database with BioPerl, then using Biopython extract this from the database as a record object with features - and get more or less the same thing as if you had loaded the GenBank file directly as a SeqRecord using -Bio.SeqIO (Chapter 5).

    Biopython’s BioSQL module is currently documented at -http://biopython.org/wiki/BioSQL which is part of our wiki pages.

    -

    Chapter 19  The Biopython testing framework

    -

    Biopython has a regression testing framework (the file -run_tests.py) based on -unittest, +Bio.SeqIO (Chapter 5).

    Biopython’s BioSQL module is currently documented at +http://biopython.org/wiki/BioSQL which is part of our wiki pages.

    + +

    Chapter 19  The Biopython testing framework

    +

    Biopython has a regression testing framework (the file +run_tests.py) based on +unittest, the standard unit testing framework for Python. Providing comprehensive tests for modules is one of the most important aspects of making sure that the Biopython code is as bug-free as possible before going out. @@ -11286,68 +11625,70 @@ Ideally, every module that goes into Biopython should have a test (and should also have documentation!). All our developers, and anyone installing Biopython from source, -are strongly encouraged to run the unit tests.

    -

    19.1  Running the tests

    When you download the Biopython source code, or check it out from +are strongly encouraged to run the unit tests.

    + +

    19.1  Running the tests

    When you download the Biopython source code, or check it out from our source code repository, you should find a subdirectory call -Tests. This contains the key script run_tests.py, -lots of individual scripts named test_XXX.py, a subdirectory -called output and lots of other subdirectories which -contain input files for the test suite.

    As part of building and installing Biopython you will typically +Tests. This contains the key script run_tests.py, +lots of individual scripts named test_XXX.py, a subdirectory +called output and lots of other subdirectories which +contain input files for the test suite.

    As part of building and installing Biopython you will typically run the full test suite at the command line from the Biopython source top level directory using the following: -

    python setup.py test
    -

    This is actually equivalent to going to the Tests +

    python setup.py test
    +

    This is actually equivalent to going to the Tests subdirectory and running: -

    python run_tests.py
    -

    You’ll often want to run just some of the tests, and this is done +

    python run_tests.py
    +

    You’ll often want to run just some of the tests, and this is done like this: -

    python run_tests.py test_SeqIO.py test_AlignIO.py
    -

    When giving the list of tests, the .py extension is optional, +

    python run_tests.py test_SeqIO.py test_AlignIO.py
    +

    When giving the list of tests, the .py extension is optional, so you can also just type: -

    python run_tests.py test_SeqIO test_AlignIO
    -

    To run the docstring tests (see section 19.3), you can use -

    python run_tests.py doctest
    -

    By default, run_tests.py runs all tests, including the docstring tests.

    If an individual test is failing, you can also try running it -directly, which may give you more information.

    Importantly, note that the individual unit tests come in two types: -

    • +

      python run_tests.py test_SeqIO test_AlignIO
      +

      To run the docstring tests (see section 19.3), you can use +

      python run_tests.py doctest
      +

      By default, run_tests.py runs all tests, including the docstring tests.

      If an individual test is failing, you can also try running it +directly, which may give you more information.

      Importantly, note that the individual unit tests come in two types: +

      • Simple print-and-compare scripts. These unit tests are essentially short example Python programs, which print out -various output text. For a test file named test_XXX.py -there will be a matching text file called test_XXX under -the output subdirectory which contains the expected +various output text. For a test file named test_XXX.py +there will be a matching text file called test_XXX under +the output subdirectory which contains the expected output. All that the test framework does to is run the script, and check the output agrees. -
      • Standard unittest- based tests. These will import unittest -and then define unittest.TestCase classes, each with one -or more sub-tests as methods starting with test_ which +
      • Standard unittest- based tests. These will import unittest +and then define unittest.TestCase classes, each with one +or more sub-tests as methods starting with test_ which check some specific aspect of the code. These tests should not print any output directly. -

      -Currently, about half of the Biopython tests are unittest-style tests, and half are print-and-compare tests.

      Running a simple print-and-compare test directly will usually give lots +

    +Currently, about half of the Biopython tests are unittest-style tests, and half are print-and-compare tests.

    Running a simple print-and-compare test directly will usually give lots of output on screen, but does not check the output matches the expected output. If the test is failing with an exception error, it should be very easy to locate where exactly the script is failing. For an example of a print-and-compare test, try: -

    python test_SeqIO.py
    -

    The unittest-based tests instead show you exactly which sub-section(s) of +

    python test_SeqIO.py
    +

    The unittest-based tests instead show you exactly which sub-section(s) of the test are failing. For example, -

    python test_Cluster.py
    -
    -

    19.2  Writing tests

    Let’s say you want to write some tests for a module called Biospam. +

    python test_Cluster.py
    +
    + +

    19.2  Writing tests

    Let’s say you want to write some tests for a module called Biospam. This can be a module you wrote, or an existing module that doesn’t have any tests yet. In the examples below, we assume that -Biospam is a module that does simple math.

    Each Biopython test can have three important files and directories involved with it:

    1. -test_Biospam.py – The actual test code for your module. -
    2. Biospam [optional]– A directory where any necessary input files +Biospam is a module that does simple math.

      Each Biopython test can have three important files and directories involved with it:

      1. +test_Biospam.py – The actual test code for your module. +
      2. Biospam [optional]– A directory where any necessary input files will be located. Any output files that will be generated should also be written here (and preferably cleaned up after the tests are done) to prevent clogging up the main Tests directory. -
      3. output/Biospam – [for print-and-compare tests only] This -file contains the expected output from running test_Biospam.py. -This file is not needed for unittest-style tests, since there -the validation is done in the test script test_Biospam.py itself. -

      It’s up to you to decide whether you want to write a print-and-compare test script or a unittest-style test script. The important thing is that you cannot mix these two styles in a single test script. Particularly, don’t use unittest features in a print-and-compare test.

      Any script with a test_ prefix in the Tests directory will be found and run by run_tests.py. Below, we show an example test script test_Biospam.py both for a print-and-compare test and for a unittest-based test. If you put this script in the Biopython Tests directory, then run_tests.py will find it and execute the tests contained in it: -

      $ python run_tests.py     
      +
    3. output/Biospam – [for print-and-compare tests only] This +file contains the expected output from running test_Biospam.py. +This file is not needed for unittest-style tests, since there +the validation is done in the test script test_Biospam.py itself. +

    It’s up to you to decide whether you want to write a print-and-compare test script or a unittest-style test script. The important thing is that you cannot mix these two styles in a single test script. Particularly, don’t use unittest features in a print-and-compare test.

    Any script with a test_ prefix in the Tests directory will be found and run by run_tests.py. Below, we show an example test script test_Biospam.py both for a print-and-compare test and for a unittest-based test. If you put this script in the Biopython Tests directory, then run_tests.py will find it and execute the tests contained in it: +

    $ python run_tests.py     
     test_Ace ... ok
     test_AlignIO ... ok
     test_BioSQL ... ok
    @@ -11355,59 +11696,62 @@
     test_Biospam ... ok
     test_CAPS ... ok
     test_Clustalw ... ok
    -

    ----------------------------------------------------------------------
    +

    ----------------------------------------------------------------------
     Ran 107 tests in 86.127 seconds
    -
    -

    19.2.1  Writing a print-and-compare test

    A print-and-compare style test should be much simpler for beginners + + +

    19.2.1  Writing a print-and-compare test

    A print-and-compare style test should be much simpler for beginners or novices to write - essentially it is just an example script using -your new module.

    Here is what you should do to make a print-and-compare test for the -Biospam module.

    1. -Write a script called test_Biospam.py
      • This script should live in the Tests directory
      • The script should test all of the important functionality -of the module (the more you test the better your test is, of course!).
      • Try to avoid anything which might be platform specific, +your new module.

        Here is what you should do to make a print-and-compare test for the +Biospam module.

        1. +Write a script called test_Biospam.py
          • This script should live in the Tests directory
          • The script should test all of the important functionality +of the module (the more you test the better your test is, of course!).
          • Try to avoid anything which might be platform specific, such as printing floating point numbers without using an explicit formatting string to avoid having too many decimal places -(different platforms can give very slightly different values).
        2. If the script requires files to do the testing, these should go in +(different platforms can give very slightly different values).
    2. If the script requires files to do the testing, these should go in the directory Tests/Biospam (if you just need something generic, like a FASTA sequence file, or a GenBank record, try and use an existing -sample input file instead).
    3. Write out the test output and verify the output to be correct.

      There are two ways to do this:

      1. -The long way:
        • Run the script and write its output to a file. On UNIX (including +sample input file instead).
        • Write out the test output and verify the output to be correct.

          There are two ways to do this:

          1. +The long way:
            • Run the script and write its output to a file. On UNIX (including Linux and Mac OS X) machines, you would do something like: -python test_Biospam.py > test_Biospam which would write the -output to the file test_Biospam.
            • Manually look at the file test_Biospam to make sure the output is correct. When you are sure it is all right and there are no bugs, you need to quickly edit the test_Biospam file so that the first line is: ‘test_Biospam’ (no quotes).
            • copy the test_Biospam file to the directory Tests/output
          2. The quick way:
            • -Run python run_tests.py -g test_Biospam.py. The +python test_Biospam.py > test_Biospam which would write the +output to the file test_Biospam.
            • Manually look at the file test_Biospam to make sure the output is correct. When you are sure it is all right and there are no bugs, you need to quickly edit the test_Biospam file so that the first line is: ‘test_Biospam’ (no quotes).
            • copy the test_Biospam file to the directory Tests/output
          3. The quick way:
            • +Run python run_tests.py -g test_Biospam.py. The regression testing framework is nifty enough that it’ll put -the output in the right place in just the way it likes it.
            • Go to the output (which should be in Tests/output/test_Biospam) and double check the output to make sure it is all correct.
        • Now change to the Tests directory and run the regression tests -with python run_tests.py. This will run all of the tests, and -you should see your test run (and pass!).
        • That’s it! Now you’ve got a nice test for your module ready to check in, +the output in the right place in just the way it likes it.
        • Go to the output (which should be in Tests/output/test_Biospam) and double check the output to make sure it is all correct.
    4. Now change to the Tests directory and run the regression tests +with python run_tests.py. This will run all of the tests, and +you should see your test run (and pass!).
    5. That’s it! Now you’ve got a nice test for your module ready to check in, or submit to Biopython. Congratulations! -

    As an example, the test_Biospam.py test script to test the -addition and multiplication functions in the Biospam -module could look as follows:

    from Bio import Biospam
    -
    -print "2 + 3 =", Biospam.addition(2, 3)
    -print "9 - 1 =", Biospam.addition(9, -1)
    -print "2 * 3 =", Biospam.multiplication(2, 3)
    -print "9 * (- 1) =", Biospam.multiplication(9, -1)
    -

    We generate the corresponding output with python run_tests.py -g test_Biospam.py, and check the output file output/test_Biospam:

    test_Biospam
    +

    As an example, the test_Biospam.py test script to test the +addition and multiplication functions in the Biospam +module could look as follows:

    from __future__ import print_function
    +from Bio import Biospam
    +
    +print("2 + 3 =", Biospam.addition(2, 3))
    +print("9 - 1 =", Biospam.addition(9, -1))
    +print("2 * 3 =", Biospam.multiplication(2, 3))
    +print("9 * (- 1) =", Biospam.multiplication(9, -1))
    +

    We generate the corresponding output with python run_tests.py -g test_Biospam.py, and check the output file output/test_Biospam:

    test_Biospam
     2 + 3 = 5
     9 - 1 = 8
     2 * 3 = 6
     9 * (- 1) = -9
    -

    Often, the difficulty with larger print-and-compare tests is to keep track which line in the output corresponds to which command in the test script. For this purpose, it is important to print out some markers to help you match lines in the input script with the generated output.

    -

    19.2.2  Writing a unittest-based test

    We want all the modules in Biopython to have unit tests, and a simple +

    Often, the difficulty with larger print-and-compare tests is to keep track which line in the output corresponds to which command in the test script. For this purpose, it is important to print out some markers to help you match lines in the input script with the generated output.

    + +

    19.2.2  Writing a unittest-based test

    We want all the modules in Biopython to have unit tests, and a simple print-and-compare test is better than no test at all. However, although -there is a steeper learning curve, using the unittest framework +there is a steeper learning curve, using the unittest framework gives a more structured result, and if there is a test failure this can clearly pinpoint which part of the test is going wrong. The sub-tests can -also be run individually which is helpful for testing or debugging.

    The unittest-framework has been included with Python since version +also be run individually which is helpful for testing or debugging.

    The unittest-framework has been included with Python since version 2.1, and is documented in the Python Library Reference (which I know you are keeping under your pillow, as recommended). There is also -online documentaion -for unittest. -If you are familiar with the unittest system (or something similar +online documentaion +for unittest. +If you are familiar with the unittest system (or something similar like the nose test framework), you shouldn’t have any trouble. You may -find looking at the existing example within Biopython helpful too.

    Here’s a minimal unittest-style test script for Biospam, -which you can copy and paste to get started:

    import unittest
    +find looking at the existing example within Biopython helpful too.

    Here’s a minimal unittest-style test script for Biospam, +which you can copy and paste to get started:

    import unittest
     from Bio import Biospam
     
     class BiospamTestAddition(unittest.TestCase):
    @@ -11434,21 +11778,21 @@
     if __name__ == "__main__":
         runner = unittest.TextTestRunner(verbosity = 2)
         unittest.main(testRunner=runner)
    -

    In the division tests, we use assertAlmostEqual instead of assertEqual to avoid tests failing due to roundoff errors; see the unittest chapter in the Python documentation for details and for other functionality available in unittest (online reference).

    These are the key points of unittest-based tests:

    • +

    In the division tests, we use assertAlmostEqual instead of assertEqual to avoid tests failing due to roundoff errors; see the unittest chapter in the Python documentation for details and for other functionality available in unittest (online reference).

    These are the key points of unittest-based tests:

    • Test cases are stored in classes that derive from -unittest.TestCase and cover one basic aspect of your code
    • You can use methods setUp and tearDown for any repeated +unittest.TestCase and cover one basic aspect of your code
    • You can use methods setUp and tearDown for any repeated code which should be run before and after each test method. For example, -the setUp method might be used to create an instance of the object -you are testing, or open a file handle. The tearDown should do any -“tidying up”, for example closing the file handle.
    • The tests are prefixed with test_ and each test should cover +the setUp method might be used to create an instance of the object +you are testing, or open a file handle. The tearDown should do any +“tidying up”, for example closing the file handle.
    • The tests are prefixed with test_ and each test should cover one specific part of what you are trying to test. You can have as -many tests as you want in a class.
    • At the end of the test script, you can use -
      if __name__ == "__main__":
      +many tests as you want in a class.
    • At the end of the test script, you can use +
      if __name__ == "__main__":
           runner = unittest.TextTestRunner(verbosity = 2)
           unittest.main(testRunner=runner)
      -
      to execute the tests when the script is run by itself (rather than -imported from run_tests.py). -If you run this script, then you’ll see something like the following:
      $ python test_BiospamMyModule.py
      +
      to execute the tests when the script is run by itself (rather than +imported from run_tests.py). +If you run this script, then you’ll see something like the following:
      $ python test_BiospamMyModule.py
       test_addition1 (__main__.TestAddition) ... ok
       test_addition2 (__main__.TestAddition) ... ok
       test_division1 (__main__.TestDivision) ... ok
      @@ -11458,9 +11802,9 @@
       Ran 4 tests in 0.059s
       
       OK
      -
    • To indicate more clearly what each test is doing, you can add +
    • To indicate more clearly what each test is doing, you can add docstrings to each test. These are shown when running the tests, -which can be useful information if a test is failing.
      import unittest
      +which can be useful information if a test is failing.
      import unittest
       from Bio import Biospam
       
       class BiospamTestAddition(unittest.TestCase):
      @@ -11491,7 +11835,7 @@
       if __name__ == "__main__":
           runner = unittest.TextTestRunner(verbosity = 2)
           unittest.main(testRunner=runner)
      -

      Running the script will now show you:

      $ python test_BiospamMyModule.py
      +

      Running the script will now show you:

      $ python test_BiospamMyModule.py
       An addition test ... ok
       A second addition test ... ok
       Now let's check division ... ok
      @@ -11501,34 +11845,35 @@
       Ran 4 tests in 0.001s
       
       OK
      -

    If your module contains docstring tests (see section 19.3), +

    If your module contains docstring tests (see section 19.3), you may want to include those in the tests to be run. You can do so as -follows by modifying the code under if __name__ == "__main__": -to look like this:

    if __name__ == "__main__":
    +follows by modifying the code under if __name__ == "__main__":
    +to look like this:

    if __name__ == "__main__":
         unittest_suite = unittest.TestLoader().loadTestsFromName("test_Biospam")
         doctest_suite = doctest.DocTestSuite(Biospam)
         suite = unittest.TestSuite((unittest_suite, doctest_suite))
         runner = unittest.TextTestRunner(sys.stdout, verbosity = 2)
         runner.run(suite)
    -

    This is only relevant if you want to run the docstring tests when you -execute python test_Biospam.py; with -python run_tests.py, the docstring tests are run automatically +

    This is only relevant if you want to run the docstring tests when you +execute python test_Biospam.py; with +python run_tests.py, the docstring tests are run automatically (assuming they are included in the list of docstring tests in -run_tests.py, see the section below).

    -

    19.3  Writing doctests

    -

    Python modules, classes and functions support built in documentation using -docstrings. The doctest -framework (included with Python) allows the developer to embed working -examples in the docstrings, and have these examples automatically tested.

    Currently only a small part of Biopython includes doctests. The -run_tests.py script takes care of running the doctests. -For this purpose, at the top of the run_tests.py script is a +run_tests.py, see the section below).

    + +

    19.3  Writing doctests

    +

    Python modules, classes and functions support built in documentation using +docstrings. The doctest +framework (included with Python) allows the developer to embed working +examples in the docstrings, and have these examples automatically tested.

    Currently only a small part of Biopython includes doctests. The +run_tests.py script takes care of running the doctests. +For this purpose, at the top of the run_tests.py script is a manually compiled list of modules to test, which allows us to skip modules with optional external dependencies which may not be installed (e.g. the Reportlab and NumPy libraries). So, if you’ve added some doctests to the docstrings in a Biopython module, in order to have them included in the Biopython test suite, you must update -run_tests.py to include your module. Currently, the relevant part -of run_tests.py looks as follows:

    # This is the list of modules containing docstring tests.
    +run_tests.py to include your module. Currently, the relevant part
    +of run_tests.py looks as follows:

    # This is the list of modules containing docstring tests.
     # If you develop docstring tests for other modules, please add
     # those modules here.
     DOCTEST_MODULES = ["Bio.Seq",
    @@ -11542,310 +11887,326 @@
         DOCTEST_MODULES.extend(["Bio.Statistics.lowess"])
     except ImportError:
         pass
    -

    Note that we regard doctests primarily as documentation, so you should +

    Note that we regard doctests primarily as documentation, so you should stick to typical usage. Generally complicated examples dealing with error -conditions and the like would be best left to a dedicated unit test.

    Note that if you want to write doctests involving file parsing, defining +conditions and the like would be best left to a dedicated unit test.

    Note that if you want to write doctests involving file parsing, defining the file location complicates matters. Ideally use relative paths assuming -the code will be run from the Tests directory, see the -Bio.SeqIO doctests for an example of this.

    To run the docstring tests only, use -

    $ python run_tests.py doctest
    -
    -

    Chapter 20  Advanced

    -

    -

    20.1  Parser Design

    Many of the older Biopython parsers were built around an event-oriented -design that includes Scanner and Consumer objects.

    Scanners take input from a data source and analyze it line by line, +the code will be run from the Tests directory, see the +Bio.SeqIO doctests for an example of this.

    To run the docstring tests only, use +

    $ python run_tests.py doctest
    +
    + +

    Chapter 20  Advanced

    +

    + +

    20.1  Parser Design

    Many of the older Biopython parsers were built around an event-oriented +design that includes Scanner and Consumer objects.

    Scanners take input from a data source and analyze it line by line, sending off an event whenever it recognizes some information in the data. For example, if the data includes information about an organism -name, the scanner may generate an organism_name event whenever it -encounters a line containing the name.

    Consumers are objects that receive the events generated by Scanners. +name, the scanner may generate an organism_name event whenever it +encounters a line containing the name.

    Consumers are objects that receive the events generated by Scanners. Following the previous example, the consumer receives the -organism_name event, and the processes it in whatever manner -necessary in the current application.

    This is a very flexible framework, which is advantageous if you want to +organism_name event, and the processes it in whatever manner +necessary in the current application.

    This is a very flexible framework, which is advantageous if you want to be able to parse a file format into more than one representation. For -example, the Bio.GenBank module uses this to construct either -SeqRecord objects or file-format-specific record objects.

    More recently, many of the parsers added for Bio.SeqIO and -Bio.AlignIO take a much simpler approach, but only generate a -single object representation (SeqRecord and -MultipleSeqAlignment objects respectively). In some cases the -Bio.SeqIO parsers actually wrap -another Biopython parser - for example, the Bio.SwissProt parser +example, the Bio.GenBank module uses this to construct either +SeqRecord objects or file-format-specific record objects.

    More recently, many of the parsers added for Bio.SeqIO and +Bio.AlignIO take a much simpler approach, but only generate a +single object representation (SeqRecord and +MultipleSeqAlignment objects respectively). In some cases the +Bio.SeqIO parsers actually wrap +another Biopython parser - for example, the Bio.SwissProt parser produces SwissProt format specific record objects, which get converted -into SeqRecord objects.

    -

    20.2  Substitution Matrices

    -

    20.2.1  SubsMat

    This module provides a class and a few routines for generating substitution matrices, similar to BLOSUM or PAM matrices, but based on user-provided data. Additionally, you may select a matrix from MatrixInfo.py, a collection of established substitution matrices. The SeqMat class derives from a dictionary: -

    class SeqMat(dict)
    -

    The dictionary is of the form {(i1,j1):n1, (i1,j2):n2,...,(ik,jk):nk} where i, j are alphabet letters, and n is a value.

    1. +into SeqRecord objects.

      + +

      20.2  Substitution Matrices

      + +

      20.2.1  SubsMat

      This module provides a class and a few routines for generating substitution matrices, similar to BLOSUM or PAM matrices, but based on user-provided data. Additionally, you may select a matrix from MatrixInfo.py, a collection of established substitution matrices. The SeqMat class derives from a dictionary: +

      class SeqMat(dict)
      +

      The dictionary is of the form {(i1,j1):n1, (i1,j2):n2,...,(ik,jk):nk} where i, j are alphabet letters, and n is a value.

      1. Attributes -
        1. -self.alphabet: a class as defined in Bio.Alphabet
        2. self.ab_list: a list of the alphabet’s letters, sorted. Needed mainly for internal purposes -
      2. Methods
        1. __init__(self,data=None,alphabet=None, mat_name='', build_later=0):
          -
          1. data: can be either a dictionary, or another SeqMat instance. -
          2. alphabet: a Bio.Alphabet instance. If not provided, construct an alphabet from data.
          3. mat_name: matrix name, such as "BLOSUM62" or "PAM250"
          4. build_later: default false. If true, user may supply only alphabet and empty dictionary, if intending to build the matrix later. this skips the sanity check of alphabet size vs. matrix size.
        2. entropy(self,obs_freq_mat)
          -
          1. -obs_freq_mat: an observed frequency matrix. Returns the matrix’s entropy, based on the frequency in obs_freq_mat. The matrix instance should be LO or SUBS. -
        3. sum(self)
          -
          Calculates the sum of values for each letter in the matrix’s alphabet, and returns it as a dictionary of the form {i1: s1, i2: s2,...,in:sn}, where: -
          • +
            1. +self.alphabet: a class as defined in Bio.Alphabet
            2. self.ab_list: a list of the alphabet’s letters, sorted. Needed mainly for internal purposes +
          • Methods
            1. __init__(self,data=None,alphabet=None, mat_name='', build_later=0):
              +
              1. data: can be either a dictionary, or another SeqMat instance. +
              2. alphabet: a Bio.Alphabet instance. If not provided, construct an alphabet from data.
              3. mat_name: matrix name, such as "BLOSUM62" or "PAM250"
              4. build_later: default false. If true, user may supply only alphabet and empty dictionary, if intending to build the matrix later. this skips the sanity check of alphabet size vs. matrix size.
            2. entropy(self,obs_freq_mat)
              +
              1. +obs_freq_mat: an observed frequency matrix. Returns the matrix’s entropy, based on the frequency in obs_freq_mat. The matrix instance should be LO or SUBS. +
            3. sum(self)
              +
              Calculates the sum of values for each letter in the matrix’s alphabet, and returns it as a dictionary of the form {i1: s1, i2: s2,...,in:sn}, where: +
              • i: an alphabet letter; -
              • s: sum of all values in a half-matrix for that letter; -
              • n: number of letters in alphabet. -
            4. print_mat(self,f,format="%4d",bottomformat="%4s",alphabet=None)
              -

              prints the matrix to file handle f. format is the format field for the matrix values; bottomformat is the format field for the bottom row, containing matrix letters. Example output for a 3-letter alphabet matrix:

              A 23
              +
            5. s: sum of all values in a half-matrix for that letter; +
            6. n: number of letters in alphabet. +
        4. print_mat(self,f,format="%4d",bottomformat="%4s",alphabet=None)
          +

          prints the matrix to file handle f. format is the format field for the matrix values; bottomformat is the format field for the bottom row, containing matrix letters. Example output for a 3-letter alphabet matrix:

          A 23
           B 12 34
           C 7  22  27
             A   B   C
          -

          The alphabet optional argument is a string of all characters in the alphabet. If supplied, the order of letters along the axes is taken from the string, rather than by alphabetical order.

      3. Usage

        The following section is laid out in the order by which most people wish to generate a log-odds matrix. Of course, interim matrices can be generated and -investigated. Most people just want a log-odds matrix, that’s all.

        1. Generating an Accepted Replacement Matrix

          Initially, you should generate an accepted replacement matrix (ARM) from your data. The values in ARM are the counted number of replacements according to your data. The data could be a set of pairs or multiple alignments. So for instance if Alanine was replaced by Cysteine 10 times, and Cysteine by Alanine 12 times, the corresponding ARM entries would be:

          ('A','C'): 10, ('C','A'): 12
          -

          as order doesn’t matter, user can already provide only one entry:

          ('A','C'): 22
          -

          A SeqMat instance may be initialized with either a full (first method of counting: 10, 12) or half (the latter method, 22) matrices. A full protein +

          The alphabet optional argument is a string of all characters in the alphabet. If supplied, the order of letters along the axes is taken from the string, rather than by alphabetical order.

      4. Usage

        The following section is laid out in the order by which most people wish to generate a log-odds matrix. Of course, interim matrices can be generated and +investigated. Most people just want a log-odds matrix, that’s all.

        1. Generating an Accepted Replacement Matrix

          Initially, you should generate an accepted replacement matrix (ARM) from your data. The values in ARM are the counted number of replacements according to your data. The data could be a set of pairs or multiple alignments. So for instance if Alanine was replaced by Cysteine 10 times, and Cysteine by Alanine 12 times, the corresponding ARM entries would be:

          ('A','C'): 10, ('C','A'): 12
          +

          as order doesn’t matter, user can already provide only one entry:

          ('A','C'): 22
          +

          A SeqMat instance may be initialized with either a full (first method of counting: 10, 12) or half (the latter method, 22) matrices. A full protein alphabet matrix would be of the size 20x20 = 400. A half matrix of that alphabet would be 20x20/2 + 20/2 = 210. That is because same-letter entries don’t -change. (The matrix diagonal). Given an alphabet size of N:

          1. -Full matrix size:N*N
          2. Half matrix size: N(N+1)/2 -

          The SeqMat constructor automatically generates a half-matrix, if a full matrix is passed. If a half matrix is passed, letters in the key should be provided in alphabetical order: (’A’,’C’) and not (’C’,A’).

          At this point, if all you wish to do is generate a log-odds matrix, please go to the section titled Example of Use. The following text describes the nitty-gritty of internal functions, to be used by people who wish to investigate their nucleotide/amino-acid frequency data more thoroughly.

        2. Generating the observed frequency matrix (OFM)

          Use: -

          OFM = SubsMat._build_obs_freq_mat(ARM)
          -

          The OFM is generated from the ARM, only instead of replacement counts, it contains replacement frequencies.

        3. Generating an expected frequency matrix (EFM)

          Use:

          EFM = SubsMat._build_exp_freq_mat(OFM,exp_freq_table)
          -
          1. -exp_freq_table: should be a FreqTable instance. See section 20.2.2 for detailed information on FreqTable. Briefly, the expected frequency table has the frequencies of appearance for each member of the alphabet. It is +change. (The matrix diagonal). Given an alphabet size of N:

            1. +Full matrix size:N*N
            2. Half matrix size: N(N+1)/2 +

            The SeqMat constructor automatically generates a half-matrix, if a full matrix is passed. If a half matrix is passed, letters in the key should be provided in alphabetical order: (’A’,’C’) and not (’C’,A’).

            At this point, if all you wish to do is generate a log-odds matrix, please go to the section titled Example of Use. The following text describes the nitty-gritty of internal functions, to be used by people who wish to investigate their nucleotide/amino-acid frequency data more thoroughly.

          2. Generating the observed frequency matrix (OFM)

            Use: +

            OFM = SubsMat._build_obs_freq_mat(ARM)
            +

            The OFM is generated from the ARM, only instead of replacement counts, it contains replacement frequencies.

          3. Generating an expected frequency matrix (EFM)

            Use:

            EFM = SubsMat._build_exp_freq_mat(OFM,exp_freq_table)
            +
            1. +exp_freq_table: should be a FreqTable instance. See section 20.2.2 for detailed information on FreqTable. Briefly, the expected frequency table has the frequencies of appearance for each member of the alphabet. It is implemented as a dictionary with the alphabet letters as keys, and each letter’s frequency as a value. Values sum to 1. -

            The expected frequency table can (and generally should) be generated from the observed frequency matrix. So in most cases you will generate exp_freq_table using:

            >>> exp_freq_table = SubsMat._exp_freq_table_from_obs_freq(OFM)
            ->>> EFM = SubsMat._build_exp_freq_mat(OFM,exp_freq_table)
            -

            But you can supply your own exp_freq_table, if you wish

          4. Generating a substitution frequency matrix (SFM)

            Use:

            SFM = SubsMat._build_subs_mat(OFM,EFM)
            -

            Accepts an OFM, EFM. Provides the division product of the corresponding values.

          5. Generating a log-odds matrix (LOM)

            Use: -

            LOM=SubsMat._build_log_odds_mat(SFM[,logbase=10,factor=10.0,round_digit=1])
            -
            1. -Accepts an SFM.
            2. logbase: base of the logarithm used to generate the log-odds values.
            3. factor: factor used to multiply the log-odds values. Each entry is generated by log(LOM[key])*factor And rounded to the round_digit place after the decimal point, if required.
        4. Example of use

          As most people would want to generate a log-odds matrix, with minimum hassle, SubsMat provides one function which does it all:

          make_log_odds_matrix(acc_rep_mat,exp_freq_table=None,logbase=10,
          +

        The expected frequency table can (and generally should) be generated from the observed frequency matrix. So in most cases you will generate exp_freq_table using:

        >>> exp_freq_table = SubsMat._exp_freq_table_from_obs_freq(OFM)
        +>>> EFM = SubsMat._build_exp_freq_mat(OFM, exp_freq_table)
        +

        But you can supply your own exp_freq_table, if you wish

      5. Generating a substitution frequency matrix (SFM)

        Use:

        SFM = SubsMat._build_subs_mat(OFM,EFM)
        +

        Accepts an OFM, EFM. Provides the division product of the corresponding values.

      6. Generating a log-odds matrix (LOM)

        Use: +

        LOM=SubsMat._build_log_odds_mat(SFM[,logbase=10,factor=10.0,round_digit=1])
        +
        1. +Accepts an SFM.
        2. logbase: base of the logarithm used to generate the log-odds values.
        3. factor: factor used to multiply the log-odds values. Each entry is generated by log(LOM[key])*factor And rounded to the round_digit place after the decimal point, if required.
    2. Example of use

      As most people would want to generate a log-odds matrix, with minimum hassle, SubsMat provides one function which does it all:

      make_log_odds_matrix(acc_rep_mat,exp_freq_table=None,logbase=10,
                             factor=10.0,round_digit=0):
      -
      1. -acc_rep_mat: user provided accepted replacements matrix -
      2. exp_freq_table: expected frequencies table. Used if provided, if not, generated from the acc_rep_mat. -
      3. logbase: base of logarithm for the log-odds matrix. Default base 10. -
      4. round_digit: number after decimal digit to which result should be rounded. Default zero. -
    -

    20.2.2  FreqTable

    -

    FreqTable.FreqTable(UserDict.UserDict)
    -
    1. Attributes:
      1. -alphabet: A Bio.Alphabet instance. -
      2. data: frequency dictionary -
      3. count: count dictionary (in case counts are provided). -
    2. Functions: -
      1. -read_count(f): read a count file from stream f. Then convert to frequencies -
      2. read_freq(f): read a frequency data file from stream f. Of course, we then don’t have the counts, but it is usually the letter frquencies which are interesting. -
    3. Example of use: -The expected count of the residues in the database is sitting in a file, whitespace delimited, in the following format (example given for a 3-letter alphabet):
      A   35
      +
      1. +acc_rep_mat: user provided accepted replacements matrix +
      2. exp_freq_table: expected frequencies table. Used if provided, if not, generated from the acc_rep_mat. +
      3. logbase: base of logarithm for the log-odds matrix. Default base 10. +
      4. round_digit: number after decimal digit to which result should be rounded. Default zero. +
    + +

    20.2.2  FreqTable

    +

    FreqTable.FreqTable(UserDict.UserDict)
    +
    1. Attributes:
      1. +alphabet: A Bio.Alphabet instance. +
      2. data: frequency dictionary +
      3. count: count dictionary (in case counts are provided). +
    2. Functions: +
      1. +read_count(f): read a count file from stream f. Then convert to frequencies +
      2. read_freq(f): read a frequency data file from stream f. Of course, we then don’t have the counts, but it is usually the letter frquencies which are interesting. +
    3. Example of use: +The expected count of the residues in the database is sitting in a file, whitespace delimited, in the following format (example given for a 3-letter alphabet):
      A   35
       B   65
       C   100
      -

      And will be read using the FreqTable.read_count(file_handle) function.

      An equivalent frequency file:

      A  0.175
      +

      And will be read using the FreqTable.read_count(file_handle) function.

      An equivalent frequency file:

      A  0.175
       B  0.325
       C  0.5
      -

      Conversely, the residue frequencies or counts can be passed as a dictionary. -Example of a count dictionary (3-letter alphabet):

      {'A': 35, 'B': 65, 'C': 100}
      -

      Which means that an expected data count would give a 0.5 frequency +

      Conversely, the residue frequencies or counts can be passed as a dictionary. +Example of a count dictionary (3-letter alphabet):

      {'A': 35, 'B': 65, 'C': 100}
      +

      Which means that an expected data count would give a 0.5 frequency for ’C’, a 0.325 probability of ’B’ and a 0.175 probability of ’A’ -out of 200 total, sum of A, B and C)

      A frequency dictionary for the same data would be:

      {'A': 0.175, 'B': 0.325, 'C': 0.5}
      -

      Summing up to 1.

      When passing a dictionary as an argument, you should indicate whether it is a count or a frequency dictionary. Therefore the FreqTable class constructor requires two arguments: the dictionary itself, and FreqTable.COUNT or FreqTable.FREQ indicating counts or frequencies, respectively.

      Read expected counts. readCount will already generate the frequencies -Any one of the following may be done to geerate the frequency table (ftab):

      >>> from SubsMat import *
      ->>> ftab = FreqTable.FreqTable(my_frequency_dictionary,FreqTable.FREQ)
      ->>> ftab = FreqTable.FreqTable(my_count_dictionary,FreqTable.COUNT)
      +out of 200 total, sum of A, B and C)

      A frequency dictionary for the same data would be:

      {'A': 0.175, 'B': 0.325, 'C': 0.5}
      +

      Summing up to 1.

      When passing a dictionary as an argument, you should indicate whether it is a count or a frequency dictionary. Therefore the FreqTable class constructor requires two arguments: the dictionary itself, and FreqTable.COUNT or FreqTable.FREQ indicating counts or frequencies, respectively.

      Read expected counts. readCount will already generate the frequencies +Any one of the following may be done to geerate the frequency table (ftab):

      >>> from SubsMat import *
      +>>> ftab = FreqTable.FreqTable(my_frequency_dictionary, FreqTable.FREQ)
      +>>> ftab = FreqTable.FreqTable(my_count_dictionary, FreqTable.COUNT)
       >>> ftab = FreqTable.read_count(open('myCountFile'))
       >>> ftab = FreqTable.read_frequency(open('myFrequencyFile'))
      -
    -

    Chapter 21  Where to go from here – contributing to Biopython

    -

    21.1  Bug Reports + Feature Requests

    Getting feedback on the Biopython modules is very important to us. Open-source projects like this benefit greatly from feedback, bug-reports (and patches!) from a wide variety of contributors.

    The main forums for discussing feature requests and potential bugs are the -Biopython mailing lists:

    Additionally, if you think you’ve found a new bug, you can submit it to -our issue tracker at https://github.com/biopython/biopython/issues + + +

    Chapter 21  Where to go from here – contributing to Biopython

    + +

    21.1  Bug Reports + Feature Requests

    Getting feedback on the Biopython modules is very important to us. Open-source projects like this benefit greatly from feedback, bug-reports (and patches!) from a wide variety of contributors.

    The main forums for discussing feature requests and potential bugs are the +Biopython mailing lists:

    Additionally, if you think you’ve found a new bug, you can submit it to +our issue tracker at https://github.com/biopython/biopython/issues (this has replaced the older tracker hosted at -http://redmine.open-bio.org/projects/biopython). -This way, it won’t get buried in anyone’s Inbox and forgotten about.

    -

    21.2  Mailing lists and helping newcomers

    We encourage all our uses to sign up to the main Biopython mailing list. +http://redmine.open-bio.org/projects/biopython). +This way, it won’t get buried in anyone’s Inbox and forgotten about.

    + +

    21.2  Mailing lists and helping newcomers

    We encourage all our uses to sign up to the main Biopython mailing list. Once you’ve got the hang of an area of Biopython, we’d encourage you to -help answer questions from beginners. After all, you were a beginner once.

    -

    21.3  Contributing Documentation

    We’re happy to take feedback or contributions - either via a bug-report or on the Mailing List. +help answer questions from beginners. After all, you were a beginner once.

    + +

    21.3  Contributing Documentation

    We’re happy to take feedback or contributions - either via a bug-report or on the Mailing List. While reading this tutorial, perhaps you noticed some topics you were interested in which were missing, or not clearly explained. There is also Biopython’s built in documentation (the docstrings, these are also -online), where again, you may be able to help fill in any blanks.

    -

    21.4  Contributing cookbook examples

    -As explained in Chapter 18, Biopython now has a wiki +online), where again, you may be able to help fill in any blanks.

    + +

    21.4  Contributing cookbook examples

    +As explained in Chapter 18, Biopython now has a wiki collection of user contributed “cookbook” examples, -http://biopython.org/wiki/Category:Cookbook – maybe you can add -to this?

    -

    21.5  Maintaining a distribution for a platform

    -

    We currently provide source code archives (suitable for any OS, if you have the right build tools installed), and Windows Installers which are just click and run. This covers all the major operating systems.

    Most major Linux distributions have volunteers who take these source code releases, and compile them into packages for Linux users to easily install (taking care of dependencies etc). This is really great and we are of course very grateful. If you would like to contribute to this work, please find out more about how your Linux distribution handles this.

    Below are some tips for certain platforms to maybe get people started with helping out:

    Windows
    – Windows products typically have a nice graphical installer that installs all of the essential components in the right place. We use Distutils to create a installer of this type fairly easily.

    You must first make sure you have a C compiler on your Windows computer, and that you can compile and install things (this is the hard bit - see the Biopython installation instructions for info on how to do this).

    Once you are setup with a C compiler, making the installer just requires doing:

    python setup.py bdist_wininst
    -

    Now you’ve got a Windows installer. Congrats! At the moment we have no trouble shipping installers built on 32 bit windows. If anyone would like to look into supporting 64 bit Windows that would be great.

    RPMs
    – RPMs are pretty popular package systems on some Linux platforms. There is lots of documentation on RPMs available at http://www.rpm.org to help you get started with them. To create an RPM for your platform is really easy. You just need to be able to build the package from source (having a C compiler that works is thus essential) – see the Biopython installation instructions for more info on this.

    To make the RPM, you just need to do:

    python setup.py bdist_rpm
    -

    This will create an RPM for your specific platform and a source RPM in the directory dist. This RPM should be good and ready to go, so this is all you need to do! Nice and easy.

    Macintosh
    – Since Apple moved to Mac OS X, things have become much easier on the Mac. We generally +http://biopython.org/wiki/Category:Cookbook – maybe you can add +to this?

    + +

    21.5  Maintaining a distribution for a platform

    +

    We currently provide source code archives (suitable for any OS, if you have the right build tools installed), and Windows Installers which are just click and run. This covers all the major operating systems.

    Most major Linux distributions have volunteers who take these source code releases, and compile them into packages for Linux users to easily install (taking care of dependencies etc). This is really great and we are of course very grateful. If you would like to contribute to this work, please find out more about how your Linux distribution handles this.

    Below are some tips for certain platforms to maybe get people started with helping out:

    Windows
    – Windows products typically have a nice graphical installer that installs all of the essential components in the right place. We use Distutils to create a installer of this type fairly easily.

    You must first make sure you have a C compiler on your Windows computer, and that you can compile and install things (this is the hard bit - see the Biopython installation instructions for info on how to do this).

    Once you are setup with a C compiler, making the installer just requires doing:

    python setup.py bdist_wininst
    +

    Now you’ve got a Windows installer. Congrats! At the moment we have no trouble shipping installers built on 32 bit windows. If anyone would like to look into supporting 64 bit Windows that would be great.

    RPMs
    – RPMs are pretty popular package systems on some Linux platforms. There is lots of documentation on RPMs available at http://www.rpm.org to help you get started with them. To create an RPM for your platform is really easy. You just need to be able to build the package from source (having a C compiler that works is thus essential) – see the Biopython installation instructions for more info on this.

    To make the RPM, you just need to do:

    python setup.py bdist_rpm
    +

    This will create an RPM for your specific platform and a source RPM in the directory dist. This RPM should be good and ready to go, so this is all you need to do! Nice and easy.

    Macintosh
    – Since Apple moved to Mac OS X, things have become much easier on the Mac. We generally treat it as just another Unix variant, and installing Biopython from source is just as easy as on Linux. The easiest way to get all the GCC compilers etc installed is to install Apple’s X-Code. -We might be able to provide click and run installers for Mac OS X, but to date there hasn’t been any demand.

    Once you’ve got a package, please test it on your system to make sure it installs everything in a good way and seems to work properly. Once you feel good about it, send it off to one of the Biopython developers (write to our main mailing list at biopython@biopython.org if you’re not sure who to send it to) and you’ve done it. Thanks!

    -

    21.6  Contributing Unit Tests

    Even if you don’t have any new functionality to add to Biopython, but you want to write some code, please -consider extending our unit test coverage. We’ve devoted all of Chapter 19 to this topic.

    -

    21.7  Contributing Code

    There are no barriers to joining Biopython code development other +We might be able to provide click and run installers for Mac OS X, but to date there hasn’t been any demand.

    Once you’ve got a package, please test it on your system to make sure it installs everything in a good way and seems to work properly. Once you feel good about it, send it off to one of the Biopython developers (write to our main mailing list at biopython@biopython.org if you’re not sure who to send it to) and you’ve done it. Thanks!

    + +

    21.6  Contributing Unit Tests

    Even if you don’t have any new functionality to add to Biopython, but you want to write some code, please +consider extending our unit test coverage. We’ve devoted all of Chapter 19 to this topic.

    + +

    21.7  Contributing Code

    There are no barriers to joining Biopython code development other than an interest in creating biology-related code in Python. The best place to express an interest is on the Biopython mailing lists – just let us know you are interested in coding and what kind of stuff you want to work on. Normally, we try to have some discussion on modules before coding them, since that helps generate good ideas -– then just feel free to jump right in and start coding!

    The main Biopython release tries to be fairly uniform and interworkable, +– then just feel free to jump right in and start coding!

    The main Biopython release tries to be fairly uniform and interworkable, to make it easier for users. You can read about some of (fairly informal) coding style guidelines we try to use in Biopython in the contributing documentation at -http://biopython.org/wiki/Contributing. We also try to add code to the distribution along with tests (see Chapter 19 for more info on the regression testing framework) and documentation, so that everything can stay as workable and well documented as possible (including docstrings). This is, of course, the most ideal situation, under many situations you’ll be able to find other people on the list who will be willing to help add documentation or more tests for your code once you make it available. So, to end this paragraph like the last, feel free to start working!

    Please note that to make a code contribution you must have the legal right to contribute it and license it under the Biopython license. If you wrote it all yourself, and it is not based on any other code, this shouldn’t be a problem. However, there are issues if you want to contribute a derivative work - for example something based on GPL or LPGL licenced code would not be compatible with our license. If you have any queries on this, please discuss the issue on the biopython-dev mailing list.

    Another point of concern for any additions to Biopython regards any build time or run time dependencies. Generally speaking, writing code to interact with a standalone tool (like BLAST, EMBOSS or ClustalW) doesn’t present a big problem. However, any dependency on another library - even a Python library (especially one needed in order to compile and install Biopython like NumPy) would need further discussion.

    Additionally, if you have code that you don’t think fits in the +http://biopython.org/wiki/Contributing. We also try to add code to the distribution along with tests (see Chapter 19 for more info on the regression testing framework) and documentation, so that everything can stay as workable and well documented as possible (including docstrings). This is, of course, the most ideal situation, under many situations you’ll be able to find other people on the list who will be willing to help add documentation or more tests for your code once you make it available. So, to end this paragraph like the last, feel free to start working!

    Please note that to make a code contribution you must have the legal right to contribute it and license it under the Biopython license. If you wrote it all yourself, and it is not based on any other code, this shouldn’t be a problem. However, there are issues if you want to contribute a derivative work - for example something based on GPL or LPGL licenced code would not be compatible with our license. If you have any queries on this, please discuss the issue on the biopython-dev mailing list.

    Another point of concern for any additions to Biopython regards any build time or run time dependencies. Generally speaking, writing code to interact with a standalone tool (like BLAST, EMBOSS or ClustalW) doesn’t present a big problem. However, any dependency on another library - even a Python library (especially one needed in order to compile and install Biopython like NumPy) would need further discussion.

    Additionally, if you have code that you don’t think fits in the distribution, but that you want to make available, we maintain Script -Central (http://biopython.org/wiki/Scriptcentral) -which has pointers to freely available code in Python for bioinformatics.

    Hopefully this documentation has got you excited enough about +Central (http://biopython.org/wiki/Scriptcentral) +which has pointers to freely available code in Python for bioinformatics.

    Hopefully this documentation has got you excited enough about Biopython to try it out (and most importantly, contribute!). Thanks -for reading all the way through!

    -

    Chapter 22  Appendix: Useful stuff about Python

    -

    If you haven’t spent a lot of time programming in Python, many +for reading all the way through!

    + +

    Chapter 22  Appendix: Useful stuff about Python

    +

    If you haven’t spent a lot of time programming in Python, many questions and problems that come up in using Biopython are often related to Python itself. This section tries to present some ideas and code that come up often (at least for us!) while using the Biopython libraries. If you have any suggestions for useful pointers that could -go here, please contribute!

    -

    22.1  What the heck is a handle?

    -

    Handles are mentioned quite frequently throughout this documentation, +go here, please contribute!

    + +

    22.1  What the heck is a handle?

    +

    Handles are mentioned quite frequently throughout this documentation, and are also fairly confusing (at least to me!). Basically, you can -think of a handle as being a “wrapper” around text information.

    Handles provide (at least) two benefits over plain text information:

    1. +think of a handle as being a “wrapper” around text information.

      Handles provide (at least) two benefits over plain text information:

      1. They provide a standard way to deal with information stored in different ways. The text information can be in a file, or in a string stored in memory, or the output from a command line program, or at some remote website, but the handle provides a common way of -dealing with information in all of these formats.
      2. They allow text information to be read incrementally, instead +dealing with information in all of these formats.
      3. They allow text information to be read incrementally, instead of all at once. This is really important when you are dealing with huge text files which would use up all of your memory if you had to load them all. -

      Handles can deal with text information that is being read (e. g. reading +

    Handles can deal with text information that is being read (e. g. reading from a file) or written (e. g. writing information to a file). In the -case of a “read” handle, commonly used functions are read(), +case of a “read” handle, commonly used functions are read(), which reads the entire text information from the handle, and -readline(), which reads information one line at a time. For -“write” handles, the function write() is regularly used.

    The most common usage for handles is reading information from a file, -which is done using the built-in Python function open. Here, we open a -handle to the file m_cold.fasta +readline(), which reads information one line at a time. For +“write” handles, the function write() is regularly used.

    The most common usage for handles is reading information from a file, +which is done using the built-in Python function open. Here, we open a +handle to the file m_cold.fasta (also available online -here):

    >>> handle = open("m_cold.fasta", "r")
    +here):

    >>> handle = open("m_cold.fasta", "r")
     >>> handle.readline()
     ">gi|8332116|gb|BE037100.1|BE037100 MP14H09 MP Mesembryanthemum ...\n"
    -

    Handles are regularly used in Biopython for passing information to parsers. -For example, since Biopython 1.54 the main functions in Bio.SeqIO -and Bio.AlignIO have allowed you to use a filename instead of a -handle:

    from Bio import SeqIO
    +

    Handles are regularly used in Biopython for passing information to parsers. +For example, since Biopython 1.54 the main functions in Bio.SeqIO +and Bio.AlignIO have allowed you to use a filename instead of a +handle:

    from Bio import SeqIO
     for record in SeqIO.parse("m_cold.fasta", "fasta"):
    -    print record.id, len(record)
    -

    On older versions of Biopython you had to use a handle, e.g.

    from Bio import SeqIO
    +    print(record.id, len(record))
    +

    On older versions of Biopython you had to use a handle, e.g.

    from Bio import SeqIO
     handle = open("m_cold.fasta", "r")
     for record in SeqIO.parse(handle, "fasta"):
    -    print record.id, len(record)
    +    print(record.id, len(record))
     handle.close()
    -

    This pattern is still useful - for example suppose you have a gzip -compressed FASTA file you want to parse:

    import gzip
    +

    This pattern is still useful - for example suppose you have a gzip +compressed FASTA file you want to parse:

    import gzip
     from Bio import SeqIO
     handle = gzip.open("m_cold.fasta.gz")
     for record in SeqIO.parse(handle, "fasta"):
    -    print record.id, len(record)
    +    print(record.id, len(record))
     handle.close()
    -

    See Section 5.2 for more examples like this, -including reading bzip2 compressed files.

    -

    22.1.1  Creating a handle from a string

    One useful thing is to be able to turn information contained in a +

    See Section 5.2 for more examples like this, +including reading bzip2 compressed files.

    + +

    22.1.1  Creating a handle from a string

    One useful thing is to be able to turn information contained in a string into a handle. The following example shows how to do this using -cStringIO from the Python standard library:

    >>> my_info = 'A string\n with multiple lines.'
    ->>> print my_info
    +cStringIO from the Python standard library:

    >>> my_info = 'A string\n with multiple lines.'
    +>>> print(my_info)
     A string
      with multiple lines.
     >>> from StringIO import StringIO
     >>> my_info_handle = StringIO(my_info)
     >>> first_line = my_info_handle.readline()
    ->>> print first_line
    +>>> print(first_line)
     A string
     <BLANKLINE>
     >>> second_line = my_info_handle.readline()
    ->>> print second_line
    +>>> print(second_line)
      with multiple lines.
    -
    -

    References

    +
    +

    References

    -[1]
    -Peter J. A. Cock, Tiago Antao, Jeffrey T. Chang, Brad A. Chapman, Cymon J. Cox, Andrew Dalke, Iddo Friedberg, Thomas Hamelryck, Frank Kauff, Bartek Wilczynski, Michiel J. L. de Hoon: “Biopython: freely available Python tools for computational molecular biology and bioinformatics”. Bioinformatics 25 (11), 1422–1423 (2009). doi:10.1093/bioinformatics/btp163, -
    [2]
    -Leighton Pritchard, Jennifer A. White, Paul R.J. Birch, Ian K. Toth: “GenomeDiagram: a python package for the visualization of large-scale genomic data”. Bioinformatics 22 (5): 616–617 (2006). -doi:10.1093/bioinformatics/btk021, -
    [3]
    -Ian K. Toth, Leighton Pritchard, Paul R. J. Birch: “Comparative genomics reveals what makes an enterobacterial plant pathogen”. Annual Review of Phytopathology 44: 305–336 (2006). -doi:10.1146/annurev.phyto.44.070505.143444, -
    [4]
    +[1]
    +Peter J. A. Cock, Tiago Antao, Jeffrey T. Chang, Brad A. Chapman, Cymon J. Cox, Andrew Dalke, Iddo Friedberg, Thomas Hamelryck, Frank Kauff, Bartek Wilczynski, Michiel J. L. de Hoon: “Biopython: freely available Python tools for computational molecular biology and bioinformatics”. Bioinformatics 25 (11), 1422–1423 (2009). doi:10.1093/bioinformatics/btp163, +
    [2]
    +Leighton Pritchard, Jennifer A. White, Paul R.J. Birch, Ian K. Toth: “GenomeDiagram: a python package for the visualization of large-scale genomic data”. Bioinformatics 22 (5): 616–617 (2006). +doi:10.1093/bioinformatics/btk021, +
    [3]
    +Ian K. Toth, Leighton Pritchard, Paul R. J. Birch: “Comparative genomics reveals what makes an enterobacterial plant pathogen”. Annual Review of Phytopathology 44: 305–336 (2006). +doi:10.1146/annurev.phyto.44.070505.143444, +
    [4]
    Géraldine A. van der Auwera, Jaroslaw E. Król, Haruo Suzuki, Brian Foster, Rob van Houdt, Celeste J. Brown, Max Mergeay, Eva M. Top: “Plasmids captured in C. metallidurans CH34: defining the PromA family of broad-host-range plasmids”. -Antonie van Leeuwenhoek 96 (2): 193–204 (2009). -doi:10.1007/s10482-009-9316-9 -
    [5]
    +Antonie van Leeuwenhoek 96 (2): 193–204 (2009). +doi:10.1007/s10482-009-9316-9 +
    [5]
    Caroline Proux, Douwe van Sinderen, Juan Suarez, Pilar Garcia, Victor Ladero, Gerald F. Fitzgerald, Frank Desiere, Harald Brüssow: -“The dilemma of phage taxonomy illustrated by comparative genomics of Sfi21-Like Siphoviridae in lactic acid bacteria”. Journal of Bacteriology 184 (21): 6026–6036 (2002). -http://dx.doi.org/10.1128/JB.184.21.6026-6036.2002 -
    [6]
    -Florian Jupe, Leighton Pritchard, Graham J. Etherington, Katrin MacKenzie, Peter JA Cock, Frank Wright, Sanjeev Kumar Sharma1, Dan Bolser, Glenn J Bryan, Jonathan DG Jones, Ingo Hein: “Identification and localisation of the NB-LRR gene family within the potato genome”. BMC Genomics 13: 75 (2012). -http://dx.doi.org/10.1186/1471-2164-13-75 -
    [7]
    -Peter J. A. Cock, Christopher J. Fields, Naohisa Goto, Michael L. Heuer, Peter M. Rice: “The Sanger FASTQ file format for sequences with quality scores, and the Solexa/Illumina FASTQ variants”. Nucleic Acids Research 38 (6): 1767–1771 (2010). doi:10.1093/nar/gkp1137 -
    [8]
    -Patrick O. Brown, David Botstein: “Exploring the new world of the genome with DNA microarrays”. Nature Genetics 21 (Supplement 1), 33–37 (1999). doi:10.1038/4462 -
    [9]
    -Eric Talevich, Brandon M. Invergo, Peter J.A. Cock, Brad A. Chapman: “Bio.Phylo: A unified toolkit for processing, analyzing and visualizing phylogenetic trees in Biopython”. BMC Bioinformatics 13: 209 (2012). doi:10.1186/1471-2105-13-209 -
    [10]
    -Athel Cornish-Bowden: “Nomenclature for incompletely specified bases in nucleic acid sequences: Recommendations 1984.” Nucleic Acids Research 13 (9): 3021–3030 (1985). doi:10.1093/nar/13.9.3021 -
    [11]
    -Douglas R. Cavener: “Comparison of the consensus sequence flanking translational start sites in Drosophila and vertebrates.” Nucleic Acids Research 15 (4): 1353–1361 (1987). doi:10.1093/nar/15.4.1353 -
    [12]
    -Timothy L. Bailey and Charles Elkan: “Fitting a mixture model by expectation maximization to discover motifs in biopolymers”, Proceedings of the Second International Conference on Intelligent Systems for Molecular Biology 28–36. AAAI Press, Menlo Park, California (1994). -
    [13]
    -Brad Chapman and Jeff Chang: “Biopython: Python tools for computational biology”. ACM SIGBIO Newsletter 20 (2): 15–19 (August 2000). -
    [14]
    -Michiel J. L. de Hoon, Seiya Imoto, John Nolan, Satoru Miyano: “Open source clustering software”. Bioinformatics 20 (9): 1453–1454 (2004). doi:10.1093/bioinformatics/bth078 -
    [15]
    -Michiel B. Eisen, Paul T. Spellman, Patrick O. Brown, David Botstein: “Cluster analysis and display of genome-wide expression patterns”. Proceedings of the National Academy of Science USA 95 (25): 14863–14868 (1998). doi:10.1073/pnas.96.19.10943-c -
    [16]
    -Gene H. Golub, Christian Reinsch: “Singular value decomposition and least squares solutions”. In Handbook for Automatic Computation, 2, (Linear Algebra) (J. H. Wilkinson and C. Reinsch, eds), 134–151. New York: Springer-Verlag (1971). -
    [17]
    -Gene H. Golub, Charles F. Van Loan: Matrix computations, 2nd edition (1989). -
    [18]
    +“The dilemma of phage taxonomy illustrated by comparative genomics of Sfi21-Like Siphoviridae in lactic acid bacteria”. Journal of Bacteriology 184 (21): 6026–6036 (2002). +http://dx.doi.org/10.1128/JB.184.21.6026-6036.2002 +
    [6]
    +Florian Jupe, Leighton Pritchard, Graham J. Etherington, Katrin MacKenzie, Peter JA Cock, Frank Wright, Sanjeev Kumar Sharma1, Dan Bolser, Glenn J Bryan, Jonathan DG Jones, Ingo Hein: “Identification and localisation of the NB-LRR gene family within the potato genome”. BMC Genomics 13: 75 (2012). +http://dx.doi.org/10.1186/1471-2164-13-75 +
    [7]
    +Peter J. A. Cock, Christopher J. Fields, Naohisa Goto, Michael L. Heuer, Peter M. Rice: “The Sanger FASTQ file format for sequences with quality scores, and the Solexa/Illumina FASTQ variants”. Nucleic Acids Research 38 (6): 1767–1771 (2010). doi:10.1093/nar/gkp1137 +
    [8]
    +Patrick O. Brown, David Botstein: “Exploring the new world of the genome with DNA microarrays”. Nature Genetics 21 (Supplement 1), 33–37 (1999). doi:10.1038/4462 +
    [9]
    +Eric Talevich, Brandon M. Invergo, Peter J.A. Cock, Brad A. Chapman: “Bio.Phylo: A unified toolkit for processing, analyzing and visualizing phylogenetic trees in Biopython”. BMC Bioinformatics 13: 209 (2012). doi:10.1186/1471-2105-13-209 +
    [10]
    +Athel Cornish-Bowden: “Nomenclature for incompletely specified bases in nucleic acid sequences: Recommendations 1984.” Nucleic Acids Research 13 (9): 3021–3030 (1985). doi:10.1093/nar/13.9.3021 +
    [11]
    +Douglas R. Cavener: “Comparison of the consensus sequence flanking translational start sites in Drosophila and vertebrates.” Nucleic Acids Research 15 (4): 1353–1361 (1987). doi:10.1093/nar/15.4.1353 +
    [12]
    +Timothy L. Bailey and Charles Elkan: “Fitting a mixture model by expectation maximization to discover motifs in biopolymers”, Proceedings of the Second International Conference on Intelligent Systems for Molecular Biology 28–36. AAAI Press, Menlo Park, California (1994). +
    [13]
    +Brad Chapman and Jeff Chang: “Biopython: Python tools for computational biology”. ACM SIGBIO Newsletter 20 (2): 15–19 (August 2000). +
    [14]
    +Michiel J. L. de Hoon, Seiya Imoto, John Nolan, Satoru Miyano: “Open source clustering software”. Bioinformatics 20 (9): 1453–1454 (2004). doi:10.1093/bioinformatics/bth078 +
    [15]
    +Michiel B. Eisen, Paul T. Spellman, Patrick O. Brown, David Botstein: “Cluster analysis and display of genome-wide expression patterns”. Proceedings of the National Academy of Science USA 95 (25): 14863–14868 (1998). doi:10.1073/pnas.96.19.10943-c +
    [16]
    +Gene H. Golub, Christian Reinsch: “Singular value decomposition and least squares solutions”. In Handbook for Automatic Computation, 2, (Linear Algebra) (J. H. Wilkinson and C. Reinsch, eds), 134–151. New York: Springer-Verlag (1971). +
    [17]
    +Gene H. Golub, Charles F. Van Loan: Matrix computations, 2nd edition (1989). +
    [18]
    Thomas Hamelryck and Bernard Manderick: 11PDB parser and structure class -implemented in Python”. Bioinformatics, 19 (17): 2308–2310 (2003) doi: 10.1093/bioinformatics/btg299. -
    [19]
    -Thomas Hamelryck: “Efficient identification of side-chain patterns using a multidimensional index tree”. Proteins 51 (1): 96–108 (2003). doi:10.1002/prot.10338 -
    [20]
    -Thomas Hamelryck: “An amino acid has two sides; A new 2D measure provides a different view of solvent exposure”. Proteins 59 (1): 29–48 (2005). doi:10.1002/prot.20379. -
    [21]
    -John A. Hartiga. Clustering algorithms. New York: Wiley (1975). -
    [22]
    -Anil L. Jain, Richard C. Dubes: Algorithms for clustering data. Englewood Cliffs, N.J.: Prentice Hall (1988). -
    [23]
    -Voratas Kachitvichyanukul, Bruce W. Schmeiser: Binomial Random Variate Generation. Communications of the ACM 31 (2): 216–222 (1988). doi:10.1145/42372.42381 -
    [24]
    +implemented in Python”. Bioinformatics, 19 (17): 2308–2310 (2003) doi: 10.1093/bioinformatics/btg299. +
    [19]
    +Thomas Hamelryck: “Efficient identification of side-chain patterns using a multidimensional index tree”. Proteins 51 (1): 96–108 (2003). doi:10.1002/prot.10338 +
    [20]
    +Thomas Hamelryck: “An amino acid has two sides; A new 2D measure provides a different view of solvent exposure”. Proteins 59 (1): 29–48 (2005). doi:10.1002/prot.20379. +
    [21]
    +John A. Hartiga. Clustering algorithms. New York: Wiley (1975). +
    [22]
    +Anil L. Jain, Richard C. Dubes: Algorithms for clustering data. Englewood Cliffs, N.J.: Prentice Hall (1988). +
    [23]
    +Voratas Kachitvichyanukul, Bruce W. Schmeiser: Binomial Random Variate Generation. Communications of the ACM 31 (2): 216–222 (1988). doi:10.1145/42372.42381 +
    [24]
    Teuvo Kohonen: “Self-organizing maps”, 2nd Edition. Berlin; New York: Springer-Verlag (1997). -
    [25]
    +
    [25]
    Pierre L’Ecuyer: “Efficient and Portable Combined Random Number Generators.” -Communications of the ACM 31 (6): 742–749,774 (1988). doi:10.1145/62959.62969 -
    [26]
    -Indraneel Majumdar, S. Sri Krishna, Nick V. Grishin: “PALSSE: A program to delineate linear secondary structural elements from protein structures.” BMC Bioinformatics, 6: 202 (2005). doi:10.1186/1471-2105-6-202. -
    [27]
    -V. Matys, E. Fricke, R. Geffers, E. Gössling, M. Haubrock, R. Hehl, K. Hornischer, D. Karas, A.E. Kel, O.V. Kel-Margoulis, D.U. Kloos, S. Land, B. Lewicki-Potapov, H. Michael, R. Münch, I. Reuter, S. Rotert, H. Saxel, M. Scheer, S. Thiele, E. Wingender E: “TRANSFAC: transcriptional regulation, from patterns to profiles.” Nucleic Acids Research 31 (1): 374–378 (2003). doi:10.1093/nar/gkg108 -
    [28]
    -Robin Sibson: “SLINK: An optimally efficient algorithm for the single-link cluster method”. The Computer Journal 16 (1): 30–34 (1973). doi:10.1093/comjnl/16.1.30 -
    [29]
    -George W. Snedecor, William G. Cochran: Statistical methods. Ames, Iowa: Iowa State University Press (1989). -
    [30]
    -Pablo Tamayo, Donna Slonim, Jill Mesirov, Qing Zhu, Sutisak Kitareewan, Ethan Dmitrovsky, Eric S. Lander, Todd R. Golub: “Interpreting patterns of gene expression with self-organizing maps: Methods and application to hematopoietic differentiation”. Proceedings of the National Academy of Science USA 96 (6): 2907–2912 (1999). doi:10.1073/pnas.96.6.2907 -
    [31]
    -Robert C. Tryon, Daniel E. Bailey: Cluster analysis. New York: McGraw-Hill (1970). -
    [32]
    +Communications of the ACM 31 (6): 742–749,774 (1988). doi:10.1145/62959.62969 +
    [26]
    +Indraneel Majumdar, S. Sri Krishna, Nick V. Grishin: “PALSSE: A program to delineate linear secondary structural elements from protein structures.” BMC Bioinformatics, 6: 202 (2005). doi:10.1186/1471-2105-6-202. +
    [27]
    +V. Matys, E. Fricke, R. Geffers, E. Gössling, M. Haubrock, R. Hehl, K. Hornischer, D. Karas, A.E. Kel, O.V. Kel-Margoulis, D.U. Kloos, S. Land, B. Lewicki-Potapov, H. Michael, R. Münch, I. Reuter, S. Rotert, H. Saxel, M. Scheer, S. Thiele, E. Wingender E: “TRANSFAC: transcriptional regulation, from patterns to profiles.” Nucleic Acids Research 31 (1): 374–378 (2003). doi:10.1093/nar/gkg108 +
    [28]
    +Robin Sibson: “SLINK: An optimally efficient algorithm for the single-link cluster method”. The Computer Journal 16 (1): 30–34 (1973). doi:10.1093/comjnl/16.1.30 +
    [29]
    +George W. Snedecor, William G. Cochran: Statistical methods. Ames, Iowa: Iowa State University Press (1989). +
    [30]
    +Pablo Tamayo, Donna Slonim, Jill Mesirov, Qing Zhu, Sutisak Kitareewan, Ethan Dmitrovsky, Eric S. Lander, Todd R. Golub: “Interpreting patterns of gene expression with self-organizing maps: Methods and application to hematopoietic differentiation”. Proceedings of the National Academy of Science USA 96 (6): 2907–2912 (1999). doi:10.1073/pnas.96.6.2907 +
    [31]
    +Robert C. Tryon, Daniel E. Bailey: Cluster analysis. New York: McGraw-Hill (1970). +
    [32]
    John W. Tukey: “Exploratory data analysis”. Reading, Mass.: Addison-Wesley Pub. Co. (1977). -
    [33]
    -Ka Yee Yeung, Walter L. Ruzzo: “Principal Component Analysis for clustering gene expression data”. Bioinformatics 17 (9): 763–774 (2001). doi:10.1093/bioinformatics/17.9.763 -
    [34]
    -Alok Saldanha: “Java Treeview—extensible visualization of microarray data”. Bioinformatics 20 (17): 3246–3248 (2004). -http://dx.doi.org/10.1093/bioinformatics/bth349 -
    +
    [33]
    +Ka Yee Yeung, Walter L. Ruzzo: “Principal Component Analysis for clustering gene expression data”. Bioinformatics 17 (9): 763–774 (2001). doi:10.1093/bioinformatics/17.9.763 +
    [34]
    +Alok Saldanha: “Java Treeview—extensible visualization of microarray data”. Bioinformatics 20 (17): 3246–3248 (2004). +http://dx.doi.org/10.1093/bioinformatics/bth349 +
    -
    This document was translated from LATEX by -HEVEA.
    - +
    This document was translated from LATEX by +HEVEA.
    + Binary files /tmp/EAI2iEqCCm/python-biopython-1.62/Doc/Tutorial.pdf and /tmp/XMH5G9mdHg/python-biopython-1.63/Doc/Tutorial.pdf differ diff -Nru python-biopython-1.62/Doc/Tutorial.tex python-biopython-1.63/Doc/Tutorial.tex --- python-biopython-1.62/Doc/Tutorial.tex 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Doc/Tutorial.tex 2013-12-05 14:10:43.000000000 +0000 @@ -80,7 +80,7 @@ \author{Jeff Chang, Brad Chapman, Iddo Friedberg, Thomas Hamelryck, \\ Michiel de Hoon, Peter Cock, Tiago Antao, Eric Talevich, Bartek Wilczy\'{n}ski} -\date{Last Update -- 28 August 2013 (Biopython 1.62)} +\date{Last Update -- 1 December 2013 (Biopython 1.63)} %Hack to get the logo at the start of the HTML front page: %(hopefully this isn't going to be too wide for most people) @@ -181,7 +181,6 @@ operating systems you must install from source as described in the included README file. This is usually as simple as the standard commands: - \begin{verbatim} python setup.py build python setup.py test @@ -219,11 +218,46 @@ The correct capitalization is ``Biopython'', not ``BioPython'' (even though that would have matched BioPerl, BioJava and BioRuby). + \item \emph{What is going wrong with my print commands?} \\ + This tutorial now uses the Python 3 style print \emph{function}. + As of Biopython 1.62, we support both Python 2 and Python 3. + The most obvious language difference is the print \emph{statement} + in Python 2 became a print \emph{function} in Python 3. + + For example, this will only work under Python 2: + +\begin{verbatim} +>>> print "Hello World!" +Hello World! +\end{verbatim} + + If you try that on Python 3 you'll get a \verb|SyntaxError|. + Under Python 3 you must write: + +%doctest +\begin{verbatim} +>>> print("Hello World!") +Hello World! +\end{verbatim} + + Surprisingly that will also work on Python 2 -- but only for simple + examples printing one thing. In general you need to add this magic + line to the start of your Python scripts to use the print function + under Python 2.6 and 2.7: + +\begin{verbatim} +from __future__ import print_function +\end{verbatim} + + If you forget to add this magic import, under Python 2 you'll see + extra brackets produced by trying to use the print function when + Python 2 is interpretting it as a print statement and a tuple. + \item \emph{How do I find out what version of Biopython I have installed?} \\ Use this: \begin{verbatim} >>> import Bio - >>> print Bio.__version__ + >>> print(Bio.__version__) ... \end{verbatim} If the ``\verb|import Bio|'' line fails, Biopython is not installed. @@ -246,15 +280,6 @@ \item \url{http://biopython.org/DIST/docs/tutorial/Tutorial-dev.pdf} \end{itemize} - \item \emph{Which ``Numerical Python'' do I need?} \\ - For Biopython 1.48 or earlier, you needed the old Numeric module. - For Biopython 1.49 onwards, you need the newer NumPy instead. - Both Numeric and NumPy can be installed on the same machine fine. - See also: \url{http://numpy.scipy.org/} - - \item \emph{Why is the} \verb|Seq| \emph{object missing the (back) transcription \& translation methods described in this Tutorial?} \\ - You need Biopython 1.49 or later. Alternatively, use the \verb|Bio.Seq| module functions described in Section~\ref{sec:seq-module-functions}. - \item \emph{Why is the} \verb|Seq| \emph{object missing the upper \& lower methods described in this Tutorial?} \\ You need Biopython 1.53 or later. Alternatively, use \verb|str(my_seq).upper()| to get an upper case string. If you need a Seq object, try \verb|Seq(str(my_seq).upper())| but be careful about blindly re-using the same alphabet. @@ -262,21 +287,9 @@ \item \emph{Why doesn't the} \verb|Seq| \emph{object translation method support the} \verb|cds| \emph{option described in this Tutorial?} \\ You need Biopython 1.51 or later. - \item \emph{Why doesn't} \verb|Bio.SeqIO| \emph{work? It imports fine but there is no parse function etc.} \\ - You need Biopython 1.43 or later. Older versions did contain some related code under the \verb|Bio.SeqIO| name which has since been removed - and this is why the import ``works''. - - \item \emph{Why doesn't} \verb|Bio.SeqIO.read()| \emph{work? The module imports fine but there is no read function!} \\ - You need Biopython 1.45 or later. Or, use \texttt{Bio.SeqIO.parse(...).next()} instead. - - \item \emph{Why isn't} \verb|Bio.AlignIO| \emph{present? The module import fails!} \\ - You need Biopython 1.46 or later. - \item \emph{What file formats do} \verb|Bio.SeqIO| \emph{and} \verb|Bio.AlignIO| \emph{read and write?} \\ Check the built in docstrings (\texttt{from Bio import SeqIO}, then \texttt{help(SeqIO)}), or see \url{http://biopython.org/wiki/SeqIO} and \url{http://biopython.org/wiki/AlignIO} on the wiki for the latest listing. - \item \emph{Why don't the } \verb|Bio.SeqIO| \emph{and} \verb|Bio.AlignIO| \emph{input functions let me provide a sequence alphabet?} \\ - You need Biopython 1.49 or later. - \item \emph{Why won't the } \verb|Bio.SeqIO| \emph{and} \verb|Bio.AlignIO| \emph{functions} \verb|parse|\emph{,} \verb|read| \emph{and} \verb|write| \emph{take filenames? They insist on handles!} \\ You need Biopython 1.54 or later, or just use handles explicitly (see Section~\ref{sec:appendix-handles}). It is especially important to remember to close output handles explicitly after writing your data. @@ -292,13 +305,9 @@ If you aren't using the latest version of Biopython, you could try upgrading. However, we (and the NCBI) recommend you use the XML output instead, which is designed to be read by a computer program. - \item \emph{Why doesn't} \verb|Bio.Entrez.read()| \emph{work? The module imports fine but there is no read function!} \\ - You need Biopython 1.46 or later. - \item \emph{Why doesn't} \verb|Bio.Entrez.parse()| \emph{work? The module imports fine but there is no parse function!} \\ You need Biopython 1.52 or later. - \item \emph{Why has my script using} \verb|Bio.Entrez.efetch()| \emph{stopped working?} \\ This could be due to NCBI changes in February 2012 introducing EFetch 2.0. First, they changed the default return modes - you probably want to add \verb|retmode="text"| to @@ -311,7 +320,7 @@ and they do not match the QBLAST defaults anymore. Check things like the gap penalties and expectation threshold. \item \emph{Why doesn't} \verb|Bio.Blast.NCBIXML.read()| \emph{work? The module imports but there is no read function!} \\ - You need Biopython 1.50 or later. Or, use \texttt{Bio.Blast.NCBIXML.parse(...).next()} instead. + You need Biopython 1.50 or later. Or, use \texttt{next(Bio.Blast.NCBIXML.parse(...))} instead. \item \emph{Why doesn't my} \verb|SeqRecord| \emph{object have a} \verb|letter_annotations| \emph{attribute?} \\ Per-letter-annotation support was added in Biopython 1.50. @@ -375,7 +384,7 @@ >>> my_seq = Seq("AGTACACTGGT") >>> my_seq Seq('AGTACACTGGT', Alphabet()) ->>> print my_seq +>>> print(my_seq) AGTACACTGGT >>> my_seq.alphabet Alphabet() @@ -448,9 +457,9 @@ \begin{verbatim} from Bio import SeqIO for seq_record in SeqIO.parse("ls_orchid.fasta", "fasta"): - print seq_record.id - print repr(seq_record.seq) - print len(seq_record) + print(seq_record.id) + print(repr(seq_record.seq)) + print(len(seq_record)) \end{verbatim} \noindent You should get something like this on your screen: @@ -474,9 +483,9 @@ \begin{verbatim} from Bio import SeqIO for seq_record in SeqIO.parse("ls_orchid.gbk", "genbank"): - print seq_record.id - print repr(seq_record.seq) - print len(seq_record) + print(seq_record.id) + print(repr(seq_record.seq)) + print(len(seq_record)) \end{verbatim} \noindent This should give: @@ -595,13 +604,13 @@ >>> from Bio.Alphabet import IUPAC >>> my_seq = Seq("GATCG", IUPAC.unambiguous_dna) >>> for index, letter in enumerate(my_seq): -... print index, letter +... print("%i %s" % (index, letter)) 0 G 1 A 2 T 3 C 4 G ->>> print len(my_seq) +>>> print(len(my_seq)) 5 \end{verbatim} @@ -609,11 +618,11 @@ %cont-doctest \begin{verbatim} ->>> print my_seq[0] #first letter +>>> print(my_seq[0]) #first letter G ->>> print my_seq[2] #third letter +>>> print(my_seq[2]) #third letter T ->>> print my_seq[-1] #last letter +>>> print(my_seq[-1]) #last letter G \end{verbatim} @@ -712,10 +721,11 @@ Since calling \verb|str()| on a \verb|Seq| object returns the full sequence as a string, you often don't actually have to do this conversion explicitly. -Python does this automatically with a print statement: +Python does this automatically in the print function +(and the print statement under Python 2): %cont-doctest \begin{verbatim} ->>> print my_seq +>>> print(my_seq) GATCGATGGGCCTATATAGGATCGAAAATCGC \end{verbatim} @@ -723,7 +733,7 @@ %cont-doctest \begin{verbatim} >>> fasta_format_string = ">Name\n%s\n" % my_seq ->>> print fasta_format_string +>>> print(fasta_format_string) >Name GATCGATGGGCCTATATAGGATCGAAAATCGC @@ -1095,7 +1105,7 @@ You can compare the actual tables visually by printing them: %TODO - handle automatically in doctest? \begin{verbatim} ->>> print standard_table +>>> print(standard_table) Table 1 Standard, SGC0 | T | C | A | G | @@ -1123,7 +1133,7 @@ \end{verbatim} \noindent and: \begin{verbatim} ->>> print mito_table +>>> print(mito_table) Table 2 Vertebrate Mitochondrial, SGC1 | T | C | A | G | @@ -1317,7 +1327,7 @@ >>> unk = UnknownSeq(20) >>> unk UnknownSeq(20, alphabet = Alphabet(), character = '?') ->>> print unk +>>> print(unk) ???????????????????? >>> len(unk) 20 @@ -1333,7 +1343,7 @@ >>> unk_dna = UnknownSeq(20, alphabet=IUPAC.ambiguous_dna) >>> unk_dna UnknownSeq(20, alphabet = IUPACAmbiguousDNA(), character = 'N') ->>> print unk_dna +>>> print(unk_dna) NNNNNNNNNNNNNNNNNNNN \end{verbatim} @@ -1353,7 +1363,7 @@ >>> unk_protein = unk_dna.translate() >>> unk_protein UnknownSeq(6, alphabet = ProteinAlphabet(), character = 'X') ->>> print unk_protein +>>> print(unk_protein) XXXXXX >>> len(unk_protein) 6 @@ -1370,7 +1380,7 @@ sequence -- instead there is a partner FASTA file which \emph{does} have the sequence. -\section{Working with directly strings} +\section{Working with strings directly} \label{sec:seq-module-functions} To close this chapter, for those you who \emph{really} don't want to use the sequence objects (or who prefer a functional programming style to an object orientated one), @@ -1463,7 +1473,7 @@ '' >>> simple_seq_r.id = "AC12345" >>> simple_seq_r.description = "Made up sequence I wish I could write a paper about" ->>> print simple_seq_r.description +>>> print(simple_seq_r.description) Made up sequence I wish I could write a paper about >>> simple_seq_r.seq Seq('GATC', Alphabet()) @@ -1486,9 +1496,9 @@ %cont-doctest \begin{verbatim} >>> simple_seq_r.annotations["evidence"] = "None. I just made it up." ->>> print simple_seq_r.annotations +>>> print(simple_seq_r.annotations) {'evidence': 'None. I just made it up.'} ->>> print simple_seq_r.annotations["evidence"] +>>> print(simple_seq_r.annotations["evidence"]) None. I just made it up. \end{verbatim} @@ -1498,10 +1508,10 @@ %cont-doctest \begin{verbatim} ->>> simple_seq_r.letter_annotations["phred_quality"] = [40,40,38,30] ->>> print simple_seq_r.letter_annotations +>>> simple_seq_r.letter_annotations["phred_quality"] = [40, 40, 38, 30] +>>> print(simple_seq_r.letter_annotations) {'phred_quality': [40, 40, 38, 30]} ->>> print simple_seq_r.letter_annotations["phred_quality"] +>>> print(simple_seq_r.letter_annotations["phred_quality"]) [40, 40, 38, 30] \end{verbatim} @@ -1826,7 +1836,7 @@ %cont-doctest \begin{verbatim} ->>> print my_location +>>> print(my_location) [>5:(8^9)] \end{verbatim} @@ -1836,11 +1846,11 @@ \begin{verbatim} >>> my_location.start AfterPosition(5) ->>> print my_location.start +>>> print(my_location.start) >5 >>> my_location.end BetweenPosition(9, left=8, right=9) ->>> print my_location.end +>>> print(my_location.end) (8^9) \end{verbatim} @@ -1874,7 +1884,7 @@ %cont-doctest \begin{verbatim} >>> exact_location = SeqFeature.FeatureLocation(5, 9) ->>> print exact_location +>>> print(exact_location) [5:9] >>> exact_location.start ExactPosition(5) @@ -1906,8 +1916,8 @@ >>> record = SeqIO.read("NC_005816.gb", "genbank") >>> for feature in record.features: ... if my_snp in feature: -... print feature.type, feature.qualifiers.get('db_xref') -... +... print("%s %s" % (feature.type, feature.qualifiers.get('db_xref'))) +... source ['taxon:229193'] gene ['GeneID:2767712'] CDS ['GI:45478716', 'GeneID:2767712'] @@ -1936,7 +1946,7 @@ %cont-doctest \begin{verbatim} >>> feature_seq = example_parent[example_feature.location.start:example_feature.location.end].reverse_complement() ->>> print feature_seq +>>> print(feature_seq) AGCCTTTGCCGTC \end{verbatim} @@ -1945,7 +1955,7 @@ %cont-doctest \begin{verbatim} >>> feature_seq = example_feature.extract(example_parent) ->>> print feature_seq +>>> print(feature_seq) AGCCTTTGCCGTC \end{verbatim} @@ -1954,13 +1964,13 @@ %cont-doctest \begin{verbatim} ->>> print example_feature.extract(example_parent) +>>> print(example_feature.extract(example_parent)) AGCCTTTGCCGTC ->>> print len(example_feature.extract(example_parent)) +>>> print(len(example_feature.extract(example_parent))) 13 ->>> print len(example_feature) +>>> print(len(example_feature)) 13 ->>> print len(example_feature.location) +>>> print(len(example_feature.location)) 13 \end{verbatim} @@ -1999,7 +2009,7 @@ id="gi|14150838|gb|AAK54648.1|AF376133_1", description="chalcone synthase [Cucumis sativus]") -print record.format("fasta") +print(record.format("fasta")) \end{verbatim} \noindent which should give: \begin{verbatim} @@ -2057,7 +2067,7 @@ %cont-doctest \begin{verbatim} ->>> print record.features[20] +>>> print(record.features[20]) type: gene location: [4342:4780](+) qualifiers: @@ -2068,7 +2078,7 @@ \end{verbatim} %This one is truncated so can't use for doctest \begin{verbatim} ->>> print record.features[21] +>>> print(record.features[21]) type: CDS location: [4342:4780](+) qualifiers: @@ -2110,7 +2120,7 @@ %cont-doctest \begin{verbatim} ->>> print sub_record.features[0] +>>> print(sub_record.features[0]) type: gene location: [42:480](+) qualifiers: @@ -2120,7 +2130,7 @@ \end{verbatim} \begin{verbatim} ->>> print sub_record.features[20] +>>> print(sub_record.features[20]) type: CDS location: [42:480](+) qualifiers: @@ -2171,7 +2181,7 @@ \begin{verbatim} >>> sub_record.description = "Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, partial." ->>> print sub_record.format("genbank") +>>> print(sub_record.format("genbank")) ... \end{verbatim} @@ -2194,15 +2204,15 @@ %doctest ../Tests/Quality \begin{verbatim} >>> from Bio import SeqIO ->>> record = SeqIO.parse("example.fastq", "fastq").next() +>>> record = next(SeqIO.parse("example.fastq", "fastq")) >>> len(record) 25 ->>> print record.seq +>>> print(record.seq) CCCTTCTTGTCTTCAGCGTTTCTCC \end{verbatim} %TODO - doctest wrapping \begin{verbatim} ->>> print record.letter_annotations["phred_quality"] +>>> print(record.letter_annotations["phred_quality"]) [26, 26, 18, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 22, 26, 26, 26, 26, 26, 26, 26, 23, 23] \end{verbatim} @@ -2215,14 +2225,14 @@ %cont-doctest \begin{verbatim} >>> left = record[:20] ->>> print left.seq +>>> print(left.seq) CCCTTCTTGTCTTCAGCGTT ->>> print left.letter_annotations["phred_quality"] +>>> print(left.letter_annotations["phred_quality"]) [26, 26, 18, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 22, 26, 26, 26, 26] >>> right = record[21:] ->>> print right.seq +>>> print(right.seq) CTCC ->>> print right.letter_annotations["phred_quality"] +>>> print(right.letter_annotations["phred_quality"]) [26, 26, 23, 23] \end{verbatim} @@ -2233,11 +2243,11 @@ >>> edited = left + right >>> len(edited) 24 ->>> print edited.seq +>>> print(edited.seq) CCCTTCTTGTCTTCAGCGTTCTCC \end{verbatim} \begin{verbatim} ->>> print edited.letter_annotations["phred_quality"] +>>> print(edited.letter_annotations["phred_quality"]) [26, 26, 18, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 22, 26, 26, 26, 26, 26, 26, 23, 23] \end{verbatim} @@ -2364,7 +2374,7 @@ \begin{verbatim} >>> from Bio import SeqIO >>> record = SeqIO.read("NC_005816.gb", "genbank") ->>> print record.id, len(record), len(record.features), len(record.dbxrefs), len(record.annotations) +>>> print("%s %i %i %i %i" % (record.id, len(record), len(record.features), len(record.dbxrefs), len(record.annotations))) NC_005816.1 9609 41 1 11 \end{verbatim} @@ -2374,7 +2384,7 @@ %cont-doctest \begin{verbatim} >>> rc = record.reverse_complement(id="TESTING") ->>> print rc.id, len(rc), len(rc.features), len(rc.dbxrefs), len(rc.annotations) +>>> print("%s %i %i %i %i" % (rc.id, len(rc), len(rc.features), len(rc.dbxrefs), len(rc.annotations))) TESTING 9609 41 0 0 \end{verbatim} @@ -2415,9 +2425,9 @@ \begin{verbatim} from Bio import SeqIO for seq_record in SeqIO.parse("ls_orchid.fasta", "fasta"): - print seq_record.id - print repr(seq_record.seq) - print len(seq_record) + print(seq_record.id) + print(repr(seq_record.seq)) + print(len(seq_record)) \end{verbatim} The above example is repeated from the introduction in Section~\ref{sec:sequence-parsing}, and will load the orchid DNA sequences in the FASTA format file \href{http://biopython.org/DIST/docs/tutorial/examples/ls_orchid.fasta}{ls\_orchid.fasta}. If instead you wanted to load a GenBank format file like \href{http://biopython.org/DIST/docs/tutorial/examples/ls_orchid.gbk}{ls\_orchid.gbk} then all you need to do is change the filename and the format string: @@ -2425,9 +2435,9 @@ \begin{verbatim} from Bio import SeqIO for seq_record in SeqIO.parse("ls_orchid.gbk", "genbank"): - print seq_record.id - print seq_record.seq - print len(seq_record) + print(seq_record.id) + print(seq_record.seq) + print(len(seq_record)) \end{verbatim} Similarly, if you wanted to read in a file in another file format, then assuming \verb|Bio.SeqIO.parse()| supports it you would just need to change the format string as appropriate, for example ``swiss'' for SwissProt files or ``embl'' for EMBL text files. There is a full listing on the wiki page (\url{http://biopython.org/wiki/SeqIO}) and in the built in documentation (also \href{http://biopython.org/DIST/docs/api/Bio.SeqIO-module.html}{online}). @@ -2453,31 +2463,31 @@ The object returned by \verb|Bio.SeqIO| is actually an iterator which returns \verb|SeqRecord| objects. You get to see each record in turn, but once and only once. The plus point is that an iterator can save you memory when dealing with large files. -Instead of using a for loop, can also use the \verb|.next()| method of an iterator to step through the entries, like this: +Instead of using a for loop, can also use the \verb|next()| function on an iterator to step through the entries, like this: \begin{verbatim} from Bio import SeqIO record_iterator = SeqIO.parse("ls_orchid.fasta", "fasta") -first_record = record_iterator.next() -print first_record.id -print first_record.description +first_record = next(record_iterator) +print(first_record.id) +print(first_record.description) -second_record = record_iterator.next() -print second_record.id -print second_record.description +second_record = next(record_iterator) +print(second_record.id) +print(second_record.description) \end{verbatim} -Note that if you try and use \verb|.next()| and there are no more results, you'll get the special \verb|StopIteration| exception. +Note that if you try to use \verb|next()| and there are no more results, you'll get the special \verb|StopIteration| exception. One special case to consider is when your sequence files have multiple records, but you only want the first one. In this situation the following code is very concise: \begin{verbatim} from Bio import SeqIO -first_record = SeqIO.parse("ls_orchid.gbk", "genbank").next() +first_record = next(SeqIO.parse("ls_orchid.gbk", "genbank")) \end{verbatim} -A word of warning here -- using the \verb|.next()| method like this will silently ignore any additional records in the file. +A word of warning here -- using the \verb|next()| function like this will silently ignore any additional records in the file. If your files have {\it one and only one} record, like some of the online examples later in this chapter, or a GenBank file for a single chromosome, then use the new \verb|Bio.SeqIO.read()| function instead. This will check there are no extra unexpected records present. @@ -2489,19 +2499,19 @@ from Bio import SeqIO records = list(SeqIO.parse("ls_orchid.gbk", "genbank")) -print "Found %i records" % len(records) +print("Found %i records" % len(records)) -print "The last record" +print("The last record") last_record = records[-1] #using Python's list tricks -print last_record.id -print repr(last_record.seq) -print len(last_record) +print(last_record.id) +print(repr(last_record.seq)) +print(len(last_record)) -print "The first record" +print("The first record") first_record = records[0] #remember, Python counts from zero -print first_record.id -print repr(first_record.seq) -print len(first_record) +print(first_record.id) +print(repr(first_record.seq)) +print(len(first_record)) \end{verbatim} \noindent Giving: @@ -2528,8 +2538,8 @@ \begin{verbatim} from Bio import SeqIO record_iterator = SeqIO.parse("ls_orchid.gbk", "genbank") -first_record = record_iterator.next() -print first_record +first_record = next(record_iterator) +print(first_record) \end{verbatim} \noindent That should give something like this: @@ -2557,15 +2567,15 @@ The contents of this annotations dictionary were shown when we printed the record above. You can also print them out directly: \begin{verbatim} -print first_record.annotations +print(first_record.annotations) \end{verbatim} \noindent Like any Python dictionary, you can easily get a list of the keys: \begin{verbatim} -print first_record.annotations.keys() +print(first_record.annotations.keys()) \end{verbatim} \noindent or values: \begin{verbatim} -print first_record.annotations.values() +print(first_record.annotations.values()) \end{verbatim} In general, the annotation values are strings, or lists of strings. One special case is any references in the file get stored as reference objects. @@ -2573,14 +2583,14 @@ Suppose you wanted to extract a list of the species from the \href{http://biopython.org/DIST/docs/tutorial/examples/ls_orchid.gbk}{ls\_orchid.gbk} GenBank file. The information we want, \emph{Cypripedium irapeanum}, is held in the annotations dictionary under `source' and `organism', which we can access like this: \begin{verbatim} ->>> print first_record.annotations["source"] +>>> print(first_record.annotations["source"]) Cypripedium irapeanum \end{verbatim} \noindent or: \begin{verbatim} ->>> print first_record.annotations["organism"] +>>> print(first_record.annotations["organism"]) Cypripedium irapeanum \end{verbatim} @@ -2595,7 +2605,7 @@ all_species = [] for seq_record in SeqIO.parse("ls_orchid.gbk", "genbank"): all_species.append(seq_record.annotations["organism"]) -print all_species +print(all_species) \end{verbatim} Another way of writing this code is to use a list comprehension: @@ -2604,7 +2614,7 @@ from Bio import SeqIO all_species = [seq_record.annotations["organism"] for seq_record in \ SeqIO.parse("ls_orchid.gbk", "genbank")] -print all_species +print(all_species) \end{verbatim} \noindent In either case, the result is: @@ -2632,7 +2642,7 @@ all_species = [] for seq_record in SeqIO.parse("ls_orchid.fasta", "fasta"): all_species.append(seq_record.description.split()[1]) -print all_species +print(all_species) \end{verbatim} \noindent This gives: @@ -2647,7 +2657,7 @@ from Bio import SeqIO all_species == [seq_record.description.split()[1] for seq_record in \ SeqIO.parse("ls_orchid.fasta", "fasta")] -print all_species +print(all_species) \end{verbatim} In general, extracting information from the FASTA description line is not very nice. @@ -2669,20 +2679,19 @@ %doctest examples \begin{verbatim} >>> from Bio import SeqIO ->>> print sum(len(r) for r in SeqIO.parse("ls_orchid.gbk", "gb")) +>>> print(sum(len(r) for r in SeqIO.parse("ls_orchid.gbk", "gb"))) 67518 \end{verbatim} \noindent Here we use a file handle instead, using the \verb|with| statement -(Python 2.5 or later) to close the handle automatically: +to close the handle automatically: -%This doctest won't work on Python 2.5, even with the __future__ import. Odd. +%doctest examples \begin{verbatim} ->>> from __future__ import with_statement #Needed on Python 2.5 >>> from Bio import SeqIO >>> with open("ls_orchid.gbk") as handle: -... print sum(len(r) for r in SeqIO.parse(handle, "gb")) +... print(sum(len(r) for r in SeqIO.parse(handle, "gb"))) 67518 \end{verbatim} @@ -2693,7 +2702,7 @@ \begin{verbatim} >>> from Bio import SeqIO >>> handle = open("ls_orchid.gbk") ->>> print sum(len(r) for r in SeqIO.parse(handle, "gb")) +>>> print(sum(len(r) for r in SeqIO.parse(handle, "gb"))) 67518 >>> handle.close() \end{verbatim} @@ -2707,7 +2716,7 @@ >>> import gzip >>> from Bio import SeqIO >>> handle = gzip.open("ls_orchid.gbk.gz", "r") ->>> print sum(len(r) for r in SeqIO.parse(handle, "gb")) +>>> print(sum(len(r) for r in SeqIO.parse(handle, "gb"))) 67518 >>> handle.close() \end{verbatim} @@ -2720,7 +2729,7 @@ >>> import bz2 >>> from Bio import SeqIO >>> handle = bz2.BZ2File("ls_orchid.gbk.bz2", "r") ->>> print sum(len(r) for r in SeqIO.parse(handle, "gb")) +>>> print(sum(len(r) for r in SeqIO.parse(handle, "gb"))) 67518 >>> handle.close() \end{verbatim} @@ -2766,7 +2775,7 @@ handle = Entrez.efetch(db="nucleotide", rettype="fasta", retmode="text", id="6273291") seq_record = SeqIO.read(handle, "fasta") handle.close() -print "%s with %i features" % (seq_record.id, len(seq_record.features)) +print("%s with %i features" % (seq_record.id, len(seq_record.features))) \end{verbatim} \noindent Expected output: @@ -2791,7 +2800,7 @@ handle = Entrez.efetch(db="nucleotide", rettype="gb", retmode="text", id="6273291") seq_record = SeqIO.read(handle, "gb") #using "gb" as an alias for "genbank" handle.close() -print "%s with %i features" % (seq_record.id, len(seq_record.features)) +print("%s with %i features" % (seq_record.id, len(seq_record.features))) \end{verbatim} \noindent The expected output of this example is: @@ -2845,12 +2854,12 @@ handle = ExPASy.get_sprot_raw("O23729") seq_record = SeqIO.read(handle, "swiss") handle.close() -print seq_record.id -print seq_record.name -print seq_record.description -print repr(seq_record.seq) -print "Length %i" % len(seq_record) -print seq_record.annotations["keywords"] +print(seq_record.id) +print(seq_record.name) +print(seq_record.description) +print(repr(seq_record.seq)) +print("Length %i" % len(seq_record)) +print(seq_record.annotations["keywords"]) \end{verbatim} \noindent Assuming your network connection is OK, you should get back: @@ -2920,7 +2929,7 @@ \end{verbatim} %Can't use following for doctest due to abbreviation \begin{verbatim} ->>> print orchid_dict.keys() +>>> orchid_dict.keys() ['Z78484.1', 'Z78464.1', 'Z78455.1', 'Z78442.1', 'Z78532.1', 'Z78453.1', ..., 'Z78471.1'] \end{verbatim} @@ -2935,9 +2944,9 @@ %cont-doctest \begin{verbatim} >>> seq_record = orchid_dict["Z78475.1"] ->>> print seq_record.description +>>> print(seq_record.description) P.supardii 5.8S rRNA gene and ITS1 and ITS2 DNA. ->>> print repr(seq_record.seq) +>>> print(repr(seq_record.seq)) Seq('CGTAACAAGGTTTCCGTAGGTGAACCTGCGGAAGGATCATTGTTGAGATCACAT...GGT', IUPACAmbiguousDNA()) \end{verbatim} @@ -2953,7 +2962,7 @@ \begin{verbatim} from Bio import SeqIO orchid_dict = SeqIO.to_dict(SeqIO.parse("ls_orchid.fasta", "fasta")) -print orchid_dict.keys() +print(orchid_dict.keys()) \end{verbatim} \noindent This time the keys are: @@ -2983,13 +2992,13 @@ \begin{verbatim} from Bio import SeqIO orchid_dict = SeqIO.to_dict(SeqIO.parse("ls_orchid.fasta", "fasta"), key_function=get_accession) -print orchid_dict.keys() +print(orchid_dict.keys()) \end{verbatim} \noindent Finally, as desired, the new dictionary keys: \begin{verbatim} ->>> print orchid_dict.keys() +>>> print(orchid_dict.keys()) ['Z78484.1', 'Z78464.1', 'Z78455.1', 'Z78442.1', 'Z78532.1', 'Z78453.1', ..., 'Z78471.1'] \end{verbatim} @@ -3005,7 +3014,7 @@ from Bio import SeqIO from Bio.SeqUtils.CheckSum import seguid for record in SeqIO.parse("ls_orchid.gbk", "genbank"): - print record.id, seguid(record.seq) + print(record.id, seguid(record.seq)) \end{verbatim} \noindent This should give: @@ -3026,9 +3035,9 @@ >>> seguid_dict = SeqIO.to_dict(SeqIO.parse("ls_orchid.gbk", "genbank"), ... lambda rec : seguid(rec.seq)) >>> record = seguid_dict["MN/s0q9zDoCVEEc+k/IFwCNF2pY"] ->>> print record.id +>>> print(record.id) Z78532.1 ->>> print record.description +>>> print(record.description) C.californicum 5.8S rRNA gene and ITS1 and ITS2 DNA. \end{verbatim} @@ -3067,7 +3076,7 @@ %cont-doctest \begin{verbatim} >>> seq_record = orchid_dict["Z78475.1"] ->>> print seq_record.description +>>> print(seq_record.description) P.supardii 5.8S rRNA gene and ITS1 and ITS2 DNA. >>> seq_record.seq Seq('CGTAACAAGGTTTCCGTAGGTGAACCTGCGGAAGGATCATTGTTGAGATCACAT...GGT', IUPACAmbiguousDNA()) @@ -3120,7 +3129,7 @@ \begin{verbatim} >>> from Bio import SeqIO >>> orchid_dict = SeqIO.index("ls_orchid.fasta", "fasta", key_function=get_acc) ->>> print orchid_dict.keys() +>>> print(orchid_dict.keys()) ['Z78484.1', 'Z78464.1', 'Z78455.1', 'Z78442.1', 'Z78532.1', 'Z78453.1', ..., 'Z78471.1'] \end{verbatim} @@ -3190,7 +3199,7 @@ >>> from Bio import SeqIO >>> files = ["gbvrl%i.seq" % (i+1) for i in range(16)] >>> gb_vrl = SeqIO.index_db("gbvrl.idx", files, "genbank") ->>> print "%i sequences indexed" % len(gb_vrl) +>>> print("%i sequences indexed" % len(gb_vrl)) 958086 sequences indexed \end{verbatim} @@ -3200,7 +3209,7 @@ about which file the sequence comes from, e.g. \begin{verbatim} ->>> print gb_vrl["GQ333173.1"].description +>>> print(gb_vrl["GQ333173.1"].description) HIV-1 isolate F12279A1 from Uganda gag protein (gag) gene, partial cds. \end{verbatim} @@ -3211,7 +3220,7 @@ get at the raw text of each record: \begin{verbatim} ->>> print gb_vrl.get_raw("GQ333173.1") +>>> print(gb_vrl.get_raw("GQ333173.1")) LOCUS GQ333173 459 bp DNA linear VRL 21-OCT-2009 DEFINITION HIV-1 isolate F12279A1 from Uganda gag protein (gag) gene, partial cds. @@ -3443,7 +3452,7 @@ from Bio import SeqIO records = SeqIO.parse("ls_orchid.gbk", "genbank") count = SeqIO.write(records, "my_example.fasta", "fasta") -print "Converted %i records" % count +print("Converted %i records" % count) \end{verbatim} Still, that is a little bit complicated. So, because file conversion is such a @@ -3452,7 +3461,7 @@ \begin{verbatim} from Bio import SeqIO count = SeqIO.convert("ls_orchid.gbk", "genbank", "my_example.fasta", "fasta") -print "Converted %i records" % count +print("Converted %i records" % count) \end{verbatim} The \verb|Bio.SeqIO.convert()| function will take handles \emph{or} filenames. @@ -3490,8 +3499,8 @@ \begin{verbatim} >>> from Bio import SeqIO >>> for record in SeqIO.parse("ls_orchid.gbk", "genbank"): -... print record.id -... print record.seq.reverse_complement() +... print(record.id) +... print(record.seq.reverse_complement()) \end{verbatim} Now, if we want to save these reverse complements to a file, we'll need to make \verb|SeqRecord| objects. @@ -3552,7 +3561,7 @@ out_handle = StringIO() SeqIO.write(records, out_handle, "fasta") fasta_data = out_handle.getvalue() -print fasta_data +print(fasta_data) \end{verbatim} This isn't entirely straightforward the first time you see it! On the bright side, for the special case where you would like a string containing a \emph{single} record in a particular file format, use the the \verb|SeqRecord| class' \verb|format()| method (see Section~\ref{sec:SeqRecord-format}). @@ -3658,7 +3667,7 @@ %cont-doctest \begin{verbatim} ->>> print alignment +>>> print(alignment) SingleLetterAlphabet() alignment with 7 rows and 52 columns AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRL...SKA COATB_BPIKE/30-81 AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKL...SRA Q9T0Q8_BPIKE/1-52 @@ -3675,10 +3684,10 @@ \begin{verbatim} >>> from Bio import AlignIO >>> alignment = AlignIO.read("PF05371_seed.sth", "stockholm") ->>> print "Alignment length %i" % alignment.get_alignment_length() +>>> print("Alignment length %i" % alignment.get_alignment_length()) Alignment length 52 >>> for record in alignment: -... print "%s - %s" % (record.seq, record.id) +... print("%s - %s" % (record.seq, record.id)) AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA - COATB_BPIKE/30-81 AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA - Q9T0Q8_BPIKE/1-52 DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA - COATB_BPI22/32-83 @@ -3696,7 +3705,7 @@ \begin{verbatim} >>> for record in alignment: ... if record.dbxrefs: -... print record.id, record.dbxrefs +... print("%s %s" % (record.id, record.dbxrefs)) COATB_BPIKE/30-81 ['PDB; 1ifl ; 1-52;'] COATB_BPM13/24-72 ['PDB; 2cpb ; 1-49;', 'PDB; 2cps ; 1-49;'] Q9T0Q9_BPFD/1-49 ['PDB; 1nh4 A; 1-49;'] @@ -3707,7 +3716,7 @@ \begin{verbatim} >>> for record in alignment: -... print record +... print(record) \end{verbatim} Sanger provide a nice web interface at \url{http://pfam.sanger.ac.uk/family?acc=PF05371} which will actually let you download this alignment in several other formats. This is what the file looks like in the FASTA file format: @@ -3734,7 +3743,7 @@ \begin{verbatim} from Bio import AlignIO alignment = AlignIO.read("PF05371_seed.faa", "fasta") -print alignment +print(alignment) \end{verbatim} All that has changed in this code is the filename and the format string. You'll get the same output as before, the sequences and record identifiers are the same. @@ -3797,12 +3806,13 @@ If you wanted to read this in using \verb|Bio.AlignIO| you could use: +%TODO - Replace the print blank line with print()? \begin{verbatim} from Bio import AlignIO alignments = AlignIO.parse("resampled.phy", "phylip") for alignment in alignments: - print alignment - print + print(alignment) + print("") \end{verbatim} \noindent This would give the following output, again abbreviated for display: @@ -3914,12 +3924,13 @@ To interpret these FASTA examples as several separate alignments, we can use \verb|Bio.AlignIO.parse()| with the optional \verb|seq_count| argument which specifies how many sequences are expected in each alignment (in these examples, 3, 2 and 2 respectively). For example, using the third example as the input data: +%TODO - Replace the print blank line with print()? \begin{verbatim} for alignment in AlignIO.parse(handle, "fasta", seq_count=2): - print "Alignment length %i" % alignment.get_alignment_length() + print("Alignment length %i" % alignment.get_alignment_length()) for record in alignment: - print "%s - %s" % (record.seq, record.id) - print + print("%s - %s" % (record.seq, record.id)) + print("") \end{verbatim} \noindent giving: @@ -4023,7 +4034,7 @@ \begin{verbatim} from Bio import AlignIO count = AlignIO.convert("PF05371_seed.sth", "stockholm", "PF05371_seed.aln", "clustal") -print "Converted %i alignments" % count +print("Converted %i alignments" % count) \end{verbatim} Or, using \verb|Bio.AlignIO.parse()| and \verb|Bio.AlignIO.write()|: @@ -4032,7 +4043,7 @@ from Bio import AlignIO alignments = AlignIO.parse("PF05371_seed.sth", "stockholm") count = AlignIO.write(alignments, "PF05371_seed.aln", "clustal") -print "Converted %i alignments" % count +print("Converted %i alignments" % count) \end{verbatim} The \verb|Bio.AlignIO.write()| function expects to be given multiple alignment objects. In the example above we gave it the alignment iterator returned by \verb|Bio.AlignIO.parse()|. @@ -4105,7 +4116,7 @@ for i, record in enumerate(alignment): name_mapping[i] = record.id record.id = "seq%i" % i -print name_mapping +print(name_mapping) AlignIO.write([alignment], "PF05371_seed.phy", "phylip") \end{verbatim} @@ -4146,7 +4157,7 @@ \begin{verbatim} from Bio import AlignIO alignment = AlignIO.read("PF05371_seed.sth", "stockholm") -print alignment.format("clustal") +print(alignment.format("clustal")) \end{verbatim} As described in Section~\ref{sec:SeqRecord-format}), the \verb|SeqRecord| object has a similar method using output formats supported by \verb|Bio.SeqIO|. @@ -4165,7 +4176,7 @@ AlignIO.write(alignments, out_handle, "clustal") clustal_data = out_handle.getvalue() -print clustal_data +print(clustal_data) \end{verbatim} \section{Manipulating Alignments} @@ -4184,10 +4195,10 @@ \begin{verbatim} >>> from Bio import AlignIO >>> alignment = AlignIO.read("PF05371_seed.sth", "stockholm") ->>> print "Number of rows: %i" % len(alignment) +>>> print("Number of rows: %i" % len(alignment)) Number of rows: 7 >>> for record in alignment: -... print "%s - %s" % (record.seq, record.id) +... print("%s - %s" % (record.seq, record.id)) AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA - COATB_BPIKE/30-81 AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA - Q9T0Q8_BPIKE/1-52 DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA - COATB_BPI22/32-83 @@ -4204,7 +4215,7 @@ %cont-doctest \begin{verbatim} ->>> print alignment +>>> print(alignment) SingleLetterAlphabet() alignment with 7 rows and 52 columns AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRL...SKA COATB_BPIKE/30-81 AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKL...SRA Q9T0Q8_BPIKE/1-52 @@ -4213,7 +4224,7 @@ AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPZJ2/1-49 AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA Q9T0Q9_BPFD/1-49 FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKL...SRA COATB_BPIF1/22-73 ->>> print alignment[3:7] +>>> print(alignment[3:7]) SingleLetterAlphabet() alignment with 4 rows and 52 columns AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPM13/24-72 AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPZJ2/1-49 @@ -4226,7 +4237,7 @@ %cont-doctest \begin{verbatim} ->>> print alignment[2,6] +>>> print(alignment[2, 6]) T \end{verbatim} @@ -4234,7 +4245,7 @@ %cont-doctest \begin{verbatim} ->>> print alignment[2].seq[6] +>>> print(alignment[2].seq[6]) T \end{verbatim} @@ -4242,7 +4253,7 @@ %cont-doctest \begin{verbatim} ->>> print alignment[:,6] +>>> print(alignment[:, 6]) TTT---T \end{verbatim} @@ -4251,7 +4262,7 @@ %cont-doctest \begin{verbatim} ->>> print alignment[3:6,:6] +>>> print(alignment[3:6, :6]) SingleLetterAlphabet() alignment with 3 rows and 6 columns AEGDDP COATB_BPM13/24-72 AEGDDP COATB_BPZJ2/1-49 @@ -4262,7 +4273,7 @@ %cont-doctest \begin{verbatim} ->>> print alignment[:,:6] +>>> print(alignment[:, :6]) SingleLetterAlphabet() alignment with 7 rows and 6 columns AEPNAA COATB_BPIKE/30-81 AEPNAA Q9T0Q8_BPIKE/1-52 @@ -4278,7 +4289,7 @@ %cont-doctest \begin{verbatim} ->>> print alignment[:,6:9] +>>> print(alignment[:, 6:9]) SingleLetterAlphabet() alignment with 7 rows and 3 columns TNY COATB_BPIKE/30-81 TNY Q9T0Q8_BPIKE/1-52 @@ -4293,7 +4304,7 @@ %cont-doctest \begin{verbatim} ->>> print alignment[:,9:] +>>> print(alignment[:, 9:]) SingleLetterAlphabet() alignment with 7 rows and 43 columns ATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA COATB_BPIKE/30-81 ATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA Q9T0Q8_BPIKE/1-52 @@ -4309,8 +4320,8 @@ %cont-doctest \begin{verbatim} ->>> edited = alignment[:,:6] + alignment[:,9:] ->>> print edited +>>> edited = alignment[:, :6] + alignment[:, 9:] +>>> print(edited) SingleLetterAlphabet() alignment with 7 rows and 49 columns AEPNAAATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA COATB_BPIKE/30-81 AEPNAAATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA Q9T0Q8_BPIKE/1-52 @@ -4330,7 +4341,7 @@ %cont-doctest \begin{verbatim} >>> edited.sort() ->>> print edited +>>> print(edited) SingleLetterAlphabet() alignment with 7 rows and 49 columns DGTSTAATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA COATB_BPI22/32-83 FAADDAAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA COATB_BPIF1/22-73 @@ -4444,7 +4455,7 @@ \begin{verbatim} >>> from Bio.Align.Applications import ClustalwCommandline >>> cline = ClustalwCommandline("clustalw2", infile="opuntia.fasta") ->>> print cline +>>> print(cline) clustalw2 -infile=opuntia.fasta \end{verbatim} @@ -4514,7 +4525,7 @@ \begin{verbatim} >>> from Bio import AlignIO >>> align = AlignIO.read("opuntia.aln", "clustal") ->>> print align +>>> print(align) SingleLetterAlphabet() alignment with 7 rows and 906 columns TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF191 TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF191 @@ -4575,7 +4586,7 @@ \begin{verbatim} >>> from Bio.Align.Applications import MuscleCommandline >>> cline = MuscleCommandline(input="opuntia.fasta", out="opuntia.txt") ->>> print cline +>>> print(cline) muscle -in opuntia.fasta -out opuntia.txt \end{verbatim} @@ -4592,7 +4603,7 @@ \begin{verbatim} >>> from Bio.Align.Applications import MuscleCommandline >>> cline = MuscleCommandline(input="opuntia.fasta", out="opuntia.aln", clw=True) ->>> print cline +>>> print(cline) muscle -in opuntia.fasta -out opuntia.aln -clw \end{verbatim} @@ -4603,7 +4614,7 @@ \begin{verbatim} >>> from Bio.Align.Applications import MuscleCommandline >>> cline = MuscleCommandline(input="opuntia.fasta", out="opuntia.aln", clwstrict=True) ->>> print cline +>>> print(cline) muscle -in opuntia.fasta -out opuntia.aln -clwstrict \end{verbatim} @@ -4633,7 +4644,7 @@ \begin{verbatim} >>> from Bio.Align.Applications import MuscleCommandline >>> muscle_cline = MuscleCommandline(input="opuntia.fasta") ->>> print muscle_cline +>>> print(muscle_cline) muscle -in opuntia.fasta \end{verbatim} @@ -4648,7 +4659,7 @@ >>> from StringIO import StringIO >>> from Bio import AlignIO >>> align = AlignIO.read(StringIO(stdout), "fasta") ->>> print align +>>> print(align) SingleLetterAlphabet() alignment with 7 rows and 906 columns TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF191663 TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273291|gb|AF191665.1|AF191665 @@ -4674,7 +4685,7 @@ ... shell=(sys.platform!="win32")) >>> from Bio import AlignIO >>> align = AlignIO.read(child.stdout, "fasta") ->>> print align +>>> print(align) SingleLetterAlphabet() alignment with 7 rows and 906 columns TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF191663 TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273291|gb|AF191665.1|AF191665 @@ -4710,7 +4721,7 @@ \begin{verbatim} >>> from Bio.Align.Applications import MuscleCommandline >>> muscle_cline = MuscleCommandline(clwstrict=True) ->>> print muscle_cline +>>> print(muscle_cline) muscle -clwstrict \end{verbatim} @@ -4743,7 +4754,7 @@ \begin{verbatim} >>> from Bio import AlignIO >>> align = AlignIO.read(child.stdout, "clustal") ->>> print align +>>> print(align) SingleLetterAlphabet() alignment with 6 rows and 900 columns TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF19166 TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF19166 @@ -4788,7 +4799,7 @@ >>> stdout, stderr = muscle_cline(stdin=data) >>> from Bio import AlignIO >>> align = AlignIO.read(StringIO(stdout), "clustal") ->>> print align +>>> print(align) SingleLetterAlphabet() alignment with 6 rows and 900 columns TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF19166 TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF19166 @@ -4834,7 +4845,7 @@ >>> from Bio.Emboss.Applications import NeedleCommandline >>> needle_cline = NeedleCommandline(asequence="alpha.faa", bsequence="beta.faa", ... gapopen=10, gapextend=0.5, outfile="needle.txt") ->>> print needle_cline +>>> print(needle_cline) needle -outfile=needle.txt -asequence=alpha.faa -bsequence=beta.faa -gapopen=10 -gapextend=0.5 \end{verbatim} @@ -4880,9 +4891,9 @@ >>> needle_cline.gapopen=10 >>> needle_cline.gapextend=0.5 >>> needle_cline.outfile="needle.txt" ->>> print needle_cline +>>> print(needle_cline) needle -outfile=needle.txt -asequence=alpha.faa -bsequence=beta.faa -gapopen=10 -gapextend=0.5 ->>> print needle_cline.outfile +>>> print(needle_cline.outfile) needle.txt \end{verbatim} @@ -4892,7 +4903,7 @@ \begin{verbatim} >>> stdout, stderr = needle_cline() ->>> print stdout + stderr +>>> print(stdout + stderr) Needleman-Wunsch global alignment of two sequences \end{verbatim} @@ -4902,7 +4913,7 @@ \begin{verbatim} >>> from Bio import AlignIO >>> align = AlignIO.read("needle.txt", "emboss") ->>> print align +>>> print(align) SingleLetterAlphabet() alignment with 2 rows and 149 columns MV-LSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTY...KYR HBA_HUMAN MVHLTPEEKSAVTALWGKV--NVDEVGGEALGRLLVVYPWTQRF...KYH HBB_HUMAN @@ -5102,39 +5113,15 @@ \end{itemize} \noindent -To further confuse matters there are at least four different standalone BLAST packages, +To further confuse matters there are several different BLAST packages available, and there are also other tools which can produce imitation BLAST output files, such as BLAT. -\subsection{Standalone NCBI ``legacy'' BLAST} - -\href{http://blast.ncbi.nlm.nih.gov/Blast.cgi?CMD=Web&PAGE_TYPE=BlastDocs&DOC_TYPE=Download} -{NCBI ``legacy'' BLAST} included command line tools \verb|blastall|, \verb|blastpgp| and -\verb|rpsblast|. This was the most widely used standalone BLAST tool up until its replacement -BLAST+ was released by the NCBI. - -The \verb|Bio.Blast.Applications| module has wrappers for the ``legacy'' NCBI BLAST tools -like \verb|blastall|, \verb|blastpgp| and \verb|rpsblast|, and there are also helper -functions in \verb|Bio.Blast.NCBIStandalone|. These are now considered obsolete, and will -be deprecated and eventually removed from Biopython as people move over to the replacement -BLAST+ suite. - -To try and avoid confusion, we will not cover calling these old tools from Biopython -in this tutorial. Have a look at the older edition of this tutorial included with -Biopython 1.52 if you are curious (look at the Tutorial PDF or HTML file in the Doc -directory within \texttt{biopython-1.52.tar.gz} or \texttt{biopython-1.52.zip}). - \subsection{Standalone NCBI BLAST+} +The ``new'' \href{http://blast.ncbi.nlm.nih.gov/Blast.cgi?CMD=Web&PAGE_TYPE=BlastDocs&DOC_TYPE=Download} -{NCBI ``new'' BLAST+} was released in 2009. This replaces the old NCBI ``legacy'' BLAST -package. The \verb|Bio.Blast.Applications| module has wrappers for these ``new'' tools -like \verb|blastn|, \verb|blastp|, \verb|blastx|, \verb|tblastn|, \verb|tblastx| -(which all used to be handled by \verb|blastall|), \verb|psiblast| -(replacing \verb|blastpgp|) and \verb|rpsblast| and \verb|rpstblastn| -(which replace the old \verb|rpsblast|). -We don't include a wrapper for the \verb|makeblastdb| used in BLAST+ to build a -local BLAST database from FASTA file, nor the equivalent tool \verb|formatdb| in -``legacy'' BLAST. +{NCBI BLAST+} suite was released in 2009. This replaces the old NCBI ``legacy'' BLAST +package (see below). This section will show briefly how to use these tools from within Python. If you have already read or tried the alignment tool examples in Section~\ref{sec:alignment-tools} @@ -5169,7 +5156,7 @@ >>> blastx_cline NcbiblastxCommandline(cmd='blastx', out='opuntia.xml', outfmt=5, query='opuntia.fasta', db='nr', evalue=0.001) ->>> print blastx_cline +>>> print(blastx_cline) blastx -out opuntia.xml -outfmt 5 -query opuntia.fasta -db nr -evalue 0.001 >>> stdout, stderr = blastx_cline() \end{verbatim} @@ -5183,13 +5170,24 @@ Therefore use \verb|Bio.Blast.NCBIXML.parse()| to parse it as described below in Section~\ref{sec:parsing-blast}. -\subsection{WU-BLAST and AB-BLAST} +\subsection{Other versions of BLAST} + +NCBI BLAST+ (written in C++) was first released in 2009 as a replacement for +the original NCBI ``legacy'' BLAST (written in C) which is no longer being updated. +There were a lot of changes -- the old version had a single core command line +tool \verb|blastall| which covered multiple different BLAST search types (which +are now separate commands in BLAST+), and all the command line options +were renamed. +Biopython's wrappers for the NCBI ``legacy'' BLAST tools have been deprecated +and will be removed in a future release. +To try to avoid confusion, we do not cover calling these old tools from Biopython +in this tutorial. You may also come across \href{http://blast.wustl.edu/}{Washington University BLAST} (WU-BLAST), and its successor, \href{http://blast.advbiocomp.com}{Advanced Biocomputing BLAST} (AB-BLAST, released in 2009, not free/open source). These packages include -the command line tools \verb|wu-blastall| and \verb|ab-blastall|. - +the command line tools \verb|wu-blastall| and \verb|ab-blastall|, which mimicked +\verb|blastall| from the NCBI ``legacy'' BLAST stuie. Biopython does not currently provide wrappers for calling these tools, but should be able to parse any NCBI compatible output from them. @@ -5285,13 +5283,13 @@ \begin{verbatim} >>> from Bio.Blast import NCBIXML >>> blast_records = NCBIXML.parse(result_handle) ->>> blast_record = blast_records.next() +>>> blast_record = next(blast_records) # ... do something with blast_record ->>> blast_record = blast_records.next() +>>> blast_record = next(blast_records) # ... do something with blast_record ->>> blast_record = blast_records.next() +>>> blast_record = next(blast_records) # ... do something with blast_record ->>> blast_record = blast_records.next() +>>> blast_record = next(blast_records) Traceback (most recent call last): File "", line 1, in StopIteration @@ -5320,7 +5318,7 @@ \begin{verbatim} >>> from Bio.Blast import NCBIXML >>> blast_records = NCBIXML.parse(result_handle) ->>> blast_record = blast_records.next() +>>> blast_record = next(blast_records) \end{verbatim} \noindent or more elegantly: \begin{verbatim} @@ -5350,13 +5348,13 @@ >>> for alignment in blast_record.alignments: ... for hsp in alignment.hsps: ... if hsp.expect < E_VALUE_THRESH: -... print '****Alignment****' -... print 'sequence:', alignment.title -... print 'length:', alignment.length -... print 'e value:', hsp.expect -... print hsp.query[0:75] + '...' -... print hsp.match[0:75] + '...' -... print hsp.sbjct[0:75] + '...' +... print('****Alignment****') +... print('sequence:', alignment.title) +... print('length:', alignment.length) +... print('e value:', hsp.expect) +... print(hsp.query[0:75] + '...') +... print(hsp.match[0:75] + '...') +... print(hsp.sbjct[0:75] + '...') \end{verbatim} This will print out summary reports like the following: @@ -5449,13 +5447,13 @@ >>> for alignment in blast_record.alignments: ... for hsp in alignment.hsps: ... if hsp.expect < E_VALUE_THRESH: -... print '****Alignment****' -... print 'sequence:', alignment.title -... print 'length:', alignment.length -... print 'e value:', hsp.expect -... print hsp.query[0:75] + '...' -... print hsp.match[0:75] + '...' -... print hsp.sbjct[0:75] + '...' +... print('****Alignment****') +... print('sequence:', alignment.title) +... print('length:', alignment.length) +... print('e value:', hsp.expect) +... print(hsp.query[0:75] + '...') +... print(hsp.match[0:75] + '...') +... print(hsp.sbjct[0:75] + '...') \end{verbatim} If you also read the section~\ref{sec:parsing-blast} on parsing BLAST XML output, you'll notice that the above code is identical to what is found in that section. Once you parse something into a record class you can deal with it independent of the format of the original BLAST info you were parsing. Pretty snazzy! @@ -5484,7 +5482,7 @@ Now that we've got an iterator, we start retrieving blast records (generated by our parser) using \verb|next()|: \begin{verbatim} ->>> blast_record = blast_iterator.next() +>>> blast_record = next(blast_iterator) \end{verbatim} Each call to next will return a new record that we can deal with. Now we can iterate through this records and generate our old favorite, a nice little blast report: @@ -5495,20 +5493,20 @@ ... for alignment in blast_record.alignments: ... for hsp in alignment.hsps: ... if hsp.expect < E_VALUE_THRESH: -... print '****Alignment****' -... print 'sequence:', alignment.title -... print 'length:', alignment.length -... print 'e value:', hsp.expect +... print('****Alignment****') +... print('sequence:', alignment.title) +... print('length:', alignment.length) +... print('e value:', hsp.expect) ... if len(hsp.query) > 75: ... dots = '...' ... else: ... dots = '' -... print hsp.query[0:75] + dots -... print hsp.match[0:75] + dots -... print hsp.sbjct[0:75] + dots +... print(hsp.query[0:75] + dots) +... print(hsp.match[0:75] + dots) +... print(hsp.sbjct[0:75] + dots) \end{verbatim} -%Notice that \verb|b_iterator.next()| will return \verb|None| when it runs out of records to parse, so it is easy to iterate through the entire file with a while loop that checks for the existence of a record. +%Notice that \verb|next(b_iterator)| will return \verb|None| when it runs out of records to parse, so it is easy to iterate through the entire file with a while loop that checks for the existence of a record. The iterator allows you to deal with huge blast records without any memory problems, since things are read in one at a time. I have parsed tremendously huge files without any problems using this. @@ -5548,12 +5546,12 @@ \begin{verbatim} >>> try: -... next_record = iterator.next() -... except NCBIStandalone.LowQualityBlastError, info: -... print "LowQualityBlastError detected in id %s" % info[1] +... next_record = next(iterator) +... except NCBIStandalone.LowQualityBlastError as info: +... print("LowQualityBlastError detected in id %s" % info[1]) \end{verbatim} -The \verb|.next()| method is normally called indirectly via a \verb|for|-loop. +The \verb|next()| functionality is normally called indirectly via a \verb|for|-loop. Right now the \verb|BlastErrorParser| can generate the following errors: \begin{itemize} @@ -5727,7 +5725,7 @@ \begin{verbatim} >>> from Bio import SearchIO >>> blast_qresult = SearchIO.read('my_blast.xml', 'blast-xml') ->>> print blast_qresult +>>> print(blast_qresult) Program: blastn (2.2.27+) Query: 42291 (61) mystery_seq @@ -5792,7 +5790,7 @@ %cont-doctest \begin{verbatim} >>> blat_qresult = SearchIO.read('my_blat.psl', 'blat-psl') ->>> print blat_qresult +>>> print(blat_qresult) Program: blat () Query: mystery_seq (61) @@ -5833,9 +5831,9 @@ %cont-doctest \begin{verbatim} ->>> print "%s %s" % (blast_qresult.program, blast_qresult.version) +>>> print("%s %s" % (blast_qresult.program, blast_qresult.version)) blastn 2.2.27+ ->>> print "%s %s" % (blat_qresult.program, blat_qresult.version) +>>> print("%s %s" % (blat_qresult.program, blat_qresult.version)) blat >>> blast_qresult.param_evalue_threshold # blast-xml specific 10.0 @@ -5896,7 +5894,7 @@ %cont-doctest \begin{verbatim} >>> blast_slice = blast_qresult[:3] # slices the first three hits ->>> print blast_slice +>>> print(blast_slice) Program: blastn (2.2.27+) Query: 42291 (61) mystery_seq @@ -5970,8 +5968,8 @@ %cont-doctest \begin{verbatim} >>> for hit in blast_qresult[:5]: # id and sequence length of the first five hits -... print hit.id, hit.seq_len -... +... print("%s %i" % (hit.id, hit.seq_len)) +... gi|262205317|ref|NR_030195.1| 61 gi|301171311|ref|NR_035856.1| 60 gi|270133242|ref|NR_032573.1| 85 @@ -5981,8 +5979,8 @@ >>> sort_key = lambda hit: hit.seq_len >>> sorted_qresult = blast_qresult.sort(key=sort_key, reverse=True, in_place=False) >>> for hit in sorted_qresult[:5]: -... print hit.id, hit.seq_len -... +... print("%s %i" % (hit.id, hit.seq_len)) +... gi|397513516|ref|XM_003827011.1| 6002 gi|390332045|ref|XM_776818.2| 4082 gi|390332043|ref|XM_003723358.1| 4079 @@ -6034,7 +6032,7 @@ >>> len(filtered_qresult) # no. of hits after filtering 37 >>> for hit in filtered_qresult[:5]: # quick check for the hit lengths -... print hit.id, len(hit.hsps) +... print("%s %i" % (hit.id, len(hit.hsps))) gi|301171322|ref|NR_035857.1| 2 gi|262205330|ref|NR_030198.1| 2 gi|301171447|ref|NR_035871.1| 2 @@ -6061,7 +6059,7 @@ ... >>> mapped_qresult = blast_qresult.hit_map(map_func) >>> for hit in mapped_qresult[:5]: -... print hit.id +... print(hit.id) NR_030195.1 NR_035856.1 NR_032573.1 @@ -6087,10 +6085,7 @@ >>> from Bio import SearchIO >>> blast_qresult = SearchIO.read('my_blast.xml', 'blast-xml') >>> blast_hit = blast_qresult[3] # fourth hit from the query result -\end{verbatim} -%HACK: because Py2.5 in windows output floating points slightly different -\begin{verbatim} ->>> print blast_hit +>>> print(blast_hit) Query: 42291 mystery_seq Hit: gi|301171322|ref|NR_035857.1| (86) @@ -6125,7 +6120,7 @@ \begin{verbatim} >>> blat_qresult = SearchIO.read('my_blat.psl', 'blat-psl') >>> blat_hit = blat_qresult[0] # the only hit ->>> print blat_hit +>>> print(blat_hit) Query: mystery_seq Hit: chr19 (59128983) @@ -6203,7 +6198,7 @@ >>> sliced_hit = blat_hit[4:9] # retrieve multiple items >>> len(sliced_hit) 5 ->>> print sliced_hit +>>> print(sliced_hit) Query: mystery_seq Hit: chr19 (59128983) @@ -6247,10 +6242,7 @@ >>> from Bio import SearchIO >>> blast_qresult = SearchIO.read('my_blast.xml', 'blast-xml') >>> blast_hsp = blast_qresult[0][0] # first hit, first hsp -\end{verbatim} -%HACK: because Py2.5 in windows output floating points slightly different -\begin{verbatim} ->>> print blast_hsp +>>> print(blast_hsp) Query: 42291 mystery_seq Hit: gi|262205317|ref|NR_030195.1| Homo sapiens microRNA 520b (MIR520... Query range: [0:61] (1) @@ -6354,7 +6346,7 @@ %cont-doctest \begin{verbatim} ->>> print blast_hsp.aln +>>> print(blast_hsp.aln) DNAAlphabet() alignment with 2 rows and 61 columns CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAG...GGG 42291 CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAG...GGG gi|262205317|ref|NR_030195.1| @@ -6368,7 +6360,7 @@ \begin{verbatim} >>> blat_qresult = SearchIO.read('my_blat.psl', 'blat-psl') >>> blat_hsp = blat_qresult[0][0] # first hit, first hsp ->>> print blat_hsp +>>> print(blat_hsp) Query: mystery_seq Hit: chr19 Query range: [0:61] (1) @@ -6431,7 +6423,7 @@ %cont-doctest \begin{verbatim} >>> blat_hsp2 = blat_qresult[0][1] # first hit, second hsp ->>> print blat_hsp2 +>>> print(blat_hsp2) Query: mystery_seq Hit: chr19 Query range: [0:61] (1) @@ -6536,7 +6528,7 @@ >>> from Bio import SearchIO >>> blast_qresult = SearchIO.read('my_blast.xml', 'blast-xml') >>> blast_frag = blast_qresult[0][0][0] # first hit, first hsp, first fragment ->>> print blast_frag +>>> print(blast_frag) Query: 42291 mystery_seq Hit: gi|262205317|ref|NR_030195.1| Homo sapiens microRNA 520b (MIR520... Query range: [0:61] (1) @@ -6554,7 +6546,7 @@ \begin{verbatim} >>> blat_qresult = SearchIO.read('my_blat.psl', 'blat-psl') >>> blat_frag = blat_qresult[0][0][0] # first hit, first hsp, first fragment ->>> print blat_frag +>>> print(blat_frag) Query: mystery_seq Hit: chr19 Query range: [0:61] (1) @@ -6671,12 +6663,12 @@ >>> from Bio import SearchIO >>> qresults = SearchIO.parse('tab_2226_tblastn_001.txt', 'blast-tab') >>> for qresult in qresults: -... print qresult.id +... print(qresult.id) gi|16080617|ref|NP_391444.1| gi|11464971:4-101 >>> qresults2 = SearchIO.parse('tab_2226_tblastn_005.txt', 'blast-tab', comments=True) >>> for qresult in qresults2: -... print qresult.id +... print(qresult.id) random_s00 gi|16080617|ref|NP_391444.1| gi|11464971:4-101 @@ -6847,7 +6839,7 @@ \end{verbatim} The variable \verb+result+ now contains a list of databases in XML format: \begin{verbatim} ->>> print result +>>> print(result) @@ -6932,7 +6924,7 @@ \begin{verbatim} >>> for field in record["DbInfo"]["FieldList"]: -... print "%(Name)s, %(FullName)s, %(Description)s" % field +... print("%(Name)s, %(FullName)s, %(Description)s" % field) ALL, All Fields, All terms from all searchable fields UID, UID, Unique number assigned to publication FILT, Filter, Limits the records @@ -6971,7 +6963,7 @@ find out which fields you can search in each Entrez database): \begin{verbatim} ->>> handle = Entrez.esearch(db="nucleotide",term="Cypripedioideae[Orgn] AND matK[Gene]") +>>> handle = Entrez.esearch(db="nucleotide", term="Cypripedioideae[Orgn] AND matK[Gene]") >>> record = Entrez.read(handle) >>> record["Count"] '25' @@ -7021,7 +7013,7 @@ >>> from Bio import Entrez >>> Entrez.email = "A.N.Other@example.com" # Always tell NCBI who you are >>> id_list = ["19304878", "18606172", "16403221", "16377612", "14871861", "14630660"] ->>> print Entrez.epost("pubmed", id=",".join(id_list)).read() +>>> print(Entrez.epost("pubmed", id=",".join(id_list)).read()) @@ -7071,7 +7063,7 @@ >>> from Bio import Entrez >>> Entrez.email = "A.N.Other@example.com" # Always tell NCBI who you are >>> handle = Entrez.efetch(db="nucleotide", id="186972394", rettype="gb", retmode="text") ->>> print handle.read() +>>> print(handle.read()) LOCUS EU490707 1302 bp DNA linear PLN 05-MAY-2008 DEFINITION Selenipedium aequinoctiale maturase K (matK) gene, partial cds; chloroplast. @@ -7158,10 +7150,10 @@ \begin{verbatim} >>> from Bio import Entrez, SeqIO ->>> handle = Entrez.efetch(db="nucleotide", id="186972394",rettype="gb", retmode="text") +>>> handle = Entrez.efetch(db="nucleotide", id="186972394", rettype="gb", retmode="text") >>> record = SeqIO.read(handle, "genbank") >>> handle.close() ->>> print record +>>> print(record) ID: EU490707.1 Name: EU490707 Description: Selenipedium aequinoctiale maturase K (matK) gene, partial cds; chloroplast. @@ -7185,11 +7177,11 @@ out_handle.write(net_handle.read()) out_handle.close() net_handle.close() - print "Saved" + print("Saved") -print "Parsing..." +print("Parsing...") record = SeqIO.read(filename, "genbank") -print record +print(record) \end{verbatim} To get the output in XML format, which you can parse using the \verb+Bio.Entrez.read()+ function, use \verb+retmode="xml"+: @@ -7239,7 +7231,7 @@ >>> len(record[0]["LinkSetDb"]) 5 >>> for linksetdb in record[0]["LinkSetDb"]: -... print linksetdb["DbTo"], linksetdb["LinkName"], len(linksetdb["Link"]) +... print(linksetdb["DbTo"], linksetdb["LinkName"], len(linksetdb["Link"])) ... pubmed pubmed_pubmed 110 pubmed pubmed_pubmed_combined 6 @@ -7267,7 +7259,8 @@ We can use a loop to print out all PubMed IDs: \begin{verbatim} ->>> for link in record[0]["LinkSetDb"][0]["Link"] : print link["Id"] +>>> for link in record[0]["LinkSetDb"][0]["Link"]: +... print(link["Id"]) 19304878 14630660 18689808 @@ -7293,8 +7286,9 @@ >>> Entrez.email = "A.N.Other@example.com" # Always tell NCBI who you are >>> handle = Entrez.egquery(term="biopython") >>> record = Entrez.read(handle) ->>> for row in record["eGQueryResult"]: print row["DbName"], row["Count"] -... +>>> for row in record["eGQueryResult"]: +... print(row["DbName"], row["Count"]) +... pubmed 6 pmc 62 journals 0 @@ -7343,7 +7337,7 @@ ... continue ... geneid = record['Entrezgene_track-info']['Gene-track']['Gene-track_geneid'] ... genename = record['Entrezgene_gene']['Gene-ref']['Gene-ref_locus'] -... print geneid, genename +... print(geneid, genename) \end{verbatim} This will print: @@ -7473,7 +7467,7 @@ \begin{verbatim} >>> from Bio import Entrez >>> handle = open("einfo3.xml") ->>> record = Entrez.read(handle,validate=False) +>>> record = Entrez.read(handle, validate=False) >>> \end{verbatim} Of course, the information contained in the XML tags that are not in the DTD are not present in the record returned by \verb|Entrez.read|. @@ -7547,7 +7541,7 @@ >>> input = open("pubmed_result2.txt") >>> records = Medline.parse(input) >>> for record in records: -... print record["TI"] +... print(record["TI"]) A high level interface to SCOP and ASTRAL implemented in python. GenomeDiagram: a python package for the visualization of large-scale genomic data. Open source clustering software. @@ -7558,7 +7552,7 @@ \begin{verbatim} >>> from Bio import Entrez >>> Entrez.email = "A.N.Other@example.com" # Always tell NCBI who you are ->>> handle = Entrez.esearch(db="pubmed",term="biopython") +>>> handle = Entrez.esearch(db="pubmed", term="biopython") >>> record = Entrez.read(handle) >>> record["IdList"] ['19304878', '18606172', '16403221', '16377612', '14871861', '14630660', '12230038'] @@ -7566,14 +7560,14 @@ We now use \verb+Bio.Entrez.efetch+ to download these Medline records: \begin{verbatim} >>> idlist = record["IdList"] ->>> handle = Entrez.efetch(db="pubmed",id=idlist,rettype="medline",retmode="text") +>>> handle = Entrez.efetch(db="pubmed", id=idlist, rettype="medline", retmode="text") \end{verbatim} Here, we specify \verb+rettype="medline", retmode="text"+ to obtain the Medline records in plain-text Medline format. Now we use \verb+Bio.Medline+ to parse these records: \begin{verbatim} >>> from Bio import Medline >>> records = Medline.parse(handle) >>> for record in records: -... print record["AU"] +... print(record["AU"]) ['Cock PJ', 'Antao T', 'Chang JT', 'Chapman BA', 'Cox CJ', 'Dalke A', ..., 'de Hoon MJ'] ['Munteanu CR', 'Gonzalez-Diaz H', 'Magalhaes AL'] ['Casbon JA', 'Crooks GE', 'Saqi MA'] @@ -7586,10 +7580,10 @@ For comparison, here we show an example using the XML format: \begin{verbatim} >>> idlist = record["IdList"] ->>> handle = Entrez.efetch(db="pubmed",id=idlist,rettype="medline",retmode="xml") +>>> handle = Entrez.efetch(db="pubmed", id=idlist, rettype="medline", retmode="xml") >>> records = Entrez.read(handle) >>> for record in records: -... print record["MedlineCitation"]["Article"]["ArticleTitle"] +... print(record["MedlineCitation"]["Article"]["ArticleTitle"]) Biopython: freely available Python tools for computational molecular biology and bioinformatics. Enzymes/non-enzymes classification model complexity based on composition, sequence, @@ -7621,7 +7615,7 @@ >>> handle = open("GSE16.txt") >>> records = Geo.parse(handle) >>> for record in records: -... print record +... print(record) \end{verbatim} You can search the ``gds'' database (GEO datasets) with ESearch: @@ -7629,7 +7623,7 @@ \begin{verbatim} >>> from Bio import Entrez >>> Entrez.email = "A.N.Other@example.com" # Always tell NCBI who you are ->>> handle = Entrez.esearch(db="gds",term="GSE16") +>>> handle = Entrez.esearch(db="gds", term="GSE16") >>> record = Entrez.read(handle) >>> record["Count"] 2 @@ -7725,7 +7719,7 @@ >>> input = open("unigenerecords.data") >>> records = UniGene.parse(input) >>> for record in records: -... print record.ID +... print(record.ID) \end{verbatim} \section{Using a proxy} @@ -7766,7 +7760,7 @@ >>> record = Entrez.read(handle) >>> for row in record["eGQueryResult"]: ... if row["DbName"]=="pubmed": -... print row["Count"] +... print(row["Count"]) 463 \end{verbatim} @@ -7775,7 +7769,7 @@ >>> handle = Entrez.esearch(db="pubmed", term="orchid", retmax=463) >>> record = Entrez.read(handle) >>> idlist = record["IdList"] ->>> print idlist +>>> print(idlist) \end{verbatim} @@ -7802,12 +7796,13 @@ \end{verbatim} Let's now iterate over the records to print out some information about each record: +%TODO - Replace the print blank line with print()? \begin{verbatim} >>> for record in records: -... print "title:", record.get("TI", "?") -... print "authors:", record.get("AU", "?") -... print "source:", record.get("SO", "?") -... print +... print("title:", record.get("TI", "?")) +... print("authors:", record.get("AU", "?")) +... print("source:", record.get("SO", "?")) +... print("") \end{verbatim} The output for this looks like: @@ -7828,7 +7823,7 @@ ... if not "AU" in record: ... continue ... if search_author in record["AU"]: -... print "Author %s found: %s" % (search_author, record["SO"]) +... print("Author %s found: %s" % (search_author, record["SO"])) \end{verbatim} Hopefully this section gave you an idea of the power and flexibility of the Entrez and Medline interfaces and how they can be used together. @@ -7846,7 +7841,7 @@ >>> record = Entrez.read(handle) >>> for row in record["eGQueryResult"]: ... if row["DbName"]=="nuccore": -... print row["Count"] +... print(row["Count"]) 814 \end{verbatim} @@ -7859,22 +7854,22 @@ Here, \verb+record+ is a Python dictionary containing the search results and some auxiliary information. Just for information, let's look at what is stored in this dictionary: \begin{verbatim} ->>> print record.keys() +>>> print(record.keys()) [u'Count', u'RetMax', u'IdList', u'TranslationSet', u'RetStart', u'QueryTranslation'] \end{verbatim} First, let's check how many results were found: \begin{verbatim} ->>> print record["Count"] +>>> print(record["Count"]) '814' \end{verbatim} which is the number we expected. The 814 results are stored in \verb+record['IdList']+: \begin{verbatim} ->>> print len(record["IdList"]) +>>> len(record["IdList"]) 814 \end{verbatim} Let's look at the first five results: \begin{verbatim} ->>> print record["IdList"][:5] +>>> record["IdList"][:5] ['187237168', '187372713', '187372690', '187372688', '187372686'] \end{verbatim} @@ -7885,16 +7880,16 @@ \begin{verbatim} >>> idlist = ",".join(record["IdList"][:5]) ->>> print idlist +>>> print(idlist) 187237168,187372713,187372690,187372688,187372686 >>> handle = Entrez.efetch(db="nucleotide", id=idlist, retmode="xml") >>> records = Entrez.read(handle) ->>> print len(records) +>>> len(records) 5 \end{verbatim} Each of these records corresponds to one GenBank record. \begin{verbatim} ->>> print records[0].keys() +>>> print(records[0].keys()) [u'GBSeq_moltype', u'GBSeq_source', u'GBSeq_sequence', u'GBSeq_primary-accession', u'GBSeq_definition', u'GBSeq_accession-version', u'GBSeq_topology', u'GBSeq_length', u'GBSeq_feature-table', @@ -7902,17 +7897,17 @@ u'GBSeq_taxonomy', u'GBSeq_references', u'GBSeq_update-date', u'GBSeq_organism', u'GBSeq_locus', u'GBSeq_strandedness'] ->>> print records[0]["GBSeq_primary-accession"] +>>> print(records[0]["GBSeq_primary-accession"]) DQ110336 ->>> print records[0]["GBSeq_other-seqids"] +>>> print(records[0]["GBSeq_other-seqids"]) ['gb|DQ110336.1|', 'gi|187237168'] ->>> print records[0]["GBSeq_definition"] +>>> print(records[0]["GBSeq_definition"]) Cypripedium calceolus voucher Davis 03-03 A maturase (matR) gene, partial cds; mitochondrial ->>> print records[0]["GBSeq_organism"] +>>> print(records[0]["GBSeq_organism"]) Cypripedium calceolus \end{verbatim} @@ -7935,7 +7930,7 @@ >>> record = Entrez.read(handle) >>> for row in record["eGQueryResult"]: ... if row["DbName"]=="nuccore": -... print row["Count"] +... print(row["Count"]) ... 9 \end{verbatim} @@ -7960,7 +7955,7 @@ \begin{verbatim} >>> text = handle.read() ->>> print text +>>> print(text) LOCUS AY851612 892 bp DNA linear PLN 10-APR-2007 DEFINITION Opuntia subulata rpl16 gene, intron; chloroplast. ACCESSION AY851612 @@ -7987,8 +7982,8 @@ \noindent We can now step through the records and look at the information we are interested in: \begin{verbatim} >>> for record in records: ->>> ... print "%s, length %i, with %i features" \ ->>> ... % (record.name, len(record), len(record.features)) +>>> ... print("%s, length %i, with %i features" \ +>>> ... % (record.name, len(record), len(record.features))) AY851612, length 892, with 3 features AY851611, length 881, with 3 features AF191661, length 895, with 3 features @@ -8101,7 +8096,7 @@ out_handle = open("orchid_rpl16.fasta", "w") for start in range(0,count,batch_size): end = min(count, start+batch_size) - print "Going to download record %i to %i" % (start+1, end) + print("Going to download record %i to %i" % (start+1, end)) fetch_handle = Entrez.efetch(db="nucleotide", rettype="fasta", retmode="text", retstart=start, retmax=batch_size, webenv=webenv, query_key=query_key) @@ -8124,13 +8119,13 @@ reldate=365, datetype="pdat", usehistory="y")) count = int(search_results["Count"]) -print "Found %i results" % count +print("Found %i results" % count) batch_size = 10 out_handle = open("recent_orchid_papers.txt", "w") for start in range(0,count,batch_size): end = min(count, start+batch_size) - print "Going to download record %i to %i" % (start+1, end) + print("Going to download record %i to %i" % (start+1, end)) fetch_handle = Entrez.efetch(db="pubmed", rettype="medline", retmode="text", retstart=start, retmax=batch_size, @@ -8236,17 +8231,18 @@ This function should be used if the handle points to exactly one Swiss-Prot record. It raises a \verb|ValueError| if no Swiss-Prot record was found, and also if more than one record was found. We can now print out some information about this record: +%TODO - Check the single quotes when printing record.description here: \begin{verbatim} ->>> print record.description +>>> print(record.description) 'RecName: Full=Chalcone synthase 3; EC=2.3.1.74; AltName: Full=Naringenin-chalcone synthase 3;' >>> for ref in record.references: -... print "authors:", ref.authors -... print "title:", ref.title -... +... print("authors:", ref.authors) +... print("title:", ref.title) +... authors: Liew C.F., Lim S.H., Loh C.S., Goh C.J.; title: "Molecular cloning and sequence analysis of chalcone synthase cDNAs of Bromheadia finlaysoniana."; ->>> print record.organism_classification +>>> print(record.organism_classification) ['Eukaryota', 'Viridiplantae', 'Streptophyta', 'Embryophyta', ..., 'Bromheadia'] \end{verbatim} @@ -8346,8 +8342,8 @@ >>> handle = open("keywlist.txt") >>> records = KeyWList.parse(handle) >>> for record in records: -... print record['ID'] -... print record['DE'] +... print(record['ID']) +... print(record['DE']) \end{verbatim} This prints @@ -8376,21 +8372,21 @@ >>> from Bio.ExPASy import Prosite >>> handle = open("prosite.dat") >>> records = Prosite.parse(handle) ->>> record = records.next() +>>> record = next(records) >>> record.accession 'PS00001' >>> record.name 'ASN_GLYCOSYLATION' >>> record.pdoc 'PDOC00001' ->>> record = records.next() +>>> record = next(records) >>> record.accession 'PS00004' >>> record.name 'CAMP_PHOSPHO_SITE' >>> record.pdoc 'PDOC00004' ->>> record = records.next() +>>> record = next(records) >>> record.accession 'PS00005' >>> record.name @@ -8406,7 +8402,7 @@ >>> n = 0 >>> for record in records: n+=1 ... ->>> print n +>>> n 2073 \end{verbatim} @@ -8544,7 +8540,7 @@ ... try: ... record = SwissProt.read(handle) ... except ValueException: -... print "WARNING: Accession %s not found" % accession +... print("WARNING: Accession %s not found" % accession) ... records.append(record) \end{verbatim} @@ -8589,7 +8585,7 @@ >>> from Bio import ExPASy >>> handle = ExPASy.get_prosite_raw('PS00001') >>> text = handle.read() ->>> print text +>>> print(text) \end{verbatim} To retrieve a Prosite record and parse it into a \verb|Bio.Prosite.Record| object, use @@ -8748,7 +8744,7 @@ object, ie. directly from the PDB file: \begin{verbatim} ->>> file = open(filename,'r') +>>> file = open(filename, 'r') >>> header_dict = parse_pdb_header(file) >>> file.close() \end{verbatim} @@ -8827,7 +8823,7 @@ ... return True ... else: ... return False -... +... >>> io = PDBIO() >>> io.set_structure(s) >>> io.save('gly_only.pdb', GlySelect()) @@ -8919,7 +8915,7 @@ \begin{verbatim} >>> full_id = residue.get_full_id() ->>> print full_id +>>> print(full_id) ("1abc", 0, "A", ("", 10, "A")) \end{verbatim} @@ -9201,10 +9197,10 @@ \begin{verbatim} >>> atom.disordered_select('A') # select altloc A atom ->>> print atom.get_altloc() +>>> print(atom.get_altloc()) "A" >>> atom.disordered_select('B') # select altloc B atom ->>> print atom.get_altloc() +>>> print(atom.get_altloc()) "B" \end{verbatim} @@ -9302,7 +9298,7 @@ ... for chain in model: ... for residue in chain: ... for atom in residue: -... print atom +... print(atom) ... \end{verbatim} @@ -9310,7 +9306,7 @@ \begin{verbatim} >>> atoms = structure.get_atoms() >>> for atom in atoms: -... print atom +... print(atom) ... \end{verbatim} @@ -9318,7 +9314,7 @@ \begin{verbatim} >>> atoms = chain.get_atoms() >>> for atom in atoms: -... print atom +... print(atom) ... \end{verbatim} @@ -9328,7 +9324,7 @@ \begin{verbatim} >>> residues = model.get_residues() >>> for residue in residues: -... print residue +... print(residue) ... \end{verbatim} @@ -9365,7 +9361,7 @@ ... residue_id = residue.get_id() ... hetfield = residue_id[0] ... if hetfield[0]=="H": -... print residue_id +... print(residue_id) ... \end{verbatim} @@ -9378,7 +9374,7 @@ ... if residue.has_id("CA"): ... ca = residue["CA"] ... if ca.get_bfactor() > 50.0: -... print ca.get_coord() +... print(ca.get_coord()) ... \end{verbatim} @@ -9393,8 +9389,8 @@ ... resname = residue.get_resname() ... model_id = model.get_id() ... chain_id = chain.get_id() -... print model_id, chain_id, resname, resseq -... +... print(model_id, chain_id, resname, resseq) +... \end{verbatim} \subsubsection*{Loop over all disordered atoms, and select all atoms with altloc A (if present)} @@ -9421,7 +9417,7 @@ >>> model_nr = 1 >>> polypeptide_list = build_peptides(structure, model_nr) >>> for polypeptide in polypeptide_list: -... print polypeptide +... print(polypeptide) ... \end{verbatim} @@ -9434,12 +9430,12 @@ # Using C-N >>> ppb=PPBuilder() >>> for pp in ppb.build_peptides(structure): -... print pp.get_sequence() +... print(pp.get_sequence()) ... # Using CA-CA >>> ppb=CaPPBuilder() >>> for pp in ppb.build_peptides(structure): -... print pp.get_sequence() +... print(pp.get_sequence()) ... \end{verbatim} Note that in the above case only model 0 of the structure is considered @@ -9459,7 +9455,7 @@ \begin{verbatim} >>> seq = polypeptide.get_sequence() ->>> print seq +>>> print(seq) Seq('SNVVE...', ) \end{verbatim} @@ -9525,8 +9521,8 @@ # The moving atoms will be put on the fixed atoms >>> sup.set_atoms(fixed, moving) # Print rotation/translation/rmsd ->>> print sup.rotran ->>> print sup.rms +>>> print(sup.rotran) +>>> print(sup.rms) # Apply rotation/translation to the moving atoms >>> sup.apply(moving) \end{verbatim} @@ -9568,7 +9564,7 @@ # Calculate classical coordination number >>> exp_fs = hse.calc_fs_exposure(model) # Print HSEalpha for a residue ->>> print exp_ca[some_residue] +>>> print(exp_ca[some_residue]) \end{verbatim} \subsection{Determining the secondary structure} @@ -10518,7 +10514,7 @@ Printing the tree object as a string gives us a look at the entire object hierarchy. \begin{verbatim} ->>> print tree +>>> print(tree) Tree(weight=1.0, rooted=False, name="") Clade(branch_length=1.0) @@ -10655,7 +10651,7 @@ \verb|[0,1]| refers to the second child of the first child of the root. \begin{verbatim} ->>> tree.clade[0,1].color = "blue" +>>> tree.clade[0, 1].color = "blue" \end{verbatim} Finally, show our work (see Fig. \ref{fig:phylo-color-draw}): @@ -10728,7 +10724,7 @@ \begin{verbatim} >>> from Bio import Phylo >>> tree = Phylo.read("Tests/Nexus/int_node_labels.nwk", "newick") ->>> print tree +>>> print(tree) \end{verbatim} (Example files are available in the \texttt{Tests/Nexus/} and \texttt{Tests/PhyloXML/} @@ -10740,7 +10736,7 @@ \begin{verbatim} >>> trees = Phylo.parse("Tests/PhyloXML/phyloxml_examples.xml", "phyloxml") >>> for tree in trees: -... print tree +... print(tree) \end{verbatim} Write a tree or iterable of trees back to file with the \verb|write| function: @@ -10780,9 +10776,10 @@ The simplest way to get an overview of a \verb|Tree| object is to \verb|print| it: +%TODO - make this into a doctest? \begin{verbatim} >>> tree = Phylo.read("Tests/PhyloXML/example.xml", "phyloxml") ->>> print tree +>>> print(tree) Phylogeny(rooted='True', description='phyloXML allows to use either a "branch_length" attribute...', name='example from Prof. Joe Felsenstein's book "Inferring Phyl...') Clade() @@ -11241,7 +11238,7 @@ % The object hierarchy still looks and behaves similarly: % \begin{verbatim} -% >>> print tree +% >>> print(tree) % Phylogeny(rooted=True, name="") % Clade(branch_length=1.0) @@ -11336,13 +11333,13 @@ >>> ns_sites = results.get("NSsites") >>> m0 = ns_sites.get(0) >>> m0_params = m0.get("parameters") ->>> print m0_params.get("omega") +>>> print(m0_params.get("omega")) \end{verbatim} Existing output files may be parsed as well using a module's \texttt{read()} function: \begin{verbatim} >>> results = codeml.read("Tests/PAML/Results/codeml/codeml_NSsites_all.out") ->>> print results.get("lnL max") +>>> print(results.get("lnL max")) \end{verbatim} Detailed documentation for this new module currently lives on the Biopython wiki: @@ -11445,7 +11442,7 @@ Printing out the Motif object shows the instances from which it was constructed: %cont-doctest \begin{verbatim} ->>> print m +>>> print(m) TACAA TACGC TACAC @@ -11465,7 +11462,7 @@ nucleotide at each position. Printing this counts matrix shows it in an easily readable format: %cont-doctest \begin{verbatim} ->>> print m.counts +>>> print(m.counts) 0 1 2 3 4 A: 3.00 7.00 0.00 2.00 1.00 C: 0.00 0.00 5.00 2.00 6.00 @@ -11484,17 +11481,17 @@ dimension and the position as the second dimension: %cont-doctest \begin{verbatim} ->>> m.counts['T',0] +>>> m.counts['T', 0] 4 ->>> m.counts['T',2] +>>> m.counts['T', 2] 2 ->>> m.counts['T',3] +>>> m.counts['T', 3] 0 \end{verbatim} You can also directly access columns of the counts matrix %Don't doctest this as dictionary order is platform dependent: \begin{verbatim} ->>> m.counts[:,3] +>>> m.counts[:, 3] {'A': 2, 'C': 2, 'T': 0, 'G': 3} \end{verbatim} Instead of the nucleotide itself, you can also use the index of the nucleotide @@ -11547,7 +11544,7 @@ Seq('GCGTA', IUPACUnambiguousDNA()) >>> r.degenerate_consensus Seq('GBGTW', IUPACAmbiguousDNA()) ->>> print r +>>> print(r) TTGTA GCGTA GTGTA @@ -11627,10 +11624,10 @@ The instances from which this motif was created is stored in the \verb+.instances+ property: %cont-doctest \begin{verbatim} ->>> print arnt.instances[:3] +>>> print(arnt.instances[:3]) [Seq('CACGTG', IUPACUnambiguousDNA()), Seq('CACGTG', IUPACUnambiguousDNA()), Seq('CACGTG', IUPACUnambiguousDNA())] >>> for instance in arnt.instances: -... print instance +... print(instance) ... CACGTG CACGTG @@ -11656,7 +11653,7 @@ The counts matrix of this motif is automatically calculated from the instances: %cont-doctest \begin{verbatim} ->>> print arnt.counts +>>> print(arnt.counts) 0 1 2 3 4 5 A: 4.00 19.00 0.00 0.00 0.00 0.00 C: 16.00 0.00 20.00 0.00 0.00 0.00 @@ -11681,8 +11678,8 @@ We can create a motif for this count matrix as follows: %cont-doctest \begin{verbatim} ->>> srf = motifs.read(open("SRF.pfm"),"pfm") ->>> print srf.counts +>>> srf = motifs.read(open("SRF.pfm"), "pfm") +>>> print(srf.counts) 0 1 2 3 4 5 6 7 8 9 10 11 A: 2.00 9.00 0.00 1.00 32.00 3.00 46.00 1.00 43.00 15.00 2.00 2.00 C: 1.00 33.00 45.00 45.00 1.00 1.00 0.00 0.00 0.00 1.00 0.00 1.00 @@ -11693,15 +11690,15 @@ As this motif was created from the counts matrix directly, it has no instances associated with it: %cont-doctest \begin{verbatim} ->>> print srf.instances +>>> print(srf.instances) None \end{verbatim} We can now ask for the consensus sequence of these two motifs: %cont-doctest \begin{verbatim} ->>> print arnt.counts.consensus +>>> print(arnt.counts.consensus) CACGTG ->>> print srf.counts.consensus +>>> print(srf.counts.consensus) GCCCATATATGG \end{verbatim} @@ -11731,7 +11728,7 @@ \begin{verbatim} >>> fh = open("jaspar_motifs.txt") >>> for m in motifs.parse(fh, "jaspar")) -... print m +... print(m) TF name Arnt Matrix ID MA0004.1 Matrix: @@ -11791,7 +11788,7 @@ \end{verbatim} Printing the motif reveals that the JASPAR SQL database stores much more meeta-information than the flat files: \begin{verbatim} ->>> print arnt +>>> print(arnt) TF name Arnt Matrix ID MA0004.1 Collection CORE @@ -11817,7 +11814,7 @@ We can also fetch motifs by name. The name must be an exact match (partial matches or database wildcards are not currently supported). Note that as the name is not guaranteed to be unique, the \verb+fetch_motifs_by_name+ method actually returns a list. \begin{verbatim} >>> motifs = jdb.fetch_motifs_by_name("Arnt") ->>> print motifs[0] +>>> print(motifs[0]) TF name Arnt Matrix ID MA0004.1 Collection CORE @@ -11878,6 +11875,7 @@ >>> rel_score = (abs_score - pssm.min) / (pssm.max - pssm.min) \end{verbatim} For example, using the Arnt motif before, let's search a sequence with a relative score threshold of 0.8. +%TODO - Check missing ... lines, make into a doctest? \begin{verbatim} >>> test_seq=Seq("TAAGCGTGCACGCGCAACACGTGCATTA", unambiguous_dna) >>> arnt.pseudocounts = motifs.jaspar.calculate_pseudocounts(arnt) @@ -11888,8 +11886,8 @@ >>> for position, score in pssm.search(test_seq, threshold=abs_score_threshold): ... rel_score = (score - min_score) / (max_score - min_score) -... print "Position %d: score = %5.3f, rel. score = %5.3f" % ( - position, score, rel_score) +... print("Position %d: score = %5.3f, rel. score = %5.3f" % ( + position, score, rel_score)) ... Position 2: score = 5.362, rel. score = 0.801 Position 8: score = 6.112, rel. score = 0.831 @@ -11984,9 +11982,9 @@ >>> len(record) 2 >>> motif = record[0] ->>> print motif.consensus +>>> print(motif.consensus) TTCACATGCCGC ->>> print motif.degenerate_consensus +>>> print(motif.degenerate_consensus) TTCACATGSCNC \end{verbatim} In addition to these generic motif attributes, each motif also stores its @@ -11998,7 +11996,7 @@ >>> motif.length 12 >>> evalue = motif.evalue ->>> print "%3.1g" % evalue +>>> print("%3.1g" % evalue) 0.2 >>> motif.name 'Motif 1' @@ -12028,10 +12026,7 @@ >>> motif.instances[0].length 12 >>> pvalue = motif.instances[0].pvalue -\end{verbatim} -%Sadly Python 2.5 on Windows gives 1.85e-008 breaking doctest: -\begin{verbatim} ->>> print "%5.3g" % pvalue +>>> print("%5.3g" % pvalue) 1.85e-08 \end{verbatim} @@ -12165,7 +12160,7 @@ Printing the motifs writes them out in their native TRANSFAC format: %cont-doctest \begin{verbatim} ->>> print record +>>> print(record) VV EXAMPLE January 15, 2013 XX // @@ -12218,7 +12213,7 @@ We can use the \verb+format+ method to write the motif in the simple JASPAR \verb+pfm+ format: %the tabs in the output confuse doctest; don't test \begin{verbatim} ->>> print arnt.format("pfm") +>>> print(arnt.format("pfm")) 4.00 19.00 0.00 0.00 0.00 0.00 16.00 0.00 20.00 0.00 0.00 0.00 0.00 1.00 0.00 20.00 0.00 20.00 @@ -12226,7 +12221,7 @@ \end{verbatim} Similarly, we can use \verb+format+ to write the motif in the JASPAR \verb+jaspar+ format: \begin{verbatim} ->>> print arnt.format("jaspar") +>>> print(arnt.format("jaspar")) >MA0004.1 Arnt A [ 4.00 19.00 0.00 0.00 0.00 0.00] C [ 16.00 0.00 20.00 0.00 0.00 0.00] @@ -12237,7 +12232,7 @@ To write the motif in a TRANSFAC-like matrix format, use %cont-doctest \begin{verbatim} ->>> print m.format("transfac") +>>> print(m.format("transfac")) P0 A C G T 01 3 0 0 4 W 02 7 0 0 0 A @@ -12254,7 +12249,7 @@ %cont-doctest \begin{verbatim} >>> two_motifs = [arnt, srf] ->>> print motifs.write(two_motifs, 'transfac') +>>> print(motifs.write(two_motifs, 'transfac')) P0 A C G T 01 4 16 0 0 C 02 19 0 1 0 A @@ -12285,7 +12280,7 @@ Or, to write multiple motifs in the \verb+jaspar+ format: \begin{verbatim} >>> two_motifs = [arnt, mef2a] ->>> print motifs.write(two_motifs, "jaspar") +>>> print(motifs.write(two_motifs, "jaspar")) >MA0004.1 Arnt A [ 4.00 19.00 0.00 0.00 0.00 0.00] C [ 16.00 0.00 20.00 0.00 0.00 0.00] @@ -12318,7 +12313,7 @@ %cont-doctest \begin{verbatim} >>> pwm = m.counts.normalize(pseudocounts=0.5) ->>> print pwm +>>> print(pwm) 0 1 2 3 4 A: 0.39 0.83 0.06 0.28 0.17 C: 0.06 0.06 0.61 0.28 0.72 @@ -12333,7 +12328,7 @@ %cont-doctest \begin{verbatim} >>> pwm = m.counts.normalize(pseudocounts={'A':0.6, 'C': 0.4, 'G': 0.4, 'T': 0.6}) ->>> print pwm +>>> print(pwm) 0 1 2 3 4 A: 0.40 0.84 0.07 0.29 0.18 C: 0.04 0.04 0.60 0.27 0.71 @@ -12365,7 +12360,7 @@ %cont-doctest \begin{verbatim} >>> rpwm = pwm.reverse_complement() ->>> print rpwm +>>> print(rpwm) 0 1 2 3 4 A: 0.07 0.07 0.29 0.07 0.51 C: 0.04 0.38 0.04 0.04 0.04 @@ -12384,7 +12379,7 @@ %cont-doctest \begin{verbatim} >>> pssm = pwm.log_odds() ->>> print pssm +>>> print(pssm) 0 1 2 3 4 A: 0.68 1.76 -1.91 0.21 -0.49 C: -2.49 -2.49 1.26 0.09 1.51 @@ -12405,7 +12400,7 @@ \begin{verbatim} >>> background = {'A':0.3,'C':0.2,'G':0.2,'T':0.3} >>> pssm = pwm.log_odds(background) ->>> print pssm +>>> print(pssm) 0 1 2 3 4 A: 0.42 1.49 -2.17 -0.05 -0.75 C: -2.17 -2.17 1.58 0.42 1.83 @@ -12418,9 +12413,9 @@ \verb+.max+ and \verb+.min+ properties: %cont-doctest \begin{verbatim} ->>> print "%4.2f" % pssm.max +>>> print("%4.2f" % pssm.max) 6.59 ->>> print "%4.2f" % pssm.min +>>> print("%4.2f" % pssm.min) -10.85 \end{verbatim} @@ -12430,7 +12425,7 @@ \begin{verbatim} >>> mean = pssm.mean(background) >>> std = pssm.std(background) ->>> print "mean = %0.2f, standard deviation = %0.2f" % (mean, std) +>>> print("mean = %0.2f, standard deviation = %0.2f" % (mean, std)) mean = 3.21, standard deviation = 2.59 \end{verbatim} A uniform background is used if \verb+background+ is not specified. @@ -12451,7 +12446,7 @@ %cont-doctest \begin{verbatim} ->>> test_seq=Seq("TACACTGCATTACAACCCAAGCATTA",m.alphabet) +>>> test_seq=Seq("TACACTGCATTACAACCCAAGCATTA", m.alphabet) >>> len(test_seq) 26 \end{verbatim} @@ -12462,8 +12457,8 @@ the true instances of the motif: %cont-doctest \begin{verbatim} ->>> for pos,seq in m.instances.search(test_seq): -... print pos, seq +>>> for pos, seq in m.instances.search(test_seq): +... print("%i %s" % (pos, seq)) ... 0 TACAC 10 TACAA @@ -12472,8 +12467,8 @@ We can do the same with the reverse complement (to find instances on the complementary strand): %cont-doctest \begin{verbatim} ->>> for pos,seq in r.instances.search(test_seq): -... print pos, seq +>>> for pos, seq in r.instances.search(test_seq): +... print("%i %s" % (pos, seq)) ... 6 GCATT 20 GCATT @@ -12485,7 +12480,7 @@ %cont-doctest \begin{verbatim} >>> for position, score in pssm.search(test_seq, threshold=3.0): -... print "Position %d: score = %5.3f" % (position, score) +... print("Position %d: score = %5.3f" % (position, score)) ... Position 0: score = 5.622 Position -20: score = 4.601 @@ -12546,21 +12541,21 @@ %cont-doctest \begin{verbatim} >>> threshold = distribution.threshold_fpr(0.01) ->>> print "%5.3f" % threshold +>>> print("%5.3f" % threshold) 4.009 \end{verbatim} or the false-negative rate (probability of ``not finding'' an instance generated from the motif): %cont-doctest \begin{verbatim} >>> threshold = distribution.threshold_fnr(0.1) ->>> print "%5.3f" % threshold +>>> print("%5.3f" % threshold) -0.510 \end{verbatim} or a threshold (approximately) satisfying some relation between the false-positive rate and the false-negative rate ($\frac{\textrm{fnr}}{\textrm{fpr}}\simeq t$): %cont-doctest \begin{verbatim} >>> threshold = distribution.threshold_balanced(1000) ->>> print "%5.3f" % threshold +>>> print("%5.3f" % threshold) 6.241 \end{verbatim} or a threshold satisfying (roughly) the equality between the @@ -12569,7 +12564,7 @@ %cont-doctest \begin{verbatim} >>> threshold = distribution.threshold_patser() ->>> print "%5.3f" % threshold +>>> print("%5.3f" % threshold) 0.346 \end{verbatim} @@ -12579,10 +12574,10 @@ %cont-doctest \begin{verbatim} >>> threshold = distribution.threshold_fpr(0.01) ->>> print "%5.3f" % threshold +>>> print("%5.3f" % threshold) 4.009 ->>> for position, score in pssm.search(test_seq,threshold=threshold): -... print "Position %d: score = %5.3f" % (position, score) +>>> for position, score in pssm.search(test_seq, threshold=threshold): +... print("Position %d: score = %5.3f" % (position, score)) ... Position 0: score = 5.622 Position -20: score = 4.601 @@ -12599,14 +12594,14 @@ >>> from Bio import motifs >>> handle = open("Arnt.sites") >>> motif = motifs.read(handle, 'sites') ->>> print motif.counts +>>> print(motif.counts) 0 1 2 3 4 5 A: 4.00 19.00 0.00 0.00 0.00 0.00 C: 16.00 0.00 20.00 0.00 0.00 0.00 G: 0.00 1.00 0.00 20.00 0.00 20.00 T: 0.00 0.00 0.00 0.00 20.00 0.00 ->>> print motif.pwm +>>> print(motif.pwm) 0 1 2 3 4 5 A: 0.20 0.95 0.00 0.00 0.00 0.00 C: 0.80 0.00 1.00 0.00 0.00 0.00 @@ -12616,7 +12611,7 @@ \end{verbatim} %Can't use next bit in doctest, Windows Python 2.5 and 2.6 put -1.$ not -inf \begin{verbatim} ->>> print motif.pssm +>>> print(motif.pssm) 0 1 2 3 4 5 A: -0.32 1.93 -inf -inf -inf -inf C: 1.68 -inf 2.00 -inf -inf -inf @@ -12628,8 +12623,8 @@ %cont-doctest \begin{verbatim} >>> for letter in "ACGT": -... print "%s: %4.2f" % (letter, motif.pseudocounts[letter]) -... +... print("%s: %4.2f" % (letter, motif.pseudocounts[letter])) +... A: 0.00 C: 0.00 G: 0.00 @@ -12640,8 +12635,8 @@ \begin{verbatim} >>> motif.pseudocounts = 3.0 >>> for letter in "ACGT": -... print "%s: %4.2f" % (letter, motif.pseudocounts[letter]) -... +... print("%s: %4.2f" % (letter, motif.pseudocounts[letter])) +... A: 3.00 C: 3.00 G: 3.00 @@ -12650,7 +12645,7 @@ %Can't use this in doctest, Windows Python 2.5 and 2.6 give G/1 as 0.13 not 0.12 %TODO - Check why... \begin{verbatim} ->>> print motif.pwm +>>> print(motif.pwm) 0 1 2 3 4 5 A: 0.22 0.69 0.09 0.09 0.09 0.09 C: 0.59 0.09 0.72 0.09 0.09 0.09 @@ -12660,7 +12655,7 @@ \end{verbatim} %cont-doctest \begin{verbatim} ->>> print motif.pssm +>>> print(motif.pssm) 0 1 2 3 4 5 A: -0.19 1.46 -1.42 -1.42 -1.42 -1.42 C: 1.25 -1.42 1.52 -1.42 -1.42 -1.42 @@ -12674,8 +12669,8 @@ %cont-doctest \begin{verbatim} >>> for letter in "ACGT": -... print "%s: %4.2f" % (letter, motif.background[letter]) -... +... print("%s: %4.2f" % (letter, motif.background[letter])) +... A: 0.25 C: 0.25 G: 0.25 @@ -12685,7 +12680,7 @@ %cont-doctest \begin{verbatim} >>> motif.background = {'A': 0.2, 'C': 0.3, 'G': 0.3, 'T': 0.2} ->>> print motif.pssm +>>> print(motif.pssm) 0 1 2 3 4 5 A: 0.13 1.78 -1.09 -1.09 -1.09 -1.09 C: 0.98 -1.68 1.26 -1.68 -1.68 -1.68 @@ -12698,8 +12693,8 @@ \begin{verbatim} >>> motif.background = None >>> for letter in "ACGT": -... print "%s: %4.2f" % (letter, motif.background[letter]) -... +... print("%s: %4.2f" % (letter, motif.background[letter])) +... A: 0.25 C: 0.25 G: 0.25 @@ -12710,8 +12705,8 @@ \begin{verbatim} >>> motif.background = 0.8 >>> for letter in "ACGT": -... print "%s: %4.2f" % (letter, motif.background[letter]) -... +... print("%s: %4.2f" % (letter, motif.background[letter])) +... A: 0.10 C: 0.40 G: 0.40 @@ -12720,13 +12715,13 @@ Note that you can now calculate the mean of the PSSM scores over the background against which it was computed: %cont-doctest \begin{verbatim} ->>> print "%f" % motif.pssm.mean(motif.background) +>>> print("%f" % motif.pssm.mean(motif.background)) 4.703928 \end{verbatim} as well as its standard deviation: %cont-doctest \begin{verbatim} ->>> print "%f" % motif.pssm.std(motif.background) +>>> print("%f" % motif.pssm.std(motif.background)) 3.290900 \end{verbatim} and its distribution: @@ -12734,7 +12729,7 @@ \begin{verbatim} >>> distribution = motif.pssm.distribution(background=motif.background) >>> threshold = distribution.threshold_fpr(0.01) ->>> print "%f" % threshold +>>> print("%f" % threshold) 3.854375 \end{verbatim} @@ -12770,7 +12765,7 @@ >>> m_reb1 = motifs.read(open("REB1.pfm"), "pfm") >>> m_reb1.consensus Seq('GTTACCCGG', IUPACUnambiguousDNA()) ->>> print m_reb1.counts +>>> print(m_reb1.counts) 0 1 2 3 4 5 6 7 8 A: 30.00 0.00 0.00 100.00 0.00 0.00 0.00 0.00 15.00 C: 10.00 0.00 0.00 0.00 100.00 100.00 100.00 0.00 15.00 @@ -12785,7 +12780,7 @@ >>> m_reb1.pseudocounts = {'A':0.6, 'C': 0.4, 'G': 0.4, 'T': 0.6} >>> m_reb1.background = {'A':0.3,'C':0.2,'G':0.2,'T':0.3} >>> pssm_reb1 = m_reb1.pssm ->>> print pssm_reb1 +>>> print(pssm_reb1) 0 1 2 3 4 5 6 7 8 A: 0.00 -5.67 -5.67 1.72 -5.67 -5.67 -5.67 -5.67 -0.97 C: -0.97 -5.67 -5.67 -5.67 2.30 2.30 2.30 -5.67 -0.41 @@ -12799,9 +12794,9 @@ %cont-doctest \begin{verbatim} >>> distance, offset = pssm.dist_pearson(pssm_reb1) ->>> print "distance = %5.3g" % distance +>>> print("distance = %5.3g" % distance) distance = 0.239 ->>> print offset +>>> print(offset) -2 \end{verbatim} This means that the best PCC between motif \verb|m| and \verb|m_reb1| is obtained with the following alignment: @@ -12878,7 +12873,7 @@ %cont-doctest \begin{verbatim} >>> from Bio import motifs ->>> motifsA = motifs.parse(open("alignace.out"),"alignace") +>>> motifsA = motifs.parse(open("alignace.out"), "alignace") \end{verbatim} Again, your motifs behave as they should: @@ -12905,14 +12900,14 @@ >>> command="/opt/bin/AlignACE" >>> input_file="test.fa" >>> from Bio.motifs.applications import AlignAceCommandline ->>> cmd = AlignAceCommandline(cmd=command,input=input_file,gcback=0.6,numcols=10) ->>> stdout,stderr= cmd() +>>> cmd = AlignAceCommandline(cmd=command, input=input_file, gcback=0.6, numcols=10) +>>> stdout, stderr= cmd() \end{verbatim} Since AlignAce prints all of its output to standard output, you can get to your motifs by parsing the first part of the result: \begin{verbatim} ->>> motifs = motifs.parse(stdout,"alignace") +>>> motifs = motifs.parse(stdout, "alignace") \end{verbatim} @@ -12959,10 +12954,10 @@ %cont-doctest \begin{verbatim} >>> from Bio.Seq import Seq ->>> m.add_instance(Seq("TATAA",m.alphabet)) ->>> m.add_instance(Seq("TATTA",m.alphabet)) ->>> m.add_instance(Seq("TATAA",m.alphabet)) ->>> m.add_instance(Seq("TATAA",m.alphabet)) +>>> m.add_instance(Seq("TATAA", m.alphabet)) +>>> m.add_instance(Seq("TATTA", m.alphabet)) +>>> m.add_instance(Seq("TATAA", m.alphabet)) +>>> m.add_instance(Seq("TATAA", m.alphabet)) \end{verbatim} Now we have a full \verb|Motif| instance, so we can try to get some basic information about it. Let's start with length and consensus @@ -12982,7 +12977,7 @@ >>> m.reverse_complement().consensus() Seq('TTATA', IUPACUnambiguousDNA()) >>> for i in m.reverse_complement().instances: -... print i +... print(i) TTATA TAATA TTATA @@ -12992,7 +12987,7 @@ We can also calculate the information content of a motif with a simple call: %cont-doctest \begin{verbatim} ->>> print "%0.2f" % m.ic() +>>> print("%0.2f" % m.ic()) 5.27 \end{verbatim} This gives us a number of bits of information provided by the motif, @@ -13081,12 +13076,12 @@ %doctest ../Tests/Motif \begin{verbatim} >>> from Bio import Motif ->>> arnt = Motif.read(open("Arnt.sites"),"jaspar-sites") +>>> arnt = Motif.read(open("Arnt.sites"), "jaspar-sites") \end{verbatim} and from a count matrix: %cont-doctest \begin{verbatim} ->>> srf = Motif.read(open("SRF.pfm"),"jaspar-pfm") +>>> srf = Motif.read(open("SRF.pfm"), "jaspar-pfm") \end{verbatim} The \verb|arnt| and \verb|srf| motifs can both do the same things for @@ -13136,7 +13131,7 @@ Speaking of exporting, let's look at export functions. We can export to fasta: \begin{verbatim} ->>> print m.format("fasta") +>>> print(m.format("fasta")) >instance0 TATAA >instance1 @@ -13148,7 +13143,7 @@ \end{verbatim} or to TRANSFAC-like matrix format (used by some motif processing software) \begin{verbatim} ->>> print m.format("transfac") +>>> print(m.format("transfac")) XX TY Motif ID @@ -13180,8 +13175,8 @@ The simplest way to find instances, is to look for exact matches of the true instances of the motif: \begin{verbatim} ->>> for pos,seq in m.search_instances(test_seq): -... print pos,seq.tostring() +>>> for pos, seq in m.search_instances(test_seq): +... print(pos, seq.tostring()) ... 10 TATAA 15 TATAA @@ -13189,8 +13184,8 @@ \end{verbatim} We can do the same with the reverse complement (to find instances on the complementary strand): \begin{verbatim} ->>> for pos,seq in m.reverse_complement().search_instances(test_seq): -... print pos,seq.tostring() +>>> for pos, seq in m.reverse_complement().search_instances(test_seq): +... print(pos, seq.tostring()) ... 12 TAATA 20 TTATA @@ -13198,8 +13193,8 @@ It's just as easy to look for positions, giving rise to high log-odds scores against our motif: \begin{verbatim} ->>> for pos,score in m.search_pwm(test_seq,threshold=5.0): -... print pos,score +>>> for pos, score in m.search_pwm(test_seq, threshold=5.0): +... print(pos, score) ... 10 8.44065060871 -12 7.06213898545 @@ -13219,7 +13214,7 @@ distribution grows exponentially with motif length, we are using an approximation with a given precision to keep computation cost manageable: \begin{verbatim} ->>> sd = Motif.score_distribution(m,precision=10**4) +>>> sd = Motif.score_distribution(m, precision=10**4) \end{verbatim} The sd object can be used to determine a number of different thresholds. @@ -13250,8 +13245,8 @@ you exactly the same results (for this sequence) as searching for instances with balanced threshold with rate of $1000$. \begin{verbatim} ->>> for pos,score in m.search_pwm(test_seq,threshold=sd.threshold_balanced(1000)): -... print pos,score +>>> for pos, score in m.search_pwm(test_seq, threshold=sd.threshold_balanced(1000)): +... print(pos, score) ... 10 8.44065060871 15 8.44065060871 @@ -13286,7 +13281,7 @@ To show how these functions work, let us first load another motif, which is similar to our test motif \verb|m|: \begin{verbatim} ->>> ubx=Motif.read(open("Ubx.pfm"),"jaspar-pfm") +>>> ubx=Motif.read(open("Ubx.pfm"), "jaspar-pfm") >>> ubx.consensus() Seq('TAAT', IUPACUnambiguousDNA()) @@ -13348,7 +13343,7 @@ running the following piece of code: \begin{verbatim} ->>> motifsM = list(Motif.parse(open("meme.out"),"MEME")) +>>> motifsM = list(Motif.parse(open("meme.out"), "MEME")) >>> motifsM [] \end{verbatim} @@ -13388,7 +13383,7 @@ with the following code: \begin{verbatim} ->>> motifsA=list(Motif.parse(open("alignace.out"),"AlignAce")) +>>> motifsA=list(Motif.parse(open("alignace.out"), "AlignAce")) \end{verbatim} Again, your motifs behave as they should: @@ -13413,8 +13408,8 @@ >>> command="/opt/bin/AlignACE" >>> input_file="test.fa" >>> from Bio.Motif.Applications import AlignAceCommandline ->>> cmd = AlignAceCommandline(cmd=command,input=input_file,gcback=0.6,numcols=10) ->>> stdout,stderr= cmd() +>>> cmd = AlignAceCommandline(cmd=command, input=input_file, gcback=0.6, numcols=10) +>>> stdout, stderr= cmd() \end{verbatim} Since AlignAce prints all its output to standard output, you can get @@ -13844,16 +13839,16 @@ \begin{verbatim} >>> from Bio.Cluster import Node ->>> Node(2,3) +>>> Node(2, 3) (2, 3): 0 ->>> Node(2,3,0.91) +>>> Node(2, 3, 0.91) (2, 3): 0.91 \end{verbatim} The attributes \verb|left|, \verb|right|, and \verb|distance| of an existing \verb|Node| object can be modified directly: \begin{verbatim} ->>> node = Node(4,5) +>>> node = Node(4, 5) >>> node.left = 6 >>> node.right = 2 >>> node.distance = 0.73 @@ -13866,9 +13861,9 @@ \begin{verbatim} >>> from Bio.Cluster import Node, Tree ->>> nodes = [Node(1,2,0.2), Node(0,3,0.5), Node(-2,4,0.6), Node(-1,-3,0.9)] +>>> nodes = [Node(1, 2, 0.2), Node(0, 3, 0.5), Node(-2, 4, 0.6), Node(-1, -3, 0.9)] >>> tree = Tree(nodes) ->>> print tree +>>> print(tree) (1, 2): 0.2 (0, 3): 0.5 (-2, 4): 0.6 @@ -13878,7 +13873,7 @@ The \verb|Tree| initializer checks if the list of nodes is a valid hierarchical clustering result: \begin{verbatim} ->>> nodes = [Node(1,2,0.2), Node(0,2,0.5)] +>>> nodes = [Node(1, 2, 0.2), Node(0, 2, 0.5)] >>> Tree(nodes) Traceback (most recent call last): File "", line 1, in ? @@ -13888,7 +13883,7 @@ Individual nodes in a \verb|Tree| object can be accessed using square brackets: \begin{verbatim} ->>> nodes = [Node(1,2,0.2), Node(0,-1,0.5)] +>>> nodes = [Node(1, 2, 0.2), Node(0, -1, 0.5)] >>> tree = Tree(nodes) >>> tree[0] (1, 2): 0.2 @@ -13901,16 +13896,16 @@ As a \verb|Tree| object is read-only, we cannot change individual nodes in a \verb|Tree| object. However, we can convert the tree to a list of nodes, modify this list, and create a new tree from this list: \begin{verbatim} ->>> tree = Tree([Node(1,2,0.1), Node(0,-1,0.5), Node(-2,3,0.9)]) ->>> print tree +>>> tree = Tree([Node(1, 2, 0.1), Node(0, -1, 0.5), Node(-2, 3, 0.9)]) +>>> print(tree) (1, 2): 0.1 (0, -1): 0.5 (-2, 3): 0.9 >>> nodes = tree[:] ->>> nodes[0] = Node(0,1,0.2) +>>> nodes[0] = Node(0, 1, 0.2) >>> nodes[1].left = 2 >>> tree = Tree(nodes) ->>> print tree +>>> print(tree) (0, 1): 0.2 (2, -1): 0.5 (-2, 3): 0.9 @@ -14491,7 +14486,7 @@ \begin{verbatim} >>> def show_progress(iteration, loglikelihood): - print "Iteration:", iteration, "Log-likelihood function:", loglikelihood + print("Iteration:", iteration, "Log-likelihood function:", loglikelihood) >>> >>> model = LogisticRegression.train(xs, ys, update_fn=show_progress) Iteration: 0 Log-likelihood function: -11.7835020695 @@ -14562,30 +14557,30 @@ The logistic regression model classifies {\it yxcE}, {\it yxcD} as belonging to the same operon (class OP), while {\it yxiB}, {\it yxiA} are predicted to belong to different operons: \begin{verbatim} ->>> print "yxcE, yxcD:", LogisticRegression.classify(model, [6,-173.143442352]) +>>> print("yxcE, yxcD:", LogisticRegression.classify(model, [6, -173.143442352])) yxcE, yxcD: 1 ->>> print "yxiB, yxiA:", LogisticRegression.classify(model, [309, -271.005880394]) +>>> print("yxiB, yxiA:", LogisticRegression.classify(model, [309, -271.005880394])) yxiB, yxiA: 0 \end{verbatim} (which, by the way, agrees with the biological literature). To find out how confident we can be in these predictions, we can call the \verb+calculate+ function to obtain the probabilities (equations (\ref{eq:OP}) and \ref{eq:NOP}) for class OP and NOP. For {\it yxcE}, {\it yxcD} we find \begin{verbatim} ->>> q, p = LogisticRegression.calculate(model, [6,-173.143442352]) ->>> print "class OP: probability =", p, "class NOP: probability =", q +>>> q, p = LogisticRegression.calculate(model, [6, -173.143442352]) +>>> print("class OP: probability =", p, "class NOP: probability =", q) class OP: probability = 0.993242163503 class NOP: probability = 0.00675783649744 \end{verbatim} and for {\it yxiB}, {\it yxiA} \begin{verbatim} >>> q, p = LogisticRegression.calculate(model, [309, -271.005880394]) ->>> print "class OP: probability =", p, "class NOP: probability =", q +>>> print("class OP: probability =", p, "class NOP: probability =", q) class OP: probability = 0.000321211251817 class NOP: probability = 0.999678788748 \end{verbatim} To get some idea of the prediction accuracy of the logistic regression model, we can apply it to the training data: \begin{verbatim} >>> for i in range(len(ys)): - print "True:", ys[i], "Predicted:", LogisticRegression.classify(model, xs[i]) + print("True:", ys[i], "Predicted:", LogisticRegression.classify(model, xs[i])) True: 1 Predicted: 1 True: 1 Predicted: 0 True: 1 Predicted: 1 @@ -14608,7 +14603,7 @@ \begin{verbatim} >>> for i in range(len(ys)): model = LogisticRegression.train(xs[:i]+xs[i+1:], ys[:i]+ys[i+1:]) - print "True:", ys[i], "Predicted:", LogisticRegression.classify(model, xs[i]) + print("True:", ys[i], "Predicted:", LogisticRegression.classify(model, xs[i])) True: 1 Predicted: 1 True: 1 Predicted: 0 True: 1 Predicted: 1 @@ -14664,10 +14659,10 @@ For the example of the gene pairs {\it yxcE}, {\it yxcD} and {\it yxiB}, {\it yxiA}, we find: \begin{verbatim} >>> x = [6, -173.143442352] ->>> print "yxcE, yxcD:", kNN.classify(model, x) +>>> print("yxcE, yxcD:", kNN.classify(model, x)) yxcE, yxcD: 1 >>> x = [309, -271.005880394] ->>> print "yxiB, yxiA:", kNN.classify(model, x) +>>> print("yxiB, yxiA:", kNN.classify(model, x)) yxiB, yxiA: 0 \end{verbatim} In agreement with the logistic regression model, {\it yxcE}, {\it yxcD} are classified as belonging to the same operon (class OP), while {\it yxiB}, {\it yxiA} are predicted to belong to different operons. @@ -14680,9 +14675,9 @@ ... assert len(x2)==2 ... distance = abs(x1[0]-x2[0]) + abs(x1[1]-x2[1]) ... return distance -... +... >>> x = [6, -173.143442352] ->>> print "yxcE, yxcD:", kNN.classify(model, x, distance_fn = cityblock) +>>> print("yxcE, yxcD:", kNN.classify(model, x, distance_fn = cityblock)) yxcE, yxcD: 1 \end{verbatim} @@ -14693,9 +14688,9 @@ ... assert len(x1)==2 ... assert len(x2)==2 ... return exp(-abs(x1[0]-x2[0]) - abs(x1[1]-x2[1])) -... +... >>> x = [6, -173.143442352] ->>> print "yxcE, yxcD:", kNN.classify(model, x, weight_fn = weight) +>>> print("yxcE, yxcD:", kNN.classify(model, x, weight_fn = weight)) yxcE, yxcD: 1 \end{verbatim} By default, all neighbors are given an equal weight. @@ -14704,7 +14699,7 @@ \begin{verbatim} >>> x = [6, -173.143442352] >>> weight = kNN.calculate(model, x) ->>> print "class OP: weight =", weight[0], "class NOP: weight =", weight[1] +>>> print("class OP: weight =", weight[0], "class NOP: weight =", weight[1]) class OP: weight = 0.0 class NOP: weight = 3.0 \end{verbatim} which means that all three neighbors of \verb+x1+, \verb+x2+ are in the NOP class. As another example, for {\it yesK}, {\it yesL} we find @@ -14712,7 +14707,7 @@ \begin{verbatim} >>> x = [117, -267.14] >>> weight = kNN.calculate(model, x) ->>> print "class OP: weight =", weight[0], "class NOP: weight =", weight[1] +>>> print("class OP: weight =", weight[0], "class NOP: weight =", weight[1]) class OP: weight = 2.0 class NOP: weight = 1.0 \end{verbatim} which means that two neighbors are operon pairs and one neighbor is a non-operon pair. @@ -14720,7 +14715,7 @@ To get some idea of the prediction accuracy of the $k$-nearest neighbors approach, we can apply it to the training data: \begin{verbatim} >>> for i in range(len(ys)): - print "True:", ys[i], "Predicted:", kNN.classify(model, xs[i]) + print("True:", ys[i], "Predicted:", kNN.classify(model, xs[i])) True: 1 Predicted: 1 True: 1 Predicted: 0 True: 1 Predicted: 1 @@ -14743,7 +14738,7 @@ \begin{verbatim} >>> for i in range(len(ys)): model = kNN.train(xs[:i]+xs[i+1:], ys[:i]+ys[i+1:]) - print "True:", ys[i], "Predicted:", kNN.classify(model, xs[i]) + print("True:", ys[i], "Predicted:", kNN.classify(model, xs[i])) True: 1 Predicted: 1 True: 1 Predicted: 0 True: 1 Predicted: 1 @@ -15732,7 +15727,7 @@ ("Chr V", "CHR_V/NC_003076.fna")] for (name, filename) in entries: record = SeqIO.read(filename,"fasta") - print name, len(record) + print(name, len(record)) \end{verbatim} \noindent This gave the lengths of the five chromosomes, which we'll now use in @@ -15913,12 +15908,12 @@ id_file = "short_list.txt" output_file = "short_list.sff" wanted = set(line.rstrip("\n").split(None,1)[0] for line in open(id_file)) -print "Found %i unique identifiers in %s" % (len(wanted), id_file) +print("Found %i unique identifiers in %s" % (len(wanted), id_file)) records = (r for r in SeqIO.parse(input_file, "sff") if r.id in wanted) count = SeqIO.write(records, output_file, "sff") -print "Saved %i records from %s to %s" % (count, input_file, output_file) +print("Saved %i records from %s to %s" % (count, input_file, output_file)) if count < len(wanted): - print "Warning %i IDs not found in %s" % (len(wanted)-count, input_file) + print("Warning %i IDs not found in %s" % (len(wanted)-count, input_file)) \end{verbatim} Note that we use a Python \verb|set| rather than a \verb|list|, this makes @@ -15944,7 +15939,7 @@ %doctest ../Tests/GenBank \begin{verbatim} >>> from Bio import SeqIO ->>> original_rec = SeqIO.read("NC_005816.gb","genbank") +>>> original_rec = SeqIO.read("NC_005816.gb", "genbank") \end{verbatim} So, how can we generate a shuffled versions of the original sequence? I would @@ -16079,7 +16074,7 @@ from Bio import SeqIO records = (rec.upper() for rec in SeqIO.parse("mixed.fas", "fasta")) count = SeqIO.write(records, "upper.fas", "fasta") -print "Converted %i records to upper case" % count +print("Converted %i records to upper case" % count) \end{verbatim} How does this work? The first line is just importing the \verb|Bio.SeqIO| @@ -16204,7 +16199,7 @@ count = 0 for rec in SeqIO.parse("SRR020192.fastq", "fastq"): count += 1 -print "%i reads" % count +print("%i reads" % count) \end{verbatim} \noindent Now let's do a simple filtering for a minimum PHRED quality of 20: @@ -16215,7 +16210,7 @@ SeqIO.parse("SRR020192.fastq", "fastq") \ if min(rec.letter_annotations["phred_quality"]) >= 20) count = SeqIO.write(good_reads, "good_quality.fastq", "fastq") -print "Saved %i reads" % count +print("Saved %i reads" % count) \end{verbatim} \noindent This pulled out only $14580$ reads out of the $41892$ present. @@ -16246,7 +16241,7 @@ SeqIO.parse("SRR020192.fastq", "fastq") \ if rec.seq.startswith("GATGACGGTGT")) count = SeqIO.write(primer_reads, "with_primer.fastq", "fastq") -print "Saved %i reads" % count +print("Saved %i reads" % count) \end{verbatim} \noindent That should find $13819$ reads from \texttt{SRR014849.fastq} and save them to @@ -16263,7 +16258,7 @@ SeqIO.parse("SRR020192.fastq", "fastq") \ if rec.seq.startswith("GATGACGGTGT")) count = SeqIO.write(trimmed_primer_reads, "with_primer_trimmed.fastq", "fastq") -print "Saved %i reads" % count +print("Saved %i reads" % count) \end{verbatim} \noindent Again, that should pull out the $13819$ reads from \texttt{SRR020192.fastq}, @@ -16286,7 +16281,7 @@ trimmed_reads = (trim_primer(record, "GATGACGGTGT") for record in \ SeqIO.parse("SRR020192.fastq", "fastq")) count = SeqIO.write(trimmed_reads, "trimmed.fastq", "fastq") -print "Saved %i reads" % count +print("Saved %i reads" % count) \end{verbatim} This takes longer, as this time the output file contains all $41892$ reads. @@ -16312,7 +16307,7 @@ original_reads = SeqIO.parse("SRR020192.fastq", "fastq") trimmed_reads = trim_primers(original_reads, "GATGACGGTGT") count = SeqIO.write(trimmed_reads, "trimmed.fastq", "fastq") -print "Saved %i reads" % count +print("Saved %i reads" % count) \end{verbatim} This form is more flexible if you want to do something more complicated @@ -16351,7 +16346,7 @@ original_reads = SeqIO.parse("SRR020192.fastq", "fastq") trimmed_reads = trim_adaptors(original_reads, "GATGACGGTGT") count = SeqIO.write(trimmed_reads, "trimmed.fastq", "fastq") -print "Saved %i reads" % count +print("Saved %i reads" % count) \end{verbatim} Because we are using a FASTQ input file in this example, the \verb|SeqRecord| @@ -16391,7 +16386,7 @@ original_reads = SeqIO.parse("SRR020192.fastq", "fastq") trimmed_reads = trim_adaptors(original_reads, "GATGACGGTGT", 100) count = SeqIO.write(trimmed_reads, "trimmed.fastq", "fastq") -print "Saved %i reads" % count +print("Saved %i reads" % count) \end{verbatim} By changing the format names, you could apply this to FASTA files instead. @@ -16527,7 +16522,7 @@ \begin{verbatim} from Bio.SeqIO.QualityIO import PairedFastaQualIterator for record in PairedFastaQualIterator(open("example.fasta"), open("example.qual")): - print record + print(record) \end{verbatim} This function will check that the FASTA and QUAL files are consistent (e.g. @@ -16542,7 +16537,7 @@ records = PairedFastaQualIterator(open("example.fasta"), open("example.qual")) count = SeqIO.write(records, handle, "fastq") handle.close() -print "Converted %i records" % count +print("Converted %i records" % count) \end{verbatim} \subsection{Indexing a FASTQ file} @@ -16662,7 +16657,7 @@ %doctest ../Tests/GenBank \begin{verbatim} >>> from Bio import SeqIO ->>> record = SeqIO.read("NC_005816.fna","fasta") +>>> record = SeqIO.read("NC_005816.fna", "fasta") >>> table = 11 >>> min_pro_len = 100 \end{verbatim} @@ -16677,8 +16672,8 @@ ... length = 3 * ((len(record)-frame) // 3) #Multiple of three ... for pro in nuc[frame:frame+length].translate(table).split("*"): ... if len(pro) >= min_pro_len: -... print "%s...%s - length %i, strand %i, frame %i" \ -... % (pro[:30], pro[-3:], len(pro), strand, frame) +... print("%s...%s - length %i, strand %i, frame %i" \ +... % (pro[:30], pro[-3:], len(pro), strand, frame)) GCLMKKSSIVATIITILSGSANAASSQLIP...YRF - length 315, strand 1, frame 0 KSGELRQTPPASSTLHLRLILQRSGVMMEL...NPE - length 285, strand 1, frame 1 GLNCSFFSICNWKFIDYINRLFQIIYLCKN...YYH - length 176, strand 1, frame 1 @@ -16742,8 +16737,8 @@ orf_list = find_orfs_with_trans(record.seq, table, min_pro_len) for start, end, strand, pro in orf_list: - print "%s...%s - length %i, strand %i, %i:%i" \ - % (pro[:30], pro[-3:], len(pro), strand, start, end) + print("%s...%s - length %i, strand %i, %i:%i" \ + % (pro[:30], pro[-3:], len(pro), strand, start, end)) \end{verbatim} \noindent And the output: @@ -16944,8 +16939,8 @@ from Bio import SeqIO handle = open("ls_orchid.fasta") record_iterator = SeqIO.parse(handle, "fasta") -rec_one = record_iterator.next() -rec_two = record_iterator.next() +rec_one = next(record_iterator) +rec_two = next(record_iterator) handle.close() \end{verbatim} @@ -17027,7 +17022,7 @@ #Now find any sub-sequences found in both sequences #(Python 2.3 would require slightly different code here) matches = set(dict_one).intersection(dict_two) -print "%i unique matches" % len(matches) +print("%i unique matches" % len(matches)) \end{verbatim} \noindent In order to use the \verb|pylab.scatter()| we need separate lists for the $x$ and $y$ co-ordinates: \begin{verbatim} @@ -17106,7 +17101,7 @@ pylab.ylabel("PHRED quality score") pylab.xlabel("Position") pylab.savefig("SRR001666.png") -print "Done" +print("Done") \end{verbatim} You should note that we are using the \verb|Bio.SeqIO| format name \texttt{fastq} @@ -17236,7 +17231,9 @@ \end{enumerate} -The command above returns a \verb|PSSM| object. To print out the PSSM as we showed above, we simply need to do a \verb|print my_pssm|, which gives: +The command above returns a \verb|PSSM| object. +To print out the PSSM as shown above, +we simply need to do a \verb|print(my_pssm)|, which gives: \begin{verbatim} A C G T @@ -17254,7 +17251,7 @@ You can access any element of the PSSM by subscripting like \verb|your_pssm[sequence_number][residue_count_name]|. For instance, to get the counts for the 'A' residue in the second element of the above PSSM you would do: \begin{verbatim} ->>> print my_pssm[1]["A"] +>>> print(my_pssm[1]["A"]) 7.0 \end{verbatim} @@ -17681,12 +17678,13 @@ module could look as follows: \begin{verbatim} +from __future__ import print_function from Bio import Biospam -print "2 + 3 =", Biospam.addition(2, 3) -print "9 - 1 =", Biospam.addition(9, -1) -print "2 * 3 =", Biospam.multiplication(2, 3) -print "9 * (- 1) =", Biospam.multiplication(9, -1) +print("2 + 3 =", Biospam.addition(2, 3)) +print("9 - 1 =", Biospam.addition(9, -1)) +print("2 * 3 =", Biospam.multiplication(2, 3)) +print("9 * (- 1) =", Biospam.multiplication(9, -1)) \end{verbatim} We generate the corresponding output with \verb|python run_tests.py -g test_Biospam.py|, and check the output file \verb|output/test_Biospam|: @@ -18087,7 +18085,7 @@ \begin{verbatim} >>> exp_freq_table = SubsMat._exp_freq_table_from_obs_freq(OFM) ->>> EFM = SubsMat._build_exp_freq_mat(OFM,exp_freq_table) +>>> EFM = SubsMat._build_exp_freq_mat(OFM, exp_freq_table) \end{verbatim} But you can supply your own \verb|exp_freq_table|, if you wish @@ -18207,8 +18205,8 @@ \begin{verbatim} >>> from SubsMat import * ->>> ftab = FreqTable.FreqTable(my_frequency_dictionary,FreqTable.FREQ) ->>> ftab = FreqTable.FreqTable(my_count_dictionary,FreqTable.COUNT) +>>> ftab = FreqTable.FreqTable(my_frequency_dictionary, FreqTable.FREQ) +>>> ftab = FreqTable.FreqTable(my_count_dictionary, FreqTable.COUNT) >>> ftab = FreqTable.read_count(open('myCountFile')) >>> ftab = FreqTable.read_frequency(open('myFrequencyFile')) \end{verbatim} @@ -18389,7 +18387,7 @@ \begin{verbatim} from Bio import SeqIO for record in SeqIO.parse("m_cold.fasta", "fasta"): - print record.id, len(record) + print(record.id, len(record)) \end{verbatim} On older versions of Biopython you had to use a handle, e.g. @@ -18398,7 +18396,7 @@ from Bio import SeqIO handle = open("m_cold.fasta", "r") for record in SeqIO.parse(handle, "fasta"): - print record.id, len(record) + print(record.id, len(record)) handle.close() \end{verbatim} @@ -18410,7 +18408,7 @@ from Bio import SeqIO handle = gzip.open("m_cold.fasta.gz") for record in SeqIO.parse(handle, "fasta"): - print record.id, len(record) + print(record.id, len(record)) handle.close() \end{verbatim} @@ -18426,17 +18424,17 @@ %doctest \begin{verbatim} >>> my_info = 'A string\n with multiple lines.' ->>> print my_info +>>> print(my_info) A string with multiple lines. >>> from StringIO import StringIO >>> my_info_handle = StringIO(my_info) >>> first_line = my_info_handle.readline() ->>> print first_line +>>> print(first_line) A string >>> second_line = my_info_handle.readline() ->>> print second_line +>>> print(second_line) with multiple lines. \end{verbatim} Binary files /tmp/EAI2iEqCCm/python-biopython-1.62/Doc/biopdb_faq.pdf and /tmp/XMH5G9mdHg/python-biopython-1.63/Doc/biopdb_faq.pdf differ diff -Nru python-biopython-1.62/Doc/examples/ACT_example.py python-biopython-1.63/Doc/examples/ACT_example.py --- python-biopython-1.62/Doc/examples/ACT_example.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Doc/examples/ACT_example.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,10 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + +from __future__ import print_function + import sys import os import time @@ -22,7 +29,7 @@ for f in [file_a, file_b, file_a_vs_b]: if not os.path.isfile(os.path.join(input_folder, f)): - print "Missing input file %s.fna" % f + print("Missing input file %s.fna" % f) sys.exit(1) #Only doing a_vs_b here, could also have b_vs_c and c_vs_d etc @@ -46,7 +53,7 @@ greytrack=True, greytrack_labels=0) feature_sets[f] = tracks[f].new_set() -print "Drawing matches..." +print("Drawing matches...") for i, crunch_file in enumerate(comparisons): q = genomes[i+1][0] # query file s = genomes[i][0] # subject file @@ -96,7 +103,7 @@ #Note ACT puts long hits at the back, and colours by hit score handle.close() -print "Drawing CDS features..." +print("Drawing CDS features...") for f, format in genomes: record = records[f] feature_set = feature_sets[f] diff -Nru python-biopython-1.62/Doc/examples/Proux_et_al_2002_Figure_6.py python-biopython-1.63/Doc/examples/Proux_et_al_2002_Figure_6.py --- python-biopython-1.62/Doc/examples/Proux_et_al_2002_Figure_6.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Doc/examples/Proux_et_al_2002_Figure_6.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """GenomeDiagram script to mimic Proux et al 2002 Figure 6 You can use the Entrez module to download the 3 required GenBank files diff -Nru python-biopython-1.62/Doc/examples/clustal_run.py python-biopython-1.63/Doc/examples/clustal_run.py --- python-biopython-1.62/Doc/examples/clustal_run.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Doc/examples/clustal_run.py 2013-12-05 14:10:43.000000000 +0000 @@ -4,6 +4,9 @@ Example code to show how to create a clustalw command line, run clustalw and parse the results into an object that can be dealt with easily.""" # standard library + +from __future__ import print_function + import os import sys import subprocess @@ -28,26 +31,26 @@ alignment = AlignIO.read("test.aln", "clustal", alphabet=Gapped(IUPAC.unambiguous_dna)) -print alignment +print(alignment) -print 'first description:', alignment[0].description -print 'first sequence:', alignment[0].seq +print('first description: %s' % alignment[0].description) +print('first sequence: %s' % alignment[0].seq) # get the length of the alignment -print 'length', alignment.get_alignment_length() +print('length %i' % alignment.get_alignment_length()) -print alignment +print(alignment) # print out interesting information about the alignment summary_align = AlignInfo.SummaryInfo(alignment) consensus = summary_align.dumb_consensus() -print 'consensus', consensus +print('consensus %s' % consensus) my_pssm = summary_align.pos_specific_score_matrix(consensus, chars_to_ignore=['N']) -print my_pssm +print(my_pssm) expect_freq = { 'A': .3, @@ -62,4 +65,4 @@ chars_to_ignore=['N'], e_freq_table=freq_table_info) -print "relative info content:", info_content +print("relative info content: %f" % info_content) diff -Nru python-biopython-1.62/Doc/examples/fasta_dictionary.py python-biopython-1.63/Doc/examples/fasta_dictionary.py --- python-biopython-1.62/Doc/examples/fasta_dictionary.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Doc/examples/fasta_dictionary.py 2013-12-05 14:10:43.000000000 +0000 @@ -4,6 +4,8 @@ # and then turns it into an in-memory python dictionary. # This is *not* suitable for FASTA files with millions of entries. +from __future__ import print_function + from Bio.Alphabet import generic_dna from Bio import SeqIO @@ -18,9 +20,9 @@ orchid_dict = SeqIO.to_dict(rec_iterator, get_accession_num) for id_num in orchid_dict: - print 'id number:', id_num - print 'description:', orchid_dict[id_num].description - print 'sequence:', orchid_dict[id_num].seq + print('id number: %s' % id_num) + print('description: %s' % orchid_dict[id_num].description) + print('sequence: %s' % orchid_dict[id_num].seq) # Indexed @@ -42,6 +44,6 @@ orchid_dict = SeqIO.index("ls_orchid.fasta", "fasta", generic_dna) for id_num in orchid_dict: - print 'id number:', id_num - print 'description:', orchid_dict[id_num].description - print 'sequence:', orchid_dict[id_num].seq + print('id number: %s' % id_num) + print('description: %s' % orchid_dict[id_num].description) + print('sequence: %s' % orchid_dict[id_num].seq) diff -Nru python-biopython-1.62/Doc/examples/fasta_iterator.py python-biopython-1.63/Doc/examples/fasta_iterator.py --- python-biopython-1.62/Doc/examples/fasta_iterator.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Doc/examples/fasta_iterator.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,6 +1,11 @@ -# The New Way -# =========== -# This next bit of code use Bio.SeqIO to parse a FASTA file +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + +"""Example using Bio.SeqIO to parse a FASTA file.""" + +from __future__ import print_function from Bio import SeqIO @@ -18,44 +23,7 @@ return all_species if __name__ == "__main__": - print "Using Bio.SeqIO on a FASTA file" + print("Using Bio.SeqIO on a FASTA file") all_species = extract_organisms("ls_orchid.fasta", "fasta") - print "number of species:", len(all_species) - print 'species names:', all_species - - -# The Old Way -# =========== -# This next bit of code still works fine, it uses Bio.Fasta instead - -from Bio import Fasta - - -def extract_organisms(file_to_parse): - # set up the parser and iterator - parser = Fasta.RecordParser() - file = open(file_to_parse, 'r') - iterator = Fasta.Iterator(file, parser) - - all_species = [] - - while 1: - cur_record = iterator.next() - - if cur_record is None: - break - - # extract the info from the title - new_species = cur_record.title.split()[1] - - # append the new species to the list if it isn't there - if new_species not in all_species: - all_species.append(new_species) - - return all_species - -if __name__ == "__main__": - print "Using Bio.Fasta" - all_species = extract_organisms("ls_orchid.fasta") - print "number of species:", len(all_species) - print 'species names:', all_species + print("number of species: %i" % len(all_species)) + print("species names: %s" % all_species) diff -Nru python-biopython-1.62/Doc/examples/getgene.py python-biopython-1.63/Doc/examples/getgene.py --- python-biopython-1.62/Doc/examples/getgene.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Doc/examples/getgene.py 2013-12-05 14:10:43.000000000 +0000 @@ -29,11 +29,17 @@ db_index.Get_OS_OC_GN('EFTU_ECOLI') """ +from __future__ import print_function + import os import re import string import sys -import gdbm + +try: + import gdbm # Python 2 +except ImportError: + from dbm import gnu as gdbm # Python 3 class DB_Index: @@ -47,7 +53,7 @@ db['datafile'] = os.path.abspath(infile) - while 1: + while True: line = fid.readline() if not line or not len(line): break @@ -69,8 +75,8 @@ db[acc] = value id, acc, start, stop = None, None, None, None except: - print 'AARRGGGG', start, stop, type(start), type(stop) - print id, acc + print("AARRGGGG %d %d %s %s" % (start, stop, type(start), type(stop))) + print("%s %s" % (id, acc)) db.close() fid.close() @@ -91,7 +97,7 @@ values = self.db[id] except: return None - start, stop = map(int, string.split(values)) + start, stop = [int(x) for x in values.split()] self.fid.seek(start) txt = self.fid.read(stop - start) return txt @@ -132,7 +138,7 @@ def Get_Kingdom(self, id): res = self.Get_Taxonomy(id) - #print id, res + #print("%s %s" % (id, res)) if not res: return "U" kd = string.strip(string.split(res, ";")[0]) @@ -145,7 +151,7 @@ elif kd == "Viridae" or kd == "Viruses": return "V" else: - print kd, "UNKNOWN" + print("%s UNKNOWN" % kd) return "U" def Get_Gene(self, id): @@ -261,8 +267,8 @@ def help(exit=0): name = os.path.basename(sys.argv[0]) - print 'Usage: %s ' % name - print ' or %s --index ' % name + print('Usage: %s ' % name) + print(' or %s --index ' % name) if exit: sys.exit(0) @@ -302,5 +308,5 @@ dbfile = os.path.join(pyphy_home, db + '.indexed') db_index.Open(dbfile) for id in ids: - #print db_index.Get(id) - print func(id) + #print(db_index.Get(id)) + print(func(id)) diff -Nru python-biopython-1.62/Doc/examples/local_blast.py python-biopython-1.63/Doc/examples/local_blast.py --- python-biopython-1.62/Doc/examples/local_blast.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Doc/examples/local_blast.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,50 +0,0 @@ -#!/usr/bin/env python -"""Script demonstrating the ability to interact with local BLAST. - -The contents of this script are described more fully in the available -documentation. -""" -# standard library -import os -import sys - -# biopython -from Bio.Blast import NCBIStandalone - -my_blast_db = os.path.join(os.getcwd(), 'at-est', 'a_cds-10-7.fasta') -my_blast_file = os.path.join(os.getcwd(), 'at-est', 'test_blast', - 'sorghum_est-test.fasta') -my_blast_exe = os.path.join(os.getcwd(), 'blast', 'blastall') - -print 'Running blastall...' -blast_out, error_info = NCBIStandalone.blastall(my_blast_exe, 'blastn', - my_blast_db, my_blast_file) - - -b_parser = NCBIStandalone.BlastParser() - -b_iterator = NCBIStandalone.Iterator(blast_out, b_parser) - -while 1: - b_record = b_iterator.next() - - if b_record is None: - break - - E_VALUE_THRESH = 0.04 - for alignment in b_record.alignments: - for hsp in alignment.hsps: - if hsp.expect < E_VALUE_THRESH: - print '****Alignment****' - print 'sequence:', alignment.title - print 'length:', alignment.length - print 'e value:', hsp.expect - - if len(hsp.query) > 75: - dots = '...' - else: - dots = '' - - print hsp.query[0:75] + dots - print hsp.match[0:75] + dots - print hsp.sbjct[0:75] + dots diff -Nru python-biopython-1.62/Doc/examples/make_subsmat.py python-biopython-1.63/Doc/examples/make_subsmat.py --- python-biopython-1.62/Doc/examples/make_subsmat.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Doc/examples/make_subsmat.py 2013-12-05 14:10:43.000000000 +0000 @@ -2,16 +2,19 @@ """Example of generating a substitution matrix from an alignment. """ # standard library +from __future__ import print_function + import sys # Biopython from Bio import SubsMat -from Bio import Clustalw -from Bio.Alphabet import IUPAC +from Bio import AlignIO +from Bio.Alphabet import IUPAC, Gapped from Bio.Align import AlignInfo # get an alignment object from a Clustalw alignment output -c_align = Clustalw.parse_file('protein.aln', IUPAC.protein) +c_align = AlignIO.read('protein.aln', 'clustal', + alphabet=Gapped(IUPAC.protein)) summary_align = AlignInfo.SummaryInfo(c_align) # get a replacement dictionary and accepted replacement matrix @@ -22,10 +25,10 @@ my_arm = SubsMat.SeqMat(replace_info) -print replace_info +print(replace_info) my_lom = SubsMat.make_log_odds_matrix(my_arm) -print 'log_odds_mat:', my_lom +print('log_odds_mat: %s' % my_lom) my_lom.print_mat() diff -Nru python-biopython-1.62/Doc/examples/nmr/simplepredict.py python-biopython-1.63/Doc/examples/nmr/simplepredict.py --- python-biopython-1.62/Doc/examples/nmr/simplepredict.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Doc/examples/nmr/simplepredict.py 2013-12-05 14:10:43.000000000 +0000 @@ -43,6 +43,8 @@ # *********************************************************************** # ***** LOAD MODULES ***** + +from __future__ import print_function import getopt import string import sys @@ -125,10 +127,10 @@ # *-*-* The data table contains the assignment, coordinates and # *-*-* intensity of the resonance. - print string.split(entry1.fields["15N2.L"], ".")[0], "-->", \ + print(string.split(entry1.fields["15N2.L"], ".")[0], "-->", \ string.split(entry1.fields["N15.L"], ".")[0], "\t", \ entry1.fields["H1.P"], entry1.fields["N15.P"], \ - entry1.fields["15N2.P"], entry1.fields["int"] + entry1.fields["15N2.P"], entry1.fields["int"]) noe1 = noe1 + "\012" noe1 = xpktools.replace_entry(noe1, 1, count) diff -Nru python-biopython-1.62/Doc/examples/swissprot.py python-biopython-1.63/Doc/examples/swissprot.py --- python-biopython-1.62/Doc/examples/swissprot.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Doc/examples/swissprot.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,6 +1,13 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Example of connecting with exPASy and parsing SwissProt records.""" # biopython +from __future__ import print_function + from Bio import ExPASy, SwissProt # 'O23729', 'O23730', 'O23731', Chalcone synthases from Orchid @@ -10,10 +17,10 @@ for id in ids: handle = ExPASy.get_sprot_raw(id) record = SwissProt.read(handle) - print "description:", record.description + print("description: %s" % record.description) for ref in record.references: - print "authors:", ref.authors - print "title:", ref.title + print("authors: %s" % ref.authors) + print("title: %s" % ref.title) - print "classification:", record.organism_classification - print + print("classification: %s" % record.organism_classification) + print("") diff -Nru python-biopython-1.62/Doc/examples/www_blast.py python-biopython-1.63/Doc/examples/www_blast.py --- python-biopython-1.62/Doc/examples/www_blast.py 2013-08-28 21:34:02.000000000 +0000 +++ python-biopython-1.63/Doc/examples/www_blast.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,20 +5,23 @@ documentation. """ # standard library -import cStringIO +from __future__ import print_function + +try: + from StringIO import StringIO # Python 2 +except ImportError: + from io import StringIO # Python 3 # biopython +from Bio import SeqIO from Bio.Blast import NCBIWWW -from Bio import Fasta +from Bio.Blast import NCBIXML # first get the sequence we want to parse from a FASTA file -file_for_blast = open('m_cold.fasta', 'r') -f_iterator = Fasta.Iterator(file_for_blast) - -f_record = f_iterator.next() +f_record = next(SeqIO.parse('m_cold.fasta', 'fasta')) -print 'Doing the BLAST and retrieving the results...' -result_handle = NCBIWWW.qblast('blastn', 'nr', f_record) +print('Doing the BLAST and retrieving the results...') +result_handle = NCBIWWW.qblast('blastn', 'nr', f_record.format('fasta')) # save the results for later, in case we want to look at it save_file = open('m_cold_blast.out', 'w') @@ -26,15 +29,12 @@ save_file.write(blast_results) save_file.close() -print 'Parsing the results and extracting info...' -b_parser = NCBIWWW.BlastParser() - -# option 1 -- parse the string directly -# b_record = b_parser.parse_str(blast_results) +print('Parsing the results and extracting info...') +# option 1 -- open the saved file to parse it # option 2 -- create a handle from the string and parse it -string_result_handle = cStringIO.StringIO(blast_results) -b_record = b_parser.parse(string_result_handle) +string_result_handle = StringIO(blast_results) +b_record = NCBIXML.read(string_result_handle) # now get the alignment info for all e values greater than some threshold E_VALUE_THRESH = 0.1 @@ -42,10 +42,10 @@ for alignment in b_record.alignments: for hsp in alignment.hsps: if hsp.expect < E_VALUE_THRESH: - print '****Alignment****' - print 'sequence:', alignment.title - print 'length:', alignment.length - print 'e value:', hsp.expect - print hsp.query[0:75] + '...' - print hsp.match[0:75] + '...' - print hsp.sbjct[0:75] + '...' + print('****Alignment****') + print('sequence: %s' % alignment.title) + print('length: %i' % alignment.length) + print('e value: %f' % hsp.expect) + print(hsp.query[0:75] + '...') + print(hsp.match[0:75] + '...') + print(hsp.sbjct[0:75] + '...') diff -Nru python-biopython-1.62/Doc/install/Installation.html python-biopython-1.63/Doc/install/Installation.html --- python-biopython-1.62/Doc/install/Installation.html 2013-08-28 21:39:05.000000000 +0000 +++ python-biopython-1.63/Doc/install/Installation.html 2013-12-05 14:11:56.000000000 +0000 @@ -1,40 +1,45 @@ - - - -Biopython Installation - - - - - - - - - -

    Biopython Installation

    Brad Chapman, with other contributors

    -

    Contents

    -

    1  Purpose and Assumptions

    For those of you familiar with installing python packages and who don’t + +Biopython Installation + + + + + +

    Biopython Installation

    Brad Chapman, with other contributors

    +

    Contents

    + +

    1  Purpose and Assumptions

    For those of you familiar with installing python packages and who don’t care for following details instructions can try going to -http://biopython.org/wiki/Download, installing -the relevant prerequisites, and Biopython.

    This document describes installing Biopython on your computer. To make +http://biopython.org/wiki/Download, installing +the relevant prerequisites, and Biopython.

    This document describes installing Biopython on your computer. To make things as simple as possible, it basically assumes you have nothing related to Python or Biopython on your computer and want to end up with a working installation of Biopython when you are finished following -through this documentation.

    Biopython should work on just any operating system where Python works, +through this documentation.

    Biopython should work on just any operating system where Python works, so these instructions contain directions for installation on UNIX/Linux, Windows and Macintosh machines. The directions assume that you have permission to install programs on the machine (root access on UNIX and Administrator privileges on Windows or Mac machines). While it is certainly possible to install things without these privileges, this is a serious pain and all the tedious workarounds -aren’t something that I’ll go into very much in this documentation.

    With all this said, hopefully these directions will make it +aren’t something that I’ll go into very much in this documentation.

    With all this said, hopefully these directions will make it straightforward to get Biopython installed on your machine so you can -begin using it as quick as possible.

    -

    2  C Compiler

    Although mostly written in Python, Biopython (and some of its dependencies) +begin using it as quick as possible.

    + +

    2  C Compiler

    Although mostly written in Python, Biopython (and some of its dependencies) include C code, which must be compiled to run. If you are going to be installing from source you will therefore need a C compiler. However, in many cases this can be avoided by using pre-compiled packages (which -is what we recommend on Windows).

    -

    2.1  Unix

    +is what we recommend on Windows).

    + +

    2.1  Unix

    We recommend GCC as the C compiler, this is usually available as part -of the standard set of packages on any Unix or Linux system.

    -

    2.2  Mac OS X

    +of the standard set of packages on any Unix or Linux system.

    + +

    2.2  Mac OS X

    Please install Apple’s XCode suite from the App Store, and then from -the Xcode options also install the optional command line utilities.

    -

    2.3  Windows

    +the Xcode options also install the optional command line utilities.

    + +

    2.3  Windows

    We recommend you install Biopython and its dependencies using the -provided pre-compiled Windows Installers. i.e. You don’t need -a C compiler. See Section 5.4 for more details.

    -

    3  Installing Python

    Python is a interpreting, interactive object-oriented programming +provided pre-compiled Windows Installers. i.e. You don’t need +a C compiler. See Section 5.4 for more details.

    + +

    3  Installing Python

    Python is a interpreting, interactive object-oriented programming language and the home for all things python is -http://www.python.org. Presumedly you have some idea of +http://www.python.org. Presumedly you have some idea of python and what it can do if you are interested in Biopython, but if not the python website contains tons of documentation and reasons to learn -to program in python.

    Biopython is designed to work with Python 2.5 to 2.7 inclusive. +to program in python.

    Biopython is designed to work with Python 2.5 to 2.7 inclusive. Python 2.7 is the final 2.x series release, and this would be our recommended version (assuming all other Python libraries you plan -to use support it).

    Upgrading bug-fix releases (for example. 2.6.1 to 2.6.2) -is incredibly easy and won’t require any re-installation of libraries.

    Upgrading between versions (e.g. 2.6 to 2.7) is more time consuming since you -need to re-install all libraries you have added to python.

    As of Biopython 1.62 we officially support Python 3, specifically Python 3.3. -Python 3.0, 3.1 and 3.2 will not be supported.

    Let’s get started with installation on various platforms.

    -

    3.1  Python installation on UNIX systems

    First, you should go the main python web site and head over to the information +to use support it).

    Upgrading bug-fix releases (for example. 2.6.1 to 2.6.2) +is incredibly easy and won’t require any re-installation of libraries.

    Upgrading between versions (e.g. 2.6 to 2.7) is more time consuming since you +need to re-install all libraries you have added to python.

    As of Biopython 1.62 we officially support Python 3, specifically Python 3.3. +Python 3.0, 3.1 and 3.2 will not be supported.

    Let’s get started with installation on various platforms.

    + +

    3.1  Python installation on UNIX systems

    First, you should go the main python web site and head over to the information page for the latest python release. At the time of this writing the latest stable Python 2 release is 2.7.5, which is available from -http://www.python.org/download/releases/2.7.5/. This page contains links +http://www.python.org/download/releases/2.7.5/. This page contains links to all released files for the given release. For UNIX, we’ll want to use -the tarred and gzipped file, which is called Python-2.7.5.tgz at -the time of this writing.

    Download this file and then unpack it with the following command:

    $ tar -zxvf Python-2.7.5.tar.gz
    -

    Then enter into the created directory:

    $ cd Python-2.7
    -

    Now, start the build process by configuring everything to your system:

    $ ./configure
    -

    Build all of the files with:

    $ make
    -

    Finally, you’ll need to have root permissions on the system and then -install everything:

    $ make install
    -

    If there were no errors and everything worked correctly, you should now -be able to type python at a command prompt and enter into the -python interpreter:

    $ python
    +the tarred and gzipped file, which is called Python-2.7.5.tgz at
    +the time of this writing.

    Download this file and then unpack it with the following command:

    $ tar -zxvf Python-2.7.5.tar.gz
    +

    Then enter into the created directory:

    $ cd Python-2.7
    +

    Now, start the build process by configuring everything to your system:

    $ ./configure
    +

    Build all of the files with:

    $ make
    +

    Finally, you’ll need to have root permissions on the system and then +install everything:

    $ make install
    +

    If there were no errors and everything worked correctly, you should now +be able to type python at a command prompt and enter into the +python interpreter:

    $ python
     Python 2.7.5 (...)
     ...
     Type "help", "copyright", "credits" or "license" for more information.
     >>>
    -

    (The precise version text and details will depend on the version you installed and your operating system.)

    -

    3.1.1  RPM and other Package Manager Installation

    There are a multitude of package manager systems out there for which +

    (The precise version text and details will depend on the version you installed and your operating system.)

    + +

    3.1.1  RPM and other Package Manager Installation

    There are a multitude of package manager systems out there for which python is available. One popular one is the RPM (RedHat Package Manager) system. Each of these package managing systems has its own quirks and tricks and I certainly can’t pretend to understand them all so I won’t -try to describe them all here.

    While these package repositories may include Biopython all ready to install, +try to describe them all here.

    While these package repositories may include Biopython all ready to install, you will typically want to install Biopython from source to get the very -latest version.

    However, there is one general point which it is important to remember +latest version.

    However, there is one general point which it is important to remember when installing from any of these systems: you need to download and install the development packages for python. A number of distributions contain a "basic" python which contains libraries and enough stuff to @@ -178,161 +193,184 @@ libraries necessary to build third-party python applications (like Biopython and it’s dependencies). You’ll need to install these libraries and header files, which are often found in a separate package called -python-devel or something similar.

    -

    3.2  Python installation on Windows

    Installation on Windows is most easily done using handy windows +python-devel or something similar.

    + +

    3.2  Python installation on Windows

    Installation on Windows is most easily done using handy windows installers. As described above in the UNIX section, you should go to the webpage for the current stable version of Python to download this installer. At the current time, you’d go to -http://www.python.org/download/releases/2.7.5/ and download -Python-2.7.5.msi.

    The installer is an executable program, so you only need to double click +http://www.python.org/download/releases/2.7.5/ and download +Python-2.7.5.msi.

    The installer is an executable program, so you only need to double click it to run it. Then just follow the friendly instructions. On all newer Windows machines you’ll need to have Administrator privileges to do this -installation.

    -

    3.3  Python installation on Mac OS X

    Apple includes python on Mac OS X, and while you can use this many people have +installation.

    + +

    3.3  Python installation on Mac OS X

    Apple includes python on Mac OS X, and while you can use this many people have preferred to install the latest version of python as well in parallel. We refer -you to the http://www.python.org for more details, although -otherwise the UNIX instructions apply.

    (See note above about installing XCode to get the compiler tools.)

    -

    4  Installing Biopython dependencies

    Once python is installed, the next step is getting the dependencies +you to the http://www.python.org for more details, although +otherwise the UNIX instructions apply.

    (See note above about installing XCode to get the compiler tools.)

    + +

    4  Installing Biopython dependencies

    Once python is installed, the next step is getting the dependencies for Biopython installed. Since not all functionality is included in the main python installation, Biopython needs some support libraries to save us a lot of work re-writing code that already exists. We try to keep as few dependencies as possible to make installation as easy as -possible.

    -

    4.1  Numerical Python (NumPy) (strongly recommended)

    The Numerical Python distribution is a fast implementation of arrays and +possible.

    + +

    4.1  Numerical Python (NumPy) (strongly recommended)

    The Numerical Python distribution is a fast implementation of arrays and associated array functionality. This is important for a number of Biopython -modules that deal with number processing (e.g. Bio.Cluster and Bio.PDB).

    As of release 1.49, Biopython supports the standard NumPy distribution. +modules that deal with number processing (e.g. Bio.Cluster and Bio.PDB).

    As of release 1.49, Biopython supports the standard NumPy distribution. Previous releases instead used the older Numeric module (which is no -longer being maintained).

    The main web site for NumPy is: -http://numpy.scipy.org/.

    -

    4.1.1  UNIX and Mac OS X systems

    You should download the tar.gz file, and follow the standard python -build process. Note you will need a C compiler installed (see above):

    $ tar -zxvf numpy-1.7.1.tar.gz
    +longer being maintained).

    The main web site for NumPy is: +http://numpy.scipy.org/.

    + +

    4.1.1  UNIX and Mac OS X systems

    You should download the tar.gz file, and follow the standard python +build process. Note you will need a C compiler installed (see above):

    $ tar -zxvf numpy-1.7.1.tar.gz
     $ cd numpy-1.7.1/
     $ python setup.py build
    -

    Once it is built, you should become root, and then install it:

    $ python setup.py install
    -

    One important note if you use an package system and not installing +

    Once it is built, you should become root, and then install it:

    $ python setup.py install
    +

    One important note if you use an package system and not installing NumPy from source: you may also need to install the header files which are not included with some packages. As with the main python distribution, this means -you’ll need to look for something like python-numpy-devel -and make sure to install this as well as the basic package.

    -

    4.1.2  Windows systems

    We recommend using the NumPy provided windows installers for your installed +you’ll need to look for something like python-numpy-devel +and make sure to install this as well as the basic package.

    + +

    4.1.2  Windows systems

    We recommend using the NumPy provided windows installers for your installed version of python. For Python 2.7, at the current time this would be -numpy-1.7.1-win32-superpack-python2.7.exe. You should follow the +numpy-1.7.1-win32-superpack-python2.7.exe. You should follow the now-standard procedure of downloading the installer, double clicking it and then following the installation instructions. As before, -you will need to have administrator permissions to do this.

    -

    4.1.3  Making sure it installed correctly

    To make sure everything went okay during the install, fire up the python -interpreter and ensure you can import NumPy without any errors:

    $ python2.7
    +you will need to have administrator permissions to do this.

    + +

    4.1.3  Making sure it installed correctly

    To make sure everything went okay during the install, fire up the python +interpreter and ensure you can import NumPy without any errors:

    $ python2.7
     Python 2.7.4 (default, Apr  8 2013, 15:01:09) 
     [GCC 4.4.6 20120305 (Red Hat 4.4.6-4)] on linux2
     Type "help", "copyright", "credits" or "license" for more information.
     >>> import numpy
     >>>
    -

    Note that for the import statement, NumPy should be in lower case!

    -

    4.2  ReportLab (optional)

    The ReportLab package is a library for generating PDF documents. It is +

    Note that for the import statement, NumPy should be in lower case!

    + +

    4.2  ReportLab (optional)

    The ReportLab package is a library for generating PDF documents. It is used in the Biopython Graphics modules, which contains basic functionality for drawing biological objects like chromosomes. If you are not planning on using this, installing ReportLab is not necessary. ReportLab in itself is very useful for a number of tasks besides just Biopython, so you may want to check out -http://www.reportlab.org before making your decision.

    The main download page for ReportLab is -http://www.reportlab.org/downloads.html. The ReportLab +http://www.reportlab.org before making your decision.

    The main download page for ReportLab is +http://www.reportlab.org/downloads.html. The ReportLab company has some commercial products as well, but just scroll down their page to the Open Source software section for the base ReportLab -downloads.

    If you want to generate bitmap images, you will also need the ReportLab +downloads.

    If you want to generate bitmap images, you will also need the ReportLab module renderPM. This in turn requires the -Python Imaging Library (PIL).

    -

    4.2.1  UNIX and Mac OS X systems

    For UNIX installs, you should download the tarred and gzipped version of +Python Imaging Library (PIL).

    + +

    4.2.1  UNIX and Mac OS X systems

    For UNIX installs, you should download the tarred and gzipped version of the ReportLab distribution. At the time of this writing, this is called -ReportLab_2_3.tar.gz. First, unpack the distribution and change -into the created directory:

    $ gunzip ReportLab_2_3.tar.gz
    +ReportLab_2_3.tar.gz. First, unpack the distribution and change
    +into the created directory:

    $ gunzip ReportLab_2_3.tar.gz
     $ tar -xvpf ReportLab_2_3.tar
     $ cd reportlab_2_3/
    -

    Once again, ReportLab uses the standard python installation system which +

    Once again, ReportLab uses the standard python installation system which you are probably feeling really comfortable with by now. So, first build -the package:

    $ python setup.py build
    -

    Now become root, and install it:

    $ python setup.py install
    -
    -

    4.2.2  Windows systems

    ReportLab now has graphical windows installers. Nice and easy.

    -

    4.2.3  Making sure it installed correctly

    If reportlab is installed correctly, you should be able to do the -following:

    $ python2.7
    +the package:

    $ python setup.py build
    +

    Now become root, and install it:

    $ python setup.py install
    +
    + +

    4.2.2  Windows systems

    ReportLab now has graphical windows installers. Nice and easy.

    + +

    4.2.3  Making sure it installed correctly

    If reportlab is installed correctly, you should be able to do the +following:

    $ python2.7
     Python 2.7.4 (default, Apr  8 2013, 15:01:09) 
     [GCC 4.4.6 20120305 (Red Hat 4.4.6-4)] on linux2
     Type "help", "copyright", "credits" or "license" for more information.
     >>> from reportlab.graphics import renderPDF
     >>>
    -

    Depending on your version of python and what you have installed, you may +

    Depending on your version of python and what you have installed, you may get the following warning message: -Warn: Python Imaging Library not available. This isn’t anything +Warn: Python Imaging Library not available. This isn’t anything to worry about unless you want to produce bitmap images, since the -Biopython parts that use ReportLab will work just fine without it.

    -

    4.3  Database Access (MySQLdb, ...) (optional)

    The MySQLdb package is a library for accessing MySQL databases. +Biopython parts that use ReportLab will work just fine without it.

    + +

    4.3  Database Access (MySQLdb, ...) (optional)

    The MySQLdb package is a library for accessing MySQL databases. Biopython includes an accessory module, DocSQL, which provides a convenient interface to MySQLdb. If you are not planning on using Bio.DocSQL, installing -MySQLdb is not necessary.

    Additionally, both MySQLdb and psycopg (a PostgreSQL database adaptor) +MySQLdb is not necessary.

    Additionally, both MySQLdb and psycopg (a PostgreSQL database adaptor) can be used for accessing BioSQL databases through Biopython -(see http://biopython.org/wiki/BioSQL). Again if +(see http://biopython.org/wiki/BioSQL). Again if you are not going to use BioSQL, there shouldn’t be any need to install -these modules.

    -

    4.4  mxTextTools (no longer needed)

    Historically this was an important Biopython dependency, used extensively +these modules.

    + +

    4.4  mxTextTools (no longer needed)

    Historically this was an important Biopython dependency, used extensively in a number of parsers. However, we have gradually phased out its use, -and as of Biopython 1.50, mxTextTools is no longer used at all.

    mxTextTools is available along with the entire mx-base system (which +and as of Biopython 1.50, mxTextTools is no longer used at all.

    mxTextTools is available along with the entire mx-base system (which contains a number of other useful utilities as well) and the latest version is available for download at: -http://www.egenix.com/products/python/mxBase/mxTextTools/.

    -

    5  Installing Biopython

    -

    5.1  Obtaining Biopython

    +http://www.egenix.com/products/python/mxBase/mxTextTools/.

    + +

    5  Installing Biopython

    + +

    5.1  Obtaining Biopython

    Biopython’s internet home is at, naturally enough, -http://www.biopython.org. This is the home of all things +http://www.biopython.org. This is the home of all things Biopython, so it is the best place to start looking around. -You have two choices for obtaining Biopython:

    1. Release code – We made available releases on the download page -(http://biopython.org/wiki/Download). +You have two choices for obtaining Biopython:

      1. Release code – We made available releases on the download page +(http://biopython.org/wiki/Download). The releases are also available both as source and as installers (windows installers right now), so you have some choices to pick from -on releases if you prefer not to deal with source code directly.
      2. git – The current working copy of the Biopython sources is available -via git hosted on github – http://github.com/biopython/biopython). +on releases if you prefer not to deal with source code directly.
      3. git – The current working copy of the Biopython sources is available +via git hosted on github – http://github.com/biopython/biopython). Concise instructions for accessing this copy are available at -http://biopython.org/wiki/SourceCode. Our code in git +http://biopython.org/wiki/SourceCode. Our code in git is normally quite stable but there is always the caveat that the code -there is under development.

      Based on which way you choose, you’ll need to follow one of the following installation options. Read on for the platform you are working on.

      -

      5.2  Installing on UNIX and Mac OS X

      -

      -

      5.2.1  Installation from source on UNIX and Mac OS X

      Biopython uses Distutils, the standard python installation package, for +there is under development.

    Based on which way you choose, you’ll need to follow one of the following installation options. Read on for the platform you are working on.

    + +

    5.2  Installing on UNIX and Mac OS X

    +

    + +

    5.2.1  Installation from source on UNIX and Mac OS X

    Biopython uses Distutils, the standard python installation package, for its installation. If you read the install instructions above you are already quite familiar with its workings. Distutils comes standard with -Python 1.6 and beyond.

    Now that we’ve got what we need, let’s get into the installation:

    1. First you need to unpack the distribution. If you got the git version, you are all set to go and can skip on ahead. Otherwise, you’ll need to unpack it. On UN*X machines, a tar.gz package is provided, which you can unpack with tar -xzvpf biopython-X.X.tar.gz. A zip file is also provided for other platforms.
    2. Now that everything is unpacked, move into the biopython* directory (this will just be biopython for git users, and will be biopython-X.X for those using a packaged download).
    3. Now you are ready for your one step install – python setup.py install. This performs the default install, and will put Biopython into the site-packages directory of your python library tree (on my machine this is /usr/local/lib/python2.4/site-packages). You will have to have permissions to write to this directory, so you’ll need to have root access on the machine.
      1. This install requires that you have the python source available. You can check this by looking for Python.h and config.h in some place like /usr/local/include/python2.5. If you installed python with RPMs or +Python 1.6 and beyond.

        Now that we’ve got what we need, let’s get into the installation:

        1. First you need to unpack the distribution. If you got the git version, you are all set to go and can skip on ahead. Otherwise, you’ll need to unpack it. On UN*X machines, a tar.gz package is provided, which you can unpack with tar -xzvpf biopython-X.X.tar.gz. A zip file is also provided for other platforms.
        2. Now that everything is unpacked, move into the biopython* directory (this will just be biopython for git users, and will be biopython-X.X for those using a packaged download).
        3. Now you are ready for your one step install – python setup.py install. This performs the default install, and will put Biopython into the site-packages directory of your python library tree (on my machine this is /usr/local/lib/python2.4/site-packages). You will have to have permissions to write to this directory, so you’ll need to have root access on the machine.
          1. This install requires that you have the python source available. You can check this by looking for Python.h and config.h in some place like /usr/local/include/python2.5. If you installed python with RPMs or some other packaging system, this means you’ll also have to install the header files. This requires installing the python development libraries -as well (normally called something like python-devel-2.5.rpm).
          2. The distutils setup process allows you to do some customization of your install so you don’t have to stick everything in the default location (in case you don’t have write permissions there, or just want to test Biopython out). You have quite a few choices, which are covered in detail in the distutils installation manual (http://www.python.org/sigs/distutils-sig/doc/inst/inst.html), specifically in the Alternative installation section. For example, to install Biopython into your home directory, you need to type python setup.py install --home=$HOME. This will install the package into someplace like $HOME/lib/python2.5/site-packages. You’ll need to subsequently modify the PYTHONPATH environmental variable to include this directory so python will be able to find the installation.
        4. That’s it! Biopython is installed. Wasn’t that easy? Now let’s check and make sure it worked properly. Skip on ahead to section 6.
        -

        5.2.2  Using the Python package index

        Another simple option is to use the Python package index -(http://pypi.python.org/pypi) with the easy_install -command:

        $ easy_install -f http://biopython.org/DIST/ biopython
        -

        If Python is installed in the standard location, you will need administrator -privileges to do this; the sudo command works well:

        $ sudo easy_install -f http://biopython.org/DIST/ biopython
        -
        -

        5.2.3  Installation on Mac OS X using the fink package manager

        Instead of installing from source, on Mac OS X you can also use the fink package manager, see http://fink.sf.net. Fink should take care of downloading the source code and installing all needed packages for Biopython, including Python itself. Once you have installed fink, you can install biopython using:

        $ fink install biopython-pyXX
        -

        where XX is the python version you would like to use. Currently, python 2.4, 2.5, and 2.6 are available through fink on Mac OS X 10.4, so you would have to replace XX with 24, 25, or 26, respectively. Most likely, you will have to enable the unstable tree of fink in order to install the most recent versions of the package, see also this item in the Fink FAQ: http://fink.sourceforge.net/faq/usage-fink.php#unstable. Note that ’unstable’ doesn’t mean that a package won’t work, but only that there has not been feedback to the fink team from users.

        -

        5.2.4  Installation on UNIX systems using RPMs

        Warning. Right now we’re not making RPMs for biopython (because I +as well (normally called something like python-devel-2.5.rpm).

      2. The distutils setup process allows you to do some customization of your install so you don’t have to stick everything in the default location (in case you don’t have write permissions there, or just want to test Biopython out). You have quite a few choices, which are covered in detail in the distutils installation manual (http://www.python.org/sigs/distutils-sig/doc/inst/inst.html), specifically in the Alternative installation section. For example, to install Biopython into your home directory, you need to type python setup.py install --home=$HOME. This will install the package into someplace like $HOME/lib/python2.5/site-packages. You’ll need to subsequently modify the PYTHONPATH environmental variable to include this directory so python will be able to find the installation.
    4. That’s it! Biopython is installed. Wasn’t that easy? Now let’s check and make sure it worked properly. Skip on ahead to section 6.
    + +

    5.2.2  Using the Python package index

    Another simple option is to use the Python package index +(http://pypi.python.org/pypi) with the easy_install +command:

    $ easy_install -f http://biopython.org/DIST/ biopython
    +

    If Python is installed in the standard location, you will need administrator +privileges to do this; the sudo command works well:

    $ sudo easy_install -f http://biopython.org/DIST/ biopython
    +
    + +

    5.2.3  Installation on Mac OS X using the fink package manager

    Instead of installing from source, on Mac OS X you can also use the fink package manager, see http://fink.sf.net. Fink should take care of downloading the source code and installing all needed packages for Biopython, including Python itself. Once you have installed fink, you can install biopython using:

    $ fink install biopython-pyXX
    +

    where XX is the python version you would like to use. Currently, python 2.4, 2.5, and 2.6 are available through fink on Mac OS X 10.4, so you would have to replace XX with 24, 25, or 26, respectively. Most likely, you will have to enable the unstable tree of fink in order to install the most recent versions of the package, see also this item in the Fink FAQ: http://fink.sourceforge.net/faq/usage-fink.php#unstable. Note that ’unstable’ doesn’t mean that a package won’t work, but only that there has not been feedback to the fink team from users.

    + +

    5.2.4  Installation on UNIX systems using RPMs

    Warning. Right now we’re not making RPMs for biopython (because I stopped using an RPM system, basically). If anyone wants to pick this up, or feels especially strongly that they’d like RPMs, please let us -know.

    To simplify things for people running RPM-based systems, biopython can +know.

    To simplify things for people running RPM-based systems, biopython can also be installed via the RPM system. Additionally, this saves the -necessity of having a C compiler to install biopython.

    Installing Biopython from a RPM package should be much the same process as used for other RPMs. If you need general information about how RPMs work, the best place to go is http://www.rpm.org.

    To install it, you should just need to do:

    $ rpm -i your_biopython.rpm
    -

    To see what you installed try doing rpm -qpl your_biopython.rpm which will list all of the installed files.

    RPMs do not install the documentation, tests, or example code, so you might want to also grab a source distribution, so you can use these resources (and also look at the source code if you want to).

    -

    5.3  Installing with a Windows Installer

    Installing things on Windows with the installer should be really easy (hey, that’s why they’ve got graphical installers, right?). You should just need to download the Biopython-version.exe installer from biopython web site. Then you just need to double click and voila, a nice little installer will come up and you can stick the libraries where you need to. No need for a C compiler or anything fancy. You will need to have Administrator privileges on the machine to do the installation.

    This does not install the documentation, tests, example code or source code, so it is probably also a good idea to download the zip file containing this so you can test your installation and learn how to use it.

    -

    5.4  Installing from source on Windows

    -

    This section deals with installing the source (i. e. from git or from a source zip file) on a Windows machine. Much of the information from the UNIX install applies here, so it would be good to read section 5.2 before starting. You will need a suitable C compiler. -What you choose may depend on your version of Python.

    For Python 2.6 we currently use Microsoft’s free VC++ 2008 Express Edition from http://www.microsoft.com/express/download/, installation of this is pretty simple. Then go to the Biopython source directory and run:

    c:\python26\python setup.py build
    +necessity of having a C compiler to install biopython. 

    Installing Biopython from a RPM package should be much the same process as used for other RPMs. If you need general information about how RPMs work, the best place to go is http://www.rpm.org.

    To install it, you should just need to do:

    $ rpm -i your_biopython.rpm
    +

    To see what you installed try doing rpm -qpl your_biopython.rpm which will list all of the installed files.

    RPMs do not install the documentation, tests, or example code, so you might want to also grab a source distribution, so you can use these resources (and also look at the source code if you want to).

    + +

    5.3  Installing with a Windows Installer

    Installing things on Windows with the installer should be really easy (hey, that’s why they’ve got graphical installers, right?). You should just need to download the Biopython-version.exe installer from biopython web site. Then you just need to double click and voila, a nice little installer will come up and you can stick the libraries where you need to. No need for a C compiler or anything fancy. You will need to have Administrator privileges on the machine to do the installation.

    This does not install the documentation, tests, example code or source code, so it is probably also a good idea to download the zip file containing this so you can test your installation and learn how to use it.

    + +

    5.4  Installing from source on Windows

    +

    This section deals with installing the source (i. e. from git or from a source zip file) on a Windows machine. Much of the information from the UNIX install applies here, so it would be good to read section 5.2 before starting. You will need a suitable C compiler. +What you choose may depend on your version of Python.

    For Python 2.6 we currently use Microsoft’s free VC++ 2008 Express Edition from http://www.microsoft.com/express/download/, installation of this is pretty simple. Then go to the Biopython source directory and run:

    c:\python26\python setup.py build
     c:\python26\python setup.py test
     c:\python26\python setup.py install
    -

    For older versions of Python, we use mingw32 installed from cygwin (http://www.cygwin.com). Once everything is setup (which is a bit complicated), you would again get the source, and from that directory run:

    c:\python25\python setup.py build --compiler=mingw32
    +

    For older versions of Python, we use mingw32 installed from cygwin (http://www.cygwin.com). Once everything is setup (which is a bit complicated), you would again get the source, and from that directory run:

    c:\python25\python setup.py build --compiler=mingw32
     c:\python25\python setup.py test
     c:\python25\python setup.py install
    -

    Previously (back on Python 2.0), Brad has also managed to use Borland’s free C++ compiler (available from http://www.inprise.com/bcppbuilder/freecompiler/), but this required extra work.

    Now that you’ve got everything installed, carry on ahead to section 6 to make sure everything worked.

    -

    6  Making sure everything worked

    -

    First, we’ll just do a quick test to make sure Biopython is installed correctly. The most important thing is that python can find the biopython installation. Biopython installs into top level Bio and BioSQL directories, so you’ll want to make sure these directories are located in a directory specified -in your $PYTHONPATH environmental variable. If you used the default install, this shouldn’t be a problem, but if not, you’ll need to set the PYTHONPATH with something like export PYTHONPATH = $PYTHONPATH':/directory/where/you/put/Biopython' (on UNIX). Now that we think we are ready, fire up your python interpreter and follow along with the following code:

    $ python
    +

    Previously (back on Python 2.0), Brad has also managed to use Borland’s free C++ compiler (available from http://www.inprise.com/bcppbuilder/freecompiler/), but this required extra work.

    Now that you’ve got everything installed, carry on ahead to section 6 to make sure everything worked.

    + +

    6  Making sure everything worked

    +

    First, we’ll just do a quick test to make sure Biopython is installed correctly. The most important thing is that python can find the biopython installation. Biopython installs into top level Bio and BioSQL directories, so you’ll want to make sure these directories are located in a directory specified +in your $PYTHONPATH environmental variable. If you used the default install, this shouldn’t be a problem, but if not, you’ll need to set the PYTHONPATH with something like export PYTHONPATH = $PYTHONPATH':/directory/where/you/put/Biopython' (on UNIX). Now that we think we are ready, fire up your python interpreter and follow along with the following code:

    $ python
     Python 2.5 (r25:51908, Nov 23 2006, 18:40:28) 
     [GCC 4.1.1 20061011 (Red Hat 4.1.1-30)] on linux2
     Type "help", "copyright", "credits" or "license" for more information.
    @@ -344,40 +382,42 @@
     >>> new_seq.translate()
     Seq('DQK', HasStopCodon(IUPACProtein(), '*'))
     >>>
    -

    If this worked properly, then it looks like Biopython is in a happy place where python can find it, so now you might want to do some more rigorous tests. The Tests directory inside the distribution contains a number of tests you can run to make sure all of the different parts of biopython are working. These should all work just by running python test_WhateverTheTestIs.py.

    If you didn’t do this earlier, you should also all of our tests. To do this, you just need to be in the source code installation directory and type:

    $ python setup.py test
    -

    You can also run them by typing python run_tests.py in the Tests sub directory. -See the main Tutorial for further details (there is a whole chapter on the test framework).

    If you’ve made it this far, you’ve gotten Biopython installed and running. -Congratulations!

    -

    7  Third Party Tools

    Note that Biopython includes support for interfacing with or parsing the output from a number of third party command line tools. These are not required to install Biopython, but may be of interest. This includes:

    • -NCBI Standalone BLAST, which can used with the Bio.Blast module and parsed with the Bio.SearchIO module. -
    • EMBOSS tools, which can be invoked using the Bio.Emboss module. The Bio.AlignIO module can also parse some alignment formats output by the EMBOSS suite. -
    • ClustalW, which can be parsed using Bio.AlignIO and invoked using the Bio.Align.Applications module. -
    • SIMCOAL2 and FDist tools for population genetics can be used via the Bio.PopGen module. -
    • Bill Pearson’s FASTA tools output can be parsed using the Bio.AlignIO and Bio.SearchIO module. -
    • Wise2 includes the useful tool dnal. -

    See also the listing on http://biopython.org/wiki/Download which should include URLs for these tools, and may also be more up to date.

    -

    8  Notes for installing with non-administrator permissions

    Although I mentioned above that I wouldn’t go much into installing in +

    If this worked properly, then it looks like Biopython is in a happy place where python can find it, so now you might want to do some more rigorous tests. The Tests directory inside the distribution contains a number of tests you can run to make sure all of the different parts of biopython are working. These should all work just by running python test_WhateverTheTestIs.py.

    If you didn’t do this earlier, you should also all of our tests. To do this, you just need to be in the source code installation directory and type:

    $ python setup.py test
    +

    You can also run them by typing python run_tests.py in the Tests sub directory. +See the main Tutorial for further details (there is a whole chapter on the test framework).

    If you’ve made it this far, you’ve gotten Biopython installed and running. +Congratulations!

    + +

    7  Third Party Tools

    Note that Biopython includes support for interfacing with or parsing the output from a number of third party command line tools. These are not required to install Biopython, but may be of interest. This includes:

    • +NCBI Standalone BLAST, which can used with the Bio.Blast module and parsed with the Bio.SearchIO module. +
    • EMBOSS tools, which can be invoked using the Bio.Emboss module. The Bio.AlignIO module can also parse some alignment formats output by the EMBOSS suite. +
    • ClustalW, which can be parsed using Bio.AlignIO and invoked using the Bio.Align.Applications module. +
    • SIMCOAL2 and FDist tools for population genetics can be used via the Bio.PopGen module. +
    • Bill Pearson’s FASTA tools output can be parsed using the Bio.AlignIO and Bio.SearchIO module. +
    • Wise2 includes the useful tool dnal. +

    See also the listing on http://biopython.org/wiki/Download which should include URLs for these tools, and may also be more up to date.

    + +

    8  Notes for installing with non-administrator permissions

    Although I mentioned above that I wouldn’t go much into installing in non-root directories, if you are stuck installing Biopython and it’s dependencies into your home directory here are a -few notes and tricks to keep you going:

    • Building some C modules, such as Bio.Cluster require that +few notes and tricks to keep you going:

      • Building some C modules, such as Bio.Cluster require that the NumPy include files (normally installed in -your_dir/include/python/Numeric) be available. If the +your_dir/include/python/Numeric) be available. If the compiler can’t find these directories you’ll normally get an error -like:
        Bio/Cluster/clustermodule.c:2: NumpPy/arrayobject.h: No such file or directory
        -    

        Followed by a long messy list of syntax errors. To fix this, you’ll -have to edit the setup.py file to let it know where the +like:

        Bio/Cluster/clustermodule.c:2: NumpPy/arrayobject.h: No such file or directory
        +    

        Followed by a long messy list of syntax errors. To fix this, you’ll +have to edit the setup.py file to let it know where the include directories are located. Look for the line in -setup.py that looks like:

            include_dirs=["Bio/Cluster"]
        -    

        and adjust it so that it includes the include directory where the -NumPy libraries were installed:

            include_dirs=["Bio/Cluster", "your_dir/include/python"]
        -    

        Then you should be able to install everything happily.

      Yes, it’s a bit of a mess installing lots of packages in non-standard +setup.py that looks like:

          include_dirs=["Bio/Cluster"]
      +    

      and adjust it so that it includes the include directory where the +NumPy libraries were installed:

          include_dirs=["Bio/Cluster", "your_dir/include/python"]
      +    

      Then you should be able to install everything happily.

    Yes, it’s a bit of a mess installing lots of packages in non-standard locations. The best solution is to talk with your friendly system administrator and get them to assist with the installation of at least the required packages (they are generally quite useful for any python -install) before going ahead with Biopython installation.

    +install) before going ahead with Biopython installation.

    -
    This document was translated from LATEX by -HEVEA.
    - +
    This document was translated from LATEX by +HEVEA.
    + Binary files /tmp/EAI2iEqCCm/python-biopython-1.62/Doc/install/Installation.pdf and /tmp/XMH5G9mdHg/python-biopython-1.63/Doc/install/Installation.pdf differ diff -Nru python-biopython-1.62/NEWS python-biopython-1.63/NEWS --- python-biopython-1.62/NEWS 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/NEWS 2013-12-05 14:10:43.000000000 +0000 @@ -10,7 +10,62 @@ =================================================================== -(In progress, not released yet) Biopython 1.62 +4 December 2013: Biopython 1.63 released. + +This release supports Python 3.3 onwards without conversion via the 2to3 +library. See the Biopython 1.63 beta release notes below for details. Since +the beta release we have made some minor bug fixes and test improvements. + +The restriction enzyme list in Bio.Restriction has been updated to the +December 2013 release of REBASE. + +Additional contributors since the beta: + +Gokcen Eraslan (first contribution) + +=================================================================== + +12 November 2013: Biopython 1.63 beta released. + +This is a beta release for testing purposes, the main reason for a +beta version is the large amount of changes imposed by the removal of +the 2to3 library previously required for the support of Python 3.X. +This was made possible by dropping Python 2.5 (and Jython 2.5). + +This release of Biopython supports Python 2.6 and 2.7, and also Python +3.3. + +The Biopython Tutorial & Cookbook, and the docstring examples in the source +code, now use the Python 3 style print function in place of the Python 2 +style print statement. This language feature is available under Python 2.6 +and 2.7 via: + + from __future__ import print_function + +Similarly we now use the Python 3 style built-in next function in place of +the Python 2 style iterators' .next() method. This language feature is also +available under Python 2.6 and 2.7. + +Many thanks to the Biopython developers and community for making this release +possible, especially the following contributors: + +Chris Mitchell (first contribution) +Christian Brueffer +Eric Talevich +Josha Inglis (first contribution) +Konstantin Tretyakov (first contribution) +Lenna Peterson +Martin Mokrejs +Nigel Delaney (first contribution) +Peter Cock +Sergei Lebedev (first contribution) +Tiago Antao +Wayne Decatur (first contribution) +Wibowo 'Bow' Arindrarto + +=================================================================== + +28 August 2013: Biopython 1.62 released. This is our first release to officially support Python 3, however it is also our final release supporting Python 2.5. Specifically this release diff -Nru python-biopython-1.62/PKG-INFO python-biopython-1.63/PKG-INFO --- python-biopython-1.62/PKG-INFO 2013-08-28 21:40:08.000000000 +0000 +++ python-biopython-1.63/PKG-INFO 2013-12-05 14:13:16.000000000 +0000 @@ -1,6 +1,6 @@ -Metadata-Version: 1.0 +Metadata-Version: 1.1 Name: biopython -Version: 1.62 +Version: 1.63 Summary: Freely available tools for computational molecular biology. Home-page: http://www.biopython.org/ Author: The Biopython Consortium diff -Nru python-biopython-1.62/README python-biopython-1.63/README --- python-biopython-1.62/README 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/README 2013-12-05 14:10:43.000000000 +0000 @@ -6,8 +6,9 @@ Our user-centric documentation is hosted on http://biopython.org including the main Biopython Tutorial and Cookbook: - * HTML - http://biopython.org/DIST/docs/tutorial/Tutorial.html - * PDF - http://biopython.org/DIST/docs/tutorial/Tutorial.pdf + +* HTML - http://biopython.org/DIST/docs/tutorial/Tutorial.html +* PDF - http://biopython.org/DIST/docs/tutorial/Tutorial.pdf This README file is intended primarily for people interested in working with the Biopython source code, either one of the releases from the @@ -30,7 +31,7 @@ ================= To build and install Biopython, download and unzip the source code, go to this -directory at the command line, and type: +directory at the command line, and type:: python setup.py build python setup.py test @@ -49,27 +50,21 @@ Biopython is currently supported and tested on the following Python verions: -- Python 2.5, 2.6, 2.7 -- see http://www.python.org +- Python 2.6, 2.7, 3.3 -- see http://www.python.org This is the currently the primary development platform for Biopython. -- Python 3.3 -- see http://www.python.org - - Under Python 3 our setup.py script calls the 2to3 library automatically - to convert our Python 2 code into Python 3 code. Most of the Biopython - modules are available under Python 3 (but not yet all). - -- PyPy 1.9, 2.0, 2.1 -- see http://www.pypy.org +- PyPy 1.9, 2.0, 2.1, 2.2 -- see http://www.pypy.org Aside from modules with C code or dependent of NumPy, everything should work. PyPy's NumPy reimplementation NumPyPy is still in progress. -- Jython 2.5, 2.7 -- see http://www.jython.org +- Jython 2.7 -- see http://www.jython.org Aside from modules with C code, or dependent on SQLite3 or NumPy, everything should work. -Please note that after Biopython 1.62 we will drop support for Python 2.5 +Please note that Biopython 1.62 was our final release to support Python 2.5 and Jython 2.5. @@ -80,7 +75,7 @@ number of other optional Python dependencies - which can in general be installed after Biopython. -- NumPy, see http://numpy.scipy.org (optional, but strongly recommended) +- NumPy, see http://www.numpy.org (optional, but strongly recommended) This package is only used in the computationally-oriented modules. It is required for Bio.Cluster, Bio.PDB and a few other modules. If you think you might need these modules, then please install NumPy first BEFORE @@ -93,9 +88,8 @@ it later if needed. - matplotlib, see http://matplotlib.org/ (optional) - The Bio.Phylo uses this package to plot phylogenetic trees. As with - ReportLab, you can install this at any time to enable the plotting - functionality. + Bio.Phylo uses this package to plot phylogenetic trees. As with ReportLab, + you can install this at any time to enable the plotting functionality. - networkx, see http://networkx.lanl.gov/ (optional) and pygraphviz or pydot, see http://networkx.lanl.gov/pygraphviz/ and @@ -104,6 +98,10 @@ Again, they are only needed to enable these functions and can be installed later if needed. +- rdflib, see https://github.com/RDFLib/rdflib (optional) + This package is used in the CDAO parser under Bio.Phylo, and can be installed + as needed. + - psycopg2, see http://initd.org/psycopg/ (optional) or PyGreSQL (pgdb), see http://www.pygresql.org/ (optional) These packages are used by BioSQL to access a PostgreSQL database. @@ -127,7 +125,7 @@ from our website (each is specific to a different Python version). Installation from source should be as simple as going to the Biopython -source code directory, and typing: +source code directory, and typing:: python setup.py build python setup.py test @@ -138,8 +136,9 @@ If you need to do additional configuration, e.g. changing the base directory, please type `python setup.py`, or see the documentation here: - * HTML - http://biopython.org/DIST/docs/install/Installation.html - * PDF - http://biopython.org/DIST/docs/install/Installation.pdf + +* HTML - http://biopython.org/DIST/docs/install/Installation.html +* PDF - http://biopython.org/DIST/docs/install/Installation.pdf Testing @@ -147,11 +146,11 @@ Biopython includes a suite of regression tests to check if everything is running correctly. To run the tests, go to the biopython source code -directory and type: +directory and type:: python setup.py test -Do not panic if you see messages warning of skipped tests: +Do not panic if you see messages warning of skipped tests:: test_DocSQL ... skipping. Install MySQLdb if you want to use Bio.DocSQL. @@ -188,8 +187,8 @@ (and hopefully fixed), and if not please do report the bug. We can't fix problems we don't know about ;) - * Old issue tracker: https://redmine.open-bio.org/projects/biopython - * Current issue tracker: https://github.com/biopython/biopython/issues +* Old issue tracker: https://redmine.open-bio.org/projects/biopython +* Current issue tracker: https://github.com/biopython/biopython/issues If you suspect the problem lies within a parser, it is likely that the data format has changed and broken the parsing code. (The text BLAST and GenBank @@ -203,15 +202,15 @@ Finally, you can send a bug report to the bug database or the mailing list at biopython@biopython.org. In the bug report, please let us know: - 1. Which operating system and hardware (32 bit or 64 bit) you are using - 2. Python version - 3. Biopython version (or git version/date) - 4. Traceback that occurs (the full error message) +1. Which operating system and hardware (32 bit or 64 bit) you are using +2. Python version +3. Biopython version (or git commit/date) +4. Traceback that occurs (the full error message) - And also ideally: +And also ideally: - 5. Example code that breaks - 6. A data file that causes the problem +5. Example code that breaks +6. A data file that causes the problem Contributing, Bug Reports @@ -230,17 +229,17 @@ ====================== - README -- This file. -- NEWS -- Release notes and news +- NEWS -- Release notes and news. - LICENSE -- What you can do with the code. - CONTRIB -- An (incomplete) list of people who helped Biopython in - one way or another. + one way or another. - DEPRECATED -- Contains information about modules in Biopython that are - removed or no longer recommended for use, and how to update - code that uses those modules. -- MANIFEST.in -- Tells distutils what files to distribute + removed or no longer recommended for use, and how to update + code that uses those modules. +- MANIFEST.in -- Tells distutils what files to distribute. - setup.py -- Installation file. - Bio/ -- The main code base code. - BioSQL/ -- Code for using Biopython with BioSQL databases. - Doc/ -- Documentation. -- Scripts/ -- Miscellaneous, possibly useful, standalone scripts -- Tests/ -- Regression testing code +- Scripts/ -- Miscellaneous, possibly useful, standalone scripts. +- Tests/ -- Regression testing code including sample data files. diff -Nru python-biopython-1.62/Scripts/GenBank/check_output.py python-biopython-1.63/Scripts/GenBank/check_output.py --- python-biopython-1.62/Scripts/GenBank/check_output.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Scripts/GenBank/check_output.py 2013-12-05 14:10:43.000000000 +0000 @@ -9,11 +9,17 @@ python check_output.py """ # standard modules +from __future__ import print_function + import sys import os -import cStringIO import gzip +try: + from StringIO import StringIO # Python 2 +except ImportError: + from io import StringIO # Python 3 + # biopython from Bio import GenBank @@ -24,10 +30,10 @@ Ths compares the two GenBank record, and will raise an AssertionError if two lines do not match, showing the non-matching lines. """ - good_handle = cStringIO.StringIO(good_record) - test_handle = cStringIO.StringIO(test_record) + good_handle = StringIO(good_record) + test_handle = StringIO(test_record) - while 1: + while True: good_line = good_handle.readline() test_line = test_handle.readline() @@ -50,7 +56,7 @@ def write_format(file): record_parser = GenBank.RecordParser(debug_level=2) - print "Testing GenBank writing for %s..." % os.path.basename(file) + print("Testing GenBank writing for %s..." % os.path.basename(file)) # be able to handle gzipped files if '.gz' in file: cur_handle = gzip.open(file, "r") @@ -62,28 +68,28 @@ iterator = GenBank.Iterator(cur_handle, record_parser) compare_iterator = GenBank.Iterator(compare_handle) - while 1: - cur_record = iterator.next() - compare_record = compare_iterator.next() + while True: + cur_record = next(iterator) + compare_record = next(compare_iterator) if cur_record is None or compare_record is None: break - # print "\tTesting for %s" % cur_record.version + # print("\tTesting for %s" % cur_record.version) output_record = str(cur_record) + "\n" try: do_comparison(compare_record, output_record) - except AssertionError, msg: - print "\tTesting for %s" % cur_record.version - print msg + except AssertionError as msg: + print("\tTesting for %s" % cur_record.version) + print(msg) cur_handle.close() compare_handle.close() if __name__ == "__main__": if len(sys.argv) != 2: - print __doc__ + print(__doc__) sys.exit() write_format(sys.argv[1]) diff -Nru python-biopython-1.62/Scripts/GenBank/check_output_simple.py python-biopython-1.63/Scripts/GenBank/check_output_simple.py --- python-biopython-1.62/Scripts/GenBank/check_output_simple.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Scripts/GenBank/check_output_simple.py 2013-12-05 14:10:43.000000000 +0000 @@ -10,13 +10,15 @@ """ # standard library +from __future__ import print_function + import sys # GenBank stuff to test from Bio import GenBank if len(sys.argv) != 2: - print "Usage ./check_output.py " + print("Usage ./check_output.py ") sys.exit() parser = GenBank.FeatureParser(debug_level=2) @@ -25,28 +27,28 @@ iterator = GenBank.Iterator(handle, parser) -while 1: - cur_record = iterator.next() +while True: + cur_record = next(iterator) if not(cur_record): break - print "***Record" - print "Seq:", cur_record.seq - print "Id:", cur_record.id - print "Name:", cur_record.name - print "Description", cur_record.description - print "Annotations****" - for annotation_key in cur_record.annotations.keys(): + print("***Record") + print("Seq: %s" % cur_record.seq) + print("Id: %s" % cur_record.id) + print("Name: %s" % cur_record.name) + print("Description: %s" % cur_record.description) + print("Annotations****") + for annotation_key in cur_record.annotations: if annotation_key != 'references': - print "Key: %s" % annotation_key - print "Value: %s" % cur_record.annotations[annotation_key] + print("Key: %s" % annotation_key) + print("Value: %s" % cur_record.annotations[annotation_key]) else: - print "References*" + print("References*") for reference in cur_record.annotations[annotation_key]: - print str(reference) - print "Feaures" + print(str(reference)) + print("Feaures") for feature in cur_record.features: - print feature + print(feature) handle.close() diff -Nru python-biopython-1.62/Scripts/GenBank/find_parser_problems.py python-biopython-1.63/Scripts/GenBank/find_parser_problems.py --- python-biopython-1.62/Scripts/GenBank/find_parser_problems.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Scripts/GenBank/find_parser_problems.py 2013-12-05 14:10:43.000000000 +0000 @@ -8,6 +8,8 @@ find_parser_problems.py """ # standard library +from __future__ import print_function + import sys # GenBank @@ -16,7 +18,7 @@ verbose = 0 if len(sys.argv) != 2: - print "Usage ./find_parser_problems " + print("Usage ./find_parser_problems ") sys.exit() feature_parser = GenBank.FeatureParser(debug_level=0) @@ -25,31 +27,31 @@ handle = open(sys.argv[1], 'r') iterator = GenBank.Iterator(handle, parser, has_header=1) -while 1: +while True: have_record = 0 while have_record == 0: try: - cur_record = iterator.next() + cur_record = next(iterator) have_record = 1 - except GenBank.ParserFailureError, msg: - print "Parsing Problem:", msg + except GenBank.ParserFailureError as msg: + print("Parsing Problem: %s" % msg) sys.exit() if cur_record is None: break - print "Successfully parsed record", cur_record.id + print("Successfully parsed record %s" % cur_record.id) if verbose: - print "***Record" - print "Seq:", cur_record.seq - print "Id:", cur_record.id - print "Name:", cur_record.name - print "Description", cur_record.description - print "Annotations", cur_record.annotations - print "Feaures" + print("***Record") + print("Seq: %s" % cur_record.seq) + print("Id: %s" % cur_record.id) + print("Name: %s" % cur_record.name) + print("Description: %s" % cur_record.description) + print("Annotations: %s" % cur_record.annotations) + print("Feaures") for feature in cur_record.features: - print feature + print(feature) handle.close() diff -Nru python-biopython-1.62/Scripts/PDB/generate_three_to_one_dict.py python-biopython-1.63/Scripts/PDB/generate_three_to_one_dict.py --- python-biopython-1.62/Scripts/PDB/generate_three_to_one_dict.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Scripts/PDB/generate_three_to_one_dict.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,17 +5,21 @@ # license. Please see the LICENSE file that should have been included # as part of this package. -""" +"""Download PDB Chemical Component Dictionary and generate dict. + Download and parse PDB Chemical Component Dictionary, then write out dict for to_one_letter_code. """ +from __future__ import print_function + import gzip import inspect import os -import urllib import warnings +from Bio._py3k import urlopen as _urlopen + url = "ftp://ftp.wwpdb.org/pub/pdb/data/monomers/components.cif.gz" # extract name of gzip file @@ -23,10 +27,10 @@ # extract name of cif file (split by sep, remove last, rejoin) cifname = os.extsep.join(gzname.split(os.extsep)[:-1]) -url_handle = urllib.urlopen(url) +url_handle = urlopen(url) with open(gzname, 'wb') as gzh: - print "Downloading file... (approx. 29 MB)" + print("Downloading file... (approx. 29 MB)") while True: data = url_handle.read(1024) if len(data) == 0: @@ -42,7 +46,7 @@ # write extracted file to disk (not necessary) #with open(cifname, 'wb') as cifh: - #print "Extracting file..." + #print("Extracting file...") #cifh.write(fh.read()) # The following code written by Hongbo Zhu diff -Nru python-biopython-1.62/Scripts/Performance/biosql_performance_load.py python-biopython-1.63/Scripts/Performance/biosql_performance_load.py --- python-biopython-1.62/Scripts/Performance/biosql_performance_load.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Scripts/Performance/biosql_performance_load.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,6 +1,8 @@ #/usr/bin/env python """Small script to test timing of loading records into a BioSQL database. """ +from __future__ import print_function + import time # set up the connection from Bio import GenBank @@ -27,6 +29,6 @@ num_records = db.load(iterator) end_time = time.time() elapsed_time = end_time - start_time -print "Loading" -print "\tDid %s records in %s seconds for\n\t%f records per second" % \ - (num_records, elapsed_time, float(num_records) / float(elapsed_time)) +print("Loading") +print("\tDid %s records in %s seconds for\n\t%f records per second" % \ + (num_records, elapsed_time, float(num_records) / float(elapsed_time))) diff -Nru python-biopython-1.62/Scripts/Performance/biosql_performance_read.py python-biopython-1.63/Scripts/Performance/biosql_performance_read.py --- python-biopython-1.62/Scripts/Performance/biosql_performance_read.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Scripts/Performance/biosql_performance_read.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,6 +1,8 @@ #/usr/bin/env python """Small script to test timing of getting records from a BioSQL database. """ +from __future__ import print_function + import time # set up the connection from BioSQL import BioSeqDatabase @@ -10,24 +12,25 @@ # -- do the fasta-only timing part start_time = time.time() -all_records = db.items() -for junk_id, record in all_records: +num_records = 0 +for junk_id, record in db.items(): + num_records += 1 sequence = record.seq.data d = record.description i = record.id n = record.name end_time = time.time() -num_records = len(all_records) elapsed_time = end_time - start_time -print "Fasta" -print "\tDid %s records in %s seconds for\n\t%f records per second" % \ - (num_records, elapsed_time, float(num_records) / float(elapsed_time)) +print("Fasta") +print("\tDid %s records in %s seconds for\n\t%f records per second" % \ + (num_records, elapsed_time, float(num_records) / float(elapsed_time))) # -- do the "EMBL" timing part start_time = time.time() -all_records = db.items() -for junk_id, record in all_records: +num_records = 0 +for junk_id, record in db.items(): + num_records += 1 sequence = record.seq.data d = record.description i = record.id @@ -38,8 +41,7 @@ species = record.species keywords = record.keywords end_time = time.time() -num_records = len(all_records) elapsed_time = end_time - start_time -print "EMBL" -print "\tDid %s records in %s seconds for\n\t%f records per second" % \ - (num_records, elapsed_time, float(num_records) / float(elapsed_time)) +print("EMBL") +print("\tDid %s records in %s seconds for\n\t%f records per second" % \ + (num_records, elapsed_time, float(num_records) / float(elapsed_time))) diff -Nru python-biopython-1.62/Scripts/Restriction/ranacompiler.py python-biopython-1.63/Scripts/Restriction/ranacompiler.py --- python-biopython-1.62/Scripts/Restriction/ranacompiler.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Scripts/Restriction/ranacompiler.py 2013-12-05 14:10:43.000000000 +0000 @@ -6,10 +6,1001 @@ # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. +# +# this script is used to produce the dictionary which will contains the data +# about the restriction enzymes from the Emboss/Rebase data files +# namely +# emboss_e.### (description of the sites), +# emboss_r.### (origin, methylation, references) +# emboss_s.### (suppliers) +# where ### is a number of three digits : 1 for the year two for the month +# +# very dirty implementation but it does the job, so... +# Not very quick either but you are not supposed to use it frequently. +# +# The results are stored in +# path/to/site-packages/Bio/Restriction/Restriction_Dictionary.py +# the file contains two dictionary: +# 'rest_dict' which contains the data for the enzymes +# and +# 'suppliers' which map the name of the suppliers to their abbreviation. +# +"""Convert a series of Rebase files into a Restriction_Dictionary.py module. + +The Rebase files are in the emboss format: + + emboss_e.### -> contains information about the restriction sites. + emboss_r.### -> contains general information about the enzymes. + emboss_s.### -> contains information about the suppliers. + +Here ### is the 3 digit number REBASE release number (e.g. 312). The first +digit is the last digit of the year (e.g. 3 for 2013) and the two last the +month (e.g. 12 for December). + +There files are available by FTP from ftp://ftp.neb.com/pub/rebase/ which +should allow automated fetching (the the update code and RanaConfig.py). +In addition there are links on this HTML page which requires manual download +and renaming of the files: http://rebase.neb.com/rebase/rebase.f37.html + +This Python file is intended to be used via the scripts Scripts/Restriction/*.py +only. +""" + +from __future__ import print_function + +from Bio._py3k import input as _input + +import os +import itertools +import time import sys +import shutil import optparse -from Bio.Restriction._Update.RestrictionCompiler import DictionaryBuilder +from functools import reduce + +from Bio.Seq import Seq +from Bio.Alphabet import generic_dna + +import Bio.Restriction.Restriction +from Bio.Restriction.Restriction import AbstractCut, RestrictionType, NoCut, OneCut +from Bio.Restriction.Restriction import TwoCuts, Meth_Dep, Meth_Undep, Palindromic +from Bio.Restriction.Restriction import NonPalindromic, Unknown, Blunt, Ov5, Ov3 +from Bio.Restriction.Restriction import NotDefined, Defined, Ambiguous +from Bio.Restriction.Restriction import Commercially_available, Not_available + +import Bio.Restriction.RanaConfig as config +from Bio.Restriction._Update.Update import RebaseUpdate +from Bio.Restriction.Restriction import * + +dna_alphabet = {'A':'A', 'C':'C', 'G':'G', 'T':'T', + 'R':'AG', 'Y':'CT', 'W':'AT', 'S':'CG', 'M':'AC', 'K':'GT', + 'H':'ACT', 'B':'CGT', 'V':'ACG', 'D':'AGT', + 'N':'ACGT', + 'a': 'a', 'c': 'c', 'g': 'g', 't': 't', + 'r':'ag', 'y':'ct', 'w':'at', 's':'cg', 'm':'ac', 'k':'gt', + 'h':'act', 'b':'cgt', 'v':'acg', 'd':'agt', + 'n':'acgt'} + + +complement_alphabet = {'A':'T', 'T':'A', 'C':'G', 'G':'C','R':'Y', 'Y':'R', + 'W':'W', 'S':'S', 'M':'K', 'K':'M', 'H':'D', 'D':'H', + 'B':'V', 'V':'B', 'N':'N','a':'t', 'c':'g', 'g':'c', + 't':'a', 'r':'y', 'y':'r', 'w':'w', 's':'s','m':'k', + 'k':'m', 'h':'d', 'd':'h', 'b':'v', 'v':'b', 'n':'n'} +enzymedict = {} +suppliersdict = {} +classdict = {} +typedict = {} + + +class OverhangError(ValueError): + """Exception for dealing with overhang.""" + pass + + +def BaseExpand(base): + """BaseExpand(base) -> string. + + given a degenerated base, returns its meaning in IUPAC alphabet. + + i.e: + b= 'A' -> 'A' + b= 'N' -> 'ACGT' + etc...""" + base = base.upper() + return dna_alphabet[base] + + +def regex(site): + """regex(site) -> string. + + Construct a regular expression from a DNA sequence. + i.e.: + site = 'ABCGN' -> 'A[CGT]CG.'""" + reg_ex = str(site) + for base in reg_ex: + if base in ('A', 'T', 'C', 'G', 'a', 'c', 'g', 't'): + pass + if base in ('N', 'n'): + reg_ex = '.'.join(reg_ex.split('N')) + reg_ex = '.'.join(reg_ex.split('n')) + if base in ('R', 'Y', 'W', 'M', 'S', 'K', 'H', 'D', 'B', 'V'): + expand = '['+ str(BaseExpand(base))+']' + reg_ex = expand.join(reg_ex.split(base)) + return reg_ex + + +def is_palindrom(sequence): + """is_palindrom(sequence) -> bool. + + True is the sequence is a palindrom. + sequence is a Seq object.""" + return str(sequence) == str(sequence.reverse_complement()) + + +def LocalTime(): + """LocalTime() -> string. + + LocalTime calculate the extension for emboss file for the current year and + month.""" + t = time.gmtime() + year = str(t.tm_year)[-1] + month = str(t.tm_mon) + if len(month) == 1: + month = '0' + month + return year+month + + +class newenzyme(object): + """construct the attributes of the enzyme corresponding to 'name'.""" + def __init__(cls, name): + cls.opt_temp = 37 + cls.inact_temp = 65 + cls.substrat = 'DNA' + target = enzymedict[name] + cls.site = target[0] + cls.size = target[1] + cls.suppl = tuple(target[9]) + cls.freq = target[11] + cls.ovhg = target[13] + cls.ovhgseq = target[14] + cls.bases = () + # + # Is the site palindromic? + # Important for the way the DNA is search for the site. + # Palindromic sites needs to be looked for only over 1 strand. + # Non Palindromic needs to be search for on the reverse complement + # as well. + # + if target[10]: + cls.bases += ('Palindromic',) + else: + cls.bases += ('NonPalindromic',) + # + # Number of cut the enzyme produce. + # 0 => unknown, the enzyme has not been fully characterised. + # 2 => 1 cut, (because one cut is realised by cutting 2 strands + # 4 => 2 cuts, same logic. + # A little bit confusing but it is the way EMBOSS/Rebase works. + # + if not target[2]: + # + # => undefined enzymes, nothing to be done. + # + cls.bases += ('NoCut', 'Unknown', 'NotDefined') + cls.fst5 = None + cls.fst3 = None + cls.scd5 = None + cls.scd3 = None + cls.ovhg = None + cls.ovhgseq = None + else: + # + # we will need to calculate the overhang. + # + if target[2] == 2: + cls.bases += ('OneCut',) + cls.fst5 = target[4] + cls.fst3 = target[5] + cls.scd5 = None + cls.scd3 = None + else: + cls.bases += ('TwoCuts',) + cls.fst5 = target[4] + cls.fst3 = target[5] + cls.scd5 = target[6] + cls.scd3 = target[7] + # + # Now, prepare the overhangs which will be added to the DNA + # after the cut. + # Undefined enzymes will not be allowed to catalyse, + # they are not available commercially anyway. + # I assumed that if an enzyme cut twice the overhang will be of + # the same kind. The only exception is HaeIV. I do not deal + # with that at the moment (ie I don't include it, + # need to be fixed). + # They generally cut outside their recognition site and + # therefore the overhang is undetermined and dependent of + # the DNA sequence upon which the enzyme act. + # + if target[3]: + # + # rebase field for blunt: blunt == 1, other == 0. + # The enzyme is blunt. No overhang. + # + cls.bases += ('Blunt', 'Defined') + cls.ovhg = 0 + elif isinstance(cls.ovhg, int): + # + # => overhang is sequence dependent + # + if cls.ovhg > 0: + # + # 3' overhang, ambiguous site (outside recognition site + # or site containing ambiguous bases (N, W, R,...) + # + cls.bases += ('Ov3', 'Ambiguous') + elif cls.ovhg < 0: + # + # 5' overhang, ambiguous site (outside recognition site + # or site containing ambiguous bases (N, W, R,...) + # + cls.bases += ('Ov5', 'Ambiguous') + else: + # + # cls.ovhg is a string => overhang is constant + # + if cls.fst5 - (cls.fst3 + cls.size) < 0: + cls.bases += ('Ov5', 'Defined') + cls.ovhg = - len(cls.ovhg) + else: + cls.bases += ('Ov3', 'Defined') + cls.ovhg = + len(cls.ovhg) + # + # Next class : sensibility to methylation. + # Set by EmbossMixer from emboss_r.txt file + # Not really methylation dependent at the moment, stands rather for + # 'is the site methylable?'. + # Proper methylation sensibility has yet to be implemented. + # But the class is there for further development. + # + if target[8]: + cls.bases += ('Meth_Dep', ) + cls.compsite = target[12] + else: + cls.bases += ('Meth_Undep',) + cls.compsite = target[12] + # + # Next class will allow to select enzymes in function of their + # suppliers. Not essential but can be useful. + # + if cls.suppl: + cls.bases += ('Commercially_available', ) + else: + cls.bases += ('Not_available', ) + cls.bases += ('AbstractCut', 'RestrictionType') + cls.__name__ = name + cls.results = None + cls.dna = None + cls.__bases__ = cls.bases + cls.charac = (cls.fst5, cls.fst3, cls.scd5, cls.scd3, cls.site) + if not target[2] and cls.suppl: + supp = ', '.join(suppliersdict[s][0] for s in cls.suppl) + print('WARNING : It seems that %s is both commercially available\ + \n\tand its characteristics are unknown. \ + \n\tThis seems counter-intuitive.\ + \n\tThere is certainly an error either in ranacompiler or\ + \n\tin this REBASE release.\ + \n\tThe supplier is : %s.' % (name, supp)) + return + + +class TypeCompiler(object): + """Build the different types possible for Restriction Enzymes""" + + def __init__(self): + """TypeCompiler() -> new TypeCompiler instance.""" + pass + + def buildtype(self): + """TC.buildtype() -> generator. + + build the new types that will be needed for constructing the + restriction enzymes.""" + baT = (AbstractCut, RestrictionType) + cuT = (NoCut, OneCut, TwoCuts) + meT = (Meth_Dep, Meth_Undep) + paT = (Palindromic, NonPalindromic) + ovT = (Unknown, Blunt, Ov5, Ov3) + deT = (NotDefined, Defined, Ambiguous) + coT = (Commercially_available, Not_available) + All = (baT, cuT, meT, paT, ovT, deT, coT) + # + # Now build the types. Only the most obvious are left out. + # Modified even the most obvious are not so obvious. + # emboss_*.403 AspCNI is unknown and commercially available. + # So now do not remove the most obvious. + # + types = [(p, c, o, d, m, co, baT[0], baT[1]) + for p in paT for c in cuT for o in ovT + for d in deT for m in meT for co in coT] + n= 1 + for ty in types: + dct = {} + for t in ty: + dct.update(t.__dict__) + # + # here we need to customize the dictionary. + # i.e. types deriving from OneCut have always scd5 and scd3 + # equal to None. No need therefore to store that in a specific + # enzyme of this type. but it then need to be in the type. + # + dct['results'] = [] + dct['substrat'] = 'DNA' + dct['dna'] = None + if t == NoCut: + dct.update({'fst5':None,'fst3':None, + 'scd5':None,'scd3':None, + 'ovhg':None,'ovhgseq':None}) + elif t == OneCut: + dct.update({'scd5':None, 'scd3':None}) + + class klass(type): + def __new__(cls): + return type.__new__(cls, 'type%i'%n, ty, dct) + + def __init__(cls): + super(klass, cls).__init__('type%i'%n, ty, dct) + + yield klass() + n+=1 + +start = '\n\ +#!/usr/bin/env python\n\ +#\n\ +# Restriction Analysis Libraries.\n\ +# Copyright (C) 2004. Frederic Sohm.\n\ +#\n\ +# This code is part of the Biopython distribution and governed by its\n\ +# license. Please see the LICENSE file that should have been included\n\ +# as part of this package.\n\ +#\n\ +# This file is automatically generated - do not edit it by hand! Instead,\n\ +# use the tool Scripts/Restriction/ranacompiler.py which in turn uses\n\ +# Bio/Restriction/_Update/RestrictionCompiler.py\n\ +#\n\ +# The following dictionaries used to be defined in one go, but that does\n\ +# not work on Jython due to JVM limitations. Therefore we break this up\n\ +# into steps, using temporary functions to avoid the JVM limits.\n\ +\n\n' + + +class DictionaryBuilder(object): + + def __init__(self, e_mail='', ftp_proxy=''): + """DictionaryBuilder([e_mail[, ftp_proxy]) -> DictionaryBuilder instance. + + If the emboss files used for the construction need to be updated this + class will download them if the ftp connection is correctly set. + either in RanaConfig.py or given at run time. + + e_mail is the e-mail address used as password for the anonymous + ftp connection. + + proxy is the ftp_proxy to use if any.""" + self.rebase_pass = e_mail or config.Rebase_password + self.proxy = ftp_proxy or config.ftp_proxy + + def build_dict(self): + """DB.build_dict() -> None. + + Construct the dictionary and build the files containing the new + dictionaries.""" + # + # first parse the emboss files. + # + emboss_e, emboss_r, emboss_s = self.lastrebasefile() + # + # the results will be stored into enzymedict. + # + self.information_mixer(emboss_r, emboss_e, emboss_s) + emboss_r.close() + emboss_e.close() + emboss_s.close() + # + # we build all the possible type + # + tdct = {} + for klass in TypeCompiler().buildtype(): + exec(klass.__name__ +'= klass') + exec("tdct['"+klass.__name__+"'] = klass") + + # + # Now we build the enzymes from enzymedict + # and store them in a dictionary. + # The type we will need will also be stored. + # + + for name in enzymedict: + # + # the class attributes first: + # + cls = newenzyme(name) + # + # Now select the right type for the enzyme. + # + bases = cls.bases + clsbases = tuple([eval(x) for x in bases]) + typestuff = '' + for n, t in tdct.items(): + # + # if the bases are the same. it is the right type. + # create the enzyme and remember the type + # + if t.__bases__ == clsbases: + typestuff = t + typename = t.__name__ + continue + # + # now we build the dictionaries. + # + dct = dict(cls.__dict__) + del dct['bases'] + del dct['__bases__'] + del dct['__name__']# no need to keep that, it's already in the type. + classdict[name] = dct + + commonattr = ['fst5', 'fst3', 'scd5', 'scd3', 'substrat', + 'ovhg', 'ovhgseq', 'results', 'dna'] + if typename in typedict: + typedict[typename][1].append(name) + else: + enzlst= [] + tydct = dict(typestuff.__dict__) + tydct = dict([(k, v) for k, v in tydct.items() if k in commonattr]) + enzlst.append(name) + typedict[typename] = (bases, enzlst) + for letter in cls.__dict__['suppl']: + supplier = suppliersdict[letter] + suppliersdict[letter][1].append(name) + if not classdict or not suppliersdict or not typedict: + print('One of the new dictionaries is empty.') + print('Check the integrity of the emboss file before continuing.') + print('Update aborted.') + sys.exit() + # + # How many enzymes this time? + # + print('\nThe new database contains %i enzymes.\n' % len(classdict)) + # + # the dictionaries are done. Build the file + # + #update = config.updatefolder + + update = os.getcwd() + with open(os.path.join(update, 'Restriction_Dictionary.py'), 'w') as results: + print('Writing the dictionary containing the new Restriction classes...') + results.write(start) + results.write('rest_dict = {}\n') + for name in sorted(classdict) : + results.write("def _temp():\n") + results.write(" return {\n") + for key, value in classdict[name].items() : + results.write(" %s: %s,\n" % (repr(key), repr(value))) + results.write(" }\n") + results.write("rest_dict[%s] = _temp()\n" % repr(name)) + results.write("\n") + print('OK.\n') + print('Writing the dictionary containing the suppliers data...') + results.write('suppliers = {}\n') + for name in sorted(suppliersdict) : + results.write("def _temp():\n") + results.write(" return (\n") + for value in suppliersdict[name] : + results.write(" %s,\n" % repr(value)) + results.write(" )\n") + results.write("suppliers[%s] = _temp()\n" % repr(name)) + results.write("\n") + print('OK.\n') + print('Writing the dictionary containing the Restriction types...') + results.write('typedict = {}\n') + for name in sorted(typedict) : + results.write("def _temp():\n") + results.write(" return (\n") + for value in typedict[name] : + results.write(" %s,\n" % repr(value)) + results.write(" )\n") + results.write("typedict[%s] = _temp()\n" % repr(name)) + results.write("\n") + #I had wanted to do "del _temp" at each stage (just for clarity), but + #that pushed the code size just over the Jython JVM limit. We include + #one the final "del _temp" to clean up the namespace. + results.write("del _temp\n") + results.write("\n") + print('OK.\n') + return + + def install_dict(self): + """DB.install_dict() -> None. + + Install the newly created dictionary in the site-packages folder. + + May need super user privilege on some architectures.""" + print('\n ' +'*'*78 + ' \n') + print('\n\t\tInstalling Restriction_Dictionary.py') + try: + import Bio.Restriction.Restriction_Dictionary as rd + except ImportError: + print('\ + \n Unable to locate the previous Restriction_Dictionary.py module\ + \n Aborting installation.') + sys.exit() + # + # first save the old file in Updates + # + old = os.path.join(os.path.split(rd.__file__)[0], + 'Restriction_Dictionary.py') + #update_folder = config.updatefolder + update_folder = os.getcwd() + shutil.copyfile(old, os.path.join(update_folder, + 'Restriction_Dictionary.old')) + # + # Now test and install. + # + new = os.path.join(update_folder, 'Restriction_Dictionary.py') + try: + exec(compile(open(new).read(), new, 'exec')) + print('\ + \n\tThe new file seems ok. Proceeding with the installation.') + except SyntaxError: + print('\ + \n The new dictionary file is corrupted. Aborting the installation.') + return + try: + shutil.copyfile(new, old) + print('\n\t Everything ok. If you need it a version of the old\ + \n\t dictionary have been saved in the Updates folder under\ + \n\t the name Restriction_Dictionary.old.') + print('\n ' +'*'*78 + ' \n') + except IOError: + print('\n ' +'*'*78 + ' \n') + print('\ + \n\t WARNING : Impossible to install the new dictionary.\ + \n\t Are you sure you have write permission to the folder :\n\ + \n\t %s ?\n\n' % os.path.split(old)[0]) + return self.no_install() + return + + def no_install(self): + """BD.no_install() -> None. + + build the new dictionary but do not install the dictionary.""" + print('\n ' +'*'*78 + '\n') + #update = config.updatefolder + try: + import Bio.Restriction.Restriction_Dictionary as rd + except ImportError: + print('\ + \n Unable to locate the previous Restriction_Dictionary.py module\ + \n Aborting installation.') + sys.exit() + # + # first save the old file in Updates + # + old = os.path.join(os.path.split(rd.__file__)[0], + 'Restriction_Dictionary.py') + update = os.getcwd() + shutil.copyfile(old, os.path.join(update, 'Restriction_Dictionary.old')) + places = update, os.path.split(Bio.Restriction.Restriction.__file__)[0] + print("\t\tCompilation of the new dictionary : OK.\ + \n\t\tInstallation : No.\n\ + \n You will find the newly created 'Restriction_Dictionary.py' file\ + \n in the folder : \n\ + \n\t%s\n\ + \n Make a copy of 'Restriction_Dictionary.py' and place it with \ + \n the other Restriction libraries.\n\ + \n note : \ + \n This folder should be :\n\ + \n\t%s\n" % places) + print('\n ' +'*'*78 + '\n') + return + + def lastrebasefile(self): + """BD.lastrebasefile() -> None. + + Check the emboss files are up to date and download them if they are not. + """ + embossnames = ('emboss_e', 'emboss_r', 'emboss_s') + # + # first check if we have the last update: + # + emboss_now = ['.'.join((x, LocalTime())) for x in embossnames] + update_needed = False + #dircontent = os.listdir(config.Rebase) # local database content + dircontent = os.listdir(os.getcwd()) + base = os.getcwd() # added for biopython current directory + for name in emboss_now: + if name in dircontent: + pass + else: + update_needed = True + + if not update_needed: + # + # nothing to be done + # + print('\n Using the files : %s'% ', '.join(emboss_now)) + return tuple(open(os.path.join(base, n)) for n in emboss_now) + else: + # + # may be download the files. + # + print('\n The rebase files are more than one month old.\ + \n Would you like to update them before proceeding?(y/n)') + r = _input(' update [n] >>> ') + if r in ['y', 'yes', 'Y', 'Yes']: + updt = RebaseUpdate(self.rebase_pass, self.proxy) + updt.openRebase() + updt.getfiles() + updt.close() + print('\n Update complete. Creating the dictionaries.\n') + print('\n Using the files : %s'% ', '.join(emboss_now)) + return tuple(open(os.path.join(base, n)) for n in emboss_now) + else: + # + # we will use the last files found without updating. + # But first we check we have some file to use. + # + class NotFoundError(Exception): + pass + for name in embossnames: + try: + for file in dircontent: + if file.startswith(name): + break + else: + pass + raise NotFoundError + except NotFoundError: + print("\nNo %s file found. Upgrade is impossible.\n"%name) + sys.exit() + continue + pass + # + # now find the last file. + # + last = [0] + for file in dircontent: + fs = file.split('.') + try: + if fs[0] in embossnames and int(fs[1]) > int(last[-1]): + if last[0]: + last.append(fs[1]) + else: + last[0] = fs[1] + else: + continue + except ValueError: + continue + last.sort() + last = last[::-1] + if int(last[-1]) < 100: + last[0], last[-1] = last[-1], last[0] + + for number in last: + files = [(name, name+'.%s'%number) for name in embossnames] + strmess = '\nLast EMBOSS files found are :\n' + try: + for name, file in files: + if os.path.isfile(os.path.join(base, file)): + strmess += '\t%s.\n'%file + else: + raise ValueError + print(strmess) + emboss_e = open(os.path.join(base, 'emboss_e.%s'%number), 'r') + emboss_r = open(os.path.join(base, 'emboss_r.%s'%number), 'r') + emboss_s = open(os.path.join(base, 'emboss_s.%s'%number), 'r') + return emboss_e, emboss_r, emboss_s + except ValueError: + continue + + def parseline(self, line): + line = [line[0]]+[line[1].upper()]+[int(i) for i in line[2:9]]+line[9:] + name = line[0].replace("-", "_").replace(".", "_") + site = line[1] # sequence of the recognition site + dna = Seq(site, generic_dna) + size = line[2] # size of the recognition site + # + # Calculate the overhang. + # + fst5 = line[5] # first site sense strand + fst3 = line[6] # first site antisense strand + scd5 = line[7] # second site sense strand + scd3 = line[8] # second site antisense strand + + # + # the overhang is the difference between the two cut + # + ovhg1 = fst5 - fst3 + ovhg2 = scd5 - scd3 + + # + # 0 has the meaning 'do not cut' in rebase. So we get short of 1 + # for the negative numbers so we add 1 to negative sites for now. + # We will deal with the record later. + # + + if fst5 < 0: + fst5 += 1 + if fst3 < 0: + fst3 += 1 + if scd5 < 0: + scd5 += 1 + if scd3 < 0: + scd3 += 1 + + if ovhg2 != 0 and ovhg1 != ovhg2: + # + # different length of the overhang of the first and second cut + # it's a pain to deal with and at the moment it concerns only + # one enzyme which is not commercially available (HaeIV). + # So we don't deal with it but we check the progression + # of the affair. + # Should HaeIV become commercially available or other similar + # new enzymes be added, this might be modified. + # + print('\ + \nWARNING : %s cut twice with different overhang length each time.\ + \n\tUnable to deal with this behaviour. \ + \n\tThis enzyme will not be included in the database. Sorry.' %name) + print('\tChecking...') + raise OverhangError + if 0 <= fst5 <= size and 0 <= fst3 <= size: + # + # cut inside recognition site + # + if fst5 < fst3: + # + # 5' overhang + # + ovhg1 = ovhgseq = site[fst5:fst3] + elif fst5 > fst3: + # + # 3' overhang + # + ovhg1 = ovhgseq = site[fst3:fst5] + else: + # + # blunt + # + ovhg1 = ovhgseq = '' + for base in 'NRYWMSKHDBV': + if base in ovhg1: + # + # site and overhang degenerated + # + ovhgseq = ovhg1 + if fst5 < fst3: + ovhg1 = - len(ovhg1) + else: + ovhg1 = len(ovhg1) + break + else: + continue + elif 0 <= fst5 <= size: + # + # 5' cut inside the site 3' outside + # + if fst5 < fst3: + # + # 3' cut after the site + # + ovhgseq = site[fst5:] + (fst3 - size) * 'N' + elif fst5 > fst3: + # + # 3' cut before the site + # + ovhgseq = abs(fst3) * 'N' + site[:fst5] + else: + # + # blunt outside + # + ovhg1 = ovhgseq = '' + elif 0 <= fst3 <= size: + # + # 3' cut inside the site, 5' outside + # + if fst5 < fst3: + # + # 5' cut before the site + # + ovhgseq = abs(fst5) * 'N' + site[:fst3] + elif fst5 > fst3: + # + # 5' cut after the site + # + ovhgseq = site[fst3:] + (fst5 - size) * 'N' + else: + # + # should not happend + # + raise ValueError('Error in #1') + elif fst3 < 0 and size < fst5: + # + # 3' overhang. site is included. + # + ovhgseq = abs(fst3)*'N' + site + (fst5-size)*'N' + elif fst5 < 0 and size 0: + line[x] -= size + elif line[x] < 0: + line[x] = line[x] - size + 1 + # + # now is the site palindromic? + # produce the regular expression which correspond to the site. + # tag of the regex will be the name of the enzyme for palindromic + # enzymesband two tags for the other, the name for the sense sequence + # and the name with '_as' at the end for the antisense sequence. + # + rg = '' + if is_palindrom(dna): + line.append(True) + rg = ''.join(['(?P<', name, '>', regex(site.upper()), ')']) + else: + line.append(False) + sense = ''.join(['(?P<', name, '>', regex(site.upper()), ')']) + antisense = ''.join(['(?P<', name, '_as>', + regex(dna.reverse_complement()), ')']) + rg = sense + '|' + antisense + # + # exact frequency of the site. (ie freq(N) == 1, ...) + # + f = [4/len(dna_alphabet[l]) for l in site.upper()] + freq = reduce(lambda x, y : x*y, f) + line.append(freq) + # + # append regex and ovhg1, they have not been appended before not to + # break the factory class. simply to leazy to make the changes there. + # + line.append(rg) + line.append(ovhg1) + line.append(ovhgseq) + return line + + def removestart(self, file): + # + # remove the heading of the file. + # + return [l for l in itertools.dropwhile(lambda l:l.startswith('#'), file)] + + def getblock(self, file, index): + # + # emboss_r.txt, separation between blocks is // + # + take = itertools.takewhile + block = [l for l in take(lambda l :not l.startswith('//'), file[index:])] + index += len(block)+1 + return block, index + + def get(self, block): + # + # take what we want from the block. + # Each block correspond to one enzyme. + # block[0] => enzyme name + # block[3] => methylation (position and type) + # block[5] => suppliers (as a string of single letter) + # + bl3 = block[3].strip() + if not bl3: + bl3 = False # site is not methylable + return (block[0].strip(), bl3, block[5].strip()) + + def information_mixer(self, file1, file2, file3): + # + # Mix all the information from the 3 files and produce a coherent + # restriction record. + # + methfile = self.removestart(file1) + sitefile = self.removestart(file2) + supplier = self.removestart(file3) + + i1, i2= 0, 0 + try: + while True: + block, i1 = self.getblock(methfile, i1) + bl = self.get(block) + line = (sitefile[i2].strip()).split() + name = line[0] + if name == bl[0]: + line.append(bl[1]) # -> methylation + line.append(bl[2]) # -> suppliers + else: + bl = self.get(oldblock) + if line[0] == bl[0]: + line.append(bl[1]) + line.append(bl[2]) + i2 += 1 + else: + raise TypeError + oldblock = block + i2 += 1 + try: + line = self.parseline(line) + except OverhangError: # overhang error + n = name # do not include the enzyme + if not bl[2]: + print('Anyway, %s is not commercially available.\n' %n) + else: + print('Unfortunately, %s is commercially available.\n'%n) + + continue + #Hyphens and dots can't be used as a Python name, nor as a + #group name in a regular expression. e.g. 'CviKI-1', 'R2.BceSIV' + name = name.replace("-", "_").replace(".", "_") + if name in enzymedict: + # + # deal with TaqII and its two sites. + # + print('\nWARNING : %s has two different sites.\n' % name) + other = line[0].replace("-", "_").replace(".", "_") + dna = Seq(line[1], generic_dna) + sense1 = regex(dna) + antisense1 = regex(str(dna.reverse_complement())) + dna = Seq(enzymedict[other][0], generic_dna) + sense2 = regex(dna) + antisense2 = regex(dna.reverse_complement()) + sense = '(?P<'+other+'>'+sense1+'|'+sense2+')' + antisense = '(?P<'+other+'_as>'+antisense1+'|'+antisense2 + ')' + reg = sense + '|' + antisense + line[1] = line[1] + '|' + enzymedict[other][0] + line[-1] = reg + # + # the data to produce the enzyme class are then stored in + # enzymedict. + # + enzymedict[name] = line[1:] # element zero was the name + except IndexError: + pass + for i in supplier: + # + # construction of the list of suppliers. + # + t = i.strip().split(' ', 1) + suppliersdict[t[0]] = (t[1], []) + return def standalone(): diff -Nru python-biopython-1.62/Scripts/Restriction/rebase_update.py python-biopython-1.63/Scripts/Restriction/rebase_update.py --- python-biopython-1.62/Scripts/Restriction/rebase_update.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Scripts/Restriction/rebase_update.py 2013-12-05 14:10:43.000000000 +0000 @@ -6,10 +6,119 @@ # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. +# +"""Update the Rebase emboss files used by Restriction to build the +Restriction_Dictionary.py module.""" + +from __future__ import print_function + +import os import sys +import time import optparse -from Bio.Restriction._Update.Update import * + +try: + from urllib import FancyURLopener +except ImportError: + #Python 3 + from urllib.request import FancyURLopener + +from Bio.Restriction.RanaConfig import * + + +class RebaseUpdate(FancyURLopener): + + def __init__(self, e_mail='', ftpproxy=''): + """RebaseUpdate([e_mail[, ftpproxy]]) -> new RebaseUpdate instance. + + if e_mail and ftpproxy are not given RebaseUpdate uses the corresponding + variable from RanaConfig. + + e_mail is the password for the anonymous ftp connection to Rebase. + ftpproxy is the proxy to use if any.""" + proxy = {'ftp' : ftpproxy or ftp_proxy} + global Rebase_password + Rebase_password = e_mail or Rebase_password + if not Rebase_password: + raise FtpPasswordError('Rebase') + if not Rebase_name: + raise FtpNameError('Rebase') + FancyURLopener.__init__(self, proxy) + + def prompt_user_passwd(self, host, realm): + return (Rebase_name, Rebase_password) + + def openRebase(self, name = ftp_Rebase): + print('\n Please wait, trying to connect to Rebase\n') + try: + self.open(name) + except: + raise ConnectionError('Rebase') + return + + def getfiles(self, *files): + for file in self.update(*files): + print('copying %s' % file) + fn = os.path.basename(file) + #filename = os.path.join(Rebase, fn) + filename = os.path.join(os.getcwd(), fn) + print('to %s' % filename) + self.retrieve(file, filename) + self.close() + return + + def localtime(self): + t = time.gmtime() + year = str(t.tm_year)[-1] + month = str(t.tm_mon) + if len(month) == 1: + month = '0' + month + return year+month + + def update(self, *files): + if not files: + files = [ftp_emb_e, ftp_emb_s, ftp_emb_r] + return [x.replace('###', self.localtime()) for x in files] + + def __del__(self): + if hasattr(self, 'tmpcache'): + self.close() + # + # self.tmpcache is created by URLopener.__init__ method. + # + return + + +class FtpNameError(ValueError): + + def __init__(self, which_server): + print(" In order to connect to %s ftp server, you must provide a name.\ + \n Please edit Bio.Restriction.RanaConfig\n" % which_server) + sys.exit() + + +class FtpPasswordError(ValueError): + + def __init__(self, which_server): + print("\n\ + \n In order to connect to %s ftp server, you must provide a password.\ + \n Use the --e-mail switch to enter your e-mail address.\ + \n\n" % which_server) + sys.exit() + + +class ConnectionError(IOError): + + def __init__(self, which_server): + print('\ + \n Unable to connect to the %s ftp server, make sure your computer\ + \n is connected to the internet and that you have correctly configured\ + \n the ftp proxy.\ + \n Use the --proxy switch to enter the address of your proxy\ + \n' % which_server) + sys.exit() + if __name__ == '__main__': parser = optparse.OptionParser() diff -Nru python-biopython-1.62/Scripts/SeqGui/SeqGui.py python-biopython-1.63/Scripts/SeqGui/SeqGui.py --- python-biopython-1.62/Scripts/SeqGui/SeqGui.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Scripts/SeqGui/SeqGui.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,10 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + +from __future__ import print_function + from Bio.Seq import translate, transcribe, back_transcribe import wx @@ -144,12 +151,12 @@ def OnApply(self, event): codon_table_lb = self.parent.params_panel.codon_table_lb selection = codon_table_lb.GetStringSelection() - print selection + print(selection) codon_table = selection[:] transform_lb = self.parent.params_panel.transform_lb selection = transform_lb.GetStringSelection() transform = selection[:] - print transform + print(transform) if(transform == 'Translate'): self.translate(codon_table) elif(transform == 'Transcribe'): @@ -163,20 +170,20 @@ def translate(self, codon_table): seq = "".join(self.src_text.GetValue().split()) # remove whitespace - print seq + print(seq) self.dest_text.Clear() self.dest_text.SetValue(translate(seq, table=codon_table, to_stop=True)) def transcribe(self): seq = "".join(self.src_text.GetValue().split()) # remove whitespace - print seq + print(seq) self.dest_text.Clear() self.dest_text.SetValue(transcribe(seq)) def back_transcribe(self): seq = "".join(self.src_text.GetValue().split()) # remove whitespace - print seq + print(seq) self.dest_text.Clear() self.dest_text.SetValue(back_transcribe(seq)) diff -Nru python-biopython-1.62/Scripts/debug/debug_blast_parser.py python-biopython-1.63/Scripts/debug/debug_blast_parser.py --- python-biopython-1.62/Scripts/debug/debug_blast_parser.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Scripts/debug/debug_blast_parser.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,6 +5,8 @@ # - Let user specify a sequence file to BLAST on the net. # - Script should help debug connection to NCBI website. +from __future__ import print_function + import os import re import sys @@ -75,47 +77,47 @@ def test_blast_output(outfile): # Try to auto-detect the format if 1: - print "No parser specified. I'll try to choose one for you based" - print "on the format of the output file." - print + print("No parser specified. I'll try to choose one for you based") + print("on the format of the output file.") + print("") parser_class = choose_parser(outfile) - print "It looks like you have given output that should be parsed" - print "with %s.%s. If I'm wrong, you can select the correct parser" %\ - (parser_class.__module__, parser_class.__name__) - print "on the command line of this script (NOT IMPLEMENTED YET)." + print("It looks like you have given output that should be parsed") + print("with %s.%s. If I'm wrong, you can select the correct parser" %\ + (parser_class.__module__, parser_class.__name__)) + print("on the command line of this script (NOT IMPLEMENTED YET).") else: raise NotImplementedError parser_class = NCBIWWW.BlastParser - print "Using %s to parse the file." % parser_class.__name__ - print + print("Using %s to parse the file." % parser_class.__name__) + print("") scanner_class = parser_class()._scanner.__class__ consumer_class = parser_class()._consumer.__class__ #parser_class()._scanner.feed( # open(outfile), ParserSupport.TaggingConsumer()) - print "I'm going to run the data through the parser to see what happens..." + print("I'm going to run the data through the parser to see what happens...") parser = parser_class() try: rec = parser.parse_file(outfile) - except KeyboardInterrupt, SystemExit: + except (KeyboardInterrupt, SystemExit): raise - except Exception, x: + except Exception as x: exception_info = str(x) - print "Dang, the parsing failed." + print("Dang, the parsing failed.") else: - print "Parsing succeeded, no problems detected." - print "However, you should check to make sure the following scanner" - print "trace looks reasonable." - print + print("Parsing succeeded, no problems detected.") + print("However, you should check to make sure the following scanner") + print("trace looks reasonable.") + print("") parser_class()._scanner.feed( open(outfile), ParserSupport.TaggingConsumer()) return 0 - print + print("") - print "Alright. Let me try and figure out where in the parser the" - print "problem occurred..." + print("Alright. Let me try and figure out where in the parser the") + print("problem occurred...") etype, value, tb = sys.exc_info() ftb = traceback.extract_tb(tb) ftb.reverse() @@ -128,32 +130,32 @@ class_found = scanner_class break if class_found is None: - print "Sorry, I could not pinpoint the error to the parser." - print "There's nothing more I can tell you." - print "Here's the traceback:" + print("Sorry, I could not pinpoint the error to the parser.") + print("There's nothing more I can tell you.") + print("Here's the traceback:") traceback.print_exception(etype, value, tb) return 1 else: - print "I found the problem in %s.%s.%s, line %d:" % \ + print("I found the problem in %s.%s.%s, line %d:" % \ (class_found.__module__, class_found.__name__, - err_function, err_line) - print " %s" % err_text - print "This output caused an %s to be raised with the" % etype - print "information %r." % exception_info - print + err_function, err_line)) + print(" %s" % err_text) + print("This output caused an %s to be raised with the" % etype) + print("information %r." % exception_info) + print("") - print "Let me find the line in the file that triggers the problem..." + print("Let me find the line in the file that triggers the problem...") parser = parser_class() scanner, consumer = parser._scanner, parser._consumer consumer = DebuggingConsumer(consumer) try: scanner.feed(open(outfile), consumer) - except etype, x: + except etype as x: pass else: - print "Odd, the exception disappeared! What happened?" + print("Odd, the exception disappeared! What happened?") return 3 - print "It's caused by line %d:" % consumer.linenum + print("It's caused by line %d:" % consumer.linenum) lines = open(outfile).readlines() start, end = consumer.linenum - CONTEXT, consumer.linenum + CONTEXT + 1 if start < 0: @@ -170,68 +172,68 @@ s = "%s%*d %s" % (prefix, ndigits, linenum, line) s = s[:80] - print s - print + print(s) + print("") if class_found == scanner_class: - print "Problems in %s are most likely caused by changed formats." % \ - class_found.__name__ - print "You can start to fix this by going to line %d in module %s." % \ - (err_line, class_found.__module__) - print "Perhaps the scanner needs to be made more lenient by accepting" - print "the changed format?" - print + print("Problems in %s are most likely caused by changed formats." % \ + class_found.__name__) + print("You can start to fix this by going to line %d in module %s." % \ + (err_line, class_found.__module__)) + print("Perhaps the scanner needs to be made more lenient by accepting") + print("the changed format?") + print("") if VERBOSITY <= 0: - print "For more help, you can run this script in verbose mode" - print "to see detailed information about how the scanner" - print "identifies each line." + print("For more help, you can run this script in verbose mode") + print("to see detailed information about how the scanner") + print("identifies each line.") else: - print "OK, let's see what the scanner's doing!" - print - print "*" * 20 + " BEGIN SCANNER TRACE " + "*" * 20 + print("OK, let's see what the scanner's doing!") + print("") + print("*" * 20 + " BEGIN SCANNER TRACE " + "*" * 20) try: parser_class()._scanner.feed( open(outfile), ParserSupport.TaggingConsumer()) - except etype, x: + except etype as x: pass - print "*" * 20 + " END SCANNER TRACE " + "*" * 20 - print + print("*" * 20 + " END SCANNER TRACE " + "*" * 20) + print("") elif class_found == consumer_class: - print "Problems in %s can be caused by two things:" % \ - class_found.__name__ - print " - The format of the line parsed by '%s' changed." % \ - err_function - print " - The scanner misidentified the line." - print "Check to make sure '%s' should parse the line:" % \ - err_function + print("Problems in %s can be caused by two things:" % \ + class_found.__name__) + print(" - The format of the line parsed by '%s' changed." % \ + err_function) + print(" - The scanner misidentified the line.") + print("Check to make sure '%s' should parse the line:" % \ + err_function) s = " %s" % chomp(lines[consumer.linenum]) s = s[:80] - print s - print "If so, debug %s.%s. Otherwise, debug %s." % \ - (class_found.__name__, err_function, scanner_class.__name__) + print(s) + print("If so, debug %s.%s. Otherwise, debug %s." % \ + (class_found.__name__, err_function, scanner_class.__name__)) VERBOSITY = 0 if __name__ == '__main__': try: optlist, args = getopt.getopt(sys.argv[1:], "hpnov") - except getopt.error, x: - print >>sys.stderr, x + except getopt.error as x: + sys.stderr.write("%s\n" % x) sys.exit(-1) if len(args) != 1: - print >>sys.stderr, USAGE + sys.stderr.write(USAGE) sys.exit(-1) TESTFILE, = args if not os.path.exists(TESTFILE): - print >>sys.stderr, "I could not find file: %s" % TESTFILE + sys.stderr.write("I could not find file: %s\n" % TESTFILE) sys.exit(-1) PROTEIN = NUCLEOTIDE = OUTPUT = None for opt, arg in optlist: if opt == '-h': - print USAGE + print(USAGE) sys.exit(0) elif opt == '-p': PROTEIN = 1 @@ -244,9 +246,9 @@ if len([x for x in (PROTEIN, NUCLEOTIDE, OUTPUT) if x is not None]) != 1: OUTPUT = 1 - #print >>sys.stderr, "Exactly one of -p, -n, or -o should be specified." + #sys.stderr.write("Exactly one of -p, -n, or -o should be specified.\n") #sys.exit(-1) if PROTEIN or NUCLEOTIDE: - print >>sys.stderr, "-p and -n not implemented yet" + sys.stderr.write("-p and -n not implemented yet\n") sys.exit(-1) test_blast_output(TESTFILE) diff -Nru python-biopython-1.62/Scripts/query_pubmed.py python-biopython-1.63/Scripts/query_pubmed.py --- python-biopython-1.62/Scripts/query_pubmed.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Scripts/query_pubmed.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,6 +5,8 @@ # license. Please see the LICENSE file that should have been included # as part of this package. +from __future__ import print_function + import sys import getopt @@ -12,7 +14,7 @@ def print_usage(): - print """query_pubmed.py [-h] [-c] [-d delay] query + print("""query_pubmed.py [-h] [-c] [-d delay] query This script sends a query to PubMed (via the NCBI Entrez webservice*) and prints the MEDLINE formatted results to the screen. @@ -22,13 +24,13 @@ -c Count the hits, and don't print them out. * http://www.ncbi.nlm.nih.gov/Entrez/ -""" +""") if __name__ == '__main__': try: optlist, args = getopt.getopt(sys.argv[1:], "hcd:") - except getopt.error, x: - print x + except getopt.error as x: + print(x) sys.exit(0) if len(args) != 1: # If they gave extraneous arguments, print_usage() # print the instructions and quit. @@ -48,7 +50,7 @@ print_usage() sys.exit(0) - print "Doing a PubMed search for %s..." % repr(query) + print("Doing a PubMed search for %s..." % repr(query)) if count_only: handle = Entrez.esearch(db="pubmed", term=query) @@ -57,7 +59,7 @@ search_results = Entrez.read(handle) ids = search_results["IdList"] count = len(ids) - print "Found %d citations" % count + print("Found %d citations" % count) if count_only: sys.exit(0) @@ -67,7 +69,7 @@ batch_size = 3 for start in range(0, count, batch_size): end = min(count, start + batch_size) - #print "Going to download record %i to %i" % (start+1, end) + #print("Going to download record %i to %i" % (start+1, end)) fetch_handle = Entrez.efetch(db="pubmed", rettype="medline", retmode="text", retstart=start, retmax=batch_size, diff -Nru python-biopython-1.62/Scripts/scop_pdb.py python-biopython-1.63/Scripts/scop_pdb.py --- python-biopython-1.62/Scripts/scop_pdb.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Scripts/scop_pdb.py 2013-12-05 14:10:43.000000000 +0000 @@ -6,16 +6,18 @@ # as part of this package. +from __future__ import print_function + import getopt import sys -import urllib + +from Bio._py3k import urlretrieve as _urlretrieve from Bio.SCOP import * def usage(): - print \ -"""Extract a SCOP domain's ATOM and HETATOM records from the relevant PDB file. + print("""Extract a SCOP domain's ATOM and HETATOM records from the relevant PDB file. For example: scop_pdb.py astral-rapid-access-1.55.raf dir.cla.scop.txt_1.55 d3hbib_ @@ -53,7 +55,7 @@ See [http://scop.berkeley.edu/parse/index.html] sid -- A SCOP domain identifier. e.g. d3hbib_ -""" +""") default_pdb_url = "http://www.rcsb.org/pdb/cgi/export.cgi/somefile.pdb?" \ "format=PDB&pdbId=%s&compression=None" @@ -64,7 +66,7 @@ if pdb_url is None: pdb_url = default_pdb_url url = pdb_url % pdbid - fn, header = urllib.urlretrieve(url) + fn, header = _urlretrieve(url) return open(fn) @@ -73,7 +75,7 @@ opts, args = getopt.getopt(sys.argv[1:], "hp:o:i:", ["help", "usage", "pdb=", "output=", "input="]) except getopt.GetoptError: - # print help information and exit: + # show help information and exit: usage() sys.exit(2) @@ -96,26 +98,25 @@ pdb_url = a if len(args) < 2: - print >> sys.stderr, \ - "Not enough arguments. Try --help for more details." + sys.stderr.write("Not enough arguments. Try --help for more details.\n") sys.exit(2) raf_url = args[0] cla_url = args[1] - (raf_filename, headers) = urllib.urlretrieve(raf_url) + (raf_filename, headers) = _urlretrieve(raf_url) seqMapIndex = Raf.SeqMapIndex(raf_filename) - (cla_filename, headers) = urllib.urlretrieve(cla_url) + (cla_filename, headers) = _urlretrieve(cla_url) claIndex = Cla.Index(cla_filename) if input is None: sids = args[2:] elif input == '-': - sids = sys.stdin.xreadlines() + sids = sys.stdin else: in_handle = open(input) - sids = in_handle.xreadlines() + sids = in_handle try: for sid in sids: @@ -125,7 +126,7 @@ pdbid = id[1:5] s = pdbid[0:1] if s == '0' or s == 's': - print >> sys.stderr, "No coordinates for domain " + id + sys.stderr.write("No coordinates for domain %s\n" % id) continue if output is None: @@ -148,8 +149,8 @@ seqMap.getAtoms(f, out_handle) finally: f.close() - except (IOError, KeyError, RuntimeError), e: - print >> sys.stderr, "I cannot do SCOP domain ", id, ":", e + except (IOError, KeyError, RuntimeError) as e: + sys.stderr.write("I cannot do SCOP domain %s : %s\n" % (id, e)) finally: out_handle.close() finally: diff -Nru python-biopython-1.62/Scripts/xbbtools/nextorf.py python-biopython-1.63/Scripts/xbbtools/nextorf.py --- python-biopython-1.62/Scripts/xbbtools/nextorf.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Scripts/xbbtools/nextorf.py 2013-12-05 14:10:43.000000000 +0000 @@ -10,7 +10,8 @@ # Jan.O.Andersson@home.se # File: nextorf.py -import commands +from __future__ import print_function + import re import sys import os @@ -136,8 +137,8 @@ n = len(seq) start_codons = self.table.start_codons stop_codons = self.table.stop_codons -# print 'Start codons', start_codons -# print 'Stop codons', stop_codons +# print('Start codons %s' % start_codons) +# print('Stop codons %s' % stop_codons) frame_coordinates = [] for frame in range(0, 3): coordinates = [] @@ -171,9 +172,9 @@ elif codon_type == STOP: if start_site == 0: continue -# if codon == 'XXX': print 'do something' +# if codon == 'XXX': print('do something') stop = pos + 2 -# print stop +# print("stop") length = stop - start_site + 1 if length >= minlength and length <= maxlength: if nostart == '1' and start_site == 1: @@ -207,35 +208,36 @@ if out == 'aa': orf = subs.translate(table=self.genetic_code) - print self.ToFasta(head, orf.data) + print(self.ToFasta(head, orf.data)) elif out == 'nt': - print self.ToFasta(head, subs.data) + print(self.ToFasta(head, subs.data)) elif out == 'pos': - print head + print(head) def help(): global options - print 'Usage:', sys.argv[0], '() ' - - print 'Options: default' - print '--start Start position in sequence 0' - print '--stop Stop position in sequence (end of seqence)' - print '--minlength Minimum length of orf in bp 100' - print '--maxlength Maximum length of orf in bp, default 100000000' - print '--strand Strand to analyse [both, plus, minus] both' - print '--frame Frame to analyse [1 2 3] all' - print '--noframe Ignore start codons [0 1] 0' - print '--output Output to generate [aa nt pos] aa' - print '--gc Creates GC statistics of ORF [0 1] 0' - print '--table Genetic code to use (see below) 1' - -# for a,b in options.items(): print '\t', a,b -# print '' - print "\nNCBI's Codon Tables:" + print('Usage: %s () ' % sys.argv[0]) + print("") + print('Options: default') + print('--start Start position in sequence 0') + print('--stop Stop position in sequence (end of seqence)') + print('--minlength Minimum length of orf in bp 100') + print('--maxlength Maximum length of orf in bp, default 100000000') + print('--strand Strand to analyse [both, plus, minus] both') + print('--frame Frame to analyse [1 2 3] all') + print('--noframe Ignore start codons [0 1] 0') + print('--output Output to generate [aa nt pos] aa') + print('--gc Creates GC statistics of ORF [0 1] 0') + print('--table Genetic code to use (see below) 1') + +# for a,b in options.items(): +# print("\t%s %s" % (a, b) +# print("") + print("\nNCBI's Codon Tables:") for key, table in CodonTable.ambiguous_dna_by_id.items(): - print '\t', key, table._codon_table.names[0] - print '\ne.g.\n./nextorf.py --minlength 5 --strand plus --output nt --gc 1 testjan.fas' + print('\t%s %s' % (key, table._codon_table.names[0])) + print('\ne.g.\n./nextorf.py --minlength 5 --strand plus --output nt --gc 1 testjan.fas') sys.exit(0) @@ -257,7 +259,7 @@ show_help = len(sys.argv) <= 1 shorts = 'hv' - longs = map(lambda x: x + '=', options.keys()) + ['help'] + longs = [x + '=' for x in options] + ['help'] optlist, args = getopt.getopt(args, shorts, longs) if show_help: @@ -267,7 +269,7 @@ if arg[0] == '-h' or arg[0] == '--help': help() sys.exit(0) - for key in options.keys(): + for key in options: if arg[1].lower() == 'no': arg[1] = 0 elif arg[1].lower() == 'yes': @@ -277,7 +279,7 @@ options[key] = arg[1] if arg[0] == '-v': - print 'OPTIONS', options + print('OPTIONS %s' % options) file = args[0] nextorf = NextOrf(file, options) diff -Nru python-biopython-1.62/Scripts/xbbtools/xbb_blast.py python-biopython-1.63/Scripts/xbbtools/xbb_blast.py --- python-biopython-1.62/Scripts/xbbtools/xbb_blast.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Scripts/xbbtools/xbb_blast.py 2013-12-05 14:10:43.000000000 +0000 @@ -4,12 +4,18 @@ # thomas@cbs.dtu.dk, http://www.cbs.dtu.dk/thomas # File: xbb_blast.py +from __future__ import print_function + import glob import os import sys from threading import * -import commands -from Tkinter import * + +try: + from Tkinter import * # Python 2 +except ImportError: + from tkinter import * # Python 3 + import Pmw sys.path.insert(0, '.') @@ -40,8 +46,8 @@ pass nin.extend(glob.glob('*.nin')) - self.pin = map(lambda x: os.path.splitext(x)[0], pin) - self.nin = map(lambda x: os.path.splitext(x)[0], nin) + self.pin = [os.path.splitext(x)[0] for x in pin] + self.nin = [os.path.splitext(x)[0] for x in nin] def Choices(self): self.GetBlasts() @@ -99,7 +105,6 @@ def Update(self): self.notepad.update() - #print '.', self.notepad.after(1, self.Update) def oldRun(self): @@ -109,9 +114,9 @@ self.Update() - print self.command + print(self.command) self.pipe = posix.popen(self.command) - while 1: + while True: try: char = self.pipe.read(1) self.notepad.insert(END, char) diff -Nru python-biopython-1.62/Scripts/xbbtools/xbb_blastbg.py python-biopython-1.63/Scripts/xbbtools/xbb_blastbg.py --- python-biopython-1.62/Scripts/xbbtools/xbb_blastbg.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Scripts/xbbtools/xbb_blastbg.py 2013-12-05 14:10:43.000000000 +0000 @@ -4,16 +4,27 @@ # Thomas.Sicheritz@molbio.uu.se, http://evolution.bmc.uu.se/~thomas # File: xbb_blastbg.py -import commands +from __future__ import print_function + import posix import posixpath import os import sys sys.path.insert(0, '.') -import Queue + +try: + import Queue as queue # Python 2 +except ImportError: + import queue # Python 3 + import tempfile import threading -from Tkinter import * + +try: + from Tkinter import * # Python 2 +except ImportError: + from tkinter import * # Python 3 + from xbb_utils import NotePad @@ -39,7 +50,7 @@ # open the oufile and displays new appended text fid = open(self.outfile) size = 0 - while 1: + while True: if self.worker.finished: break fid.seek(size) @@ -69,12 +80,12 @@ def __init__(self, command): self.com = command - queue = Queue.Queue(0) - self.queue = queue + q = queue.Queue(0) + self.queue = q threading.Thread.__init__(self) self.finished = 0 - print dir(queue) - print queue.queue + print(dir(q)) + print(q.queue) def shutdown(self): # GRRRR How do I explicitely kill a thread ??????? @@ -82,7 +93,7 @@ del self.queue def run(self): - print 'running', self.com + print('running %s' % self.com) os.system(self.com) self.finished = 1 diff -Nru python-biopython-1.62/Scripts/xbbtools/xbb_help.py python-biopython-1.63/Scripts/xbbtools/xbb_help.py --- python-biopython-1.62/Scripts/xbbtools/xbb_help.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Scripts/xbbtools/xbb_help.py 2013-12-05 14:10:43.000000000 +0000 @@ -4,14 +4,21 @@ # thomas@cbs.dtu.dk, http://www.cbs.dtu.dk/thomas # File: xbb_help.py -from Tkinter import * -from ScrolledText import ScrolledText +try: + from Tkinter import * # Python 2 +except ImportError: + from tkinter import * # Python 3 + +try: + import ScrolledText as scrolledtext # Python 2 +except ImportError: + from tkinter import scrolledtext # Python 3 class xbbtools_help(Toplevel): def __init__(self, *args): Toplevel.__init__(self) - self.tid = ScrolledText(self) + self.tid = scrolledtext.ScrolledText(self) self.tid.pack(fill=BOTH, expand=1) self.Styles() self.Show() diff -Nru python-biopython-1.62/Scripts/xbbtools/xbb_search.py python-biopython-1.63/Scripts/xbbtools/xbb_search.py --- python-biopython-1.62/Scripts/xbbtools/xbb_search.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Scripts/xbbtools/xbb_search.py 2013-12-05 14:10:43.000000000 +0000 @@ -4,16 +4,22 @@ # thomas@cbs.dtu.dk, http://www.cbs.dtu.dk/thomas # File: xbb_search.py -import commands import os import re import sys sys.path.insert(0, '.') -from Tkinter import * -from tkColorChooser import askcolor -from Bio.Data.IUPACData import ambiguous_dna_values -import re +try: + from Tkinter import * # Python 2 +except ImportError: + from tkinter import * # Python 3 + +try: + import tkColorChooser as colorchooser # Python 2 +except ImportError: + from tkinter import colorchooser # Python 3 + +from Bio.Data.IUPACData import ambiguous_dna_values from Bio.Seq import reverse_complement @@ -24,9 +30,9 @@ def init_alphabet(self): self.alphabet = ambiguous_dna_values - other = ''.join(self.alphabet.keys()) + other = ''.join(self.alphabet) self.alphabet['N'] = self.alphabet['N'] + other - for key in self.alphabet.keys(): + for key in self.alphabet: if key == 'N': continue if key in self.alphabet[key]: @@ -65,7 +71,7 @@ def SearchAll(self): pos = -1 positions = [] - while 1: + while True: m = self._Search(pos + 1) if not m: break @@ -116,7 +122,7 @@ return if not color: try: - color = askcolor()[1] + color = colorchooser.askcolor()[1] except: color = 'cyan' self.current_color = color diff -Nru python-biopython-1.62/Scripts/xbbtools/xbb_sequence.py python-biopython-1.63/Scripts/xbbtools/xbb_sequence.py --- python-biopython-1.62/Scripts/xbbtools/xbb_sequence.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Scripts/xbbtools/xbb_sequence.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -#!/usr/bin/env python -# Created: Wed Jun 21 10:26:53 2000 -# Last changed: Time-stamp: <00/12/02 14:18:34 thomas> -# Thomas.Sicheritz@molbio.uu.se, http://evolution.bmc.uu.se/~thomas -# File: xbb_sequence.py - -import sys -sys.path.insert(0, '.') -from Bio import Sequence - - -class xbb_sequence(Sequence): - def __init__(self): - "" - -if __name__ == '__main__': - test = xbb_sequence() diff -Nru python-biopython-1.62/Scripts/xbbtools/xbb_translations.py python-biopython-1.63/Scripts/xbbtools/xbb_translations.py --- python-biopython-1.62/Scripts/xbbtools/xbb_translations.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Scripts/xbbtools/xbb_translations.py 2013-12-05 14:10:43.000000000 +0000 @@ -4,11 +4,18 @@ # thomas@cbs.dtu.dk, http://www.cbs.dtu.dk/thomas # File: xbb_translations.py +from __future__ import print_function + import sys import time sys.path.insert(0, '.') -from Tkinter import * + +try: + from Tkinter import * # Python 2 +except ImportError: + from tkinter import * # Python 3 + from Bio.Seq import reverse_complement, translate from Bio.SeqUtils import GC @@ -67,7 +74,7 @@ subseq = seq[i:i+60] p = i/3 res += '%d/%d\n' % (i+1, i/3+1) - res += ' '.join(map(None, protein[p:p+20])) + '\n' + res += ' '.join(protein[p:p+20]) + '\n' # seq res += subseq.lower() + '%5d %%\n' % int(self.gc(subseq)) @@ -95,16 +102,16 @@ p = i/3 # + frames res += '%d/%d\n' % (i+1, i/3+1) - res += ' ' + ' '.join(map(None, frames[3][p:p+20])) + '\n' - res += ' ' + ' '.join(map(None, frames[2][p:p+20])) + '\n' - res += ' '.join(map(None, frames[1][p:p+20])) + '\n' + res += ' ' + ' '.join(frames[3][p:p+20]) + '\n' + res += ' ' + ' '.join(frames[2][p:p+20]) + '\n' + res += ' '.join(frames[1][p:p+20]) + '\n' # seq res += subseq.lower() + '%5d %%\n' % int(self.gc(subseq)) res += csubseq.lower() + '\n' # - frames - res += ' '.join(map(None, frames[-2][p:p+20])) + ' \n' - res += ' ' + ' '.join(map(None, frames[-1][p:p+20])) + '\n' - res += ' ' + ' '.join(map(None, frames[-3][p:p+20])) + '\n\n' + res += ' '.join(frames[-2][p:p+20]) + ' \n' + res += ' ' + ' '.join(frames[-1][p:p+20]) + '\n' + res += ' ' + ' '.join(frames[-3][p:p+20]) + '\n\n' return res @@ -113,12 +120,12 @@ s = 'ATTCCGGTTGATCCTGCCGGACCCGACCGCTATCGGGGTAGGGATAAGCCATGGGAGTCTTACACTCCCGGGTAAGGGAGTGTGGCGGACGGCTGAGTAACACGTGGCTAACCTACCCTCGGGACGGGGATAACCCCGGGAAACTGGGGATAATCCCCGATAGGGAAGGAGTCCTGGAATGGTTCCTTCCCTAAAGGGCTATAGGCTATTTCCCGTTTGTAGCCGCCCGAGGATGGGGCTACGGCCCATCAGGCTGTCGGTGGGGTAAAGGCCCACCGAACCTATAACGGGTAGGGGCCGTGGAAGCGGGAGCCTCCAGTTGGGCACTGAGACAAGGGCCCAGGCCCTACGGGGCGCACCAGGCGCGAAACGTCCCCAATGCGCGAAAGCGTGAGGGCGCTACCCCGAGTGCCTCCGCAAGGAGGCTTTTCCCCGCTCTAAAAAGGCGGGGGAATAAGCGGGGGGCAAGTCTGGTGTCAGCCGCCGCGGTAATACCAGCTCCGCGAGTGGTCGGGGTGATTACTGGGCCTAAAGCGCCTGTAGCCGGCCCACCAAGTCGCCCCTTAAAGTCCCCGGCTCAACCGGGGAACTGGGGGCGATACTGGTGGGCTAGGGGGCGGGAGAGGCGGGGGGTACTCCCGGAGTAGGGGCGAAATCCTTAGATACCGGGAGGACCACCAGTGGCGGAAGCGCCCCGCTA' test = xbb_translations() -# for i in range(0, 4): -# print test.frame1(s[i:]) - #print s - #print test.complement(s) - print '============================================================' - print test.gcframe(s) +# for i in range(0, 4): +# print(test.frame1(s[i:])) + #print(s) + #print(test.complement(s)) + print('============================================================') + print(test.gcframe(s)) -# for i in Translate.unambiguous_dna_by_id.keys(): -# print Translate.unambiguous_dna_by_id[i].table.names[0] +# for i in Translate.unambiguous_dna_by_id: +# print(Translate.unambiguous_dna_by_id[i].table.names[0]) diff -Nru python-biopython-1.62/Scripts/xbbtools/xbb_utils.py python-biopython-1.63/Scripts/xbbtools/xbb_utils.py --- python-biopython-1.62/Scripts/xbbtools/xbb_utils.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Scripts/xbbtools/xbb_utils.py 2013-12-05 14:10:43.000000000 +0000 @@ -6,8 +6,16 @@ import sys sys.path.insert(0, '.') -from Tkinter import * -from FileDialog import SaveFileDialog + +try: + from Tkinter import * # Python 2 +except ImportError: + from tkinter import * # Python 3 + +try: + import tkFileDialog as filedialog # Python 2 +except ImportError: + from tkinter import filedialog # Python 3 class NotePad(Toplevel): @@ -34,7 +42,7 @@ self.tid.insert(start, txt) def save(self): - fd = SaveFileDialog(self) + fd = filedialog.SaveFileDialog(self) file = fd.go(key="test") if file: fid = open(file, 'w') diff -Nru python-biopython-1.62/Scripts/xbbtools/xbb_widget.py python-biopython-1.63/Scripts/xbbtools/xbb_widget.py --- python-biopython-1.62/Scripts/xbbtools/xbb_widget.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Scripts/xbbtools/xbb_widget.py 2013-12-05 14:10:43.000000000 +0000 @@ -9,12 +9,21 @@ # license. Please see the LICENSE file that should have been included # as part of this package. +from __future__ import print_function + import re import sys import time -from Tkinter import * -from tkFileDialog import askopenfilename, asksaveasfilename +try: + from Tkinter import * # Python 2 +except ImportError: + from tkinter import * # Python 3 + +try: + import tkFileDialog as filedialog # Python 2 +except ImportError: + from tkinter import filedialog # Python 3 sys.path.insert(0, '.') from xbb_utils import * @@ -23,8 +32,7 @@ from xbb_search import XDNAsearch from xbb_help import xbbtools_help from Bio.Data import CodonTable -from Bio.SeqUtils import quick_FASTA_reader - +from Bio.SeqIO.FastaIO import SimpleFastaParser class xbb_widget: def __init__(self, parent=None): @@ -61,7 +69,7 @@ def init_variables(self): self.seqwidth = 60 self.translation_tables = {} - for i, table in CodonTable.unambiguous_dna_by_id.iteritems(): + for i, table in CodonTable.unambiguous_dna_by_id.items(): self.translation_tables[table.names[0]] = i self.translator = xbb_translations() @@ -282,7 +290,7 @@ def get_selection(self): w = self.sequence_id - #print w.selection_own() + #print(w.selection_own()) #w.selection_own() try: return w.selection_get() @@ -329,13 +337,14 @@ def open(self, file=None): if not file: - file = askopenfilename() + file = filedialog.askopenfilename() if not file: return - genes = quick_FASTA_reader(file) - self.insert_sequence(genes[0]) + with open(file) as handle: + self.insert_sequence(next(SimpleFastaParser(handle))) - def insert_sequence(self, (name, sequence)): + def insert_sequence(self, name_sequence): + (name, sequence) = name_sequence self.sequence_id.delete(0.0, END) self.sequence_id.insert(END, sequence.upper()) self.fix_sequence() @@ -355,7 +364,7 @@ def export(self): seq = self.get_self_selection() - print seq, len(seq) + print("%s %i" % (seq, len(seq))) def gcframe(self): seq = self.get_selection_or_sequence() @@ -378,7 +387,7 @@ if not seq: return aa_seq = self.translator.frame(seq, frame, self.current_codon_table_id) - print '>%s<' % aa_seq + print('>%s<' % aa_seq) aa_seq = re.sub('(.{50})', '\\1\n', str(aa_seq)) np = NotePad() tid = np.text_id() @@ -423,7 +432,7 @@ start, stop = 1.0, self.sequence_id.index(END) seq = w.get(start, stop) - seq = map(None, re.sub('[^A-Z]', '', seq)) + seq = list(re.sub('[^A-Z]', '', seq)) seq.reverse() seq = ''.join(seq) @@ -444,7 +453,7 @@ seq = w.get(start, stop) seq = re.sub('[^A-Z]', '', seq) - #print 'seq >%s<' % seq + #print('seq >%s<' % seq) complementary = self.translator.complement(seq) w.delete(start, stop) w.insert(start, complementary) diff -Nru python-biopython-1.62/Scripts/xbbtools/xbbtools.py python-biopython-1.63/Scripts/xbbtools/xbbtools.py --- python-biopython-1.62/Scripts/xbbtools/xbbtools.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Scripts/xbbtools/xbbtools.py 2013-12-05 14:10:43.000000000 +0000 @@ -11,11 +11,15 @@ import sys sys.path.insert(0, '.') -from Tkinter import * + +try: + from Tkinter import * # Python 2 +except ImportError: + from tkinter import * # Python 3 from xbb_widget import xbb_widget -win = Tk() +win = Tk() xbbtools = xbb_widget() xbbtools.main_frame.option_add('*frame.background', 'dimgrey') diff -Nru python-biopython-1.62/Tests/EMBL/patents.embl python-biopython-1.63/Tests/EMBL/patents.embl --- python-biopython-1.62/Tests/EMBL/patents.embl 1970-01-01 00:00:00.000000000 +0000 +++ python-biopython-1.63/Tests/EMBL/patents.embl 2013-12-05 14:10:43.000000000 +0000 @@ -0,0 +1,79 @@ +ID NRP00000001; PRT; NR2; 1 SQ +XX +MF 10830627 +PN WO9954462 +PR GB19980008350 22-APR-1998 +ED 28-OCT-1999 WO9954462 A2 +XX +DR EPOP:AX013047; +DE Sequence 74 from Patent WO9954462. +PN WO9954462-A2/74, 28-OCT-1999 +XX +FT source 1..358 +FT /organism="Mycobacterium leprae" +FT /mol_type="protein" +FT /db_xref="taxon:1769" +XX +SQ Sequence 358 AA; 00001508eba3f78863a4f9cb2463810d; MD5; +// +ID NRP00000002; PRT; NR2; 1 SQ +XX +MF 22767515 +PN WO0190366 +PR US20000206690P 24-MAY-2000 +ED 29-NOV-2001 WO0190366 A2 +XX +DR EPOP:AX312021; +DE Sequence 5006 from Patent WO0190366. +PN WO0190366-A2/5006, 29-NOV-2001 +XX +FT source 1..65 +FT /organism="Homo sapiens" +FT /mol_type="protein" +FT /db_xref="taxon:9606" +XX +SQ Sequence 65 AA; 0000eece8396364fe22b1bdd6821bd63; MD5; +// +ID NRP00210944; PRT; NR2; 2 SQ +XX +MF 9921525 +PN WO03020945 +PR GB20010021439 05-SEP-2001 +ED 13-MAR-2003 WO03020945 A2 +XX +DR EPOP:AX716885; +DE Sequence 1 from Patent WO03020945. +PN WO03020945-A2/1, 13-MAR-2003 +XX +DR USPOP:ABY00072; +DE Sequence 1 from patent US 7294486. +PN US7294486-A/1, 13-NOV-2007 +PN US2005130274 A1 16-JUN-2005 +CC First level of publication supplied by the EPO +XX +FT source 1..25 +FT /organism="Streptomyces cattleya" +FT /mol_type="protein" +FT /db_xref="taxon:29303" +XX +SQ Sequence 25 AA; 000114cdf14c72e3b188040f9f35f5af; MD5; +// +ID NRP00210945; PRT; NR2; 1 SQ +XX +MF 9954057 +PN WO2004078914 +PR GB20030004882 04-MAR-2003 +ED 16-SEP-2004 WO2004078914 A2 +XX +DR EPOP:CQ871087; +DE Sequence 7 from Patent WO2004078914. +PN WO2004078914-A2/7, 16-SEP-2004 +XX +FT source 1..25 +FT /organism="unidentified" +FT /mol_type="protein" +FT /note="Sequence of unknown origin" +FT /db_xref="taxon:32644" +XX +SQ Sequence 25 AA; 000114cdf14c72e3b188040f9f35f5af; MD5; +// diff -Nru python-biopython-1.62/Tests/PAML/gen_results.py python-biopython-1.63/Tests/PAML/gen_results.py --- python-biopython-1.62/Tests/PAML/gen_results.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/PAML/gen_results.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,10 +3,13 @@ # license. Please see the LICENSE file that should have been included # as part of this package. +from __future__ import print_function import os.path import sys +from Bio._py3k import range + VERSIONS = ["4_1", "4_3", "4_4", "4_4c", "4_5", "4_6", "4_7"] @@ -29,7 +32,7 @@ ("SE", "alignment.phylip", "species.tree")] for test in tests: - print test[0] + print(test[0]) cml = codeml.Codeml() cml.working_dir = "temp" ctl_file = os.path.join("Control_files", @@ -41,7 +44,7 @@ cml.alignment = alignment cml.tree = tree for version in versions: - print "\t{0}".format(version.replace('_', '.')) + print("\t{0}".format(version.replace('_', '.'))) if test[0] in ["ngene2_mgene02", "ngene2_mgene34"] and \ version == "4_6": cml.tree = ".".join([cml.tree, "4.6"]) @@ -57,21 +60,21 @@ versions = [vers] else: versions = VERSIONS - tests = [("model", range(0, 9)), ("nhomo", [1, 3, 4]), - ("nparK", range(1, 5)), ("alpha1rho1", None), ("SE", None)] + tests = [("model", list(range(0, 9))), ("nhomo", [1, 3, 4]), + ("nparK", list(range(1, 5))), ("alpha1rho1", None), ("SE", None)] alignment = os.path.join("Alignments", "alignment.phylip") tree = os.path.join("Trees", "species.tree") for test in tests: - print test[0] + print(test[0]) bml = baseml.Baseml() for version in versions: - print "\t{0}".format(version.replace('_', '.')) + print("\t{0}".format(version.replace('_', '.'))) if test[1] is not None: for n in test[1]: if (version in ["4_3", "4_4", "4_4c", "4_5"] and test[0] == "nparK" and n in [3, 4]): continue - print "\t\tn = {0}".format(n) + print("\t\tn = {0}".format(n)) ctl_file = os.path.join("Control_files", "baseml", "{0}{1}.ctl".format(test[0], n)) bml.read_ctl_file(ctl_file) @@ -107,10 +110,10 @@ tests = ["yn00"] alignment = os.path.join("Alignments", "alignment.phylip") for test in tests: - print test[0] + print(test[0]) yn = yn00.Yn00() for version in versions: - print "\t{0}".format(version.replace('_', '.')) + print("\t{0}".format(version.replace('_', '.'))) ctl_file = os.path.join("Control_files", "yn00", "{0}.ctl".format(test)) yn.read_ctl_file(ctl_file) @@ -122,7 +125,7 @@ def print_usage(): - versions = ", ".join([vers.replace("_", ".") for vers in VERSIONS]) + versions = ", ".join(vers.replace("_", ".") for vers in VERSIONS) usage = \ '''Usage: gen_results.py [-v] PROGRAM [VERSION] Generate result files to be used in Bio.Phylo.PAML unit tests. @@ -150,18 +153,18 @@ verbose = True elif arg in programs: if prog is not None: - print "Only one program at a time, please." + print("Only one program at a time, please.") print_usage() prog = arg elif arg.replace(".", "_") in VERSIONS: if vers is not None: - print "Only one version at a time, sorry." + print("Only one version at a time, sorry.") vers = arg.replace(".", "_") else: - print "Unrecognized argument" + print("Unrecognized argument") print_usage() if prog is None: - print "No program specified" + print("No program specified") print_usage() if prog == "codeml": codeml(vers, verbose) diff -Nru python-biopython-1.62/Tests/PDB/1A8O.asa python-biopython-1.63/Tests/PDB/1A8O.asa --- python-biopython-1.62/Tests/PDB/1A8O.asa 1970-01-01 00:00:00.000000000 +0000 +++ python-biopython-1.63/Tests/PDB/1A8O.asa 2013-12-05 14:10:43.000000000 +0000 @@ -0,0 +1,524 @@ +ATOM 9 N ASP A 152 21.554 34.953 27.691 37.371 1.65 +ATOM 10 CA ASP A 152 21.835 36.306 28.144 10.829 1.87 +ATOM 11 C ASP A 152 21.947 37.322 27.000 .490 1.76 +ATOM 12 O ASP A 152 21.678 38.510 27.187 9.320 1.40 +ATOM 13 CB ASP A 152 23.126 36.292 28.966 26.086 1.87 +ATOM 14 CG ASP A 152 23.098 37.275 30.112 11.885 1.76 +ATOM 15 OD1 ASP A 152 23.433 38.456 29.884 34.529 1.40 +ATOM 16 OD2 ASP A 152 22.749 36.865 31.241 40.969 1.40 +ATOM 17 N ILE A 153 22.322 36.838 25.818 1.042 1.65 +ATOM 18 CA ILE A 153 22.498 37.681 24.632 .729 1.87 +ATOM 19 C ILE A 153 21.220 38.389 24.164 .000 1.76 +ATOM 20 O ILE A 153 20.214 37.743 23.876 .294 1.40 +ATOM 21 CB ILE A 153 23.062 36.854 23.441 1.882 1.87 +ATOM 22 CG1 ILE A 153 24.282 36.029 23.879 1.880 1.87 +ATOM 23 CG2 ILE A 153 23.423 37.769 22.280 .000 1.87 +ATOM 24 CD1 ILE A 153 25.429 36.840 24.455 26.201 1.87 +ATOM 25 N ARG A 154 21.280 39.719 24.101 2.027 1.65 +ATOM 26 CA ARG A 154 20.173 40.563 23.646 .000 1.87 +ATOM 27 C ARG A 154 20.766 41.644 22.751 .003 1.76 +ATOM 28 O ARG A 154 21.804 42.216 23.075 8.796 1.40 +ATOM 29 CB ARG A 154 19.444 41.206 24.830 18.323 1.87 +ATOM 30 CG ARG A 154 18.724 40.196 25.695 .092 1.87 +ATOM 31 CD ARG A 154 18.011 40.824 26.869 32.364 1.87 +ATOM 32 NE ARG A 154 17.416 39.777 27.690 13.390 1.65 +ATOM 33 CZ ARG A 154 16.221 39.234 27.476 4.926 1.76 +ATOM 34 NH1 ARG A 154 15.459 39.650 26.470 25.516 1.65 +ATOM 35 NH2 ARG A 154 15.824 38.211 28.222 53.311 1.65 +ATOM 36 N GLN A 155 20.116 41.917 21.623 .000 1.65 +ATOM 37 CA GLN A 155 20.613 42.918 20.680 .000 1.87 +ATOM 38 C GLN A 155 20.546 44.344 21.203 .000 1.76 +ATOM 39 O GLN A 155 19.488 44.804 21.635 9.720 1.40 +ATOM 40 CB GLN A 155 19.837 42.841 19.368 .000 1.87 +ATOM 41 CG GLN A 155 20.385 43.751 18.271 .000 1.87 +ATOM 42 CD GLN A 155 19.526 43.736 17.022 .000 1.76 +ATOM 43 OE1 GLN A 155 18.365 43.322 17.058 .000 1.40 +ATOM 44 NE2 GLN A 155 20.090 44.190 15.909 3.991 1.65 +ATOM 45 N GLY A 156 21.675 45.045 21.155 .303 1.65 +ATOM 46 CA GLY A 156 21.698 46.427 21.598 22.923 1.87 +ATOM 47 C GLY A 156 20.859 47.278 20.654 .000 1.76 +ATOM 48 O GLY A 156 20.729 46.935 19.475 .000 1.40 +ATOM 49 N PRO A 157 20.260 48.380 21.137 .000 1.65 +ATOM 50 CA PRO A 157 19.435 49.249 20.287 .776 1.87 +ATOM 51 C PRO A 157 20.158 49.801 19.054 .000 1.76 +ATOM 52 O PRO A 157 19.512 50.154 18.068 7.332 1.40 +ATOM 53 CB PRO A 157 18.993 50.357 21.249 26.396 1.87 +ATOM 54 CG PRO A 157 20.056 50.358 22.317 35.649 1.87 +ATOM 55 CD PRO A 157 20.300 48.887 22.519 30.627 1.87 +ATOM 56 N LYS A 158 21.486 49.867 19.109 1.292 1.65 +ATOM 57 CA LYS A 158 22.285 50.358 17.985 3.534 1.87 +ATOM 58 C LYS A 158 23.286 49.318 17.478 5.076 1.76 +ATOM 59 O LYS A 158 24.155 49.627 16.659 20.075 1.40 +ATOM 60 CB LYS A 158 23.025 51.649 18.358 27.393 1.87 +ATOM 61 CG LYS A 158 22.117 52.841 18.584 24.659 1.87 +ATOM 62 CD LYS A 158 21.236 53.111 17.369 20.931 1.87 +ATOM 63 CE LYS A 158 20.159 54.136 17.694 37.362 1.87 +ATOM 64 NZ LYS A 158 19.231 54.379 16.560 42.639 1.50 +ATOM 65 N GLU A 159 23.152 48.085 17.961 1.054 1.65 +ATOM 66 CA GLU A 159 24.037 46.996 17.561 4.111 1.87 +ATOM 67 C GLU A 159 23.563 46.364 16.255 1.016 1.76 +ATOM 68 O GLU A 159 22.398 45.994 16.132 3.126 1.40 +ATOM 69 CB GLU A 159 24.086 45.924 18.653 8.581 1.87 +ATOM 70 CG GLU A 159 25.003 44.744 18.321 9.289 1.87 +ATOM 71 CD GLU A 159 24.858 43.575 19.284 4.912 1.76 +ATOM 72 OE1 GLU A 159 23.861 43.516 20.039 .547 1.40 +ATOM 73 OE2 GLU A 159 25.748 42.701 19.277 3.382 1.40 +ATOM 74 N PRO A 160 24.459 46.247 15.256 .026 1.65 +ATOM 75 CA PRO A 160 24.089 45.645 13.969 7.316 1.87 +ATOM 76 C PRO A 160 23.580 44.224 14.212 .000 1.76 +ATOM 77 O PRO A 160 24.111 43.515 15.070 .000 1.40 +ATOM 78 CB PRO A 160 25.415 45.639 13.207 7.426 1.87 +ATOM 79 CG PRO A 160 26.116 46.856 13.749 30.220 1.87 +ATOM 80 CD PRO A 160 25.852 46.732 15.231 12.036 1.87 +ATOM 81 N PHE A 161 22.544 43.824 13.480 2.677 1.65 +ATOM 82 CA PHE A 161 21.960 42.494 13.639 .000 1.87 +ATOM 83 C PHE A 161 22.965 41.346 13.502 .000 1.76 +ATOM 84 O PHE A 161 22.928 40.397 14.283 .000 1.40 +ATOM 85 CB PHE A 161 20.793 42.292 12.666 1.403 1.87 +ATOM 86 CG PHE A 161 19.999 41.042 12.927 .000 1.76 +ATOM 87 CD1 PHE A 161 19.234 40.918 14.085 .000 1.76 +ATOM 88 CD2 PHE A 161 20.019 39.985 12.021 10.723 1.76 +ATOM 89 CE1 PHE A 161 18.495 39.758 14.340 .000 1.76 +ATOM 90 CE2 PHE A 161 19.286 38.821 12.263 8.557 1.76 +ATOM 91 CZ PHE A 161 18.523 38.708 13.427 1.900 1.76 +ATOM 92 N ARG A 162 23.861 41.443 12.522 2.294 1.65 +ATOM 93 CA ARG A 162 24.870 40.411 12.294 .617 1.87 +ATOM 94 C ARG A 162 25.788 40.216 13.509 .000 1.76 +ATOM 95 O ARG A 162 26.158 39.090 13.835 .000 1.40 +ATOM 96 CB ARG A 162 25.684 40.732 11.032 25.347 1.87 +ATOM 97 CG ARG A 162 26.777 39.725 10.715 17.281 1.87 +ATOM 98 CD ARG A 162 26.215 38.321 10.515 18.082 1.87 +ATOM 99 NE ARG A 162 27.235 37.297 10.736 2.717 1.65 +ATOM 100 CZ ARG A 162 28.136 36.918 9.833 6.269 1.76 +ATOM 101 NH1 ARG A 162 28.155 37.473 8.628 47.024 1.65 +ATOM 102 NH2 ARG A 162 29.030 35.992 10.145 44.980 1.65 +ATOM 103 N ASP A 163 26.137 41.309 14.185 .000 1.65 +ATOM 104 CA ASP A 163 26.994 41.247 15.373 2.277 1.87 +ATOM 105 C ASP A 163 26.279 40.526 16.517 .000 1.76 +ATOM 106 O ASP A 163 26.880 39.735 17.245 1.209 1.40 +ATOM 107 CB ASP A 163 27.408 42.658 15.805 9.604 1.87 +ATOM 108 CG ASP A 163 28.345 43.328 14.804 8.361 1.76 +ATOM 109 OD1 ASP A 163 28.814 42.655 13.859 24.745 1.40 +ATOM 110 OD2 ASP A 163 28.620 44.532 14.968 23.848 1.40 +ATOM 111 N TYR A 164 24.992 40.818 16.662 .000 1.65 +ATOM 112 CA TYR A 164 24.151 40.196 17.672 .000 1.87 +ATOM 113 C TYR A 164 24.025 38.704 17.350 .000 1.76 +ATOM 114 O TYR A 164 24.139 37.861 18.238 .000 1.40 +ATOM 115 CB TYR A 164 22.787 40.897 17.684 .000 1.87 +ATOM 116 CG TYR A 164 21.629 40.095 18.244 .000 1.76 +ATOM 117 CD1 TYR A 164 21.657 39.583 19.543 .000 1.76 +ATOM 118 CD2 TYR A 164 20.489 39.874 17.474 .000 1.76 +ATOM 119 CE1 TYR A 164 20.571 38.872 20.056 .000 1.76 +ATOM 120 CE2 TYR A 164 19.408 39.171 17.972 .000 1.76 +ATOM 121 CZ TYR A 164 19.450 38.673 19.258 .000 1.76 +ATOM 122 OH TYR A 164 18.365 37.977 19.732 .000 1.40 +ATOM 123 N VAL A 165 23.839 38.388 16.069 .000 1.65 +ATOM 124 CA VAL A 165 23.720 37.002 15.614 .000 1.87 +ATOM 125 C VAL A 165 24.962 36.204 15.999 .000 1.76 +ATOM 126 O VAL A 165 24.853 35.084 16.498 .000 1.40 +ATOM 127 CB VAL A 165 23.502 36.931 14.077 .000 1.87 +ATOM 128 CG1 VAL A 165 23.661 35.501 13.570 8.189 1.87 +ATOM 129 CG2 VAL A 165 22.120 37.444 13.733 2.131 1.87 +ATOM 130 N ASP A 166 26.137 36.796 15.797 .000 1.65 +ATOM 131 CA ASP A 166 27.387 36.126 16.139 2.281 1.87 +ATOM 132 C ASP A 166 27.511 35.879 17.644 1.302 1.76 +ATOM 133 O ASP A 166 27.925 34.804 18.060 1.514 1.40 +ATOM 134 CB ASP A 166 28.595 36.912 15.612 21.675 1.87 +ATOM 135 CG ASP A 166 28.723 36.860 14.085 6.903 1.76 +ATOM 136 OD1 ASP A 166 28.016 36.066 13.422 9.424 1.40 +ATOM 137 OD2 ASP A 166 29.545 37.627 13.543 23.179 1.40 +ATOM 138 N ARG A 167 27.136 36.859 18.461 .074 1.65 +ATOM 139 CA ARG A 167 27.202 36.685 19.913 1.500 1.87 +ATOM 140 C ARG A 167 26.238 35.580 20.335 .000 1.76 +ATOM 141 O ARG A 167 26.585 34.701 21.120 .732 1.40 +ATOM 142 CB ARG A 167 26.850 37.988 20.638 1.573 1.87 +ATOM 143 CG ARG A 167 27.835 39.118 20.394 18.541 1.87 +ATOM 144 CD ARG A 167 27.667 40.246 21.404 31.735 1.87 +ATOM 145 NE ARG A 167 26.352 40.877 21.333 1.345 1.65 +ATOM 146 CZ ARG A 167 25.494 40.940 22.345 4.223 1.76 +ATOM 147 NH1 ARG A 167 25.797 40.401 23.519 25.855 1.65 +ATOM 148 NH2 ARG A 167 24.325 41.539 22.181 6.135 1.65 +ATOM 149 N PHE A 168 25.037 35.622 19.769 .000 1.65 +ATOM 150 CA PHE A 168 23.984 34.649 20.039 .025 1.87 +ATOM 151 C PHE A 168 24.456 33.232 19.729 .000 1.76 +ATOM 152 O PHE A 168 24.305 32.327 20.552 1.954 1.40 +ATOM 153 CB PHE A 168 22.761 34.993 19.186 .000 1.87 +ATOM 154 CG PHE A 168 21.538 34.184 19.504 .073 1.76 +ATOM 155 CD1 PHE A 168 21.301 32.973 18.859 .107 1.76 +ATOM 156 CD2 PHE A 168 20.586 34.664 20.397 2.400 1.76 +ATOM 157 CE1 PHE A 168 20.130 32.254 19.094 2.318 1.76 +ATOM 158 CE2 PHE A 168 19.415 33.954 20.639 6.121 1.76 +ATOM 159 CZ PHE A 168 19.186 32.747 19.985 9.534 1.76 +ATOM 160 N TYR A 169 25.033 33.048 18.544 .000 1.65 +ATOM 161 CA TYR A 169 25.526 31.738 18.123 .000 1.87 +ATOM 162 C TYR A 169 26.755 31.256 18.875 .000 1.76 +ATOM 163 O TYR A 169 27.015 30.057 18.949 .000 1.40 +ATOM 164 CB TYR A 169 25.771 31.709 16.616 6.316 1.87 +ATOM 165 CG TYR A 169 24.608 31.119 15.869 2.343 1.76 +ATOM 166 CD1 TYR A 169 23.508 31.900 15.519 .715 1.76 +ATOM 167 CD2 TYR A 169 24.583 29.762 15.555 11.177 1.76 +ATOM 168 CE1 TYR A 169 22.406 31.340 14.877 .000 1.76 +ATOM 169 CE2 TYR A 169 23.490 29.193 14.913 9.956 1.76 +ATOM 170 CZ TYR A 169 22.406 29.985 14.577 .682 1.76 +ATOM 171 OH TYR A 169 21.326 29.415 13.941 9.814 1.40 +ATOM 172 N LYS A 170 27.508 32.195 19.432 .000 1.65 +ATOM 173 CA LYS A 170 28.691 31.859 20.208 .000 1.87 +ATOM 174 C LYS A 170 28.183 31.155 21.468 .665 1.76 +ATOM 175 O LYS A 170 28.705 30.117 21.859 5.086 1.40 +ATOM 176 CB LYS A 170 29.455 33.137 20.556 .997 1.87 +ATOM 177 CG LYS A 170 30.787 32.942 21.242 16.562 1.87 +ATOM 178 CD LYS A 170 31.428 34.297 21.496 25.560 1.87 +ATOM 179 CE LYS A 170 32.618 34.194 22.436 45.068 1.87 +ATOM 180 NZ LYS A 170 33.153 35.536 22.820 48.641 1.50 +ATOM 181 N THR A 171 27.116 31.695 22.055 .000 1.65 +ATOM 182 CA THR A 171 26.508 31.110 23.247 5.215 1.87 +ATOM 183 C THR A 171 25.826 29.789 22.889 .000 1.76 +ATOM 184 O THR A 171 25.827 28.840 23.676 .062 1.40 +ATOM 185 CB THR A 171 25.475 32.075 23.876 1.098 1.87 +ATOM 186 OG1 THR A 171 26.150 33.240 24.357 13.388 1.40 +ATOM 187 CG2 THR A 171 24.741 31.417 25.045 48.926 1.87 +ATOM 188 N LEU A 172 25.264 29.727 21.687 .164 1.65 +ATOM 189 CA LEU A 172 24.587 28.528 21.224 1.718 1.87 +ATOM 190 C LEU A 172 25.587 27.392 20.984 .589 1.76 +ATOM 191 O LEU A 172 25.302 26.236 21.301 .000 1.40 +ATOM 192 CB LEU A 172 23.789 28.840 19.955 .750 1.87 +ATOM 193 CG LEU A 172 22.707 27.854 19.514 .720 1.87 +ATOM 194 CD1 LEU A 172 21.787 27.515 20.682 26.378 1.87 +ATOM 195 CD2 LEU A 172 21.910 28.464 18.375 1.741 1.87 +ATOM 196 N ARG A 173 26.767 27.727 20.462 .122 1.65 +ATOM 197 CA ARG A 173 27.806 26.728 20.202 4.512 1.87 +ATOM 198 C ARG A 173 28.299 26.044 21.468 .904 1.76 +ATOM 199 O ARG A 173 28.656 24.864 21.443 4.779 1.40 +ATOM 200 CB ARG A 173 29.006 27.352 19.492 8.983 1.87 +ATOM 201 CG ARG A 173 28.944 27.266 17.984 17.930 1.87 +ATOM 202 CD ARG A 173 30.295 27.583 17.356 37.282 1.87 +ATOM 203 NE ARG A 173 30.744 28.937 17.662 14.045 1.65 +ATOM 204 CZ ARG A 173 30.326 30.032 17.033 4.464 1.76 +ATOM 205 NH1 ARG A 173 29.441 29.954 16.046 27.568 1.65 +ATOM 206 NH2 ARG A 173 30.787 31.215 17.406 29.995 1.65 +ATOM 207 N ALA A 174 28.332 26.793 22.568 .406 1.65 +ATOM 208 CA ALA A 174 28.789 26.276 23.854 9.822 1.87 +ATOM 209 C ALA A 174 27.943 25.109 24.350 .000 1.76 +ATOM 210 O ALA A 174 28.374 24.348 25.215 16.269 1.40 +ATOM 211 CB ALA A 174 28.803 27.388 24.888 41.450 1.87 +ATOM 212 N GLU A 175 26.740 24.973 23.801 .000 1.65 +ATOM 213 CA GLU A 175 25.833 23.899 24.186 2.332 1.87 +ATOM 214 C GLU A 175 25.775 22.791 23.139 .030 1.76 +ATOM 215 O GLU A 175 24.998 21.847 23.280 18.956 1.40 +ATOM 216 CB GLU A 175 24.425 24.456 24.418 12.362 1.87 +ATOM 217 CG GLU A 175 24.354 25.596 25.435 19.466 1.87 +ATOM 218 CD GLU A 175 24.816 25.190 26.824 9.282 1.76 +ATOM 219 OE1 GLU A 175 24.535 24.049 27.243 34.463 1.40 +ATOM 220 OE2 GLU A 175 25.454 26.018 27.506 32.000 1.40 +ATOM 221 N GLN A 176 26.601 22.907 22.098 .000 1.65 +ATOM 222 CA GLN A 176 26.645 21.930 21.007 7.972 1.87 +ATOM 223 C GLN A 176 25.240 21.583 20.533 1.073 1.76 +ATOM 224 O GLN A 176 24.885 20.411 20.389 20.005 1.40 +ATOM 225 CB GLN A 176 27.391 20.655 21.422 22.169 1.87 +ATOM 226 CG GLN A 176 28.884 20.833 21.646 35.203 1.87 +ATOM 227 CD GLN A 176 29.200 21.479 22.977 5.521 1.76 +ATOM 228 OE1 GLN A 176 28.729 21.028 24.025 26.283 1.40 +ATOM 229 NE2 GLN A 176 29.998 22.543 22.947 29.649 1.65 +ATOM 230 N ALA A 177 24.438 22.619 20.314 1.422 1.65 +ATOM 231 CA ALA A 177 23.066 22.454 19.863 5.561 1.87 +ATOM 232 C ALA A 177 23.001 21.782 18.498 .065 1.76 +ATOM 233 O ALA A 177 23.824 22.046 17.620 9.176 1.40 +ATOM 234 CB ALA A 177 22.370 23.806 19.817 2.348 1.87 +ATOM 235 N SER A 178 22.035 20.886 18.339 2.057 1.65 +ATOM 236 CA SER A 178 21.831 20.180 17.080 11.528 1.87 +ATOM 237 C SER A 178 21.174 21.137 16.090 .144 1.76 +ATOM 238 O SER A 178 20.852 22.271 16.441 .000 1.40 +ATOM 239 CB SER A 178 20.917 18.979 17.305 43.136 1.87 +ATOM 240 OG SER A 178 19.638 19.408 17.741 6.205 1.40 +ATOM 241 N GLN A 179 20.949 20.675 14.865 7.634 1.65 +ATOM 242 CA GLN A 179 20.315 21.512 13.851 .440 1.87 +ATOM 243 C GLN A 179 18.908 21.923 14.284 .000 1.76 +ATOM 244 O GLN A 179 18.539 23.095 14.184 .000 1.40 +ATOM 245 CB GLN A 179 20.262 20.791 12.500 28.119 1.87 +ATOM 246 CG GLN A 179 19.688 21.641 11.372 25.453 1.87 +ATOM 247 CD GLN A 179 20.414 22.968 11.212 4.860 1.76 +ATOM 248 OE1 GLN A 179 21.592 23.004 10.860 29.416 1.40 +ATOM 249 NE2 GLN A 179 19.714 24.065 11.484 17.669 1.65 +ATOM 250 N GLU A 180 18.136 20.955 14.773 .833 1.65 +ATOM 251 CA GLU A 180 16.775 21.211 15.233 .000 1.87 +ATOM 252 C GLU A 180 16.738 22.240 16.354 .000 1.76 +ATOM 253 O GLU A 180 15.875 23.117 16.360 .000 1.40 +ATOM 254 CB GLU A 180 16.101 19.916 15.692 7.079 1.87 +ATOM 255 CG GLU A 180 15.478 19.100 14.569 35.598 1.87 +ATOM 256 CD GLU A 180 14.341 19.832 13.879 8.939 1.76 +ATOM 257 OE1 GLU A 180 13.247 19.935 14.473 20.971 1.40 +ATOM 258 OE2 GLU A 180 14.542 20.307 12.743 23.306 1.40 +ATOM 259 N VAL A 181 17.668 22.133 17.300 .000 1.65 +ATOM 260 CA VAL A 181 17.730 23.079 18.412 .000 1.87 +ATOM 261 C VAL A 181 18.064 24.477 17.897 .000 1.76 +ATOM 262 O VAL A 181 17.491 25.467 18.352 4.823 1.40 +ATOM 263 CB VAL A 181 18.754 22.639 19.484 .000 1.87 +ATOM 264 CG1 VAL A 181 18.932 23.733 20.530 29.246 1.87 +ATOM 265 CG2 VAL A 181 18.279 21.357 20.158 30.227 1.87 +ATOM 266 N LYS A 182 18.971 24.552 16.929 .000 1.65 +ATOM 267 CA LYS A 182 19.343 25.835 16.344 .000 1.87 +ATOM 268 C LYS A 182 18.126 26.477 15.685 .140 1.76 +ATOM 269 O LYS A 182 17.905 27.680 15.830 .294 1.40 +ATOM 270 CB LYS A 182 20.444 25.660 15.306 .676 1.87 +ATOM 271 CG LYS A 182 21.777 25.239 15.874 .000 1.87 +ATOM 272 CD LYS A 182 22.756 25.055 14.742 5.860 1.87 +ATOM 273 CE LYS A 182 24.069 24.517 15.226 13.422 1.87 +ATOM 274 NZ LYS A 182 24.913 24.222 14.047 43.920 1.50 +ATOM 275 N ASN A 183 17.344 25.672 14.964 .000 1.65 +ATOM 276 CA ASN A 183 16.136 26.161 14.297 2.092 1.87 +ATOM 277 C ASN A 183 15.146 26.712 15.308 .000 1.76 +ATOM 278 O ASN A 183 14.599 27.791 15.108 .301 1.40 +ATOM 279 CB ASN A 183 15.468 25.055 13.475 10.678 1.87 +ATOM 280 CG ASN A 183 16.242 24.712 12.220 5.564 1.76 +ATOM 281 OD1 ASN A 183 17.164 25.430 11.828 17.046 1.40 +ATOM 282 ND2 ASN A 183 15.865 23.613 11.576 28.105 1.65 +ATOM 283 N TRP A 184 14.932 25.976 16.397 .000 1.65 +ATOM 284 CA TRP A 184 14.017 26.406 17.450 .270 1.87 +ATOM 285 C TRP A 184 14.495 27.713 18.072 6.652 1.76 +ATOM 286 O TRP A 184 13.700 28.624 18.299 .000 1.40 +ATOM 287 CB TRP A 184 13.904 25.342 18.545 16.576 1.87 +ATOM 288 CG TRP A 184 13.254 24.076 18.112 2.177 1.76 +ATOM 289 CD1 TRP A 184 12.332 23.924 17.121 11.448 1.76 +ATOM 290 CD2 TRP A 184 13.484 22.772 18.655 2.579 1.76 +ATOM 291 NE1 TRP A 184 11.975 22.601 17.007 20.144 1.65 +ATOM 292 CE2 TRP A 184 12.666 21.873 17.937 3.275 1.76 +ATOM 293 CE3 TRP A 184 14.303 22.276 19.678 13.098 1.76 +ATOM 294 CZ2 TRP A 184 12.641 20.502 18.209 22.067 1.76 +ATOM 295 CZ3 TRP A 184 14.280 20.914 19.948 20.803 1.76 +ATOM 296 CH2 TRP A 184 13.452 20.042 19.213 29.151 1.76 +ATOM 305 N THR A 186 16.438 29.964 16.716 3.674 1.65 +ATOM 306 CA THR A 186 16.375 31.015 15.695 .000 1.87 +ATOM 307 C THR A 186 14.950 31.585 15.557 .000 1.76 +ATOM 308 O THR A 186 14.778 32.797 15.378 1.326 1.40 +ATOM 309 CB THR A 186 16.869 30.474 14.331 2.345 1.87 +ATOM 310 OG1 THR A 186 18.228 30.039 14.461 1.920 1.40 +ATOM 311 CG2 THR A 186 16.791 31.544 13.245 12.538 1.87 +ATOM 312 N GLU A 187 13.947 30.705 15.643 .000 1.65 +ATOM 313 CA GLU A 187 12.529 31.082 15.544 8.546 1.87 +ATOM 314 C GLU A 187 12.045 31.815 16.785 .021 1.76 +ATOM 315 O GLU A 187 11.151 32.654 16.700 14.381 1.40 +ATOM 316 CB GLU A 187 11.625 29.849 15.408 13.346 1.87 +ATOM 317 CG GLU A 187 11.950 28.866 14.305 11.888 1.87 +ATOM 318 CD GLU A 187 11.054 27.634 14.345 8.127 1.76 +ATOM 319 OE1 GLU A 187 11.086 26.907 15.364 12.687 1.40 +ATOM 320 OE2 GLU A 187 10.326 27.392 13.357 30.194 1.40 +ATOM 321 N THR A 188 12.589 31.444 17.942 .000 1.65 +ATOM 322 CA THR A 188 12.177 32.030 19.212 .126 1.87 +ATOM 323 C THR A 188 13.076 33.117 19.787 .000 1.76 +ATOM 324 O THR A 188 12.888 34.301 19.504 .000 1.40 +ATOM 325 CB THR A 188 11.978 30.936 20.287 4.548 1.87 +ATOM 326 OG1 THR A 188 13.202 30.210 20.469 10.198 1.40 +ATOM 327 CG2 THR A 188 10.883 29.970 19.861 46.233 1.87 +ATOM 328 N LEU A 189 14.054 32.705 20.590 .074 1.65 +ATOM 329 CA LEU A 189 14.963 33.627 21.252 .000 1.87 +ATOM 330 C LEU A 189 15.702 34.645 20.392 .000 1.76 +ATOM 331 O LEU A 189 15.846 35.795 20.805 .000 1.40 +ATOM 332 CB LEU A 189 15.935 32.864 22.153 3.615 1.87 +ATOM 333 CG LEU A 189 15.286 32.289 23.417 5.355 1.87 +ATOM 334 CD1 LEU A 189 16.327 31.647 24.304 62.618 1.87 +ATOM 335 CD2 LEU A 189 14.580 33.396 24.183 27.594 1.87 +ATOM 336 N LEU A 190 16.162 34.254 19.205 .000 1.65 +ATOM 337 CA LEU A 190 16.876 35.211 18.356 .000 1.87 +ATOM 338 C LEU A 190 15.961 36.378 17.999 .000 1.76 +ATOM 339 O LEU A 190 16.391 37.528 17.968 .000 1.40 +ATOM 340 CB LEU A 190 17.402 34.552 17.078 .000 1.87 +ATOM 341 CG LEU A 190 18.238 35.486 16.188 .000 1.87 +ATOM 342 CD1 LEU A 190 19.553 35.825 16.881 .000 1.87 +ATOM 343 CD2 LEU A 190 18.506 34.834 14.842 4.339 1.87 +ATOM 344 N VAL A 191 14.695 36.068 17.738 .000 1.65 +ATOM 345 CA VAL A 191 13.703 37.080 17.395 .000 1.87 +ATOM 346 C VAL A 191 13.270 37.854 18.643 .000 1.76 +ATOM 347 O VAL A 191 13.262 39.086 18.649 .000 1.40 +ATOM 348 CB VAL A 191 12.460 36.438 16.718 .000 1.87 +ATOM 349 CG1 VAL A 191 11.372 37.479 16.491 1.342 1.87 +ATOM 350 CG2 VAL A 191 12.854 35.806 15.394 17.375 1.87 +ATOM 351 N GLN A 192 12.954 37.119 19.706 .000 1.65 +ATOM 352 CA GLN A 192 12.503 37.705 20.967 .000 1.87 +ATOM 353 C GLN A 192 13.541 38.565 21.682 .000 1.76 +ATOM 354 O GLN A 192 13.184 39.453 22.453 9.338 1.40 +ATOM 355 CB GLN A 192 12.008 36.602 21.902 6.312 1.87 +ATOM 356 CG GLN A 192 10.830 35.818 21.343 7.400 1.87 +ATOM 357 CD GLN A 192 10.505 34.578 22.155 5.545 1.76 +ATOM 358 OE1 GLN A 192 10.626 34.568 23.385 26.944 1.40 +ATOM 359 NE2 GLN A 192 10.093 33.520 21.466 22.469 1.65 +ATOM 360 N ASN A 193 14.820 38.291 21.445 .000 1.65 +ATOM 361 CA ASN A 193 15.887 39.056 22.080 1.008 1.87 +ATOM 362 C ASN A 193 16.443 40.164 21.189 1.045 1.76 +ATOM 363 O ASN A 193 17.416 40.823 21.548 1.966 1.40 +ATOM 364 CB ASN A 193 17.014 38.130 22.538 .000 1.87 +ATOM 365 CG ASN A 193 16.627 37.286 23.738 .000 1.76 +ATOM 366 OD1 ASN A 193 15.451 37.192 24.094 3.798 1.40 +ATOM 367 ND2 ASN A 193 17.619 36.681 24.378 9.884 1.65 +ATOM 368 N ALA A 194 15.830 40.353 20.023 .000 1.65 +ATOM 369 CA ALA A 194 16.248 41.392 19.084 .000 1.87 +ATOM 370 C ALA A 194 15.758 42.759 19.582 .331 1.76 +ATOM 371 O ALA A 194 14.809 42.834 20.368 8.554 1.40 +ATOM 372 CB ALA A 194 15.689 41.097 17.701 .000 1.87 +ATOM 373 N ASN A 195 16.404 43.837 19.140 .000 1.65 +ATOM 374 CA ASN A 195 16.005 45.172 19.582 3.232 1.87 +ATOM 375 C ASN A 195 14.639 45.580 19.015 .000 1.76 +ATOM 376 O ASN A 195 14.122 44.928 18.111 .000 1.40 +ATOM 377 CB ASN A 195 17.109 46.213 19.295 .321 1.87 +ATOM 378 CG ASN A 195 17.396 46.399 17.818 .563 1.76 +ATOM 379 OD1 ASN A 195 16.559 46.131 16.960 .293 1.40 +ATOM 380 ND2 ASN A 195 18.588 46.890 17.519 7.084 1.65 +ATOM 381 N PRO A 196 14.018 46.635 19.574 .392 1.65 +ATOM 382 CA PRO A 196 12.706 47.128 19.133 7.844 1.87 +ATOM 383 C PRO A 196 12.516 47.250 17.620 1.908 1.76 +ATOM 384 O PRO A 196 11.536 46.743 17.073 4.213 1.40 +ATOM 385 CB PRO A 196 12.617 48.485 19.822 31.414 1.87 +ATOM 386 CG PRO A 196 13.288 48.219 21.117 43.377 1.87 +ATOM 387 CD PRO A 196 14.522 47.454 20.693 17.291 1.87 +ATOM 388 N ASP A 197 13.454 47.913 16.952 .123 1.65 +ATOM 389 CA ASP A 197 13.383 48.098 15.506 6.388 1.87 +ATOM 390 C ASP A 197 13.351 46.786 14.733 .000 1.76 +ATOM 391 O ASP A 197 12.406 46.515 13.991 2.939 1.40 +ATOM 392 CB ASP A 197 14.564 48.939 15.018 20.609 1.87 +ATOM 393 CG ASP A 197 14.482 50.380 15.475 12.470 1.76 +ATOM 394 OD1 ASP A 197 13.353 50.889 15.662 33.551 1.40 +ATOM 395 OD2 ASP A 197 15.552 51.007 15.637 28.804 1.40 +ATOM 396 N CYS A 198 14.378 45.967 14.932 .227 1.65 +ATOM 397 CA CYS A 198 14.488 44.687 14.241 .963 1.87 +ATOM 398 C CYS A 198 13.443 43.638 14.633 .000 1.76 +ATOM 399 O CYS A 198 12.968 42.886 13.783 .000 1.40 +ATOM 400 CB CYS A 198 15.902 44.124 14.411 5.598 1.87 +ATOM 401 SG CYS A 198 16.144 42.477 13.674 .000 1.85 +ATOM 402 N LYS A 199 13.061 43.612 15.907 .000 1.65 +ATOM 403 CA LYS A 199 12.087 42.641 16.402 .000 1.87 +ATOM 404 C LYS A 199 10.746 42.686 15.673 .000 1.76 +ATOM 405 O LYS A 199 10.157 41.641 15.386 .000 1.40 +ATOM 406 CB LYS A 199 11.879 42.818 17.907 1.211 1.87 +ATOM 407 CG LYS A 199 11.014 41.753 18.541 4.192 1.87 +ATOM 408 CD LYS A 199 11.003 41.892 20.045 16.083 1.87 +ATOM 409 CE LYS A 199 10.171 40.797 20.670 16.832 1.87 +ATOM 410 NZ LYS A 199 10.269 40.823 22.154 33.658 1.50 +ATOM 411 N THR A 200 10.273 43.892 15.369 .165 1.65 +ATOM 412 CA THR A 200 9.002 44.065 14.665 5.526 1.87 +ATOM 413 C THR A 200 9.101 43.494 13.251 .000 1.76 +ATOM 414 O THR A 200 8.227 42.753 12.799 1.128 1.40 +ATOM 415 CB THR A 200 8.612 45.551 14.577 5.538 1.87 +ATOM 416 OG1 THR A 200 8.611 46.122 15.892 23.213 1.40 +ATOM 417 CG2 THR A 200 7.224 45.702 13.961 60.295 1.87 +ATOM 418 N ILE A 201 10.191 43.835 12.574 .000 1.65 +ATOM 419 CA ILE A 201 10.458 43.373 11.221 4.163 1.87 +ATOM 420 C ILE A 201 10.518 41.848 11.161 .000 1.76 +ATOM 421 O ILE A 201 9.916 41.229 10.284 1.180 1.40 +ATOM 422 CB ILE A 201 11.791 43.960 10.721 .000 1.87 +ATOM 423 CG1 ILE A 201 11.677 45.481 10.620 18.988 1.87 +ATOM 424 CG2 ILE A 201 12.184 43.356 9.389 15.109 1.87 +ATOM 425 CD1 ILE A 201 12.967 46.169 10.250 38.939 1.87 +ATOM 426 N LEU A 202 11.222 41.249 12.117 .000 1.65 +ATOM 427 CA LEU A 202 11.377 39.801 12.170 .000 1.87 +ATOM 428 C LEU A 202 10.082 39.036 12.412 .000 1.76 +ATOM 429 O LEU A 202 9.885 37.956 11.855 7.535 1.40 +ATOM 430 CB LEU A 202 12.416 39.416 13.221 .586 1.87 +ATOM 431 CG LEU A 202 13.824 39.939 12.950 .000 1.87 +ATOM 432 CD1 LEU A 202 14.764 39.438 14.027 1.240 1.87 +ATOM 433 CD2 LEU A 202 14.287 39.491 11.575 10.066 1.87 +ATOM 434 N LYS A 203 9.214 39.575 13.261 .000 1.65 +ATOM 435 CA LYS A 203 7.937 38.927 13.546 2.544 1.87 +ATOM 436 C LYS A 203 7.048 38.954 12.303 1.381 1.76 +ATOM 437 O LYS A 203 6.294 38.011 12.044 17.022 1.40 +ATOM 438 CB LYS A 203 7.230 39.620 14.712 18.502 1.87 +ATOM 439 CG LYS A 203 7.828 39.324 16.085 10.831 1.87 +ATOM 440 CD LYS A 203 7.618 37.867 16.471 21.409 1.87 +ATOM 441 CE LYS A 203 8.090 37.590 17.889 14.257 1.87 +ATOM 442 NZ LYS A 203 7.916 36.158 18.262 27.636 1.50 +ATOM 443 N ALA A 204 7.189 40.020 11.516 .159 1.65 +ATOM 444 CA ALA A 204 6.419 40.213 10.290 12.085 1.87 +ATOM 445 C ALA A 204 6.871 39.332 9.117 1.702 1.76 +ATOM 446 O ALA A 204 6.391 39.495 7.991 27.103 1.40 +ATOM 447 CB ALA A 204 6.449 41.683 9.885 45.475 1.87 +ATOM 448 N LEU A 205 7.815 38.428 9.369 .000 1.65 +ATOM 449 CA LEU A 205 8.305 37.528 8.328 1.824 1.87 +ATOM 450 C LEU A 205 7.481 36.243 8.312 1.850 1.76 +ATOM 451 O LEU A 205 7.371 35.579 7.281 26.753 1.40 +ATOM 452 CB LEU A 205 9.788 37.196 8.539 .633 1.87 +ATOM 453 CG LEU A 205 10.832 38.299 8.323 .000 1.87 +ATOM 454 CD1 LEU A 205 12.217 37.767 8.660 4.692 1.87 +ATOM 455 CD2 LEU A 205 10.789 38.797 6.888 38.970 1.87 +ATOM 456 N GLY A 206 6.886 35.909 9.455 .865 1.65 +ATOM 457 CA GLY A 206 6.080 34.704 9.548 22.542 1.87 +ATOM 458 C GLY A 206 6.922 33.478 9.835 4.345 1.76 +ATOM 459 O GLY A 206 8.149 33.569 9.881 7.444 1.40 +ATOM 460 N PRO A 207 6.294 32.310 10.042 .343 1.65 +ATOM 461 CA PRO A 207 7.024 31.068 10.328 10.674 1.87 +ATOM 462 C PRO A 207 7.912 30.540 9.197 1.266 1.76 +ATOM 463 O PRO A 207 7.680 30.812 8.017 20.161 1.40 +ATOM 464 CB PRO A 207 5.901 30.083 10.675 36.106 1.87 +ATOM 465 CG PRO A 207 4.734 30.601 9.890 39.896 1.87 +ATOM 466 CD PRO A 207 4.839 32.090 10.112 31.688 1.87 +ATOM 467 N GLY A 208 8.952 29.808 9.585 4.177 1.65 +ATOM 468 CA GLY A 208 9.861 29.227 8.617 35.704 1.87 +ATOM 469 C GLY A 208 10.886 30.161 8.004 4.118 1.76 +ATOM 470 O GLY A 208 11.642 29.736 7.130 17.956 1.40 +ATOM 471 N ALA A 209 10.910 31.423 8.429 1.610 1.65 +ATOM 472 CA ALA A 209 11.884 32.382 7.900 3.789 1.87 +ATOM 473 C ALA A 209 13.285 31.936 8.311 .067 1.76 +ATOM 474 O ALA A 209 13.524 31.614 9.478 14.483 1.40 +ATOM 475 CB ALA A 209 11.599 33.779 8.428 14.143 1.87 +ATOM 476 N THR A 210 14.199 31.887 7.347 .000 1.65 +ATOM 477 CA THR A 210 15.563 31.458 7.625 6.924 1.87 +ATOM 478 C THR A 210 16.391 32.562 8.265 .411 1.76 +ATOM 479 O THR A 210 16.022 33.735 8.212 5.286 1.40 +ATOM 480 CB THR A 210 16.290 31.000 6.345 3.512 1.87 +ATOM 481 OG1 THR A 210 16.498 32.124 5.479 2.619 1.40 +ATOM 482 CG2 THR A 210 15.473 29.943 5.616 51.918 1.87 +ATOM 483 N LEU A 211 17.509 32.169 8.871 3.623 1.65 +ATOM 484 CA LEU A 211 18.426 33.111 9.499 3.156 1.87 +ATOM 485 C LEU A 211 18.875 34.122 8.447 .000 1.76 +ATOM 486 O LEU A 211 19.012 35.308 8.739 9.136 1.40 +ATOM 487 CB LEU A 211 19.645 32.369 10.045 8.519 1.87 +ATOM 488 CG LEU A 211 20.773 33.233 10.603 5.634 1.87 +ATOM 489 CD1 LEU A 211 20.264 34.065 11.765 1.659 1.87 +ATOM 490 CD2 LEU A 211 21.920 32.342 11.045 27.920 1.87 +ATOM 491 N GLU A 212 19.082 33.643 7.221 .000 1.65 +ATOM 492 CA GLU A 212 19.510 34.489 6.111 8.516 1.87 +ATOM 493 C GLU A 212 18.471 35.569 5.808 .000 1.76 +ATOM 494 O GLU A 212 18.816 36.740 5.636 2.850 1.40 +ATOM 495 CB GLU A 212 19.784 33.638 4.863 20.774 1.87 +ATOM 496 CG GLU A 212 21.035 32.751 4.953 39.133 1.87 +ATOM 497 CD GLU A 212 20.954 31.668 6.033 8.049 1.76 +ATOM 498 OE1 GLU A 212 19.902 30.999 6.155 15.404 1.40 +ATOM 499 OE2 GLU A 212 21.955 31.483 6.762 27.553 1.40 +ATOM 500 N GLU A 213 17.199 35.173 5.771 .000 1.65 +ATOM 501 CA GLU A 213 16.109 36.113 5.512 3.614 1.87 +ATOM 502 C GLU A 213 16.001 37.117 6.660 4.742 1.76 +ATOM 503 O GLU A 213 15.690 38.289 6.438 2.378 1.40 +ATOM 504 CB GLU A 213 14.787 35.364 5.300 5.119 1.87 +ATOM 505 CG GLU A 213 14.776 34.514 4.026 23.353 1.87 +ATOM 506 CD GLU A 213 13.539 33.638 3.893 9.592 1.76 +ATOM 507 OE1 GLU A 213 13.220 32.890 4.838 5.575 1.40 +ATOM 508 OE2 GLU A 213 12.888 33.683 2.829 41.810 1.40 +ATOM 525 N THR A 216 18.915 39.521 6.253 18.181 1.65 +ATOM 526 CA THR A 216 18.636 40.413 5.133 4.541 1.87 +ATOM 527 C THR A 216 17.640 41.485 5.571 .000 1.76 +ATOM 528 O THR A 216 17.807 42.666 5.263 4.862 1.40 +ATOM 529 CB THR A 216 18.050 39.641 3.929 2.891 1.87 +ATOM 530 OG1 THR A 216 18.998 38.664 3.483 24.330 1.40 +ATOM 531 CG2 THR A 216 17.730 40.596 2.778 50.916 1.87 +ATOM 532 N ALA A 217 16.631 41.064 6.328 .490 1.65 +ATOM 533 CA ALA A 217 15.593 41.963 6.816 11.315 1.87 +ATOM 534 C ALA A 217 16.104 43.052 7.759 .000 1.76 +ATOM 535 O ALA A 217 15.685 44.202 7.659 17.373 1.40 +ATOM 536 CB ALA A 217 14.486 41.158 7.488 7.550 1.87 +ATOM 537 N CYS A 218 17.033 42.701 8.645 1.066 1.65 +ATOM 538 CA CYS A 218 17.572 43.657 9.613 4.675 1.87 +ATOM 539 C CYS A 218 18.985 44.159 9.339 .904 1.76 +ATOM 540 O CYS A 218 19.634 44.683 10.245 10.457 1.40 +ATOM 541 CB CYS A 218 17.525 43.060 11.021 1.695 1.87 +ATOM 542 SG CYS A 218 15.855 42.777 11.680 .071 1.85 +ATOM 543 N GLN A 219 19.451 44.037 8.099 .778 1.65 +ATOM 544 CA GLN A 219 20.802 44.479 7.755 8.175 1.87 +ATOM 545 C GLN A 219 21.001 45.986 7.940 .000 1.76 +ATOM 546 O GLN A 219 20.066 46.772 7.786 21.956 1.40 +ATOM 547 CB GLN A 219 21.152 44.074 6.323 20.279 1.87 +ATOM 548 CG GLN A 219 20.421 44.863 5.251 16.063 1.87 +ATOM 549 CD GLN A 219 20.725 44.362 3.860 7.981 1.76 +ATOM 550 OE1 GLN A 219 21.768 44.673 3.288 39.145 1.40 +ATOM 551 NE2 GLN A 219 19.817 43.572 3.311 25.197 1.65 +ATOM 552 N GLY A 220 22.226 46.374 8.287 6.948 1.65 +ATOM 553 CA GLY A 220 22.536 47.781 8.491 35.358 1.87 +ATOM 554 C GLY A 220 23.683 48.032 9.461 12.927 1.76 +ATOM 555 O GLY A 220 24.328 47.057 9.907 15.193 1.40 +ATOM 556 OXT GLY A 220 23.949 49.212 9.776 39.147 1.40 diff -Nru python-biopython-1.62/Tests/PDB/1A8O.rsa python-biopython-1.63/Tests/PDB/1A8O.rsa --- python-biopython-1.62/Tests/PDB/1A8O.rsa 1970-01-01 00:00:00.000000000 +0000 +++ python-biopython-1.63/Tests/PDB/1A8O.rsa 2013-12-05 14:10:43.000000000 +0000 @@ -0,0 +1,74 @@ +REM Relative accessibilites read from external file "/home/gokcen/Code/MQAP/externals/naccess/naccess2.1.1/standard.data" +REM File of summed (Sum) and % (per.) accessibilities for +REM RES _ NUM All-atoms Total-Side Main-Chain Non-polar All polar +REM ABS REL ABS REL ABS REL ABS REL ABS REL +RES ASP A 152 171.48 122.1 124.30 121.0 47.18 125.1 49.29 100.1 122.19 134.1 +RES ILE A 153 32.03 18.3 30.69 22.2 1.34 3.6 30.69 22.1 1.34 3.7 +RES ARG A 154 158.75 66.5 147.92 73.5 10.83 28.9 55.71 71.6 103.04 64.0 +RES GLN A 155 13.71 7.7 3.99 2.8 9.72 25.9 .00 .0 13.71 10.9 +RES GLY A 156 23.23 29.0 22.92 70.9 .30 .6 22.92 61.0 .30 .7 +RES PRO A 157 100.78 74.0 93.45 77.9 7.33 45.2 93.45 77.3 7.33 48.3 +RES LYS A 158 182.96 91.1 156.52 95.8 26.44 70.5 118.95 102.0 64.01 76.0 +RES GLU A 159 36.02 20.9 30.82 22.9 5.20 13.9 27.91 46.3 8.11 7.2 +RES PRO A 160 57.02 41.9 57.00 47.5 .03 .2 57.00 47.1 .03 .2 +RES PHE A 161 25.26 12.7 22.58 13.8 2.68 7.6 22.58 13.7 2.68 7.8 +RES ARG A 162 164.61 68.9 162.32 80.7 2.29 6.1 67.60 86.9 97.01 60.3 +RES ASP A 163 70.04 49.9 68.83 67.0 1.21 3.2 20.24 41.1 49.80 54.6 +RES TYR A 164 .00 .0 .00 .0 .00 .0 .00 .0 .00 .0 +RES VAL A 165 10.32 6.8 10.32 9.0 .00 .0 10.32 8.9 .00 .0 +RES ASP A 166 66.28 47.2 63.46 61.8 2.82 7.5 32.16 65.3 34.12 37.4 +RES ARG A 167 91.71 38.4 90.91 45.2 .81 2.1 57.57 74.0 34.14 21.2 +RES PHE A 168 22.53 11.3 20.58 12.5 1.95 5.5 20.58 12.5 1.95 5.7 +RES TYR A 169 41.00 19.3 41.00 23.1 .00 .0 31.19 22.8 9.81 12.9 +RES LYS A 170 142.58 71.0 136.83 83.8 5.75 15.3 88.85 76.2 53.73 63.8 +RES THR A 171 68.69 49.3 68.63 67.5 .06 .2 55.24 73.0 13.45 21.2 +RES LEU A 172 32.06 17.9 31.31 22.2 .75 2.0 31.90 22.4 .16 .5 +RES ARG A 173 150.58 63.1 144.78 71.9 5.80 15.5 74.07 95.2 76.51 47.5 +RES ALA A 174 67.95 62.9 51.27 73.9 16.67 43.3 51.27 71.8 16.67 45.6 +RES GLU A 175 128.89 74.8 109.91 81.6 18.99 50.6 43.47 72.1 85.42 76.3 +RES GLN A 176 147.88 82.8 126.80 89.9 21.08 56.2 71.94 137.8 75.94 60.1 +RES ALA A 177 18.57 17.2 7.91 11.4 10.66 27.7 7.97 11.2 10.60 29.0 +RES SER A 178 63.07 54.1 60.87 77.9 2.20 5.7 54.81 112.9 8.26 12.2 +RES GLN A 179 113.59 63.6 105.96 75.2 7.63 20.4 58.87 112.7 54.72 43.3 +RES GLU A 180 96.73 56.2 95.89 71.2 .83 2.2 51.62 85.6 45.11 40.3 +RES VAL A 181 64.30 42.5 59.47 52.0 4.82 13.0 59.47 51.5 4.82 13.4 +RES LYS A 182 64.31 32.0 63.88 39.1 .43 1.2 20.10 17.2 44.21 52.5 +RES ASN A 183 63.79 44.3 63.48 59.8 .30 .8 18.33 39.7 45.45 46.5 +RES TRP A 184 148.24 59.4 141.59 67.0 6.65 17.5 128.10 67.5 20.14 33.7 +RES THR A 186 21.80 15.7 16.80 16.5 5.00 13.3 14.88 19.7 6.92 10.9 +RES GLU A 187 99.19 57.6 84.79 62.9 14.40 38.4 41.93 69.5 57.26 51.1 +RES THR A 188 61.10 43.9 61.10 60.1 .00 .0 50.91 67.2 10.20 16.0 +RES LEU A 189 99.26 55.6 99.18 70.3 .07 .2 99.18 69.7 .07 .2 +RES LEU A 190 4.34 2.4 4.34 3.1 .00 .0 4.34 3.0 .00 .0 +RES VAL A 191 18.72 12.4 18.72 16.4 .00 .0 18.72 16.2 .00 .0 +RES GLN A 192 78.01 43.7 68.67 48.7 9.34 24.9 19.26 36.9 58.75 46.5 +RES ASN A 193 17.70 12.3 14.69 13.8 3.01 8.0 2.05 4.4 15.65 16.0 +RES ALA A 194 8.88 8.2 .00 .0 8.88 23.1 .33 .5 8.55 23.4 +RES ASN A 195 11.49 8.0 11.49 10.8 .00 .0 4.12 8.9 7.38 7.5 +RES PRO A 196 106.44 78.2 99.93 83.3 6.51 40.1 101.83 84.2 4.60 30.3 +RES ASP A 197 104.88 74.7 101.82 99.2 3.06 8.1 39.47 80.2 65.42 71.8 +RES CYS A 198 6.79 5.1 6.56 6.8 .23 .6 6.56 6.7 .23 .6 +RES LYS A 199 71.98 35.8 71.98 44.1 .00 .0 38.32 32.9 33.66 40.0 +RES THR A 200 95.87 68.8 94.57 93.0 1.29 3.4 71.36 94.2 24.51 38.6 +RES ILE A 201 78.38 44.8 77.20 56.0 1.18 3.2 77.20 55.5 1.18 3.3 +RES LEU A 202 19.43 10.9 11.89 8.4 7.53 20.1 11.89 8.4 7.53 20.7 +RES LYS A 203 113.58 56.6 95.18 58.3 18.40 49.1 68.92 59.1 44.66 53.0 +RES ALA A 204 86.52 80.2 57.56 82.9 28.96 75.2 59.26 83.0 27.26 74.5 +RES LEU A 205 74.72 41.8 46.12 32.7 28.60 76.3 47.97 33.7 26.75 73.7 +RES GLY A 206 35.20 43.9 22.54 69.7 12.65 26.5 26.89 71.6 8.31 19.5 +RES PRO A 207 140.14 102.9 118.36 98.7 21.77 134.1 119.63 98.9 20.50 135.0 +RES GLY A 208 61.95 77.3 35.70 110.4 26.25 55.0 39.82 106.1 22.13 52.0 +RES ALA A 209 34.09 31.6 17.93 25.8 16.16 41.9 18.00 25.2 16.09 44.0 +RES THR A 210 70.67 50.7 64.97 63.9 5.70 15.2 62.76 82.9 7.91 12.4 +RES LEU A 211 59.65 33.4 46.89 33.2 12.76 34.0 46.89 32.9 12.76 35.1 +RES GLU A 212 122.28 71.0 119.43 88.6 2.85 7.6 76.47 126.8 45.81 40.9 +RES GLU A 213 96.18 55.8 89.06 66.1 7.12 19.0 46.42 77.0 49.76 44.4 +RES THR A 216 105.72 75.9 82.68 81.3 23.04 61.3 58.35 77.1 47.37 74.5 +RES ALA A 217 36.73 34.0 18.86 27.2 17.86 46.3 18.86 26.4 17.86 48.8 +RES CYS A 218 18.87 14.1 6.44 6.7 12.43 33.1 7.34 7.5 11.52 31.7 +RES GLN A 219 139.57 78.2 116.84 82.9 22.73 60.6 52.50 100.5 87.08 69.0 +RES GLY A 220 109.57 136.8 35.36 109.4 74.21 155.4 48.29 128.6 61.29 144.0 +END Absolute sums over single chains surface +CHAIN 1 A 4848.7 4233.8 614.8 2934.9 1913.8 +END Absolute sums over all chains +TOTAL 4848.7 4233.8 614.8 2934.9 1913.8 diff -Nru python-biopython-1.62/Tests/PDB/2BEG_noheader.dssp python-biopython-1.63/Tests/PDB/2BEG_noheader.dssp --- python-biopython-1.62/Tests/PDB/2BEG_noheader.dssp 1970-01-01 00:00:00.000000000 +0000 +++ python-biopython-1.63/Tests/PDB/2BEG_noheader.dssp 2013-12-05 14:10:43.000000000 +0000 @@ -0,0 +1,159 @@ +==== Secondary Structure Definition by the program DSSP, CMBI version by M.L. Hekkelman/2010-10-21 ==== DATE=2013-08-30 . +REFERENCE W. KABSCH AND C.SANDER, BIOPOLYMERS 22 (1983) 2577-2637 . + . + 130 5 0 0 0 TOTAL NUMBER OF RESIDUES, NUMBER OF CHAINS, NUMBER OF SS-BRIDGES(TOTAL,INTRACHAIN,INTERCHAIN) . + 6817.2 ACCESSIBLE SURFACE OF PROTEIN (ANGSTROM**2) . + 144110.8 TOTAL NUMBER OF HYDROGEN BONDS OF TYPE O(I)-->H-N(J) , SAME NUMBER PER 100 RESIDUES . + 88 67.7 TOTAL NUMBER OF HYDROGEN BONDS IN PARALLEL BRIDGES, SAME NUMBER PER 100 RESIDUES . + 0 0.0 TOTAL NUMBER OF HYDROGEN BONDS IN ANTIPARALLEL BRIDGES, SAME NUMBER PER 100 RESIDUES . + 0 0.0 TOTAL NUMBER OF HYDROGEN BONDS OF TYPE O(I)-->H-N(I-5), SAME NUMBER PER 100 RESIDUES . + 0 0.0 TOTAL NUMBER OF HYDROGEN BONDS OF TYPE O(I)-->H-N(I-4), SAME NUMBER PER 100 RESIDUES . + 0 0.0 TOTAL NUMBER OF HYDROGEN BONDS OF TYPE O(I)-->H-N(I-3), SAME NUMBER PER 100 RESIDUES . + 0 0.0 TOTAL NUMBER OF HYDROGEN BONDS OF TYPE O(I)-->H-N(I-2), SAME NUMBER PER 100 RESIDUES . + 0 0.0 TOTAL NUMBER OF HYDROGEN BONDS OF TYPE O(I)-->H-N(I-1), SAME NUMBER PER 100 RESIDUES . + 0 0.0 TOTAL NUMBER OF HYDROGEN BONDS OF TYPE O(I)-->H-N(I+0), SAME NUMBER PER 100 RESIDUES . + 0 0.0 TOTAL NUMBER OF HYDROGEN BONDS OF TYPE O(I)-->H-N(I+1), SAME NUMBER PER 100 RESIDUES . + 52 40.0 TOTAL NUMBER OF HYDROGEN BONDS OF TYPE O(I)-->H-N(I+2), SAME NUMBER PER 100 RESIDUES . + 0 0.0 TOTAL NUMBER OF HYDROGEN BONDS OF TYPE O(I)-->H-N(I+3), SAME NUMBER PER 100 RESIDUES . + 0 0.0 TOTAL NUMBER OF HYDROGEN BONDS OF TYPE O(I)-->H-N(I+4), SAME NUMBER PER 100 RESIDUES . + 0 0.0 TOTAL NUMBER OF HYDROGEN BONDS OF TYPE O(I)-->H-N(I+5), SAME NUMBER PER 100 RESIDUES . + 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 *** HISTOGRAMS OF *** . + 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 RESIDUES PER ALPHA HELIX . + 0 0 0 0 0 0 0 0 4 0 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 PARALLEL BRIDGES PER LADDER . + 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ANTIPARALLEL BRIDGES PER LADDER . + 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 LADDERS PER SHEET . + # RESIDUE AA STRUCTURE BP1 BP2 ACC N-H-->O O-->H-N N-H-->O O-->H-N TCO KAPPA ALPHA PHI PSI X-CA Y-CA Z-CA + 1 17 A L 0 0 134 0, 0.0 2,-0.3 0, 0.0 28,-0.3 0.000 360.0 360.0 360.0 65.7 -15.4 -4.8 -3.4 + 2 18 A V E -a 29 0A 69 26,-1.4 28,-2.9 2,-0.0 2,-0.5 -0.728 360.0-146.5-105.3 155.5 -12.1 -6.0 -2.0 + 3 19 A F E -a 30 0A 73 -2,-0.3 2,-0.8 26,-0.2 28,-0.2 -0.954 12.2-176.8-127.7 112.4 -8.8 -4.2 -2.1 + 4 20 A F E +a 31 0A 106 26,-3.7 28,-3.0 -2,-0.5 2,-0.5 -0.692 21.5 158.5-108.4 77.2 -5.5 -6.2 -2.5 + 5 21 A A E +a 32 0A 48 -2,-0.8 2,-0.3 26,-0.2 28,-0.2 -0.882 8.3 146.8-104.3 128.7 -2.8 -3.5 -2.2 + 6 22 A E E -a 33 0A 83 26,-2.3 28,-1.9 -2,-0.5 2,-0.4 -0.985 34.4-150.1-158.0 152.3 0.7 -4.5 -1.2 + 7 23 A D E -a 34 0A 40 -2,-0.3 2,-0.5 26,-0.2 28,-0.2 -0.902 14.4-155.3-132.0 102.5 4.3 -3.6 -1.9 + 8 24 A V E -a 35 0A 71 26,-1.7 28,-2.4 -2,-0.4 2,-0.5 -0.659 11.3-171.3 -80.1 124.2 6.8 -6.3 -1.7 + 9 25 A G E -a 36 0A 48 -2,-0.5 2,-0.9 26,-0.1 28,-0.2 -0.927 6.8-170.1-122.8 106.3 10.3 -5.0 -0.9 + 10 26 A S E -a 37 0A 47 26,-2.3 28,-2.0 -2,-0.5 55,-0.1 -0.818 62.6 -43.3 -98.5 99.4 13.2 -7.4 -1.1 + 11 27 A N S S+ 0 0 128 -2,-0.9 28,-1.3 27,-0.2 27,-0.5 0.248 107.4 72.1 63.2 163.9 16.2 -5.7 0.4 + 12 28 A K + 0 0 114 26,-0.3 27,-1.0 27,-0.2 28,-0.8 0.828 42.6 158.9 60.3 113.4 17.1 -2.1 -0.3 + 13 29 A G + 0 0 37 26,-0.3 30,-0.2 25,-0.1 27,-0.1 0.607 10.7 149.2-128.1 -50.3 14.8 0.3 1.4 + 14 30 A A S S- 0 0 69 26,-0.1 2,-0.9 1,-0.1 28,-0.1 -0.023 74.6 -2.8 42.6-146.8 16.6 3.7 1.6 + 15 31 A I E S+e 42 0B 122 26,-0.7 28,-2.4 2,-0.0 2,-0.4 -0.638 85.3 162.0 -76.5 106.0 14.2 6.6 1.5 + 16 32 A I E -e 43 0B 72 -2,-0.9 2,-0.5 26,-0.2 28,-0.2 -0.975 26.0-159.9-129.7 142.6 10.8 5.1 0.9 + 17 33 A G E -e 44 0B 18 26,-2.3 28,-2.9 -2,-0.4 2,-1.0 -0.933 4.3-173.2-127.3 107.7 7.4 6.5 1.5 + 18 34 A L E +e 45 0B 82 -2,-0.5 2,-0.6 26,-0.2 28,-0.2 -0.803 14.4 173.3-102.2 92.2 4.4 4.1 1.8 + 19 35 A M E +e 46 0B 109 26,-3.3 28,-2.6 -2,-1.0 2,-0.4 -0.899 1.3 173.6-105.5 118.3 1.3 6.3 1.9 + 20 36 A V E -e 47 0B 106 -2,-0.6 2,-0.5 26,-0.2 28,-0.2 -0.965 13.9-163.1-125.6 140.9 -2.0 4.6 1.9 + 21 37 A G E -e 48 0B 30 26,-2.5 28,-4.2 -2,-0.4 2,-0.6 -0.964 2.6-169.2-128.7 114.9 -5.5 6.1 2.2 + 22 38 A G E +e 49 0B 70 -2,-0.5 2,-0.5 26,-0.2 28,-0.2 -0.908 10.9 170.1-107.4 114.7 -8.5 4.0 3.1 + 23 39 A V E +e 50 0B 60 26,-4.3 28,-3.4 -2,-0.6 2,-0.9 -0.836 3.1 175.9-126.3 91.8 -11.8 5.7 2.7 + 24 40 A V E +e 51 0B 119 -2,-0.5 2,-0.6 26,-0.2 28,-0.2 -0.849 6.0 171.7-100.8 102.9 -14.7 3.2 3.0 + 25 41 A I E e 52 0B 83 26,-3.2 28,-2.3 -2,-0.9 -2,-0.0 -0.950 360.0 360.0-116.5 113.8 -18.0 5.1 2.9 + 26 42 A A 0 0 120 -2,-0.6 26,-0.1 26,-0.2 -2,-0.0 -0.741 360.0 360.0-135.9 360.0 -21.1 3.0 2.7 + 27 !* 0 0 0 0, 0.0 0, 0.0 0, 0.0 0, 0.0 0.000 360.0 360.0 360.0 360.0 0.0 0.0 0.0 + 28 17 B L 0 0 97 0, 0.0 -26,-1.4 0, 0.0 2,-0.3 0.000 360.0 360.0 360.0 81.9 -15.6 -5.8 -7.8 + 29 18 B V E -ab 2 56A 38 26,-1.1 28,-1.4 -28,-0.3 2,-0.5 -0.975 360.0-151.1-140.1 151.6 -12.0 -6.1 -6.7 + 30 19 B F E -ab 3 57A 13 -28,-2.9 -26,-3.7 -2,-0.3 2,-0.5 -0.897 15.4-177.5-129.3 102.1 -9.0 -3.9 -6.5 + 31 20 B F E +ab 4 58A 41 26,-2.6 28,-0.9 -2,-0.5 2,-0.2 -0.879 10.6 163.8-103.5 125.0 -5.6 -5.5 -6.8 + 32 21 B A E +ab 5 59A 12 -28,-3.0 -26,-2.3 -2,-0.5 2,-0.4 -0.689 11.4 162.6-141.3 82.7 -2.5 -3.3 -6.5 + 33 22 B E E -ab 6 60A 46 26,-1.9 28,-2.0 -28,-0.2 2,-0.5 -0.834 20.3-163.5-106.0 142.1 0.7 -5.3 -5.8 + 34 23 B D E -ab 7 61A 2 -28,-1.9 2,-1.9 -2,-0.4 -26,-1.7 -0.898 5.7-159.9-128.4 100.8 4.2 -4.0 -6.4 + 35 24 B V E +ab 8 62A 45 26,-1.7 28,-2.3 -2,-0.5 2,-0.9 -0.589 20.1 178.9 -80.9 82.1 6.9 -6.7 -6.5 + 36 25 B G E -ab 9 63A 1 -28,-2.4 -26,-2.3 -2,-1.9 2,-0.7 -0.789 8.3-168.6 -91.9 107.1 9.8 -4.4 -5.7 + 37 26 B S E S-ab 10 64A 35 26,-3.2 28,-2.7 -2,-0.9 29,-0.4 -0.862 72.3 -13.1-100.2 111.1 13.0 -6.5 -5.5 + 38 27 B N S S+ 0 0 49 -28,-2.0 -1,-0.3 -2,-0.7 -26,-0.3 0.999 81.2 169.3 62.9 69.3 15.9 -4.5 -4.1 + 39 28 B K + 0 0 5 -28,-1.3 -26,-0.3 -27,-1.0 -27,-0.2 0.915 10.5 144.9 -73.2 -95.9 14.4 -1.1 -4.2 + 40 29 B G + 0 0 1 -28,-0.8 27,-0.3 1,-0.2 -26,-0.1 -0.078 38.6 57.6 79.5 176.2 16.5 1.4 -2.3 + 41 30 B A S S- 0 0 34 26,-0.2 -26,-0.7 28,-0.1 2,-0.7 -0.345 113.1 -16.4 64.9-144.1 17.2 5.0 -3.1 + 42 31 B I E S+ef 15 69B 82 26,-1.7 28,-2.0 -28,-0.1 2,-0.4 -0.867 70.7 164.1 -99.9 116.9 14.1 7.2 -3.4 + 43 32 B I E -ef 16 70B 2 -28,-2.4 -26,-2.3 -2,-0.7 2,-0.3 -0.932 14.3-167.7-137.5 110.3 10.9 5.3 -3.8 + 44 33 B G E -ef 17 71B 28 26,-3.2 28,-1.8 -2,-0.4 2,-0.4 -0.753 1.1-169.1 -99.7 145.1 7.5 6.9 -3.1 + 45 34 B L E +ef 18 72B 13 -28,-2.9 -26,-3.3 -2,-0.3 2,-0.4 -0.992 9.9 170.8-137.3 126.3 4.2 5.0 -2.8 + 46 35 B M E +ef 19 73B 101 26,-3.2 28,-3.9 -2,-0.4 2,-0.5 -0.891 2.8 172.9-140.4 106.4 0.8 6.6 -2.8 + 47 36 B V E -ef 20 74B 14 -28,-2.6 -26,-2.5 -2,-0.4 2,-0.6 -0.964 13.3-161.3-117.8 125.2 -2.3 4.4 -2.9 + 48 37 B G E -ef 21 75B 24 26,-4.1 28,-2.5 -2,-0.5 2,-0.8 -0.917 5.3-173.5-110.2 112.0 -5.8 6.0 -2.5 + 49 38 B G E +ef 22 76B 10 -28,-4.2 -26,-4.3 -2,-0.6 2,-0.4 -0.823 15.6 166.0-107.5 93.1 -8.5 3.5 -1.6 + 50 39 B V E +ef 23 77B 29 26,-4.1 28,-1.8 -2,-0.8 2,-0.3 -0.886 12.9 176.9-110.0 138.6 -11.8 5.4 -1.7 + 51 40 B V E +ef 24 78B 24 -28,-3.4 -26,-3.2 -2,-0.4 2,-0.6 -0.734 4.5 177.7-143.2 88.4 -15.2 3.7 -1.7 + 52 41 B I E ef 25 79B 59 26,-3.6 28,-3.0 -2,-0.3 -26,-0.2 -0.844 360.0 360.0 -97.4 120.5 -18.2 6.1 -1.6 + 53 42 B A 0 0 78 -28,-2.3 -2,-0.1 -2,-0.6 26,-0.0 -0.999 360.0 360.0-141.5 360.0 -21.6 4.4 -1.7 + 54 !* 0 0 0 0, 0.0 0, 0.0 0, 0.0 0, 0.0 0.000 360.0 360.0 360.0 360.0 0.0 0.0 0.0 + 55 17 C L 0 0 97 0, 0.0 -26,-1.1 0, 0.0 2,-0.3 0.000 360.0 360.0 360.0-116.9 -15.5 -4.1 -10.9 + 56 18 C V E +bc 29 83A 38 26,-2.2 28,-2.4 -28,-0.3 2,-0.2 -0.629 360.0 177.4 -84.6 140.2 -12.1 -5.9 -11.1 + 57 19 C F E -bc 30 84A 11 -28,-1.4 -26,-2.6 -2,-0.3 2,-0.3 -0.708 4.1-175.1-147.5 89.8 -9.0 -3.8 -11.2 + 58 20 C F E +bc 31 85A 58 26,-4.1 28,-2.0 -2,-0.2 2,-0.3 -0.692 5.9 173.4 -89.5 138.0 -5.7 -5.7 -11.2 + 59 21 C A E +bc 32 86A 8 -28,-0.9 -26,-1.9 -2,-0.3 2,-0.4 -0.811 2.9 170.3-148.2 100.8 -2.4 -3.7 -11.0 + 60 22 C E E -bc 33 87A 43 26,-1.9 28,-2.4 -2,-0.3 2,-0.5 -0.948 12.4-168.2-117.1 132.7 0.9 -5.6 -10.6 + 61 23 C D E -bc 34 88A 4 -28,-2.0 -26,-1.7 -2,-0.4 2,-0.9 -0.932 2.9-166.4-123.4 106.1 4.3 -4.0 -10.9 + 62 24 C V E +bc 35 89A 34 26,-3.5 28,-2.6 -2,-0.5 2,-0.6 -0.811 13.8 175.1 -95.3 102.5 7.2 -6.3 -11.2 + 63 25 C G E -bc 36 90A 1 -28,-2.3 -26,-3.2 -2,-0.9 2,-1.1 -0.934 16.6-162.1-114.0 112.8 10.4 -4.3 -10.5 + 64 26 C S E S-bc 37 91A 53 26,-2.6 28,-0.7 -2,-0.6 -26,-0.1 -0.773 81.8 -12.2 -95.7 93.7 13.6 -6.2 -10.4 + 65 27 C N S S+ 0 0 57 -28,-2.7 -1,-0.3 -2,-1.1 -27,-0.2 0.971 79.7 176.7 80.0 68.0 16.1 -3.9 -8.7 + 66 28 C K + 0 0 5 -29,-0.4 -27,-0.2 -3,-0.4 29,-0.1 0.908 19.3 136.4 -64.8-101.0 14.2 -0.6 -8.7 + 67 29 C G + 0 0 7 -27,-0.3 27,-0.4 1,-0.2 -26,-0.2 -0.252 37.5 65.7 80.9-171.8 16.2 2.1 -6.9 + 68 30 C A S S- 0 0 32 -29,-0.1 -26,-1.7 26,-0.1 2,-0.7 -0.263 111.8 -22.3 58.1-142.6 16.7 5.6 -8.0 + 69 31 C I E S+fg 42 96B 84 26,-2.4 28,-2.7 -28,-0.1 2,-0.4 -0.907 70.5 169.9-106.2 114.1 13.6 7.7 -8.1 + 70 32 C I E -fg 43 97B 2 -28,-2.0 -26,-3.2 -2,-0.7 2,-0.5 -0.988 13.4-165.2-128.4 123.2 10.4 5.7 -8.3 + 71 33 C G E -fg 44 98B 31 26,-2.5 28,-4.0 -2,-0.4 2,-0.6 -0.936 1.6-169.6-112.3 124.5 6.9 7.2 -7.9 + 72 34 C L E +fg 45 99B 13 -28,-1.8 -26,-3.2 -2,-0.5 2,-0.6 -0.949 6.6 177.5-116.5 113.6 3.9 5.0 -7.3 + 73 35 C M E -fg 46 100B 95 26,-3.1 28,-4.0 -2,-0.6 2,-0.8 -0.893 3.3-176.6-120.0 100.4 0.5 6.6 -7.5 + 74 36 C V E -fg 47 101B 9 -28,-3.9 -26,-4.1 -2,-0.6 2,-0.8 -0.856 5.0-169.4-100.0 107.0 -2.4 4.3 -7.1 + 75 37 C G E +fg 48 102B 24 26,-3.6 28,-1.8 -2,-0.8 2,-0.5 -0.840 16.3 161.9-101.0 102.1 -5.7 6.2 -7.5 + 76 38 C G E +fg 49 103B 0 -28,-2.5 -26,-4.1 -2,-0.8 2,-0.4 -0.845 8.8 150.9-124.4 93.7 -8.6 4.0 -6.4 + 77 39 C V E -fg 50 104B 30 26,-2.3 28,-2.1 -2,-0.5 2,-0.6 -0.991 23.0-168.0-127.5 127.4 -11.7 6.0 -5.7 + 78 40 C V E -fg 51 105B 28 -28,-1.8 -26,-3.6 -2,-0.4 2,-0.7 -0.923 6.2-176.8-118.5 104.9 -15.2 4.6 -6.2 + 79 41 C I E fg 52 106B 67 26,-3.2 28,-3.3 -2,-0.6 -26,-0.2 -0.896 360.0 360.0-105.7 109.9 -18.0 7.2 -6.0 + 80 42 C A 0 0 70 -28,-3.0 26,-0.1 -2,-0.7 -2,-0.0 -0.827 360.0 360.0-132.4 360.0 -21.4 5.8 -6.3 + 81 !* 0 0 0 0, 0.0 0, 0.0 0, 0.0 0, 0.0 0.000 360.0 360.0 360.0 360.0 0.0 0.0 0.0 + 82 17 D L 0 0 66 0, 0.0 -26,-2.2 0, 0.0 2,-0.6 0.000 360.0 360.0 360.0 116.6 -14.7 -4.1 -15.9 + 83 18 D V E -cd 56 110A 47 26,-2.4 28,-2.7 -28,-0.2 2,-0.3 -0.860 360.0-166.3-121.7 94.3 -11.5 -6.1 -15.6 + 84 19 D F E -cd 57 111A 21 -28,-2.4 -26,-4.1 -2,-0.6 2,-0.4 -0.637 7.3-179.2 -83.3 135.1 -8.5 -3.9 -15.3 + 85 20 D F E +cd 58 112A 47 26,-3.5 28,-2.2 -2,-0.3 2,-0.7 -0.869 8.5 170.2-139.9 102.8 -5.1 -5.4 -15.8 + 86 21 D A E +cd 59 113A 13 -28,-2.0 -26,-1.9 -2,-0.4 2,-0.6 -0.864 9.3 172.5-116.2 95.0 -1.9 -3.3 -15.4 + 87 22 D E E -cd 60 114A 48 26,-4.0 28,-2.8 -2,-0.7 2,-0.6 -0.917 8.1-173.8-108.1 119.5 1.1 -5.6 -15.4 + 88 23 D D E -cd 61 115A 6 -28,-2.4 -26,-3.5 -2,-0.6 2,-0.8 -0.955 5.3-172.2-116.5 116.7 4.5 -3.9 -15.5 + 89 24 D V E +cd 62 116A 41 26,-4.0 28,-3.1 -2,-0.6 2,-0.6 -0.817 15.4 167.7-110.5 90.0 7.6 -6.1 -15.9 + 90 25 D G E -cd 63 117A 1 -28,-2.6 -26,-2.6 -2,-0.8 2,-1.1 -0.918 23.5-155.1-108.9 116.3 10.6 -3.9 -15.5 + 91 26 D S E S-cd 64 118A 52 26,-2.5 28,-2.0 -2,-0.6 -26,-0.1 -0.758 81.7 -11.1 -92.2 95.7 14.0 -5.6 -15.0 + 92 27 D N S S- 0 0 61 -2,-1.1 28,-0.5 -28,-0.7 -1,-0.3 0.970 75.8-178.4 78.4 76.6 16.1 -3.0 -13.1 + 93 28 D K + 0 0 4 -3,-0.4 28,-0.5 26,-0.2 -27,-0.2 0.949 23.6 137.0 -67.3 -92.6 14.1 0.2 -13.3 + 94 29 D G + 0 0 10 -27,-0.4 27,-0.2 1,-0.2 -27,-0.1 -0.329 39.1 65.9 77.0-161.3 16.2 2.9 -11.6 + 95 30 D A S S- 0 0 32 1,-0.1 -26,-2.4 -29,-0.1 2,-0.7 -0.063 114.3 -26.5 44.6-144.6 16.6 6.4 -12.9 + 96 31 D I E S+gh 69 123B 76 26,-2.4 28,-3.2 -28,-0.2 2,-0.5 -0.896 70.8 167.5-105.1 111.3 13.3 8.3 -12.9 + 97 32 D I E -gh 70 124B 2 -28,-2.7 -26,-2.5 -2,-0.7 2,-0.7 -0.963 15.1-166.7-128.5 113.5 10.3 6.1 -13.2 + 98 33 D G E -gh 71 125B 29 26,-2.3 28,-3.6 -2,-0.5 2,-0.7 -0.879 3.9-167.1-104.2 108.7 6.8 7.5 -12.5 + 99 34 D L E -gh 72 126B 9 -28,-4.0 -26,-3.1 -2,-0.7 2,-0.5 -0.855 9.5-179.9 -98.7 112.8 4.2 4.9 -12.1 + 100 35 D M E -gh 73 127B 87 26,-3.3 28,-2.0 -2,-0.7 2,-0.6 -0.962 9.8-171.1-118.2 123.8 0.7 6.4 -12.2 + 101 36 D V E -gh 74 128B 8 -28,-4.0 -26,-3.6 -2,-0.5 2,-0.7 -0.930 7.1-161.8-117.0 107.2 -2.4 4.2 -11.8 + 102 37 D G E +gh 75 129B 22 26,-2.5 28,-0.9 -2,-0.6 2,-0.2 -0.801 23.0 157.0 -92.7 112.4 -5.7 6.0 -12.5 + 103 38 D G E +gh 76 130B 1 -28,-1.8 -26,-2.3 -2,-0.7 2,-0.4 -0.612 14.5 147.3-136.1 74.2 -8.6 4.2 -11.0 + 104 39 D V E -gh 77 131B 42 26,-1.9 28,-2.5 -28,-0.2 2,-0.4 -0.875 21.1-172.9-112.1 143.6 -11.5 6.6 -10.5 + 105 40 D V E -gh 78 132B 39 -28,-2.1 -26,-3.2 -2,-0.4 2,-0.4 -1.000 6.7-176.3-138.7 134.5 -15.2 5.7 -10.8 + 106 41 D I E gh 79 133B 70 26,-3.3 28,-3.2 -2,-0.4 -26,-0.2 -0.931 360.0 360.0-135.4 108.9 -18.2 8.0 -10.7 + 107 42 D A 0 0 79 -28,-3.3 26,-0.1 -2,-0.4 -29,-0.0 -0.583 360.0 360.0-131.9 360.0 -21.7 6.5 -10.8 + 108 !* 0 0 0 0, 0.0 0, 0.0 0, 0.0 0, 0.0 0.000 360.0 360.0 360.0 360.0 0.0 0.0 0.0 + 109 17 E L 0 0 158 0, 0.0 -26,-2.4 0, 0.0 2,-0.5 0.000 360.0 360.0 360.0 66.4 -14.5 -3.6 -20.3 + 110 18 E V E -d 83 0A 106 -28,-0.2 2,-0.4 -26,-0.1 -26,-0.2 -0.829 360.0-177.7 -97.6 127.8 -11.3 -5.6 -20.3 + 111 19 E F E +d 84 0A 107 -28,-2.7 -26,-3.5 -2,-0.5 2,-0.5 -0.753 7.2 175.4-127.7 84.1 -8.0 -3.7 -20.0 + 112 20 E F E +d 85 0A 123 -2,-0.4 2,-0.4 -28,-0.2 -26,-0.2 -0.791 0.6 175.8 -93.9 126.7 -5.0 -6.0 -20.1 + 113 21 E A E +d 86 0A 37 -28,-2.2 -26,-4.0 -2,-0.5 2,-0.5 -0.968 8.8 174.4-135.0 116.7 -1.6 -4.4 -20.1 + 114 22 E E E -d 87 0A 121 -2,-0.4 2,-0.5 -28,-0.2 -26,-0.2 -0.777 9.3-175.1-124.5 85.4 1.6 -6.4 -20.0 + 115 23 E D E -d 88 0A 71 -28,-2.8 -26,-4.0 -2,-0.5 2,-0.6 -0.715 2.1-171.7 -84.4 122.5 4.6 -4.1 -20.3 + 116 24 E V E +d 89 0A 107 -2,-0.5 2,-0.4 -28,-0.2 -26,-0.2 -0.945 15.0 158.8-120.2 109.5 7.8 -6.1 -20.6 + 117 25 E G E -d 90 0A 21 -28,-3.1 -26,-2.5 -2,-0.6 2,-0.7 -0.997 29.0-149.1-134.4 135.9 11.0 -4.0 -20.4 + 118 26 E S E S-d 91 0A 106 -2,-0.4 -26,-0.1 1,-0.3 -28,-0.1 -0.906 81.9 -5.0-107.7 110.4 14.5 -5.0 -19.5 + 119 27 E N S S+ 0 0 117 -28,-2.0 -1,-0.3 -2,-0.7 -26,-0.2 0.986 71.5 177.8 72.2 78.1 16.5 -2.3 -17.8 + 120 28 E K + 0 0 40 -28,-0.5 -27,-0.2 -3,-0.3 -26,-0.1 0.980 25.6 132.0 -72.2 -81.2 14.3 0.8 -18.0 + 121 29 E G + 0 0 12 -28,-0.5 -27,-0.1 -27,-0.2 -26,-0.0 -0.195 38.6 73.9 61.3-154.3 16.2 3.5 -16.2 + 122 30 E A S S- 0 0 70 1,-0.1 -26,-2.4 -29,-0.1 2,-0.7 -0.070 110.3 -32.7 47.2-148.9 16.4 6.9 -17.9 + 123 31 E I E S+h 96 0B 131 -28,-0.2 2,-0.3 -3,-0.1 -26,-0.2 -0.911 76.4 158.4-107.7 111.8 13.2 8.9 -17.7 + 124 32 E I E -h 97 0B 52 -28,-3.2 -26,-2.3 -2,-0.7 2,-0.3 -0.964 17.8-171.9-133.4 149.4 10.1 6.8 -17.9 + 125 33 E G E -h 98 0B 61 -2,-0.3 2,-0.5 -28,-0.2 -26,-0.2 -0.958 6.8-159.4-146.7 123.5 6.5 7.4 -16.8 + 126 34 E L E -h 99 0B 36 -28,-3.6 -26,-3.3 -2,-0.3 2,-0.4 -0.876 11.5-178.6-105.5 133.2 3.6 5.0 -16.7 + 127 35 E M E -h 100 0B 154 -2,-0.5 2,-0.7 -28,-0.2 -26,-0.2 -0.979 11.9-166.3-136.3 121.8 0.0 6.2 -16.7 + 128 36 E V E -h 101 0B 17 -28,-2.0 -26,-2.5 -2,-0.4 2,-1.6 -0.885 11.7-154.1-110.3 101.0 -3.1 4.1 -16.5 + 129 37 E G E +h 102 0B 61 -2,-0.7 2,-0.5 -28,-0.1 -26,-0.1 -0.583 30.1 158.0 -76.6 89.0 -6.2 6.1 -17.4 + 130 38 E G E +h 103 0B 4 -2,-1.6 -26,-1.9 -28,-0.9 2,-0.5 -0.604 15.0 142.4-114.3 68.7 -8.8 4.1 -15.5 + 131 39 E V E -h 104 0B 86 -2,-0.5 2,-0.5 -28,-0.2 -26,-0.2 -0.939 27.6-170.2-113.4 129.4 -11.6 6.7 -15.1 + 132 40 E V E -h 105 0B 43 -28,-2.5 -26,-3.3 -2,-0.5 2,-0.7 -0.965 3.6-176.2-122.9 114.7 -15.2 5.6 -15.3 + 133 41 E I E h 106 0B 116 -2,-0.5 -26,-0.2 -28,-0.2 -28,-0.1 -0.872 360.0 360.0-113.5 97.1 -17.9 8.4 -15.5 + 134 42 E A 0 0 99 -28,-3.2 -2,-0.0 -2,-0.7 -1,-0.0 -0.677 360.0 360.0-115.7 360.0 -21.3 6.8 -15.5 diff -Nru python-biopython-1.62/Tests/Quality/example_dos.fastq python-biopython-1.63/Tests/Quality/example_dos.fastq --- python-biopython-1.62/Tests/Quality/example_dos.fastq 1970-01-01 00:00:00.000000000 +0000 +++ python-biopython-1.63/Tests/Quality/example_dos.fastq 2013-12-05 14:10:43.000000000 +0000 @@ -0,0 +1,12 @@ +@EAS54_6_R1_2_1_413_324 +CCCTTCTTGTCTTCAGCGTTTCTCC ++ +;;3;;;;;;;;;;;;7;;;;;;;88 +@EAS54_6_R1_2_1_540_792 +TTGGCAGGCCAAGGCCGATGGATCA ++ +;;;;;;;;;;;7;;;;;-;;;3;83 +@EAS54_6_R1_2_1_443_348 +GTTGCTTCTGGCGTGGGTGGGGGGG ++ +;;;;;;;;;;;9;7;;.7;393333 Binary files /tmp/EAI2iEqCCm/python-biopython-1.62/Tests/Quality/example_dos.fastq.bgz and /tmp/XMH5G9mdHg/python-biopython-1.63/Tests/Quality/example_dos.fastq.bgz differ diff -Nru python-biopython-1.62/Tests/Roche/README.txt python-biopython-1.63/Tests/Roche/README.txt --- python-biopython-1.62/Tests/Roche/README.txt 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/Roche/README.txt 2013-12-05 14:10:43.000000000 +0000 @@ -30,3 +30,9 @@ * greek.sff - has an .srt1.00 style index * paired.sff - has an .mft1.00 style index and manifest +Finally these file are concatenations of the greek.sff and paired.sff +files with E3MFGYR02_no_manifest.sff (for testing this as a special +error condition): + +* invalid_greek_E3MFGYR02.sff - Concatenating SFF files together +* invalid_paired_E3MFGYR02.sff - Concatenating without 8 byte alignment Binary files /tmp/EAI2iEqCCm/python-biopython-1.62/Tests/Roche/invalid_greek_E3MFGYR02.sff and /tmp/XMH5G9mdHg/python-biopython-1.63/Tests/Roche/invalid_greek_E3MFGYR02.sff differ Binary files /tmp/EAI2iEqCCm/python-biopython-1.62/Tests/Roche/invalid_paired_E3MFGYR02.sff and /tmp/XMH5G9mdHg/python-biopython-1.63/Tests/Roche/invalid_paired_E3MFGYR02.sff differ diff -Nru python-biopython-1.62/Tests/common_BioSQL.py python-biopython-1.63/Tests/common_BioSQL.py --- python-biopython-1.62/Tests/common_BioSQL.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/common_BioSQL.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,11 +3,15 @@ # as part of this package. """Tests for dealing with storage of biopython objects in a relational db. """ -# standard library +from __future__ import print_function + import os import platform import unittest -from StringIO import StringIO + +from Bio._py3k import StringIO +from Bio._py3k import zip +from Bio._py3k import basestring # Hide annoying warnings from things like bonds in GenBank features, # or PostgreSQL schema rules. TODO - test these warnings are raised! @@ -73,7 +77,7 @@ host=DBHOST) server.close() del server - except Exception, e: + except Exception as e: message = "Connection failed, check settings if you plan to use BioSQL: %s" % str(e) raise MissingExternalDependencyError(message) @@ -117,10 +121,10 @@ server.adaptor.cursor.execute(sql, ()) except (server.module.OperationalError, server.module.Error, - server.module.DatabaseError), e: # the database doesn't exist + server.module.DatabaseError) as e: # the database doesn't exist pass except (server.module.IntegrityError, - server.module.ProgrammingError), e: # ditto--perhaps + server.module.ProgrammingError) as e: # ditto--perhaps if str(e).find('database "%s" does not exist' % TESTDB) == -1: raise # create a new database @@ -207,7 +211,7 @@ server = self.server self.assertTrue("biosql-test" in server) self.assertEqual(1, len(server)) - self.assertEqual(["biosql-test"], server.keys()) + self.assertEqual(["biosql-test"], list(server.keys())) #Check we can delete the namespace... del server["biosql-test"] self.assertEqual(0, len(server)) @@ -220,14 +224,14 @@ def test_get_db_items(self): """Check list, keys, length etc""" db = self.db - items = db.values() - keys = db.keys() + items = list(db.values()) + keys = list(db.keys()) l = len(items) self.assertEqual(l, len(db)) - self.assertEqual(l, len(list(db.iteritems()))) - self.assertEqual(l, len(list(db.iterkeys()))) - self.assertEqual(l, len(list(db.itervalues()))) - for (k1, r1), (k2, r2) in zip(zip(keys, items), db.iteritems()): + self.assertEqual(l, len(list(db.items()))) + self.assertEqual(l, len(list(db.keys()))) + self.assertEqual(l, len(list(db.values()))) + for (k1, r1), (k2, r2) in zip(zip(keys, items), db.items()): self.assertEqual(k1, k2) self.assertEqual(r1.id, r2.id) for k in keys: @@ -245,7 +249,7 @@ self.db.lookup(accession = "X62281") try: self.db.lookup(accession = "Not real") - raise Assertionerror("No problem on fake id retrieval") + raise AssertionError("No problem on fake id retrieval") except IndexError: pass self.db.lookup(display_id = "ATKIN2") @@ -427,7 +431,7 @@ # do some simple tests to make sure we actually loaded the right # thing. More advanced tests in a different module. - items = self.db.values() + items = list(self.db.values()) self.assertEqual(len(items), 6) self.assertEqual(len(self.db), 6) item_names = [] @@ -467,7 +471,7 @@ record = SeqRecord(Seq("ATGCTATGACTAT", Alphabet.generic_dna), id="Test1") try: count = self.db.load([record, record]) - except Exception, err: + except Exception as err: #Good! #Note we don't do a specific exception handler because the #exception class will depend on which DB back end is in use. @@ -485,7 +489,7 @@ self.assertEqual(count, 1) try: count = self.db.load([record]) - except Exception, err: + except Exception as err: #Good! self.assertTrue(err.__class__.__name__ in ["IntegrityError", "AttributeError"], @@ -499,7 +503,7 @@ record2 = SeqRecord(Seq("GGGATGCGACTAT", Alphabet.generic_dna), id="TestA") try: count = self.db.load([record1, record2]) - except Exception, err: + except Exception as err: #Good! self.assertTrue(err.__class__.__name__ in ["IntegrityError", "AttributeError"], @@ -686,7 +690,7 @@ """Make sure can't reimport existing records.""" gb_file = os.path.join(os.getcwd(), "GenBank", "cor6_6.gb") gb_handle = open(gb_file, "r") - record = SeqIO.parse(gb_handle, "gb").next() + record = next(SeqIO.parse(gb_handle, "gb")) gb_handle.close() #Should be in database already... db_record = self.db.lookup(accession = "X55053") @@ -697,7 +701,7 @@ #Good... now try reloading it! try: count = self.db.load([record]) - except Exception, err: + except Exception as err: #Good! self.assertTrue(err.__class__.__name__ in ["IntegrityError", "AttributeError"], @@ -733,7 +737,7 @@ test_feature = features[0] self.assertEqual(test_feature.type, "source") self.assertEqual(str(test_feature.location), "[0:206](+)") - self.assertEqual(len(test_feature.qualifiers.keys()), 3) + self.assertEqual(len(list(test_feature.qualifiers.keys())), 3) self.assertEqual(test_feature.qualifiers["country"], ["Russia:Bashkortostan"]) self.assertEqual(test_feature.qualifiers["organism"], ["Armoracia rusticana"]) self.assertEqual(test_feature.qualifiers["db_xref"], ["taxon:3704"]) @@ -749,7 +753,7 @@ self.assertEqual(str(test_feature._sub_features[1].location), "[142:206](+)") self.assertEqual(test_feature._sub_features[1].type, "CDS") #self.assertEqual(test_feature._sub_features[1].location_operator, "join") - self.assertEqual(len(test_feature.qualifiers.keys()), 6) + self.assertEqual(len(list(test_feature.qualifiers.keys())), 6) self.assertEqual(test_feature.qualifiers["gene"], ["csp14"]) self.assertEqual(test_feature.qualifiers["codon_start"], ["2"]) self.assertEqual(test_feature.qualifiers["product"], @@ -788,7 +792,7 @@ passwd=DBPASSWD, host=DBHOST, db=TESTDB) self.server = server - if db_name not in server.keys(): + if db_name not in server: self.db = server.new_database(db_name) server.commit() self.db = self.server[db_name] @@ -810,9 +814,9 @@ iterator = SeqIO.parse(handle=open(t_filename, "r"), format=t_format) for record in iterator: - #print " - %s, %s" % (checksum_summary(record), record.id) + #print(" - %s, %s" % (checksum_summary(record), record.id)) key = record.name - #print " - Retrieving by name/display_id '%s'," % key, + #print(" - Retrieving by name/display_id '%s'," % key) db_rec = db.lookup(name=key) compare_record(record, db_rec) db_rec = db.lookup(display_id=key) @@ -820,7 +824,7 @@ key = record.id if key.count(".") == 1 and key.split(".")[1].isdigit(): - #print " - Retrieving by version '%s'," % key, + #print(" - Retrieving by version '%s'," % key) db_rec = db.lookup(version=key) compare_record(record, db_rec) @@ -829,14 +833,14 @@ key = record.annotations["accessions"][0] assert key, "Blank accession in annotation %s" % repr(record.annotations) if key != record.id: - #print " - Retrieving by accession '%s'," % key, + #print(" - Retrieving by accession '%s'," % key) db_rec = db.lookup(accession=key) compare_record(record, db_rec) if "gi" in record.annotations: key = record.annotations['gi'] if key != record.id: - #print " - Retrieving by GI '%s'," % key, + #print(" - Retrieving by GI '%s'," % key) db_rec = db.lookup(primary_id=key) compare_record(record, db_rec) diff -Nru python-biopython-1.62/Tests/output/test_SeqIO python-biopython-1.63/Tests/output/test_SeqIO --- python-biopython-1.62/Tests/output/test_SeqIO 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/output/test_SeqIO 2013-12-05 14:10:43.000000000 +0000 @@ -2230,6 +2230,46 @@ Failed: Sequences must all be the same length Checking can write/read as 'phylip-sequential' format Failed: Sequences must all be the same length +Testing reading embl format file EMBL/patents.embl + ID and Name='NRP00000001', + Seq='XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX...XXXXXXX', length=358 + ID and Name='NRP00000002', + Seq='XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX...XXXXXXX', length=65 + ID and Name='NRP00210944', + Seq='XXXXXXXXXXXXXXXXXXXXXXXXX', length=25 + ID and Name='NRP00210945', + Seq='XXXXXXXXXXXXXXXXXXXXXXXXX', length=25 + Checking can write/read as 'fasta' format + Checking can write/read as 'clustal' format + Failed: Sequences must all be the same length + Checking can write/read as 'phylip' format + Failed: Sequences must all be the same length + Checking can write/read as 'stockholm' format + Failed: Sequences must all be the same length + Checking can write/read as 'phylip-relaxed' format + Failed: Sequences must all be the same length + Checking can write/read as 'embl' format + Checking can write/read as 'fastq' format + Failed: No suitable quality scores found in letter_annotations of SeqRecord (id=NRP00210945). + Checking can write/read as 'fastq-illumina' format + Failed: No suitable quality scores found in letter_annotations of SeqRecord (id=NRP00210945). + Checking can write/read as 'fastq-solexa' format + Failed: No suitable quality scores found in letter_annotations of SeqRecord (id=NRP00210945). + Checking can write/read as 'genbank' format + Checking can write/read as 'imgt' format + Checking can write/read as 'phd' format + Failed: No suitable quality scores found in letter_annotations of SeqRecord (id=NRP00210945). + Checking can write/read as 'qual' format + Failed: No suitable quality scores found in letter_annotations of SeqRecord (id=NRP00210945). + Checking can write/read as 'seqxml' format + Failed: Sequence type is UnknownSeq but SeqXML requires sequence + Checking can write/read as 'sff' format + Failed: Missing SFF flow information + Checking can write/read as 'tab' format + Checking can write/read as 'nexus' format + Failed: Sequences must all be the same length + Checking can write/read as 'phylip-sequential' format + Failed: Sequences must all be the same length Testing reading embl format file EMBL/TRBG361.embl ID = 'X56734.1', Name='X56734', Seq='AAACAAACCAAATATGGATTTTATTGTAGCCATATTTGCT...AAAAAAA', length=1859 @@ -3700,6 +3740,47 @@ Failed: Need a DNA, RNA or Protein alphabet Checking can write/read as 'phylip-sequential' format Failed: Repeated name 'EAS54_6_R1' (originally 'EAS54_6_R1_2_1_540_792'), possibly due to truncation +Testing reading fastq format file Quality/example_dos.fastq + ID and Name='EAS54_6_R1_2_1_413_324', + Seq='CCCTTCTTGTCTTCAGCGTTTCTCC', length=25 + ID and Name='EAS54_6_R1_2_1_540_792', + Seq='TTGGCAGGCCAAGGCCGATGGATCA', length=25 + ID and Name='EAS54_6_R1_2_1_443_348', + Seq='GTTGCTTCTGGCGTGGGTGGGGGGG', length=25 +Testing reading fastq format file Quality/example_dos.fastq as an alignment + CTG alignment column 0 + CTT alignment column 1 + CGT alignment column 2 + TGG alignment column 3 + TCC alignment column 4 + ||| ... + CAG alignment column 24 + Checking can write/read as 'fasta' format + Checking can write/read as 'clustal' format + Checking can write/read as 'phylip' format + Failed: Repeated name 'EAS54_6_R1' (originally 'EAS54_6_R1_2_1_540_792'), possibly due to truncation + Checking can write/read as 'stockholm' format + Checking can write/read as 'phylip-relaxed' format + Checking can write/read as 'embl' format + Failed: Need a DNA, RNA or Protein alphabet + Checking can write/read as 'fastq' format + Checking can write/read as 'fastq-illumina' format + Checking can write/read as 'fastq-solexa' format + Checking can write/read as 'genbank' format + Failed: Locus identifier 'EAS54_6_R1_2_1_443_348' is too long + Checking can write/read as 'imgt' format + Failed: Need a DNA, RNA or Protein alphabet + Checking can write/read as 'phd' format + Checking can write/read as 'qual' format + Checking can write/read as 'seqxml' format + Failed: Need a DNA, RNA or Protein alphabet + Checking can write/read as 'sff' format + Failed: Missing SFF flow information + Checking can write/read as 'tab' format + Checking can write/read as 'nexus' format + Failed: Need a DNA, RNA or Protein alphabet + Checking can write/read as 'phylip-sequential' format + Failed: Repeated name 'EAS54_6_R1' (originally 'EAS54_6_R1_2_1_540_792'), possibly due to truncation Testing reading fastq format file Quality/tricky.fastq ID and Name='071113_EAS56_0053:1:1:998:236', Seq='TTTCTTGCCCCCATAGACTGAGACCTTCCCTAAATA', length=36 diff -Nru python-biopython-1.62/Tests/requires_internet.py python-biopython-1.63/Tests/requires_internet.py --- python-biopython-1.62/Tests/requires_internet.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/requires_internet.py 2013-12-05 14:10:43.000000000 +0000 @@ -24,7 +24,7 @@ 80, socket.AF_UNSPEC, socket.SOCK_STREAM) - except socket.gaierror, x: + except socket.gaierror as x: check.available = False else: check.available = True diff -Nru python-biopython-1.62/Tests/requires_wise.py python-biopython-1.63/Tests/requires_wise.py --- python-biopython-1.62/Tests/requires_wise.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/requires_wise.py 2013-12-05 14:10:43.000000000 +0000 @@ -13,9 +13,9 @@ raise MissingExternalDependencyError( "Don't know how to find the Wise2 tool dnal on Windows.") -import commands +from Bio._py3k import getoutput not_found_types = ["command not found", "dnal: not found", "not recognized"] -dnal_output = commands.getoutput("dnal") +dnal_output = getoutput("dnal") for not_found in not_found_types: if not_found in dnal_output: diff -Nru python-biopython-1.62/Tests/run_tests.py python-biopython-1.63/Tests/run_tests.py --- python-biopython-1.62/Tests/run_tests.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/run_tests.py 2013-12-05 14:10:43.000000000 +0000 @@ -24,11 +24,12 @@ """ # The default verbosity (not verbose) +from __future__ import print_function + VERBOSITY = 0 # standard modules import sys -import cStringIO import os import re import getopt @@ -38,6 +39,16 @@ import doctest import distutils.util import gc +from io import BytesIO + +# Note, we want to be able to call run_tests.py BEFORE +# Biopython is installed, so we can't use this: +# from Bio._py3k import StringIO +try: + from StringIO import StringIO # Python 2 (byte strings) +except ImportError: + from io import StringIO # Python 3 (unicode strings) + def is_pypy(): import platform @@ -68,6 +79,7 @@ "Bio.Align.Generic", "Bio.Align.Applications._Clustalw", "Bio.Align.Applications._ClustalOmega", + "Bio.Align.Applications._MSAProbs", "Bio.Align.Applications._Mafft", "Bio.Align.Applications._Muscle", "Bio.Align.Applications._Probcons", @@ -84,8 +96,6 @@ "Bio.KEGG.Compound", "Bio.KEGG.Enzyme", "Bio.Motif", - "Bio.Motif.Applications._AlignAce", - "Bio.Motif.Applications._XXmotif", "Bio.motifs", "Bio.motifs.applications._alignace", "Bio.motifs.applications._xxmotif", @@ -144,12 +154,10 @@ Checks for http://bugs.python.org/issue17666 expected in Python 2.7.4, 3.2.4 and 3.3.1 only. """ + if os.name == 'java': + #Jython not affected + return False import gzip - try: - from io import BytesIO - except ImportError: - #Python 2.5 fall back - from StringIO import StringIO as BytesIO #Would like to use byte literal here: bgzf_eof = "\x1f\x8b\x08\x04\x00\x00\x00\x00\x00\xff\x06\x00BC" + \ "\x02\x00\x1b\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00" @@ -162,7 +170,7 @@ h.close() assert not data, "Should be zero length, not %i" % len(data) return False - except TypeError, err: + except TypeError as err: #TypeError: integer argument expected, got 'tuple' h.close() return True @@ -171,7 +179,7 @@ #HACK: Since Python2.5 under Windows have slightly different str(float) output, #we're removing doctests that may fail because of this -if sys.platform == "win32" and sys.version_info < (2,6): +if sys.platform == "win32" and sys.version_info < (2, 6): DOCTEST_MODULES.remove("Bio.SearchIO._model.hit") DOCTEST_MODULES.remove("Bio.SearchIO._model.hsp") @@ -206,9 +214,9 @@ try: opts, args = getopt.getopt(argv, 'gv', ["generate", "verbose", "doctest", "help", "offline"]) - except getopt.error, msg: - print msg - print __doc__ + except getopt.error as msg: + print(msg) + print(__doc__) return 2 verbosity = VERBOSITY @@ -216,22 +224,22 @@ # deal with the options for o, a in opts: if o == "--help": - print __doc__ + print(__doc__) return 0 if o == "--offline": - print "Skipping any tests requiring internet access" + print("Skipping any tests requiring internet access") #This is a bit of a hack... import requires_internet requires_internet.check.available = False #The check() function should now report internet not available if o == "-g" or o == "--generate": if len(args) > 1: - print "Only one argument (the test name) needed for generate" - print __doc__ + print("Only one argument (the test name) needed for generate") + print(__doc__) return 2 elif len(args) == 0: - print "No test name specified to generate output for." - print __doc__ + print("No test name specified to generate output for.") + print(__doc__) return 2 # strip off .py if it was included if args[0][-3:] == ".py": @@ -250,8 +258,8 @@ if args[arg_num][-3:] == ".py": args[arg_num] = args[arg_num][:-3] - print "Python version:", sys.version - print "Operating system:", os.name, sys.platform + print("Python version: %s" % sys.version) + print("Operating system: %s %s" % (os.name, sys.platform)) # run the tests runner = TestRunner(args, verbosity) @@ -376,14 +384,14 @@ if "doctest" in self.tests: self.tests.remove("doctest") self.tests.extend(DOCTEST_MODULES) - stream = cStringIO.StringIO() + stream = StringIO() unittest.TextTestRunner.__init__(self, stream, verbosity=verbosity) def runTest(self, name): from Bio import MissingExternalDependencyError result = self._makeResult() - output = cStringIO.StringIO() + output = StringIO() # Restore the language and thus default encoding (in case a prior # test changed this, e.g. to help with detecting command line tools) global system_lang @@ -429,10 +437,10 @@ sys.stderr.write("FAIL\n") result.printErrors() return False - except MissingExternalDependencyError, msg: + except MissingExternalDependencyError as msg: sys.stderr.write("skipping. %s\n" % msg) return True - except Exception, msg: + except Exception as msg: # This happened during the import sys.stderr.write("ERROR\n") result.stream.write(result.separator1+"\n") @@ -440,7 +448,7 @@ result.stream.write(result.separator2+"\n") result.stream.write(traceback.format_exc()) return False - except KeyboardInterrupt, err: + except KeyboardInterrupt as err: # Want to allow this, and abort the test # (see below for special case) raise err diff -Nru python-biopython-1.62/Tests/search_tests_common.py python-biopython-1.63/Tests/search_tests_common.py --- python-biopython-1.62/Tests/search_tests_common.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/search_tests_common.py 2013-12-05 14:10:43.000000000 +0000 @@ -4,6 +4,8 @@ # license. Please see the LICENSE file that should have been included # as part of this package. +from __future__ import print_function + import os import gzip import unittest @@ -25,18 +27,22 @@ """Index filename using **kwargs, check get_raw(id)==raw.""" idx = SearchIO.index(filename, self.fmt, **kwargs) raw = _as_bytes(raw) - self.assertEqual(raw, idx.get_raw(id)) + # Anticipate cases where the raw string and/or file uses different + # newline characters ~ we set everything to \n. + self.assertEqual(raw.replace(b'\r\n', b'\n'), + idx.get_raw(id).replace(b'\r\n', b'\n')) idx.close() #Now again, but using SQLite backend if sqlite3: idx = SearchIO.index_db(":memory:", filename, self.fmt, **kwargs) - self.assertEqual(raw, idx.get_raw(id)) + self.assertEqual(raw.replace(b'\r\n', b'\n'), + idx.get_raw(id).replace(b'\r\n', b'\n')) idx.close() if os.path.isfile(filename + ".bgz"): #Do the tests again with the BGZF compressed file - print "[BONUS %s.bgz]" % filename + print("[BONUS %s.bgz]" % filename) self.check_raw(filename + ".bgz", id, raw, **kwargs) @@ -88,14 +94,14 @@ if os.path.isfile(filename + ".bgz"): #Do the tests again with the BGZF compressed file - print "[BONUS %s.bgz]" % filename + print("[BONUS %s.bgz]" % filename) self.check_index(filename + ".bgz", format, **kwargs) def _num_difference(obj_a, obj_b): """Returns the number of instance attributes presence only in one object.""" - attrs_a = obj_a.__dict__.keys() - attrs_b = obj_b.__dict__.keys() - diff = set(attrs_a).symmetric_difference(set(attrs_b)) + attrs_a = set(obj_a.__dict__.keys()) + attrs_b = set(obj_b.__dict__.keys()) + diff = attrs_a.symmetric_difference(attrs_b) privates = len([x for x in diff if x.startswith('_')]) return len(diff) - privates @@ -147,10 +153,10 @@ # if it's a dictionary, compare values and keys elif isinstance(val_a, dict): assert isinstance(val_b, dict) - keys_a, values_a = val_a.keys(), val_a.values() - keys_b, values_b = val_b.keys(), val_b.values() - # sort all values and keys - [x.sort() for x in (keys_a, values_a, keys_b, values_b)] + keys_a = sorted(val_a.keys()) + values_a = sorted(val_a.values()) + keys_b = sorted(val_b.keys()) + values_b = sorted(val_b.values()) assert keys_a == keys_b, "%s: %r vs %r" % (attr, keys_a, keys_b) assert values_a == values_b, "%s: %r vs %r" % (attr, values_a, values_b) diff -Nru python-biopython-1.62/Tests/seq_tests_common.py python-biopython-1.63/Tests/seq_tests_common.py --- python-biopython-1.62/Tests/seq_tests_common.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/seq_tests_common.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,6 +1,10 @@ # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. + +from Bio._py3k import range +from Bio._py3k import basestring + from Bio.Seq import UnknownSeq from Bio.SeqUtils.CheckSum import seguid from Bio.SeqFeature import ExactPosition, UnknownPosition @@ -155,7 +159,7 @@ try: assert str(old_sub.location) == str(new_sub.location), \ "%s -> %s" % (str(old_sub.location), str(new_sub.location)) - except AssertionError, e: + except AssertionError as e: if isinstance(old_sub.location.start, ExactPosition) and \ isinstance(old_sub.location.end, ExactPosition): # Its not a problem with fuzzy locations, re-raise @@ -210,10 +214,10 @@ #this takes far far far too long to run! #Test both positive and negative indices if ln < 50: - indices = range(-ln,ln) + indices = list(range(-ln, ln)) else: #A selection of end cases, and the mid point - indices = [-ln,-ln+1,-(ln//2),-1,0,1,ln//2,ln-2,ln-1] + indices = [-ln, -ln+1, -(ln//2), -1, 0, 1, ln//2, ln-2, ln-1] #Test element access, for i in indices: @@ -233,7 +237,7 @@ "Slice %s vs %s" % (repr(expected), repr(new[i:j])) #Slicing with step of 1 should make no difference. #Slicing with step 3 might be useful for codons. - for step in [1,3]: + for step in [1, 3]: expected = s[i:j:step] assert expected == str(old[i:j:step]) assert expected == str(new[i:j:step]) @@ -314,8 +318,8 @@ new_comment = " ".join(new.annotations[key]) else: new_comment = new.annotations[key] - old_comment = old_comment.replace("\n"," ").replace(" ", " ") - new_comment = new_comment.replace("\n"," ").replace(" ", " ") + old_comment = old_comment.replace("\n", " ").replace(" ", " ") + new_comment = new_comment.replace("\n", " ").replace(" ", " ") assert old_comment == new_comment, \ "Comment annotation changed by load/retrieve\n" \ "Was:%s\nNow:%s" \ diff -Nru python-biopython-1.62/Tests/test_Ace.py python-biopython-1.63/Tests/test_Ace.py --- python-biopython-1.62/Tests/test_Ace.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_Ace.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,10 @@ +# Copyright 2004 by Frank Kauff. All rights reserved. +# Revisions copyright 2008-2013 by Peter Cock. All rights reserved. +# Revisions copyright 2009-2009 by Michiel de Hoon. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. + import unittest from Bio.Sequencing import Ace @@ -497,7 +504,7 @@ contigs=Ace.parse(self.handle) # First contig - contig = contigs.next() + contig = next(contigs) self.assertEqual(len(contig.reads), 2) self.assertEqual(contig.name, "Contig1") self.assertEqual(contig.nbases, 856) @@ -576,7 +583,7 @@ self.assertEqual(contig.reads[1].wr, None) # Second contig - contig = contigs.next() + contig = next(contigs) self.assertEqual(len(contig.reads), 14) self.assertEqual(contig.name, "Contig2") self.assertEqual(contig.nbases, 3296) @@ -982,7 +989,7 @@ self.assertEqual(contig.reads[13].wr[0].date, "040217:110357") # Make sure there are no more contigs - self.assertRaises(StopIteration, contigs.next) + self.assertRaises(StopIteration, next, contigs) class AceTestTwo(unittest.TestCase): @@ -1166,7 +1173,7 @@ contigs=Ace.parse(self.handle) # First (and only) contig - contig = contigs.next() + contig = next(contigs) self.assertEqual(len(contig.reads), 6) self.assertEqual(contig.name, "Contig1") @@ -1328,7 +1335,7 @@ self.assertEqual(contig.reads[5].wr, None) # Make sure there are no more contigs - self.assertRaises(StopIteration, contigs.next) + self.assertRaises(StopIteration, next, contigs) class AceTestThree(unittest.TestCase): @@ -1592,7 +1599,7 @@ contigs=Ace.parse(self.handle) # First (and only) contig - contig = contigs.next() + contig = next(contigs) self.assertEqual(len(contig.reads), 8) self.assertEqual(contig.name, "Contig1") @@ -1830,7 +1837,7 @@ self.assertEqual(contig.reads[7].wr, None) # Make sure there are no more contigs - self.assertRaises(StopIteration, contigs.next) + self.assertRaises(StopIteration, next, contigs) if __name__ == "__main__": diff -Nru python-biopython-1.62/Tests/test_AlignIO.py python-biopython-1.63/Tests/test_AlignIO.py --- python-biopython-1.62/Tests/test_AlignIO.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_AlignIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,8 +3,10 @@ # license. Please see the LICENSE file that should have been included # as part of this package. +from __future__ import print_function + import os -from StringIO import StringIO +from Bio._py3k import StringIO from Bio import SeqIO from Bio import AlignIO from Bio.Align.Generic import Alignment @@ -30,8 +32,8 @@ ("clustal", 7, 1, 'Clustalw/opuntia.aln'), ("clustal", 5, 1, 'Clustalw/hedgehog.aln'), ("clustal", 2, 1, 'Clustalw/odd_consensus.aln'), - ("clustal",20, 1, 'Clustalw/protein.aln'), # Used in the tutorial - ("clustal",20, 1, 'Clustalw/promals3d.aln'), # Nonstandard header + ("clustal", 20, 1, 'Clustalw/protein.aln'), # Used in the tutorial + ("clustal", 20, 1, 'Clustalw/promals3d.aln'), # Nonstandard header #Following examples are also used in test_GFF.py ("fasta", 3, 1, 'GFF/multi.fna'), # Trivial nucleotide alignment #Following example is also used in test_Nexus.py @@ -41,9 +43,9 @@ ("stockholm", 6, 1, 'Stockholm/funny.sth'), ("phylip", 6, 1, 'Phylip/reference_dna.phy'), ("phylip", 6, 1, 'Phylip/reference_dna2.phy'), - ("phylip",10, 1, 'Phylip/hennigian.phy'), - ("phylip",10, 1, 'Phylip/horses.phy'), - ("phylip",10, 1, 'Phylip/random.phy'), + ("phylip", 10, 1, 'Phylip/hennigian.phy'), + ("phylip", 10, 1, 'Phylip/horses.phy'), + ("phylip", 10, 1, 'Phylip/random.phy'), ("phylip", 3, 1, 'Phylip/interlaced.phy'), ("phylip", 4, 1, 'Phylip/interlaced2.phy'), ("phylip-relaxed", 12, 1, 'ExtendedPhylip/primates.phyx'), @@ -63,7 +65,7 @@ ("fasta-m10", 2, 1, 'Fasta/output005.m10'), ("fasta-m10", 2, 1, 'Fasta/output006.m10'), ("fasta-m10", 2, 9, 'Fasta/output007.m10'), - ("fasta-m10", 2, 12,'Fasta/output008.m10'), + ("fasta-m10", 2, 12, 'Fasta/output008.m10'), ("ig", 16, 1, 'IntelliGenetics/VIF_mase-pro.txt'), ("pir", 2, 1, 'NBRF/clustalw.pir'), ] @@ -85,23 +87,23 @@ #Show each sequence row horizontally for record in alignment: answer.append("%s%s %s" - % (index,str_summary(str(record.seq)),record.id)) + % (index, str_summary(str(record.seq)), record.id)) else: #Show each sequence row vertically - for i in range(min(5,alignment_len)): - answer.append(index + str_summary(alignment[:,i]) + for i in range(min(5, alignment_len)): + answer.append(index + str_summary(alignment[:, i]) + " alignment column %i" % i) if alignment_len > 5: i = alignment_len - 1 answer.append(index + str_summary("|" * rec_count) + " ...") - answer.append(index + str_summary(alignment[:,i]) + answer.append(index + str_summary(alignment[:, i]) + " alignment column %i" % i) return "\n".join(answer) def check_simple_write_read(alignments, indent=" "): - #print indent+"Checking we can write and then read back these alignments" + #print(indent+"Checking we can write and then read back these alignments") for format in test_write_read_align_with_seq_count: records_per_alignment = len(alignments[0]) for a in alignments: @@ -112,7 +114,7 @@ and format not in test_write_read_alignment_formats: continue - print indent+"Checking can write/read as '%s' format" % format + print(indent+"Checking can write/read as '%s' format" % format) #Going to write to a handle... handle = StringIO() @@ -120,10 +122,10 @@ try: c = AlignIO.write(alignments, handle=handle, format=format) assert c == len(alignments) - except ValueError, e: + except ValueError as e: #This is often expected to happen, for example when we try and #write sequences of different lengths to an alignment file. - print indent+"Failed: %s" % str(e) + print(indent+"Failed: %s" % str(e)) #Carry on to the next format: continue @@ -134,7 +136,7 @@ try: alignments2 = list(AlignIO.parse(handle=handle, format=format, seq_count=records_per_alignment)) - except ValueError, e: + except ValueError as e: #This is BAD. We can't read our own output. #I want to see the output when called from the test harness, #run_tests.py (which can be funny about new lines on Windows) @@ -149,7 +151,7 @@ handle.seek(0) try: alignments2 = list(AlignIO.parse(handle=handle, format=format)) - except ValueError, e: + except ValueError as e: #This is BAD. We can't read our own output. #I want to see the output when called from the test harness, #run_tests.py (which can be funny about new lines on Windows) @@ -170,7 +172,7 @@ for a1, a2 in zip(alignments, alignments2): assert a1.get_alignment_length() == a2.get_alignment_length() assert len(a1) == len(a2) - for r1, r2 in zip(a1,a2): + for r1, r2 in zip(a1, a2): #Check the bare minimum (ID and sequence) as #many formats can't store more than that. @@ -180,16 +182,16 @@ #Beware of different quirks and limitations in the #valid character sets and the identifier lengths! if format in ["phylip", "phylip-sequential"]: - assert r1.id.replace("[","").replace("]","")[:10] == r2.id, \ + assert r1.id.replace("[", "").replace("]", "")[:10] == r2.id, \ "'%s' vs '%s'" % (r1.id, r2.id) elif format=="phylip-relaxed": assert r1.id.replace(" ", "").replace(':', '|') == r2.id, \ "'%s' vs '%s'" % (r1.id, r2.id) elif format=="clustal": - assert r1.id.replace(" ","_")[:30] == r2.id, \ + assert r1.id.replace(" ", "_")[:30] == r2.id, \ "'%s' vs '%s'" % (r1.id, r2.id) elif format=="stockholm": - assert r1.id.replace(" ","_") == r2.id, \ + assert r1.id.replace(" ", "_") == r2.id, \ "'%s' vs '%s'" % (r1.id, r2.id) elif format=="fasta": assert r1.id.split()[0] == r2.id @@ -214,7 +216,7 @@ # This should raise a ValueError AlignIO.write(alignment, handle, 'phylip') assert False, "Duplicate IDs after truncation are not allowed." - except ValueError, e: + except ValueError as e: # Expected - check the error assert "Repeated name 'longsequen'" in str(e) @@ -235,7 +237,7 @@ % t_format #Check writers reject non-alignments -list_of_records = list(AlignIO.read(open("Clustalw/opuntia.aln"),"clustal")) +list_of_records = list(AlignIO.read(open("Clustalw/opuntia.aln"), "clustal")) for t_format in list(AlignIO._FormatToWriter)+list(SeqIO._FormatToWriter): handle = StringIO() try: @@ -249,12 +251,12 @@ #Main tests... for (t_format, t_per, t_count, t_filename) in test_files: - print "Testing reading %s format file %s with %i alignments" \ - % (t_format, t_filename, t_count) + print("Testing reading %s format file %s with %i alignments" \ + % (t_format, t_filename, t_count)) assert os.path.isfile(t_filename), t_filename #Try as an iterator using handle - alignments = list(AlignIO.parse(handle=open(t_filename,"r"), format=t_format)) + alignments = list(AlignIO.parse(handle=open(t_filename, "r"), format=t_format)) assert len(alignments) == t_count, \ "Found %i alignments but expected %i" % (len(alignments), t_count) for alignment in alignments: @@ -270,19 +272,19 @@ #Try using the iterator with the next() method alignments3 = [] - seq_iterator = AlignIO.parse(handle=open(t_filename,"r"), format=t_format) + seq_iterator = AlignIO.parse(handle=open(t_filename, "r"), format=t_format) while True: try: - record = seq_iterator.next() + record = next(seq_iterator) except StopIteration: break assert record is not None, "Should raise StopIteration not return None" alignments3.append(record) #Try a mixture of next() and list (a torture test!) - seq_iterator = AlignIO.parse(handle=open(t_filename,"r"), format=t_format) + seq_iterator = AlignIO.parse(handle=open(t_filename, "r"), format=t_format) try: - record = seq_iterator.next() + record = next(seq_iterator) except StopIteration: record = None if record is not None: @@ -293,9 +295,9 @@ assert len(alignments4) == t_count #Try a mixture of next() and for loop (a torture test!) - seq_iterator = AlignIO.parse(handle=open(t_filename,"r"), format=t_format) + seq_iterator = AlignIO.parse(handle=open(t_filename, "r"), format=t_format) try: - record = seq_iterator.next() + record = next(seq_iterator) except StopIteration: record = None if record is not None: @@ -315,38 +317,38 @@ alignment = AlignIO.read(open(t_filename), t_format) assert False, "Bio.AlignIO.read(...) should have failed" except ValueError: - #Expected to fail + # Expected to fail pass - #Print the alignment - for i,alignment in enumerate(alignments): + # Show the alignment + for i, alignment in enumerate(alignments): if i < 3 or i+1 == t_count: - print " Alignment %i, with %i sequences of length %i" \ + print(" Alignment %i, with %i sequences of length %i" \ % (i, len(alignment), - alignment.get_alignment_length()) - print alignment_summary(alignment) + alignment.get_alignment_length())) + print(alignment_summary(alignment)) elif i==3: - print " ..." + print(" ...") - #Check AlignInfo.SummaryInfo likes the alignment + # Check AlignInfo.SummaryInfo likes the alignment summary = AlignInfo.SummaryInfo(alignment) dumb_consensus = summary.dumb_consensus() #gap_consensus = summary.gap_consensus() if t_format != "nexus": - #Hack for bug 2535 + # Hack for bug 2535 pssm = summary.pos_specific_score_matrix() rep_dict = summary.replacement_dictionary() try: info_content = summary.information_content() - except ValueError, e: + except ValueError as e: if str(e) != "Error in alphabet: not Nucleotide or Protein, supply expected frequencies": raise e pass - if t_count==1 and t_format not in ["nexus","emboss","fasta-m10"]: - #print " Trying to read a triple concatenation of the input file" - data = open(t_filename,"r").read() + if t_count==1 and t_format not in ["nexus", "emboss", "fasta-m10"]: + #print(" Trying to read a triple concatenation of the input file") + data = open(t_filename, "r").read() handle = StringIO() handle.write(data + "\n\n" + data + "\n\n" + data) handle.seek(0) @@ -359,4 +361,4 @@ alignments.reverse() check_simple_write_read(alignments) -print "Finished tested reading files" +print("Finished tested reading files") diff -Nru python-biopython-1.62/Tests/test_AlignIO_FastaIO.py python-biopython-1.63/Tests/test_AlignIO_FastaIO.py --- python-biopython-1.62/Tests/test_AlignIO_FastaIO.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_AlignIO_FastaIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -7,6 +7,8 @@ Created to check for any regressions from my new implementation of the parser. """ +from __future__ import print_function + import os from Bio import AlignIO @@ -26,19 +28,19 @@ ("fasta-m10", 2, 1, 'Fasta/output005.m10'), ("fasta-m10", 2, 1, 'Fasta/output006.m10'), ("fasta-m10", 2, 9, 'Fasta/output007.m10'), - ("fasta-m10", 2, 12,'Fasta/output008.m10'), + ("fasta-m10", 2, 12, 'Fasta/output008.m10'), ] #Main tests... for (t_format, t_per, t_count, t_filename) in test_files: assert t_format == "fasta-m10" and t_per == 2 - print "Testing reading %s format file %s with %i alignments" \ - % (t_format, t_filename, t_count) + print("Testing reading %s format file %s with %i alignments" \ + % (t_format, t_filename, t_count)) assert os.path.isfile(t_filename), t_filename #Try as an iterator using handle - alignments = list(AlignIO.parse(handle=open(t_filename,"r"), format=t_format)) + alignments = list(AlignIO.parse(handle=open(t_filename, "r"), format=t_format)) assert len(alignments) == t_count, \ "Found %i alignments but expected %i" % (len(alignments), t_count) for alignment in alignments: @@ -47,25 +49,25 @@ % (t_per, len(alignment)) #Print the alignment - for i,alignment in enumerate(alignments): - print "="*78 - print "Alignment %i, with %i sequences of length %i" \ + for i, alignment in enumerate(alignments): + print("="*78) + print("Alignment %i, with %i sequences of length %i" \ % (i, len(alignment), - alignment.get_alignment_length()) + alignment.get_alignment_length())) for k in sorted(alignment._annotations): - print " - %s: %r" % (k, alignment._annotations[k]) + print(" - %s: %r" % (k, alignment._annotations[k])) assert alignment[0].name == "query" assert alignment[1].name == "match" #Show each sequence row horizontally for record in alignment: - print "-"*78 - print record.id - print record.description - print repr(record.seq) + print("-"*78) + print(record.id) + print(record.description) + print(repr(record.seq)) assert not record.features assert not record.letter_annotations for k in sorted(record.annotations): - print " - %s: %r" % (k, record.annotations[k]) - print "="*78 -print "Finished tested reading files" + print(" - %s: %r" % (k, record.annotations[k])) + print("="*78) +print("Finished tested reading files") diff -Nru python-biopython-1.62/Tests/test_AlignIO_convert.py python-biopython-1.63/Tests/test_AlignIO_convert.py --- python-biopython-1.62/Tests/test_AlignIO_convert.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_AlignIO_convert.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,7 +5,7 @@ """Unit tests for Bio.SeqIO.convert(...) function.""" import unittest -from StringIO import StringIO +from Bio._py3k import StringIO from Bio import AlignIO from Bio.Alphabet import generic_protein, generic_nucleotide, generic_dna @@ -59,12 +59,12 @@ for filename, in_format, alphabet in tests: for out_format in output_formats: - def funct(fn,fmt1, fmt2, alpha): + def funct(fn, fmt1, fmt2, alpha): f = lambda x : x.simple_check(fn, fmt1, fmt2, alpha) f.__doc__ = "Convert %s from %s to %s" % (fn, fmt1, fmt2) return f setattr(ConvertTests, "test_%s_%s_to_%s" - % (filename.replace("/","_").replace(".","_"), in_format, out_format), + % (filename.replace("/", "_").replace(".", "_"), in_format, out_format), funct(filename, in_format, out_format, alphabet)) del funct diff -Nru python-biopython-1.62/Tests/test_Application.py python-biopython-1.63/Tests/test_Application.py --- python-biopython-1.62/Tests/test_Application.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_Application.py 2013-12-05 14:10:43.000000000 +0000 @@ -9,8 +9,6 @@ stdin/stdout/stderr handling. """ -from __future__ import with_statement - import os import unittest diff -Nru python-biopython-1.62/Tests/test_BWA_tool.py python-biopython-1.63/Tests/test_BWA_tool.py --- python-biopython-1.62/Tests/test_BWA_tool.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_BWA_tool.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,8 +5,6 @@ # license. Please see the LICENSE file that should have been included # as part of this package. -from __future__ import with_statement - from Bio import MissingExternalDependencyError import sys import os @@ -45,8 +43,8 @@ if bwa_exe: break else: - import commands - output = commands.getoutput("bwa") + from Bio._py3k import getoutput + output = getoutput("bwa") #Since "not found" may be in another language, try and be sure this is #really the bwa tool's output @@ -63,21 +61,21 @@ class BwaTestCase(unittest.TestCase): """Class for implementing BWA test cases""" def setUp(self): - self.reference_file = os.path.join(os.path.dirname(os.path.abspath(__file__)),"BWA", "human_g1k_v37_truncated.fasta") - self.infile1 = os.path.join(os.path.dirname(os.path.abspath(__file__)),"BWA", "HNSCC1_1_truncated.fastq") - self.infile2 = os.path.join(os.path.dirname(os.path.abspath(__file__)),"BWA", "HNSCC1_2_truncated.fastq") - self.saifile1 = os.path.join(os.path.dirname(os.path.abspath(__file__)),"BWA" ,"1.sai") - self.saifile2 = os.path.join(os.path.dirname(os.path.abspath(__file__)),"BWA", "2.sai") - self.samfile1 = os.path.join(os.path.dirname(os.path.abspath(__file__)),"BWA" ,"1.sam") - self.samfile2 = os.path.join(os.path.dirname(os.path.abspath(__file__)),"BWA", "2.sam") - self.samfile = os.path.join(os.path.dirname(os.path.abspath(__file__)),"BWA", "out.sam") + self.reference_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "BWA", "human_g1k_v37_truncated.fasta") + self.infile1 = os.path.join(os.path.dirname(os.path.abspath(__file__)), "BWA", "HNSCC1_1_truncated.fastq") + self.infile2 = os.path.join(os.path.dirname(os.path.abspath(__file__)), "BWA", "HNSCC1_2_truncated.fastq") + self.saifile1 = os.path.join(os.path.dirname(os.path.abspath(__file__)), "BWA", "1.sai") + self.saifile2 = os.path.join(os.path.dirname(os.path.abspath(__file__)), "BWA", "2.sai") + self.samfile1 = os.path.join(os.path.dirname(os.path.abspath(__file__)), "BWA", "1.sam") + self.samfile2 = os.path.join(os.path.dirname(os.path.abspath(__file__)), "BWA", "2.sam") + self.samfile = os.path.join(os.path.dirname(os.path.abspath(__file__)), "BWA", "out.sam") def test_index(self): """Test for creating index files for the reference genome fasta file""" cmdline = BwaIndexCommandline() cmdline.set_parameter("infile", self.reference_file) - cmdline.set_parameter("algorithm","bwtsw") - stdout,stderr = cmdline() + cmdline.set_parameter("algorithm", "bwtsw") + stdout, stderr = cmdline() output = stdout.startswith("[bwt_gen]") self.assertTrue(stdout.startswith("[bwt_gen]"), "FASTA indexing failed:\n%s\nStdout:%s" \ diff -Nru python-biopython-1.62/Tests/test_CAPS.py python-biopython-1.63/Tests/test_CAPS.py --- python-biopython-1.62/Tests/test_CAPS.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_CAPS.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# Copyright 2001 by Iddo Friedberg. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. + import unittest from Bio import CAPS @@ -10,8 +15,8 @@ def createAlignment(sequences, alphabet): """Create an Alignment object from a list of sequences""" - return MultipleSeqAlignment((SeqRecord(Seq(s,alphabet), id="sequence%i"%(i+1)) - for (i,s) in enumerate(sequences)), + return MultipleSeqAlignment((SeqRecord(Seq(s, alphabet), id="sequence%i"%(i+1)) + for (i, s) in enumerate(sequences)), alphabet) @@ -63,10 +68,10 @@ self.assertEqual(map.dcuts[0].enzyme, EcoRI) self.assertEqual(map.dcuts[0].start, 5) self.assertEqual(map.dcuts[0].cuts_in, [0]) - self.assertEqual(map.dcuts[0].blocked_in, [1,2]) + self.assertEqual(map.dcuts[0].blocked_in, [1, 2]) self.assertEqual(map.dcuts[1].enzyme, AluI) self.assertEqual(map.dcuts[1].start, 144) - self.assertEqual(map.dcuts[1].cuts_in, [1,2]) + self.assertEqual(map.dcuts[1].cuts_in, [1, 2]) self.assertEqual(map.dcuts[1].blocked_in, [0]) def testNoCAPS(self): diff -Nru python-biopython-1.62/Tests/test_ClustalOmega_tool.py python-biopython-1.63/Tests/test_ClustalOmega_tool.py --- python-biopython-1.62/Tests/test_ClustalOmega_tool.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_ClustalOmega_tool.py 2013-12-05 14:10:43.000000000 +0000 @@ -25,8 +25,8 @@ #TODO raise MissingExternalDependencyError("Testing this on Windows not implemented yet") else: - import commands - output = commands.getoutput("clustalo --help") + from Bio._py3k import getoutput + output = getoutput("clustalo --help") if output.startswith("Clustal Omega"): clustalo_exe = "clustalo" @@ -93,7 +93,7 @@ cline = ClustalOmegaCommandline(clustalo_exe, infile=input_file) try: stdout, stderr = cline() - except ApplicationError, err: + except ApplicationError as err: self.assertTrue("Cannot open sequence file" in str(err) or "Cannot open input file" in str(err) or "non-zero exit status" in str(err)) @@ -108,7 +108,7 @@ cline = ClustalOmegaCommandline(clustalo_exe, infile=input_file) try: stdout, stderr = cline() - except ApplicationError, err: + except ApplicationError as err: self.assertTrue("contains 1 sequence, nothing to align" in str(err)) else: self.fail("Should have failed, returned:\n%s\n%s" % (stdout, stderr)) @@ -120,7 +120,7 @@ cline = ClustalOmegaCommandline(clustalo_exe, infile=input_file) try: stdout, stderr = cline() - except ApplicationError, err: + except ApplicationError as err: #Ideally we'd catch the return code and raise the specific #error for "invalid format". self.assertTrue("Can't determine format of sequence file" in str(err)) diff -Nru python-biopython-1.62/Tests/test_Clustalw_tool.py python-biopython-1.63/Tests/test_Clustalw_tool.py --- python-biopython-1.62/Tests/test_Clustalw_tool.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_Clustalw_tool.py 2013-12-05 14:10:43.000000000 +0000 @@ -7,6 +7,8 @@ #TODO - Clean up the extra files created by clustalw? e.g. *.dnd #and *.aln where we have not requested an explicit name? +from __future__ import print_function + from Bio import MissingExternalDependencyError import sys @@ -58,18 +60,18 @@ if clustalw_exe: break else: - import commands + from Bio._py3k import getoutput #Note that clustalw 1.83 and clustalw 2.1 don't obey the --version #command, but this does cause them to quit cleanly. Otherwise they prompt #the user for input (causing a lock up). - output = commands.getoutput("clustalw2 --version") + output = getoutput("clustalw2 --version") #Since "not found" may be in another language, try and be sure this is #really the clustalw tool's output if "not found" not in output and "CLUSTAL" in output \ and "Multiple Sequence Alignments" in output: clustalw_exe = "clustalw2" if not clustalw_exe: - output = commands.getoutput("clustalw --version") + output = getoutput("clustalw --version") if "not found" not in output and "CLUSTAL" in output \ and "Multiple Sequence Alignments" in output: clustalw_exe = "clustalw" @@ -115,7 +117,7 @@ align = AlignIO.read(cline.outfile, "clustal") #The length of the alignment will depend on the version of clustalw #(clustalw 2.1 and clustalw 1.83 are certainly different). - output_records = SeqIO.to_dict(SeqIO.parse(cline.outfile,"clustal")) + output_records = SeqIO.to_dict(SeqIO.parse(cline.outfile, "clustal")) self.assertTrue(set(input_records.keys()) == set(output_records.keys())) for record in align: self.assertTrue(str(record.seq) == str(output_records[record.id].seq)) @@ -142,7 +144,7 @@ try: stdout, stderr = cline() - except ApplicationError, err: + except ApplicationError as err: self.assertTrue("Cannot open sequence file" in str(err) or "Cannot open input file" in str(err) or "non-zero exit status" in str(err)) @@ -160,7 +162,7 @@ stdout, stderr = cline() #Zero return code is a possible bug in clustalw 2.1? self.assertTrue("cannot do multiple alignment" in (stdout + stderr)) - except ApplicationError, err: + except ApplicationError as err: #Good, non-zero return code indicating an error in clustalw #e.g. Using clustalw 1.83 get: #Command 'clustalw -infile=Fasta/f001' returned non-zero exit status 4 @@ -178,7 +180,7 @@ try: stdout, stderr = cline() - except ApplicationError, err: + except ApplicationError as err: #Ideally we'd catch the return code and raise the specific #error for "invalid format", rather than just notice there #is not output file. @@ -297,7 +299,7 @@ self.standard_test_procedure(cline) self.assertTrue(os.path.isfile(statistics_file)) else: - print "Skipping ClustalW2 specific test." + print("Skipping ClustalW2 specific test.") if __name__ == "__main__": diff -Nru python-biopython-1.62/Tests/test_Cluster.py python-biopython-1.63/Tests/test_Cluster.py --- python-biopython-1.62/Tests/test_Cluster.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_Cluster.py 2013-12-05 14:10:43.000000000 +0000 @@ -91,7 +91,7 @@ # Various references that don't point to matrices at all data6 = "snoopy" - data7 = {'a': [[2.3,1.2],[3.3,5.6]]} + data7 = {'a': [[2.3, 1.2], [3.3, 5.6]]} data8 = [] data9 = [None] @@ -121,7 +121,7 @@ nclusters = 3 # First data set - weight = numpy.array([1,1,1,1,1]) + weight = numpy.array([1, 1, 1, 1, 1]) data = numpy.array([[ 1.1, 2.2, 3.3, 4.4, 5.5], [ 3.1, 3.2, 1.3, 2.4, 1.5], [ 4.1, 2.2, 0.3, 5.4, 0.5], @@ -137,13 +137,13 @@ method='a', dist='e') self.assertEqual(len(clusterid), len(data)) - correct = [0,1,1,2] + correct = [0, 1, 1, 2] mapping = [clusterid[correct.index(i)] for i in range(nclusters)] for i in range(len(clusterid)): self.assertEqual(clusterid[i], mapping[correct[i]]) # Second data set - weight = numpy.array([1,1]) + weight = numpy.array([1, 1]) data = numpy.array([[ 1.1, 1.2 ], [ 1.4, 1.3 ], [ 1.1, 1.5 ], @@ -188,7 +188,7 @@ from Pycluster import clusterdistance # First data set - weight = numpy.array([ 1,1,1,1,1 ]) + weight = numpy.array([ 1, 1, 1, 1, 1 ]) data = numpy.array([[ 1.1, 2.2, 3.3, 4.4, 5.5 ], [ 3.1, 3.2, 1.3, 2.4, 1.5 ], [ 4.1, 2.2, 0.3, 5.4, 0.5 ], @@ -200,7 +200,7 @@ # Cluster assignments c1 = [0] - c2 = [1,2] + c2 = [1, 2] c3 = [3] distance = clusterdistance(data, mask=mask, weight=weight, @@ -217,7 +217,7 @@ self.assertAlmostEqual(distance, 15.118, places=3) # Second data set - weight = numpy.array([ 1,1 ]) + weight = numpy.array([ 1, 1 ]) data = numpy.array([[ 1.1, 1.2 ], [ 1.4, 1.3 ], [ 1.1, 1.5 ], @@ -270,7 +270,7 @@ from Pycluster import treecluster # First data set - weight1 = [ 1,1,1,1,1 ] + weight1 = [ 1, 1, 1, 1, 1 ] data1 = numpy.array([ [ 1.1, 2.2, 3.3, 4.4, 5.5], [ 3.1, 3.2, 1.3, 2.4, 1.5], [ 4.1, 2.2, 0.3, 5.4, 0.5], @@ -338,7 +338,7 @@ self.assertAlmostEqual(tree[2].distance, 32.508, places=3) # Second data set - weight2 = [ 1,1 ] + weight2 = [ 1, 1 ] data2 = numpy.array([[ 0.8223, 0.9295 ], [ 1.4365, 1.3223 ], [ 1.1623, 1.5364 ], @@ -538,7 +538,7 @@ from Pycluster import somcluster # First data set - weight = [ 1,1,1,1,1 ] + weight = [ 1, 1, 1, 1, 1 ] data = numpy.array([[ 1.1, 2.2, 3.3, 4.4, 5.5], [ 3.1, 3.2, 1.3, 2.4, 1.5], [ 4.1, 2.2, 0.3, 5.4, 0.5], @@ -555,7 +555,7 @@ self.assertEqual(len(clusterid[0]), 2) # Second data set - weight = [ 1,1 ] + weight = [ 1, 1 ] data = numpy.array([[ 1.1, 1.2 ], [ 1.4, 1.3 ], [ 1.1, 1.5 ], @@ -695,36 +695,36 @@ mean, coordinates, pc, eigenvalues = pca(data) self.assertAlmostEqual(mean[0], 3.5461538461538464) self.assertAlmostEqual(mean[1], 3.5307692307692311) - self.assertAlmostEqual(coordinates[0,0], 2.0323189722653883) - self.assertAlmostEqual(coordinates[0,1], 1.2252420399694917) - self.assertAlmostEqual(coordinates[1,0], 3.0936985166252251) - self.assertAlmostEqual(coordinates[1,1], -0.10647619705157851) - self.assertAlmostEqual(coordinates[2,0], 3.1453186907749426) - self.assertAlmostEqual(coordinates[2,1], -0.46331699855941139) - self.assertAlmostEqual(coordinates[3,0], 2.5440202962223761) - self.assertAlmostEqual(coordinates[3,1], 0.20633980959571077) - self.assertAlmostEqual(coordinates[4,0], 2.4468278463376221) - self.assertAlmostEqual(coordinates[4,1], -0.28412285736824866) - self.assertAlmostEqual(coordinates[5,0], 2.4468278463376221) - self.assertAlmostEqual(coordinates[5,1], -0.28412285736824866) - self.assertAlmostEqual(coordinates[6,0], -3.2018619434743254) - self.assertAlmostEqual(coordinates[6,1], 0.019692314198662915) - self.assertAlmostEqual(coordinates[7,0], -3.2018619434743254) - self.assertAlmostEqual(coordinates[7,1], 0.019692314198662915) - self.assertAlmostEqual(coordinates[8,0], 0.46978641990344067) - self.assertAlmostEqual(coordinates[8,1], -0.17778754731982949) - self.assertAlmostEqual(coordinates[9,0], -2.5549912731867215) - self.assertAlmostEqual(coordinates[9,1], 0.19733897451533403) - self.assertAlmostEqual(coordinates[10,0], -2.5033710990370044) - self.assertAlmostEqual(coordinates[10,1], -0.15950182699250004) - self.assertAlmostEqual(coordinates[11,0], -2.4365601663089413) - self.assertAlmostEqual(coordinates[11,1], -0.23390813900973562) - self.assertAlmostEqual(coordinates[12,0], -2.2801521629852974) - self.assertAlmostEqual(coordinates[12,1], 0.0409309711916888) - self.assertAlmostEqual(pc[0,0], -0.66810932728062988) - self.assertAlmostEqual(pc[0,1], -0.74406312017235743) - self.assertAlmostEqual(pc[1,0], 0.74406312017235743) - self.assertAlmostEqual(pc[1,1], -0.66810932728062988) + self.assertAlmostEqual(coordinates[0, 0], 2.0323189722653883) + self.assertAlmostEqual(coordinates[0, 1], 1.2252420399694917) + self.assertAlmostEqual(coordinates[1, 0], 3.0936985166252251) + self.assertAlmostEqual(coordinates[1, 1], -0.10647619705157851) + self.assertAlmostEqual(coordinates[2, 0], 3.1453186907749426) + self.assertAlmostEqual(coordinates[2, 1], -0.46331699855941139) + self.assertAlmostEqual(coordinates[3, 0], 2.5440202962223761) + self.assertAlmostEqual(coordinates[3, 1], 0.20633980959571077) + self.assertAlmostEqual(coordinates[4, 0], 2.4468278463376221) + self.assertAlmostEqual(coordinates[4, 1], -0.28412285736824866) + self.assertAlmostEqual(coordinates[5, 0], 2.4468278463376221) + self.assertAlmostEqual(coordinates[5, 1], -0.28412285736824866) + self.assertAlmostEqual(coordinates[6, 0], -3.2018619434743254) + self.assertAlmostEqual(coordinates[6, 1], 0.019692314198662915) + self.assertAlmostEqual(coordinates[7, 0], -3.2018619434743254) + self.assertAlmostEqual(coordinates[7, 1], 0.019692314198662915) + self.assertAlmostEqual(coordinates[8, 0], 0.46978641990344067) + self.assertAlmostEqual(coordinates[8, 1], -0.17778754731982949) + self.assertAlmostEqual(coordinates[9, 0], -2.5549912731867215) + self.assertAlmostEqual(coordinates[9, 1], 0.19733897451533403) + self.assertAlmostEqual(coordinates[10, 0], -2.5033710990370044) + self.assertAlmostEqual(coordinates[10, 1], -0.15950182699250004) + self.assertAlmostEqual(coordinates[11, 0], -2.4365601663089413) + self.assertAlmostEqual(coordinates[11, 1], -0.23390813900973562) + self.assertAlmostEqual(coordinates[12, 0], -2.2801521629852974) + self.assertAlmostEqual(coordinates[12, 1], 0.0409309711916888) + self.assertAlmostEqual(pc[0, 0], -0.66810932728062988) + self.assertAlmostEqual(pc[0, 1], -0.74406312017235743) + self.assertAlmostEqual(pc[1, 0], 0.74406312017235743) + self.assertAlmostEqual(pc[1, 1], -0.66810932728062988) self.assertAlmostEqual(eigenvalues[0], 9.3110471246032844) self.assertAlmostEqual(eigenvalues[1], 1.4437456297481428) @@ -739,34 +739,34 @@ self.assertAlmostEqual(mean[3], 6.0500) self.assertAlmostEqual(mean[4], 6.2750) self.assertAlmostEqual(mean[5], 8.0750) - self.assertAlmostEqual(coordinates[0,0], 2.6460846688406905) - self.assertAlmostEqual(coordinates[0,1], -2.1421701432732418) - self.assertAlmostEqual(coordinates[0,2], -0.56620932754145858) - self.assertAlmostEqual(coordinates[0,3], 0.0) - self.assertAlmostEqual(coordinates[1,0], 2.0644120899917544) - self.assertAlmostEqual(coordinates[1,1], 0.55542108669180323) - self.assertAlmostEqual(coordinates[1,2], 1.4818772348457117) - self.assertAlmostEqual(coordinates[1,3], 0.0) - self.assertAlmostEqual(coordinates[2,0], 1.0686641862092987) - self.assertAlmostEqual(coordinates[2,1], 1.9994412069101073) - self.assertAlmostEqual(coordinates[2,2], -1.000720598980291) - self.assertAlmostEqual(coordinates[2,3], 0.0) - self.assertAlmostEqual(coordinates[3,0], -5.77916094504174) - self.assertAlmostEqual(coordinates[3,1], -0.41269215032867046) - self.assertAlmostEqual(coordinates[3,2], 0.085052691676038017) - self.assertAlmostEqual(coordinates[3,3], 0.0) - self.assertAlmostEqual(pc[0,0], -0.26379660005997291) - self.assertAlmostEqual(pc[0,1], 0.064814972617134495) - self.assertAlmostEqual(pc[0,2], -0.91763310094893846) - self.assertAlmostEqual(pc[0,3], 0.26145408875373249) - self.assertAlmostEqual(pc[1,0], 0.05073770520434398) - self.assertAlmostEqual(pc[1,1], 0.68616983388698793) - self.assertAlmostEqual(pc[1,2], 0.13819106187213354) - self.assertAlmostEqual(pc[1,3], 0.19782544121828985) - self.assertAlmostEqual(pc[2,0], -0.63000893660095947) - self.assertAlmostEqual(pc[2,1], 0.091155993862151397) - self.assertAlmostEqual(pc[2,2], 0.045630391256086845) - self.assertAlmostEqual(pc[2,3], -0.67456694780914772) + self.assertAlmostEqual(coordinates[0, 0], 2.6460846688406905) + self.assertAlmostEqual(coordinates[0, 1], -2.1421701432732418) + self.assertAlmostEqual(coordinates[0, 2], -0.56620932754145858) + self.assertAlmostEqual(coordinates[0, 3], 0.0) + self.assertAlmostEqual(coordinates[1, 0], 2.0644120899917544) + self.assertAlmostEqual(coordinates[1, 1], 0.55542108669180323) + self.assertAlmostEqual(coordinates[1, 2], 1.4818772348457117) + self.assertAlmostEqual(coordinates[1, 3], 0.0) + self.assertAlmostEqual(coordinates[2, 0], 1.0686641862092987) + self.assertAlmostEqual(coordinates[2, 1], 1.9994412069101073) + self.assertAlmostEqual(coordinates[2, 2], -1.000720598980291) + self.assertAlmostEqual(coordinates[2, 3], 0.0) + self.assertAlmostEqual(coordinates[3, 0], -5.77916094504174) + self.assertAlmostEqual(coordinates[3, 1], -0.41269215032867046) + self.assertAlmostEqual(coordinates[3, 2], 0.085052691676038017) + self.assertAlmostEqual(coordinates[3, 3], 0.0) + self.assertAlmostEqual(pc[0, 0], -0.26379660005997291) + self.assertAlmostEqual(pc[0, 1], 0.064814972617134495) + self.assertAlmostEqual(pc[0, 2], -0.91763310094893846) + self.assertAlmostEqual(pc[0, 3], 0.26145408875373249) + self.assertAlmostEqual(pc[1, 0], 0.05073770520434398) + self.assertAlmostEqual(pc[1, 1], 0.68616983388698793) + self.assertAlmostEqual(pc[1, 2], 0.13819106187213354) + self.assertAlmostEqual(pc[1, 3], 0.19782544121828985) + self.assertAlmostEqual(pc[2, 0], -0.63000893660095947) + self.assertAlmostEqual(pc[2, 1], 0.091155993862151397) + self.assertAlmostEqual(pc[2, 2], 0.045630391256086845) + self.assertAlmostEqual(pc[2, 3], -0.67456694780914772) # As the last eigenvalue is zero, the corresponding eigenvector is # strongly affected by roundoff error, and is not being tested here. # For PCA, this doesn't matter since all data have a zero coefficient diff -Nru python-biopython-1.62/Tests/test_CodonTable.py python-biopython-1.63/Tests/test_CodonTable.py --- python-biopython-1.62/Tests/test_CodonTable.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_CodonTable.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,6 +3,8 @@ # license. Please see the LICENSE file that should have been included # as part of this package. +from __future__ import print_function + from Bio.Data import IUPACData from Bio.Data.CodonTable import ambiguous_generic_by_id, ambiguous_generic_by_name from Bio.Data.CodonTable import ambiguous_rna_by_id, ambiguous_dna_by_id @@ -10,15 +12,15 @@ from Bio.Data.CodonTable import list_ambiguous_codons, TranslationError #Check the extension of stop codons to include well defined ambiguous ones -assert list_ambiguous_codons(['TGA', 'TAA'],IUPACData.ambiguous_dna_values) == ['TGA', 'TAA', 'TRA'] -assert list_ambiguous_codons(['TAG', 'TGA'],IUPACData.ambiguous_dna_values) == ['TAG', 'TGA'] -assert list_ambiguous_codons(['TAG', 'TAA'],IUPACData.ambiguous_dna_values) == ['TAG', 'TAA', 'TAR'] -assert list_ambiguous_codons(['UAG', 'UAA'],IUPACData.ambiguous_rna_values) == ['UAG', 'UAA', 'UAR'] -assert list_ambiguous_codons(['TGA', 'TAA', 'TAG'],IUPACData.ambiguous_dna_values) == ['TGA', 'TAA', 'TAG', 'TAR', 'TRA'] +assert list_ambiguous_codons(['TGA', 'TAA'], IUPACData.ambiguous_dna_values) == ['TGA', 'TAA', 'TRA'] +assert list_ambiguous_codons(['TAG', 'TGA'], IUPACData.ambiguous_dna_values) == ['TAG', 'TGA'] +assert list_ambiguous_codons(['TAG', 'TAA'], IUPACData.ambiguous_dna_values) == ['TAG', 'TAA', 'TAR'] +assert list_ambiguous_codons(['UAG', 'UAA'], IUPACData.ambiguous_rna_values) == ['UAG', 'UAA', 'UAR'] +assert list_ambiguous_codons(['TGA', 'TAA', 'TAG'], IUPACData.ambiguous_dna_values) == ['TGA', 'TAA', 'TAG', 'TAR', 'TRA'] #Basic sanity test, -for n in ambiguous_generic_by_id.keys(): +for n in ambiguous_generic_by_id: assert ambiguous_rna_by_id[n].forward_table["GUU"] == "V" assert ambiguous_rna_by_id[n].forward_table["GUN"] == "V" if n != 23 : @@ -49,17 +51,17 @@ if "UAA" in unambiguous_rna_by_id[n].stop_codons \ and "UGA" in unambiguous_rna_by_id[n].stop_codons: try: - print ambiguous_dna_by_id[n].forward_table["TRA"] + print(ambiguous_dna_by_id[n].forward_table["TRA"]) assert False, "Should be a stop only" except KeyError: pass try: - print ambiguous_rna_by_id[n].forward_table["URA"] + print(ambiguous_rna_by_id[n].forward_table["URA"]) assert False, "Should be a stop only" except KeyError: pass try: - print ambiguous_generic_by_id[n].forward_table["URA"] + print(ambiguous_generic_by_id[n].forward_table["URA"]) assert False, "Should be a stop only" except KeyError: pass @@ -72,22 +74,22 @@ and "UAA" in unambiguous_rna_by_id[n].stop_codons \ and "UGA" in unambiguous_rna_by_id[n].stop_codons: try: - print ambiguous_dna_by_id[n].forward_table["TAR"] + print(ambiguous_dna_by_id[n].forward_table["TAR"]) assert False, "Should be a stop only" except KeyError: pass try: - print ambiguous_rna_by_id[n].forward_table["UAR"] + print(ambiguous_rna_by_id[n].forward_table["UAR"]) assert False, "Should be a stop only" except KeyError: pass try: - print ambiguous_generic_by_id[n].forward_table["UAR"] + print(ambiguous_generic_by_id[n].forward_table["UAR"]) assert False, "Should be a stop only" except KeyError: pass try: - print ambiguous_generic_by_id[n].forward_table["URR"] + print(ambiguous_generic_by_id[n].forward_table["URR"]) assert False, "Should be a stop OR an amino" except TranslationError: pass @@ -125,4 +127,4 @@ assert ambiguous_generic_by_id[4].stop_codons == ambiguous_generic_by_name["SGC3"].stop_codons assert ambiguous_generic_by_id[15].stop_codons == ambiguous_generic_by_name['Blepharisma Macronuclear'].stop_codons -print "Done" +print("Done") diff -Nru python-biopython-1.62/Tests/test_CodonUsage.py python-biopython-1.63/Tests/test_CodonUsage.py --- python-biopython-1.62/Tests/test_CodonUsage.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_CodonUsage.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,10 @@ +# Copyright 2003 by Iddo Friedberg. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. + +from __future__ import print_function + from Bio.SeqUtils import CodonUsage import os import sys @@ -10,14 +17,14 @@ elif os.path.exists("./Tests/CodonUsage/HighlyExpressedGenes.txt"): X.generate_index("./Tests/CodonUsage/HighlyExpressedGenes.txt") else: - print "Cannot find the file HighlyExpressedGene.txt\nMake sure you run the tests from within the Tests folder" + print("Cannot find the file HighlyExpressedGene.txt\nMake sure you run the tests from within the Tests folder") sys.exit() # alternatively you could use any predefined dictionary like this: # from CaiIndices import SharpIndex # you can save your dictionary in this file. # X.SetCaiIndex(SharpIndex) -print "The current index used:" +print("The current index used:") X.print_index() -print "-" * 60 -print "codon adaptation index for test gene: %.2f" % X.cai_for_gene("ATGAAACGCATTAGCACCACCATTACCACCACCATCACCATTACCACAGGTAACGGTGCGGGCTGA") +print("-" * 60) +print("codon adaptation index for test gene: %.2f" % X.cai_for_gene("ATGAAACGCATTAGCACCACCATTACCACCACCATCACCATTACCACAGGTAACGGTGCGGGCTGA")) diff -Nru python-biopython-1.62/Tests/test_ColorSpiral.py python-biopython-1.63/Tests/test_ColorSpiral.py --- python-biopython-1.62/Tests/test_ColorSpiral.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_ColorSpiral.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,114 +1,111 @@ -#!/usr/bin/env python -""" Tests for general functionality of the ColorSpiral utility -""" - -# Builtins -import colorsys -from math import pi -import os -import unittest - -try: - from cmath import rect -except ImportError: - #This was added in Python 2.6, fallback for Python 2.5: - from math import sin, cos - - def rect(r, phi): - return r * (cos(phi) + sin(phi)*1j) - -# Do we have ReportLab? Raise error if not present. -from Bio import MissingPythonDependencyError -try: - from reportlab.pdfgen.canvas import Canvas - from reportlab.lib.pagesizes import A4 -except ImportError: - raise MissingPythonDependencyError( - "Install reportlab if you want to use Bio.Graphics.") - - -# Biopython Bio.Graphics.ColorSpiral -from Bio.Graphics.ColorSpiral import ColorSpiral, get_colors, get_color_dict - - -class SpiralTest(unittest.TestCase): - """Construct and draw ColorSpiral colours placed on HSV spiral.""" - def setUp(self): - """Set up canvas for drawing""" - output_filename = os.path.join("Graphics","spiral_test.pdf") - self.c = Canvas(output_filename, pagesize=A4) - # co-ordinates of the centre of the canvas - self.x_0, self.y_0 = 0.5 * A4[0], 0.5 * A4[1] - - def test_colorlist(self): - """Get set of eight colours, no jitter, using ColorSpiral.""" - cs = ColorSpiral(a = 4, b = 0.33, jitter = 0) - colours = list(cs.get_colors(8)) - cstr = ["(%.2f, %.2f, %.2f)" % (r, g, b) - for r, g, b in colours] - expected = \ - ['(0.64, 0.74, 0.81)', '(0.68, 0.52, 0.76)', '(0.72, 0.41, 0.55)', - '(0.68, 0.39, 0.31)', '(0.63, 0.54, 0.22)', '(0.48, 0.59, 0.13)', - '(0.24, 0.54, 0.06)', '(0.01, 0.50, -0.00)'] - self.assertEqual(cstr, expected) - - def test_colorspiral(self): - """Get set of 16 colours, no jitter, using ColorSpiral.""" - cs = ColorSpiral(a = 4, b = 0.33, jitter = 0) - radius = A4[0] * 0.025 - for r, g, b in cs.get_colors(16): - self.c.setFillColor((r, g, b)) - # Convert HSV colour to rectangular coordinates on HSV disc - h, s, v = colorsys.rgb_to_hsv(r, g, b) - coords = rect(s * A4[0] * 0.45, h * 2 * pi) - x, y = self.x_0 + coords.real, self.y_0 + coords.imag - self.c.ellipse(x - radius, y - radius, x + radius, y + radius, - stroke = 0, fill = 1) - self.finish() - - def finish(self): - """Clean up and save image.""" - self.c.save() - - -class SquareTest(unittest.TestCase): - """Construct and draw ColorSpiral colours placed in a square, with jitter.""" - def setUp(self): - """Set up canvas for drawing""" - output_filename = os.path.join("Graphics","square_test.pdf") - self.c = Canvas(output_filename, pagesize=(500, 500)) - - def test_colorspiral(self): - """Set of 625 colours, with jitter, using get_colors().""" - boxedge = 20 - boxes_per_row = 25 - rows = 0 - for i, c in enumerate(get_colors(625)): - self.c.setFillColor(c) - x1 = boxedge * (i % boxes_per_row) - y1 = rows * boxedge - self.c.rect(x1, y1, boxedge, boxedge, fill = 1, stroke = 0) - if not (i+1) % boxes_per_row: - rows += 1 - self.finish() - - def finish(self): - """Clean up and save image.""" - self.c.save() - - -class DictTest(unittest.TestCase): - """Generate set of colours on the basis of an iterable.""" - def test_dict(self): - """get_color_dict() for classes A-D, no jitter.""" - classes = ['A', 'B', 'C', 'D'] - colors = get_color_dict(classes, jitter=0) - cstr = ["%s: (%.2f, %.2f, %.2f)" % (c, r, g, b) - for c, (r, g, b) in colors.items()] - expected = ['A: (0.52, 0.76, 0.69)', 'C: (0.59, 0.13, 0.47)', - 'B: (0.40, 0.31, 0.68)', 'D: (0.50, 0.00, 0.00)'] - self.assertEqual(cstr, expected) - -if __name__ == "__main__": - runner = unittest.TextTestRunner(verbosity = 2) - unittest.main(testRunner = runner) +#!/usr/bin/env python +# Copyright 2013 by Leighton Pritchard. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. + +""" Tests for general functionality of the ColorSpiral utility +""" + +# Builtins +import colorsys +from math import pi +import os +import unittest +from cmath import rect + +# Do we have ReportLab? Raise error if not present. +from Bio import MissingPythonDependencyError +try: + from reportlab.pdfgen.canvas import Canvas + from reportlab.lib.pagesizes import A4 +except ImportError: + raise MissingPythonDependencyError( + "Install reportlab if you want to use Bio.Graphics.") + + +# Biopython Bio.Graphics.ColorSpiral +from Bio.Graphics.ColorSpiral import ColorSpiral, get_colors, get_color_dict + + +class SpiralTest(unittest.TestCase): + """Construct and draw ColorSpiral colours placed on HSV spiral.""" + def setUp(self): + """Set up canvas for drawing""" + output_filename = os.path.join("Graphics", "spiral_test.pdf") + self.c = Canvas(output_filename, pagesize=A4) + # co-ordinates of the centre of the canvas + self.x_0, self.y_0 = 0.5 * A4[0], 0.5 * A4[1] + + def test_colorlist(self): + """Get set of eight colours, no jitter, using ColorSpiral.""" + cs = ColorSpiral(a = 4, b = 0.33, jitter = 0) + colours = list(cs.get_colors(8)) + cstr = ["(%.2f, %.2f, %.2f)" % (r, g, b) + for r, g, b in colours] + expected = \ + ['(0.64, 0.74, 0.81)', '(0.68, 0.52, 0.76)', '(0.72, 0.41, 0.55)', + '(0.68, 0.39, 0.31)', '(0.63, 0.54, 0.22)', '(0.48, 0.59, 0.13)', + '(0.24, 0.54, 0.06)', '(0.01, 0.50, -0.00)'] + self.assertEqual(cstr, expected) + + def test_colorspiral(self): + """Get set of 16 colours, no jitter, using ColorSpiral.""" + cs = ColorSpiral(a = 4, b = 0.33, jitter = 0) + radius = A4[0] * 0.025 + for r, g, b in cs.get_colors(16): + self.c.setFillColor((r, g, b)) + # Convert HSV colour to rectangular coordinates on HSV disc + h, s, v = colorsys.rgb_to_hsv(r, g, b) + coords = rect(s * A4[0] * 0.45, h * 2 * pi) + x, y = self.x_0 + coords.real, self.y_0 + coords.imag + self.c.ellipse(x - radius, y - radius, x + radius, y + radius, + stroke = 0, fill = 1) + self.finish() + + def finish(self): + """Clean up and save image.""" + self.c.save() + + +class SquareTest(unittest.TestCase): + """Construct and draw ColorSpiral colours placed in a square, with jitter.""" + def setUp(self): + """Set up canvas for drawing""" + output_filename = os.path.join("Graphics", "square_test.pdf") + self.c = Canvas(output_filename, pagesize=(500, 500)) + + def test_colorspiral(self): + """Set of 625 colours, with jitter, using get_colors().""" + boxedge = 20 + boxes_per_row = 25 + rows = 0 + for i, c in enumerate(get_colors(625)): + self.c.setFillColor(c) + x1 = boxedge * (i % boxes_per_row) + y1 = rows * boxedge + self.c.rect(x1, y1, boxedge, boxedge, fill = 1, stroke = 0) + if not (i+1) % boxes_per_row: + rows += 1 + self.finish() + + def finish(self): + """Clean up and save image.""" + self.c.save() + + +class DictTest(unittest.TestCase): + """Generate set of colours on the basis of an iterable.""" + def test_dict(self): + """get_color_dict() for classes A-D, no jitter.""" + classes = ['A', 'B', 'C', 'D'] + colors = get_color_dict(classes, jitter=0) + cstr = ["%s: (%.2f, %.2f, %.2f)" % (c, r, g, b) + for c, (r, g, b) in colors.items()] + expected = ['A: (0.52, 0.76, 0.69)', 'C: (0.59, 0.13, 0.47)', + 'B: (0.40, 0.31, 0.68)', 'D: (0.50, 0.00, 0.00)'] + self.assertEqual(cstr, expected) + +if __name__ == "__main__": + runner = unittest.TextTestRunner(verbosity = 2) + unittest.main(testRunner = runner) diff -Nru python-biopython-1.62/Tests/test_Compass.py python-biopython-1.63/Tests/test_Compass.py --- python-biopython-1.62/Tests/test_Compass.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_Compass.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# Copyright 2009 by James Casbon. All rights reserved. +# Revisions copyright 2009-2010 by Michiel de Hoon. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. """Tests for parsing Compass output. """ import os @@ -46,24 +51,24 @@ def testCompassIteratorEasy(self): handle = open(self.test_files[0]) records = Compass.parse(handle) - com_record = records.next() + com_record = next(records) self.assertEqual("60456.blo.gz.aln", com_record.query) - self.assertRaises(StopIteration, records.next) + self.assertRaises(StopIteration, next, records) handle.close() def testCompassIteratorHard(self): handle = open(self.test_files[1]) records = Compass.parse(handle) - com_record = records.next() + com_record = next(records) self.assertEqual("allscop//14982.blo.gz.aln", com_record.hit) self.assertEqual(float('1.01e+03'), com_record.evalue) - com_record = records.next() + com_record = next(records) self.assertEqual("allscop//14983.blo.gz.aln", com_record.hit) self.assertEqual(float('1.01e+03'), com_record.evalue) - com_record = records.next() + com_record = next(records) self.assertEqual("allscop//14984.blo.gz.aln", com_record.hit) self.assertEqual(float('5.75e+02'), com_record.evalue) @@ -73,15 +78,15 @@ handle = open(self.test_files[1]) records = Compass.parse(handle) - com_record = records.next() + com_record = next(records) self.assertEqual(178, com_record.query_start) self.assertEqual("KKDLEEIAD", com_record.query_aln) self.assertEqual(9, com_record.hit_start) self.assertEqual("QAAVQAVTA", com_record.hit_aln) self.assertEqual("++ ++++++", com_record.positives) - com_record = records.next() - com_record = records.next() + com_record = next(records) + com_record = next(records) self.assertEqual(371, com_record.query_start) self.assertEqual("LEEAMDRMER~~~V", com_record.query_aln) self.assertEqual(76, com_record.hit_start) @@ -93,7 +98,7 @@ def testAlignmentParsingTwo(self): handle = open(self.test_files[0]) records = Compass.parse(handle) - com_record = records.next() + com_record = next(records) self.assertEqual(2, com_record.query_start) self.assertEqual(2, com_record.hit_start) self.assertEqual("LKERKL", com_record.hit_aln[-6:]) diff -Nru python-biopython-1.62/Tests/test_Crystal.py python-biopython-1.63/Tests/test_Crystal.py --- python-biopython-1.62/Tests/test_Crystal.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_Crystal.py 2013-12-05 14:10:43.000000000 +0000 @@ -452,16 +452,20 @@ self.assertEqual(len(target.data), 0) def testKeys(self): - self.assertEqual(self.crystal.keys(), self.crystal.data.keys()) + self.assertEqual(list(self.crystal.keys()), + list(self.crystal.data.keys())) def testValues(self): - self.assertEqual(self.crystal.values(), self.crystal.data.values()) + self.assertEqual(list(self.crystal.values()), + list(self.crystal.data.values())) def testItems(self): - self.assertEqual(self.crystal.items(), self.crystal.data.items()) + self.assertEqual(list(self.crystal.items()), + list(self.crystal.data.items())) def testKeys(self): - self.assertEqual(self.crystal.keys(), self.crystal.data.keys()) + self.assertEqual(list(self.crystal.keys()), + list(self.crystal.data.keys())) def testHasKey(self): self.assertTrue('b' in self.crystal) diff -Nru python-biopython-1.62/Tests/test_Dialign_tool.py python-biopython-1.63/Tests/test_Dialign_tool.py --- python-biopython-1.62/Tests/test_Dialign_tool.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_Dialign_tool.py 2013-12-05 14:10:43.000000000 +0000 @@ -18,8 +18,8 @@ if sys.platform=="win32": raise MissingExternalDependencyError("DIALIGN2-2 not available on Windows") else: - import commands - output = commands.getoutput("dialign2-2") + from Bio._py3k import getoutput + output = getoutput("dialign2-2") if "not found" not in output and "dialign2-2" in output.lower(): dialign_exe = "dialign2-2" if "DIALIGN2_DIR" not in os.environ: diff -Nru python-biopython-1.62/Tests/test_DocSQL.py python-biopython-1.63/Tests/test_DocSQL.py --- python-biopython-1.62/Tests/test_DocSQL.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_DocSQL.py 2013-12-05 14:10:43.000000000 +0000 @@ -2,9 +2,11 @@ """Test the Bio.DocSQL module """ +from __future__ import print_function + import Bio.DocSQL -print "Skipping Bio.DocSQL doctests." -#print "Running Bio.DocSQL doctests..." +print("Skipping Bio.DocSQL doctests.") +#print("Running Bio.DocSQL doctests...") #Bio.DocSQL._test() -#print "Bio.DocSQL doctests complete." +#print("Bio.DocSQL doctests complete.") diff -Nru python-biopython-1.62/Tests/test_Emboss.py python-biopython-1.63/Tests/test_Emboss.py --- python-biopython-1.62/Tests/test_Emboss.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_Emboss.py 2013-12-05 14:10:43.000000000 +0000 @@ -8,7 +8,7 @@ import sys import unittest import subprocess -from StringIO import StringIO +from Bio._py3k import StringIO from Bio.Emboss.Applications import WaterCommandline, NeedleCommandline from Bio.Emboss.Applications import SeqretCommandline, SeqmatchallCommandline @@ -44,10 +44,10 @@ "$EMBOSS_ROOT=%r which does not exist!" % path) del path if sys.platform!="win32": - import commands + from Bio._py3k import getoutput for name in exes_wanted: #This will "just work" if installed on the path as normal on Unix - output = commands.getoutput("%s -help" % name) + output = getoutput("%s -help" % name) if "not found" not in output and "not recognized" not in output: exes[name] = name del output @@ -94,7 +94,7 @@ #To avoid confusing known errors from old versions of EMBOSS ... emboss_version = get_emboss_version() -if emboss_version < (6,1,0): +if emboss_version < (6, 1, 0): raise MissingExternalDependencyError( "Test requires EMBOSS 6.1.0 patch 3 or later.") @@ -170,7 +170,7 @@ shell=(sys.platform!="win32")) try: AlignIO.write(alignments, child.stdin, old_format) - except Exception, err: + except Exception as err: child.stdin.close() child.stderr.close() child.stdout.close() @@ -181,7 +181,7 @@ #automatically close the handle? try: aligns = list(AlignIO.parse(child.stdout, new_format)) - except Exception, err: + except Exception as err: child.stdout.close() raise child.stdout.close() @@ -198,13 +198,13 @@ #no spaces in PHYLIP files. if old.id != new.id and old.name != new.name \ and (old.id not in new.id) and (new.id not in old.id) \ - and (old.id.replace(" ","_") != new.id.replace(" ","_")): + and (old.id.replace(" ", "_") != new.id.replace(" ", "_")): raise ValueError("'%s' or '%s' vs '%s' or '%s' records" % (old.id, old.name, new.id, new.name)) if len(old.seq) != len(new.seq): raise ValueError("%i vs %i" % (len(old.seq), len(new.seq))) if str(old.seq).upper() != str(new.seq).upper(): - if str(old.seq).replace("X","N")==str(new.seq) : + if str(old.seq).replace("X", "N")==str(new.seq) : raise ValueError("X -> N (protein forced into nucleotide?)") if len(old.seq) < 200: raise ValueError("'%s' vs '%s'" % (old.seq, new.seq)) @@ -229,7 +229,7 @@ if len(old) != len(new): raise ValueError("Alignment with %i vs %i records" % (len(old), len(new))) - compare_records(old,new) + compare_records(old, new) return True @@ -246,13 +246,13 @@ records = list(SeqIO.parse(in_filename, in_format, alphabet)) else: records = list(SeqIO.parse(in_filename, in_format)) - for temp_format in ["genbank","embl","fasta"]: + for temp_format in ["genbank", "embl", "fasta"]: if temp_format in skip_formats: continue new_records = list(emboss_piped_SeqIO_convert(records, temp_format, "fasta")) try: self.assertTrue(compare_records(records, new_records)) - except ValueError, err: + except ValueError as err: raise ValueError("Disagree on file %s %s in %s format: %s" % (in_format, in_filename, temp_format, err)) @@ -262,7 +262,7 @@ #TODO: Why can't we read EMBOSS's swiss output? self.assertTrue(os.path.isfile(filename)) old_records = list(SeqIO.parse(filename, old_format)) - for new_format in ["genbank","fasta","pir","embl", "ig"]: + for new_format in ["genbank", "fasta", "pir", "embl", "ig"]: if new_format in skip_formats: continue handle = emboss_convert(filename, old_format, new_format) @@ -270,7 +270,7 @@ handle.close() try: self.assertTrue(compare_records(old_records, new_records)) - except ValueError, err: + except ValueError as err: raise ValueError("Disagree on %s file %s in %s format: %s" % (old_format, filename, new_format, err)) @@ -290,13 +290,13 @@ handle = emboss_convert(filename, "abi", "fastq-sanger") new = SeqIO.read(handle, "fastq-sanger") handle.close() - if emboss_version == (6,4,0) and new.id == "EMBOSS_001": + if emboss_version == (6, 4, 0) and new.id == "EMBOSS_001": #Avoid bug in EMBOSS 6.4.0 (patch forthcoming) pass else: self.assertEqual(old.id, new.id) self.assertEqual(str(old.seq), str(new.seq)) - if emboss_version < (6,3,0) and new.letter_annotations["phred_quality"] == [1]*len(old): + if emboss_version < (6, 3, 0) and new.letter_annotations["phred_quality"] == [1]*len(old): #Apparent bug in EMBOSS 6.2.0.1 on Windows pass else: @@ -320,7 +320,7 @@ #and will turn "X" into "N" for GenBank output. self.check_SeqIO_to_EMBOSS("IntelliGenetics/VIF_mase-pro.txt", "ig", alphabet=generic_protein, - skip_formats=["genbank","embl"]) + skip_formats=["genbank", "embl"]) #TODO - What does a % in an ig sequence mean? #e.g. "IntelliGenetics/vpu_nucaligned.txt" #and "IntelliGenetics/TAT_mase_nuc.txt" @@ -334,14 +334,14 @@ #Skip EMBL here, EMBOSS mangles the ID line #Skip GenBank, EMBOSS 6.0.1 on Windows won't output proteins as GenBank self.check_SeqIO_with_EMBOSS("NBRF/DMB_prot.pir", "pir", - skip_formats=["embl","genbank"]) + skip_formats=["embl", "genbank"]) def test_clustalw(self): """SeqIO & EMBOSS reading each other's conversions of a Clustalw file.""" self.check_SeqIO_with_EMBOSS("Clustalw/hedgehog.aln", "clustal", - skip_formats=["embl","genbank"]) + skip_formats=["embl", "genbank"]) self.check_SeqIO_with_EMBOSS("Clustalw/opuntia.aln", "clustal", - skip_formats=["embl","genbank"]) + skip_formats=["embl", "genbank"]) class SeqRetAlignIOTests(unittest.TestCase): @@ -357,7 +357,7 @@ old_aligns = list(AlignIO.parse(filename, old_format)) formats = ["clustal", "phylip", "ig"] if len(old_aligns) == 1: - formats.extend(["fasta","nexus"]) + formats.extend(["fasta", "nexus"]) for new_format in formats: if new_format in skip_formats: continue @@ -371,7 +371,7 @@ handle.close() try: self.assertTrue(compare_alignments(old_aligns, new_aligns)) - except ValueError, err: + except ValueError as err: raise ValueError("Disagree on %s file %s in %s format: %s" % (old_format, filename, new_format, err)) @@ -379,13 +379,13 @@ alphabet=None): """Can Bio.AlignIO write files seqret can read back?""" if alphabet: - old_aligns = list(AlignIO.parse(in_filename,in_format,alphabet)) + old_aligns = list(AlignIO.parse(in_filename, in_format, alphabet)) else: - old_aligns = list(AlignIO.parse(in_filename,in_format)) + old_aligns = list(AlignIO.parse(in_filename, in_format)) formats = ["clustal", "phylip"] if len(old_aligns) == 1: - formats.extend(["fasta","nexus"]) + formats.extend(["fasta", "nexus"]) for temp_format in formats: if temp_format in skip_formats: continue @@ -395,13 +395,13 @@ new_aligns = list(emboss_piped_AlignIO_convert(old_aligns, temp_format, "phylip")) - except ValueError, e: + except ValueError as e: #e.g. ValueError: Need a DNA, RNA or Protein alphabet #from writing Nexus files... continue try: self.assertTrue(compare_alignments(old_aligns, new_aligns)) - except ValueError, err: + except ValueError as err: raise ValueError("Disagree on file %s %s in %s format: %s" % (in_format, in_filename, temp_format, err)) @@ -453,18 +453,18 @@ if alignment[1].id not in target.id \ and alignment[1].id not in target.name: raise AssertionError("%s vs %s or %s" - % (alignment[1].id , target.id, target.name)) + % (alignment[1].id, target.id, target.name)) if local: #Local alignment - self.assertTrue(str(alignment[0].seq).replace("-","") + self.assertTrue(str(alignment[0].seq).replace("-", "") in query_seq) - self.assertTrue(str(alignment[1].seq).replace("-","").upper() + self.assertTrue(str(alignment[1].seq).replace("-", "").upper() in str(target.seq).upper()) else: #Global alignment - self.assertEqual(str(query_seq), str(alignment[0].seq).replace("-","")) + self.assertEqual(str(query_seq), str(alignment[0].seq).replace("-", "")) self.assertEqual(str(target.seq).upper(), - str(alignment[1].seq).replace("-","").upper()) + str(alignment[1].seq).replace("-", "").upper()) return True def run_water(self, cline): @@ -494,7 +494,7 @@ #Run the tool, self.run_water(cline) #Check we can parse the output... - align = AlignIO.read(cline.outfile,"emboss") + align = AlignIO.read(cline.outfile, "emboss") self.assertEqual(len(align), 2) self.assertEqual(str(align[0].seq), "ACCCGGGCGCGGT") self.assertEqual(str(align[1].seq), "ACCCGAGCGCGGT") @@ -554,7 +554,7 @@ self.assertTrue(os.path.isfile(filename), "Missing output file %r from:\n%s" % (filename, cline)) #Check we can parse the output... - align = AlignIO.read(filename,"emboss") + align = AlignIO.read(filename, "emboss") self.assertEqual(len(align), 2) self.assertEqual(str(align[0].seq), "ACCCGGGCGCGGT") self.assertEqual(str(align[1].seq), "ACCCGAGCGCGGT") @@ -613,8 +613,8 @@ self.run_water(cline) #Check we can parse the output and it is sensible... self.pairwise_alignment_check(query, - SeqIO.parse(in_file,"fasta"), - AlignIO.parse(out_file,"emboss"), + SeqIO.parse(in_file, "fasta"), + AlignIO.parse(out_file, "emboss"), local=True) #Clean up, os.remove(out_file) @@ -640,8 +640,8 @@ self.run_water(cline) #Check we can parse the output and it is sensible... self.pairwise_alignment_check(query, - SeqIO.parse(in_file,"genbank"), - AlignIO.parse(out_file,"emboss"), + SeqIO.parse(in_file, "genbank"), + AlignIO.parse(out_file, "emboss"), local=True) #Clean up, os.remove(out_file) @@ -669,8 +669,8 @@ self.run_water(cline) #Check we can parse the output and it is sensible... self.pairwise_alignment_check(query, - SeqIO.parse(in_file,"swiss"), - AlignIO.parse(out_file,"emboss"), + SeqIO.parse(in_file, "swiss"), + AlignIO.parse(out_file, "emboss"), local=True) #Clean up, os.remove(out_file) @@ -696,8 +696,8 @@ child.stdin.close() #Check we can parse the output and it is sensible... self.pairwise_alignment_check(query, - SeqIO.parse("Fasta/f002","fasta"), - AlignIO.parse(child.stdout,"emboss"), + SeqIO.parse("Fasta/f002", "fasta"), + AlignIO.parse(child.stdout, "emboss"), local=False) #Check no error output: self.assertEqual(child.stderr.read(), "") @@ -825,8 +825,8 @@ else: t = table if translation != str(sequence.translate(t)) \ - or translation != str(translate(sequence,t)) \ - or translation != translate(str(sequence),t): + or translation != str(translate(sequence, t)) \ + or translation != translate(str(sequence), t): #More details... for i, amino in enumerate(translation): codon = sequence[i*3:i*3+3] @@ -887,16 +887,16 @@ translation = emboss_translate(sequence) self.assertTrue(check_translation(sequence, translation)) - for table in [1,2,3,4,5,6,9,10,11,12,13,14,15,16,21,22,23]: + for table in [1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14, 15, 16, 21, 22, 23]: translation = emboss_translate(sequence, table) self.assertTrue(check_translation(sequence, translation, table)) return True def translate_all_codons(self, letters): - sequence = Seq("".join([c1+c3+c3 - for c1 in letters - for c2 in letters - for c3 in letters]), + sequence = Seq("".join(c1+c3+c3 + for c1 in letters + for c2 in letters + for c3 in letters), generic_nucleotide) self.check(sequence) diff -Nru python-biopython-1.62/Tests/test_EmbossPhylipNew.py python-biopython-1.63/Tests/test_EmbossPhylipNew.py --- python-biopython-1.62/Tests/test_EmbossPhylipNew.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_EmbossPhylipNew.py 2013-12-05 14:10:43.000000000 +0000 @@ -19,7 +19,7 @@ #Try to avoid problems when the OS is in another language os.environ['LANG'] = 'C' -exes_wanted = ['fdnadist', 'fneighbor', 'fprotdist','fprotpars','fconsense', +exes_wanted = ['fdnadist', 'fneighbor', 'fprotdist', 'fprotpars', 'fconsense', 'fseqboot', 'ftreedist', 'fdnapars'] exes = dict() # Dictionary mapping from names to exe locations @@ -33,10 +33,10 @@ exes[name] = os.path.join(path, name+".exe") del path, name if sys.platform!="win32": - import commands + from Bio._py3k import getoutput for name in exes_wanted: #This will "just work" if installed on the path as normal on Unix - output = commands.getoutput("%s -help" % name) + output = getoutput("%s -help" % name) if "not found" not in output and "not recognized" not in output: exes[name] = name del output @@ -65,7 +65,7 @@ def clean_up(): """Delete tests files (to be used as tearDown() function in test fixtures)""" - for filename in ["test_file", "Phylip/opuntia.phy","Phylip/hedgehog.phy"]: + for filename in ["test_file", "Phylip/opuntia.phy", "Phylip/hedgehog.phy"]: if os.path.isfile(filename): os.remove(filename) @@ -178,7 +178,7 @@ auto= True, stdout=True) stdout, stderr = cline() a_taxa = [s.name.replace(" ", "_") for s in - AlignIO.parse(open(filename, "r"), format).next()] + next(AlignIO.parse(open(filename, "r"), format))] for tree in parse_trees("test_file"): t_taxa = [t.replace(" ", "_") for t in tree.get_taxa()] self.assertEqual(sorted(a_taxa), sorted(t_taxa)) @@ -275,11 +275,11 @@ auto = True, filter = True) stdout, stderr = cline() #Split the next and get_taxa into two steps to help 2to3 work - tree1 = parse_trees("test_file").next() + tree1 = next(parse_trees("test_file")) taxa1 = tree1.get_taxa() for tree in parse_trees("Phylip/horses.tree"): taxa2 = tree.get_taxa() - self.assertEqual(sorted(taxa1),sorted(taxa2)) + self.assertEqual(sorted(taxa1), sorted(taxa2)) def test_ftreedist(self): """Calculate the distance between trees with ftreedist""" diff -Nru python-biopython-1.62/Tests/test_EmbossPrimer.py python-biopython-1.63/Tests/test_EmbossPrimer.py --- python-biopython-1.62/Tests/test_EmbossPrimer.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_EmbossPrimer.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,4 +1,11 @@ #!/usr/bin/env python +# Copyright 2001 by Brad Chapman. All rights reserved. +# Revisions copyright 2008-2009 by Michiel de Hoon. All rights reserved. +# Revisions copyright 2010-2011 by Peter Cock. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. + """Tests for Primer-based programs in the Emboss suite. """ # standard library diff -Nru python-biopython-1.62/Tests/test_Entrez.py python-biopython-1.63/Tests/test_Entrez.py --- python-biopython-1.62/Tests/test_Entrez.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_Entrez.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# Copyright 2008-2010 by Michiel de Hoon. All rights reserved. +# Revisions copyright 2009-2013 by Peter Cock. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. '''Testing code for Bio.Entrez parsers. ''' @@ -4735,7 +4740,7 @@ handle.close() handle = open('GenBank/NT_019265.gb', "rb") iterator = Entrez.parse(handle) - self.assertRaises(Parser.NotXMLError, iterator.next) + self.assertRaises(Parser.NotXMLError, next, iterator) handle.close() def test_fasta(self): @@ -4747,7 +4752,7 @@ handle.close() handle = open('Fasta/wisteria.nu', "rb") iterator = Entrez.parse(handle) - self.assertRaises(Parser.NotXMLError, iterator.next) + self.assertRaises(Parser.NotXMLError, next, iterator) handle.close() def test_pubmed_html(self): @@ -4762,7 +4767,7 @@ # Test if the error is also raised with Entrez.parse handle = open('Entrez/pubmed3.html', "rb") records = Entrez.parse(handle) - self.assertRaises(Parser.NotXMLError, records.next) + self.assertRaises(Parser.NotXMLError, next, records) handle.close() def test_xml_without_declaration(self): @@ -4777,7 +4782,7 @@ # Test if the error is also raised with Entrez.parse handle = open('Entrez/journals.xml', "rb") records = Entrez.parse(handle) - self.assertRaises(Parser.NotXMLError, records.next) + self.assertRaises(Parser.NotXMLError, next, records) handle.close() diff -Nru python-biopython-1.62/Tests/test_FSSP.py python-biopython-1.63/Tests/test_FSSP.py --- python-biopython-1.62/Tests/test_FSSP.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_FSSP.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,8 +1,13 @@ +# Copyright 2001 by Iddo Friedberg. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. + from Bio import FSSP from Bio.FSSP import FSSPTools import sys import os -import cPickle +#import pickle test_file = os.path.join('FSSP', '1cnv.fssp') f = sys.stdout @@ -13,7 +18,7 @@ f.write("...1cnv.fssp read\n") for i in ["author", "compnd", "database", "header", "nalign", "pdbid", "seqlength", "source"]: - f.write('head_rec.%s %s\n' % (i, str(getattr(head_rec,i)))) + f.write('head_rec.%s %s\n' % (i, str(getattr(head_rec, i)))) f.write("\nlen(sum_rec) = %d; head_rec.nalign = %d\n" % (len(sum_rec), head_rec.nalign)) f.write("The above two numbers should be the same\n") @@ -26,27 +31,21 @@ # sum_ge_15, align_ge_15 = FSSPTools.filter(sum_rec, align_rec, 'pID', 15,100) # f.write("\nnumber of records filtered in: %d\n" % len(sum_ge_15)) -# k = sum_ge_15.keys() -# k.sort() +# k = sorted(sum_ge_15) # f.write("\nRecords filtered in %s\n" % k) # Pickling takes too long.. remove from test. # f.write("\nLet's Pickle this\n") # dump_file = os.path.join('FSSP', 'mydump.pik') -# cPickle.dump((head_rec, sum_rec, align_rec),open(dump_file, 'w')) +# pickle.dump((head_rec, sum_rec, align_rec),open(dump_file, 'w')) f.write("\nFilter by name\n") name_list = ['2hvm0', '1hvq0', '1nar0', '2ebn0'] f.write("\nname list %s\n" % str(name_list)) sum_newnames, align_newnames = FSSPTools.name_filter(sum_rec, align_rec, name_list) - -ks = sum_newnames.keys() -ks.sort() -for key in ks: +for key in sorted(sum_newnames): f.write("%s : %s\n" % (key, sum_newnames[key])) -dict = align_newnames['0P168'].pos_align_dict -ks = dict.keys() -ks.sort() -for key in ks: - f.write("%s : %s\n" % (key, dict[key])) +new_dict = align_newnames['0P168'].pos_align_dict +for key in sorted(new_dict): + f.write("%s : %s\n" % (key, new_dict[key])) diff -Nru python-biopython-1.62/Tests/test_Fasttree_tool.py python-biopython-1.63/Tests/test_Fasttree_tool.py --- python-biopython-1.62/Tests/test_Fasttree_tool.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_Fasttree_tool.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,15 +1,20 @@ -# Copyright 2013 by Nate Sutton. Based on test_Clustalw_tool.py by -# Peter Cock. Example code used from Biopython's Phylo cookbook by -# Eric Talevich. All rights reserved. This code is part of the -# Biopython distribution and governed by its license. Please see -# the LICENSE file that should have been included as part of this package. +# Copyright 2013 by Nate Sutton. All rights reserved. +# Based on test_Clustalw_tool.py by Peter Cock. +# Example code used from Biopython's Phylo cookbook by Eric Talevich. +# +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. + +from __future__ import print_function from Bio import MissingExternalDependencyError import sys import os import itertools -from StringIO import StringIO +from Bio._py3k import StringIO +from Bio._py3k import zip from Bio import SeqIO from Bio import Phylo @@ -45,9 +50,9 @@ if fasttree_exe: break else: - import commands + from Bio._py3k import getoutput # Checking the -help argument - output = commands.getoutput("fasttree -help") + output = getoutput("fasttree -help") # Since "is not recognized" may be in another language, try and be sure this # is really the fasttree tool's output fasttree_found = False @@ -62,50 +67,50 @@ ################################################################# -print "Checking error conditions" -print "=========================" +print("Checking error conditions") +print("=========================") -print "Empty file" +print("Empty file") input_file = "does_not_exist.fasta" assert not os.path.isfile(input_file) cline = FastTreeCommandline(fasttree_exe, input=input_file) try: stdout, stderr = cline() assert False, "Should have failed, returned:\n%s\n%s" % (stdout, stderr) -except ApplicationError, err: - print "Failed (good)" +except ApplicationError as err: + print("Failed (good)") #Python 2.3 on Windows gave (0, 'Error') #Python 2.5 on Windows gives [Errno 0] Error assert "Cannot open sequence file" in str(err) or \ "Cannot open input file" in str(err) or \ "non-zero exit status" in str(err), str(err) -print -print "Single sequence" +print("") +print("Single sequence") input_file = "Fasta/f001" assert os.path.isfile(input_file) -assert len(list(SeqIO.parse(input_file,"fasta")))==1 +assert len(list(SeqIO.parse(input_file, "fasta")))==1 cline = FastTreeCommandline(fasttree_exe, input=input_file) try: stdout, stderr = cline() if "Unique: 1/1" in stderr: - print "Failed (good)" + print("Failed (good)") else: assert False, "Should have failed, returned:\n%s\n%s" % (stdout, stderr) -except ApplicationError, err: - print "Failed (good)" +except ApplicationError as err: + print("Failed (good)") #assert str(err) == "No records found in handle", str(err) -print -print "Invalid sequence" +print("") +print("Invalid sequence") input_file = "Medline/pubmed_result1.txt" assert os.path.isfile(input_file) cline = FastTreeCommandline(fasttree_exe, input=input_file) try: stdout, stderr = cline() assert False, "Should have failed, returned:\n%s\n%s" % (stdout, stderr) -except ApplicationError, err: - print "Failed (good)" +except ApplicationError as err: + print("Failed (good)") #Ideally we'd catch the return code and raise the specific #error for "invalid format", rather than just notice there #is not output file. @@ -118,21 +123,21 @@ or "non-zero exit status " in str(err), str(err) ################################################################# -print -print "Checking normal situations" -print "==========================" +print("") +print("Checking normal situations") +print("==========================") #Create a temp fasta file with a space in the name temp_filename_with_spaces = "Clustalw/temp horses.fasta" handle = open(temp_filename_with_spaces, "w") -SeqIO.write(SeqIO.parse("Phylip/hennigian.phy","phylip"), handle, "fasta") +SeqIO.write(SeqIO.parse("Phylip/hennigian.phy", "phylip"), handle, "fasta") handle.close() for input_file in ["Quality/example.fasta", "Clustalw/temp horses.fasta"]: - input_records = SeqIO.to_dict(SeqIO.parse(input_file,"fasta")) - print - print "Calling fasttree on %s (with %i records)" \ - % (repr(input_file), len(input_records)) + input_records = SeqIO.to_dict(SeqIO.parse(input_file, "fasta")) + print("") + print("Calling fasttree on %s (with %i records)" \ + % (repr(input_file), len(input_records))) #Any filesnames with spaces should get escaped with quotes automatically. #Using keyword arguments here. @@ -142,8 +147,8 @@ out, err = cline() assert err.strip().startswith("FastTree") - print - print "Checking generation of tree terminals" + print("") + print("Checking generation of tree terminals") tree = Phylo.read(StringIO(out), 'newick') def lookup_by_names(tree): @@ -158,23 +163,23 @@ names = lookup_by_names(tree) assert len(names) > 0.0 - print "Success" + print("Success") - print - print "Checking distances between tree terminals" + print("") + print("Checking distances between tree terminals") def terminal_neighbor_dists(self): """Return a list of distances between adjacent terminals.""" def generate_pairs(self): pairs = itertools.tee(self) - pairs[1].next() - return itertools.izip(pairs[0], pairs[1]) + next(pairs[1]) # Advance second iterator one step + return zip(pairs[0], pairs[1]) return [self.distance(*i) for i in generate_pairs(self.find_clades(terminal=True))] for dist in terminal_neighbor_dists(tree): assert dist > 0.0 - print "Success" + print("Success") -print -print "Done" +print("") +print("Done") diff -Nru python-biopython-1.62/Tests/test_File.py python-biopython-1.63/Tests/test_File.py --- python-biopython-1.62/Tests/test_File.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_File.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,12 +3,12 @@ # license. Please see the LICENSE file that should have been included # as part of this package. -from __future__ import with_statement +from __future__ import print_function import os.path import unittest import shutil -from StringIO import StringIO +from Bio._py3k import StringIO import tempfile from Bio import File @@ -24,33 +24,33 @@ h = File.UndoHandle(StringIO(data)) -print h.readline() # 'This' -print h.peekline() # 'is' -print h.readline() # 'is' +print(h.readline()) # 'This' +print(h.peekline()) # 'is' +print(h.readline()) # 'is' h.saveline("saved") -print h.peekline() # 'saved' +print(h.peekline()) # 'saved' h.saveline("another") -print h.readline() # 'another' -print h.readline() # 'saved' +print(h.readline()) # 'another' +print(h.readline()) # 'saved' # Test readlines after saveline h.saveline("saved again") lines = h.readlines() -print repr(lines[0]) # 'saved again' -print repr(lines[1]) # 'a multi-line' -print repr(lines[2]) # 'file' +print(repr(lines[0])) # 'saved again' +print(repr(lines[1])) # 'a multi-line' +print(repr(lines[2])) # 'file' # should be empty now -print repr(h.readline()) # '' +print(repr(h.readline())) # '' h.saveline("save after empty") -print h.readline() # 'save after empty' -print repr(h.readline()) # '' +print(h.readline()) # 'save after empty' +print(repr(h.readline())) # '' # test read method h = File.UndoHandle(StringIO("some text")) h.saveline("more text") -print h.read() # 'more textsome text' +print(h.read()) # 'more textsome text' class AsHandleTestCase(unittest.TestCase): diff -Nru python-biopython-1.62/Tests/test_GACrossover.py python-biopython-1.63/Tests/test_GACrossover.py --- python-biopython-1.62/Tests/test_GACrossover.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_GACrossover.py 2013-12-05 14:10:43.000000000 +0000 @@ -130,7 +130,7 @@ self.assertEqual(str(new_org_1.genome).count("1"), str(new_org_2.genome).count("2"), "There should be equal, inverse distributions") - self.assertEqual(str(new_org_1.genome).count("2") , + self.assertEqual(str(new_org_1.genome).count("2"), str(new_org_2.genome).count("1"), "There should be equal, inverse distributions") @@ -181,7 +181,7 @@ self.assertEqual(str(new_org_1.genome).count("1"), str(new_org_2.genome).count("2"), "There should be equal, inverse distributions") - self.assertEqual(str(new_org_1.genome).count("2") , + self.assertEqual(str(new_org_1.genome).count("2"), str(new_org_2.genome).count("1"), "There should be equal, inverse distributions") @@ -225,8 +225,8 @@ genome_2 = MutableSeq("22222", self.alphabet) self.org_2 = Organism(genome_2, test_fitness) - self.sym_crossover = GeneralPointCrossover(3,1.0) - self.asym_crossover = GeneralPointCrossover(4,1.0) + self.sym_crossover = GeneralPointCrossover(3, 1.0) + self.asym_crossover = GeneralPointCrossover(4, 1.0) def test_basic_crossover(self): """Test basic 4-point crossover functionality. @@ -259,7 +259,7 @@ self.assertEqual(str(new_org_1.genome).count("1"), str(new_org_2.genome).count("2"), "There should be equal, inverse distributions") - self.assertEqual(str(new_org_1.genome).count("2") , + self.assertEqual(str(new_org_1.genome).count("2"), str(new_org_2.genome).count("1"), "There should be equal, inverse distributions") diff -Nru python-biopython-1.62/Tests/test_GAQueens.py python-biopython-1.63/Tests/test_GAQueens.py --- python-biopython-1.62/Tests/test_GAQueens.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_GAQueens.py 2013-12-05 14:10:43.000000000 +0000 @@ -17,6 +17,8 @@ When called as part of the Biopython unit test suite, 5 queens are used. """ # standard library +from __future__ import print_function + import sys import random import time @@ -38,16 +40,16 @@ def main(num_queens): - print "Calculating for %s queens..." % num_queens + print("Calculating for %s queens..." % num_queens) num_orgs = 1000 - print "Generating an initial population of %s organisms..." % num_orgs + print("Generating an initial population of %s organisms..." % num_orgs) queen_alphabet = QueensAlphabet(num_queens) start_population = Organism.random_population(queen_alphabet, num_queens, num_orgs, queens_fitness) - print "Evolving the population and searching for a solution..." + print("Evolving the population and searching for a solution...") mutator = QueensMutation(mutation_rate = 0.05) crossover = QueensCrossover(queens_fitness, crossover_prob = .2, @@ -68,9 +70,9 @@ unique_solutions.append(org) if VERBOSE: - print "Search started at %s and ended at %s" % (start_time, end_time) + print("Search started at %s and ended at %s" % (start_time, end_time)) for orgm in unique_solutions: - print "We did it!", org + print("We did it! %s" % org) display_board(org.genome) @@ -80,18 +82,18 @@ Inspired by the display function in the queens.py solution to the N-queens problem in the Python demo scripts. """ - print '+-' + '--'*len(genome) + '+' + print('+-' + '--'*len(genome) + '+') for row in range(len(genome)): - print '|', + elements = [] for genome_item in genome: if genome_item == row: - print 'Q', + elements.append('Q') else: - print '.', - print '|' + elements.append('.') + print('|' + ''.join(elements) + '|') - print '+-' + '--'*len(genome) + '+' + print('+-' + '--'*len(genome) + '+') def queens_solved(organisms): @@ -217,7 +219,7 @@ # check if we should repair or not repair_chance = random.random() if repair_chance <= self._repair_prob: - while 1: + while True: # get the duplicated items we need to work on duplicated_items = self._get_duplicates(organism.genome) @@ -402,10 +404,10 @@ num_queens = int(sys.argv[1]) main(num_queens) else: - print "Usage:" - print "python test_GAQueens.py \n" - print "where is an optional parameter" - print "specifying how many queens you want to try to calculate" - print "this for. The default number of queens to place is 5." - print "Range 1 to 9 is supported." + print("Usage:") + print("python test_GAQueens.py \n") + print("where is an optional parameter") + print("specifying how many queens you want to try to calculate") + print("this for. The default number of queens to place is 5.") + print("Range 1 to 9 is supported.") sys.exit(1) diff -Nru python-biopython-1.62/Tests/test_GenBank.py python-biopython-1.63/Tests/test_GenBank.py --- python-biopython-1.62/Tests/test_GenBank.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_GenBank.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,9 +1,18 @@ #!/usr/bin/env python +# Copyright 2001-2004 by Brad Chapman. All rights reserved. +# Revisions copyright 2007-2013 by Peter Cock. All rights reserved. +# Revisions copyright 2013 by Kai Blin. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. + """Test the GenBank parser and make sure everything is working smoothly. """ # standard library +from __future__ import print_function + import os -import cStringIO +from Bio._py3k import StringIO import warnings from Bio import BiopythonParserWarning @@ -53,76 +62,71 @@ record_parser = GenBank.RecordParser(debug_level = 0) all_parsers = [feature_parser, record_parser] -print "Testing parsers..." +print("Testing parsers...") for parser in all_parsers: for filename in files_to_parse: if not os.path.isfile(filename): - print "Missing test input file: %s" % filename + print("Missing test input file: %s" % filename) continue handle = open(filename, 'r') iterator = GenBank.Iterator(handle, parser) - while 1: - cur_record = iterator.next() + while True: + cur_record = next(iterator) if cur_record is None: break if isinstance(parser, GenBank.FeatureParser): - print "***Record from %s with the FeatureParser" \ - % filename.split(os.path.sep)[-1] - print "Seq:", repr(cur_record.seq) - print "Id:", cur_record.id - print "Name:", cur_record.name - print "Description", cur_record.description - print "Annotations***" - ann_keys = cur_record.annotations.keys() - ann_keys.sort() + print("***Record from %s with the FeatureParser" \ + % filename.split(os.path.sep)[-1]) + print("Seq: %r" % cur_record.seq) + print("Id: %s" % cur_record.id) + print("Name: %s" % cur_record.name) + print("Description %s" % cur_record.description) + print("Annotations***") + ann_keys = sorted(cur_record.annotations) for ann_key in ann_keys: if ann_key != 'references': - print "Key: %s" % ann_key - print "Value: %s" % \ - cur_record.annotations[ann_key] + print("Key: %s" % ann_key) + print("Value: %s" % \ + cur_record.annotations[ann_key]) else: - print "References*" + print("References*") for reference in cur_record.annotations[ann_key]: - print str(reference) - print "Feaures" + print(str(reference)) + print("Feaures") for feature in cur_record.features: - print feature + print(feature) if isinstance(_get_base_alphabet(cur_record.seq.alphabet), ProteinAlphabet): assert feature.strand is None else: #Assuming no mixed strand examples... assert feature.strand is not None - print "DB cross refs", cur_record.dbxrefs + print("DB cross refs %s" % cur_record.dbxrefs) elif isinstance(parser, GenBank.RecordParser): - print "***Record from %s with the RecordParser" \ - % filename.split(os.path.sep)[-1] - print "sequence length: %i" % len(cur_record.sequence) - print "locus:", cur_record.locus - print "definition:", cur_record.definition - print "accession:", cur_record.accession + print("***Record from %s with the RecordParser" \ + % filename.split(os.path.sep)[-1]) + print("sequence length: %i" % len(cur_record.sequence)) + print("locus: %s" % cur_record.locus) + print("definition: %s" % cur_record.definition) + print("accession: %s" % cur_record.accession) for reference in cur_record.references: - print "reference title:", reference.title + print("reference title: %s" % reference.title) for feature in cur_record.features: - print "feature key:", feature.key - print "location:", feature.location - print "num qualifiers:", len(feature.qualifiers) + print("feature key: %s" % feature.key) + print("location: %s" % feature.location) + print("num qualifiers: %i" % len(feature.qualifiers)) for qualifier in feature.qualifiers: - print "key:", qualifier.key, "value:", qualifier.value + print("key: %s value: %s" % (qualifier.key, qualifier.value)) handle.close() -#The dictionaries code has been deprecated -#print "Testing dictionaries..." -#... - # test writing GenBank format -print "Testing writing GenBank format..." +print("Testing writing GenBank format...") def do_comparison(good_record, test_record): @@ -131,23 +135,23 @@ Ths compares the two GenBank record, and will raise an AssertionError if two lines do not match, showing the non-matching lines. """ - good_handle = cStringIO.StringIO(good_record) - test_handle = cStringIO.StringIO(test_record) + good_handle = StringIO(good_record) + test_handle = StringIO(test_record) - while 1: + while True: good_line = good_handle.readline() test_line = test_handle.readline() if not(good_line) and not(test_line): break if not(good_line): - raise AssertionError("Extra info in Test: `%s`" % test_line) + raise AssertionError("Extra info in Test: %r" % test_line) if not(test_line): - raise AssertionError("Extra info in Expected: `%s`" % good_line) - test_normalized = ' '.join([x for x in test_line.split() if x]) - good_normalized = ' '.join([x for x in good_line.split() if x]) + raise AssertionError("Extra info in Expected: %r" % good_line) + test_normalized = ' '.join(x for x in test_line.split() if x) + good_normalized = ' '.join(x for x in good_line.split() if x) assert test_normalized == good_normalized, \ - "Expected does not match Test.\nExpect:`%s`\nTest :`%s`\n" % \ + "Expected does not match Test.\nExpect: %r\nTest: %r\n" % \ (good_line, test_line) @@ -155,21 +159,21 @@ record_parser = GenBank.RecordParser(debug_level = 0) for file in write_format_files: - print "Testing GenBank writing for %s..." % os.path.basename(file) + print("Testing GenBank writing for %s..." % os.path.basename(file)) cur_handle = open(os.path.join("GenBank", file), "r") compare_handle = open(os.path.join("GenBank", file), "r") iterator = GenBank.Iterator(cur_handle, record_parser) compare_iterator = GenBank.Iterator(compare_handle) - while 1: - cur_record = iterator.next() - compare_record = compare_iterator.next() + while True: + cur_record = next(iterator) + compare_record = next(compare_iterator) if cur_record is None or compare_record is None: break - print "\tTesting for %s" % cur_record.version + print("\tTesting for %s" % cur_record.version) output_record = str(cur_record) + "\n" do_comparison(compare_record, output_record) @@ -188,7 +192,7 @@ handle = open(os.path.join("GenBank", "arab1.gb")) iterator = GenBank.Iterator(handle, parser) - first_record = iterator.next() + first_record = next(iterator) # test for cleaning of translation translation_feature = first_record.features[1] @@ -200,7 +204,7 @@ handle.close() -print "Testing feature cleaning..." +print("Testing feature cleaning...") t_cleaning_features() @@ -233,7 +237,7 @@ assert c.data.name == "HG506_HG1000_1_PATCH", c.data.name assert c._expected_size == 1219964, c._expected_size - print "Done" + print("Done") -print "Testing EnsEMBL LOCUS lines..." +print("Testing EnsEMBL LOCUS lines...") t_ensembl_locus() diff -Nru python-biopython-1.62/Tests/test_GenomeDiagram.py python-biopython-1.63/Tests/test_GenomeDiagram.py --- python-biopython-1.62/Tests/test_GenomeDiagram.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_GenomeDiagram.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,14 +5,16 @@ """Tests for GenomeDiagram general functionality. """ -########## -# IMPORTS +from __future__ import print_function -# Builtins import os import unittest import math +from Bio._py3k import zip +from Bio._py3k import range + + # Do we have ReportLab? Raise error if not present. from Bio import MissingPythonDependencyError try: @@ -113,8 +115,8 @@ results.append((middle, value)) # Add results to list # Check on last sequence - #print fragment - #print seq[-100:] + #print(fragment) + #print(seq[-100:]) return results # Return the list of (position, value) results @@ -126,13 +128,13 @@ Returns the % G+C content in a passed sequence """ d = {} - for nt in ['A','T','G','C']: + for nt in ['A', 'T', 'G', 'C']: d[nt] = sequence.count(nt) + sequence.count(nt.lower()) - gc = d.get('G',0) + d.get('C',0) + gc = d.get('G', 0) + d.get('C', 0) if gc == 0: return 0 - #print gc*100.0/(d['A'] +d['T'] + gc) + #print(gc*100.0/(d['A'] +d['T'] + gc)) return gc*1./(d['A'] +d['T'] + gc) @@ -144,9 +146,9 @@ Returns the % A+T content in a passed sequence """ d = {} - for nt in ['A','T','G','C']: + for nt in ['A', 'T', 'G', 'C']: d[nt] = sequence.count(nt) + sequence.count(nt.lower()) - at = d.get('A',0) + d.get('T',0) + at = d.get('A', 0) + d.get('T', 0) if at == 0: return 0 @@ -240,23 +242,23 @@ x=0.01, xl=0.01, xr=0.01) gdt_data = gdd.new_track(1, greytrack=False) gds_data = gdt_data.new_set("graph") - for data_values, name, color in zip([data1,data2,data3], + for data_values, name, color in zip([data1, data2, data3], ["sin", "cos", "2sin2"], - ["red","green","blue"]): - data = zip(range(points), data_values) + ["red", "green", "blue"]): + data = list(zip(range(points), data_values)) gds_data.new_graph(data, "", style="line", color = color, altcolor = color, center = 0) gdd.draw(format='linear', tracklines=False, - pagesize=(15*cm,15*cm), + pagesize=(15*cm, 15*cm), fragments=1, start=0, end=points) gdd.write(os.path.join('Graphics', "line_graph.pdf"), "pdf") #Circular diagram gdd.draw(tracklines=False, - pagesize=(15*cm,15*cm), + pagesize=(15*cm, 15*cm), circular=True, # Data designed to be periodic start=0, end=points, circle_core=0.5) gdd.write(os.path.join('Graphics', "line_graph_c.pdf"), "pdf") @@ -289,7 +291,7 @@ orient = "portrait" self.gdd.draw(format='linear', orientation=orient, tracklines=False, - pagesize=(15*cm,5*cm*tracks), + pagesize=(15*cm, 5*cm*tracks), fragments=1, start=0, end=400) self.gdd.write(os.path.join('Graphics', name+".pdf"), "pdf") @@ -310,7 +312,7 @@ if circular: #Circular diagram self.gdd.draw(tracklines=False, - pagesize=(15*cm,15*cm), + pagesize=(15*cm, 15*cm), fragments=1, circle_core=0.5, start=0, end=400) @@ -380,7 +382,7 @@ orient = "portrait" self.gdd.draw(format='linear', orientation=orient, tracklines=False, - pagesize=(15*cm,5*cm*tracks), + pagesize=(15*cm, 5*cm*tracks), fragments=1, start=0, end=400) self.gdd.write(os.path.join('Graphics', name+".pdf"), "pdf") @@ -395,7 +397,7 @@ if circular: #Circular diagram self.gdd.draw(tracklines=False, - pagesize=(15*cm,15*cm), + pagesize=(15*cm, 15*cm), fragments=1, circle_core=0.5, start=0, end=400) @@ -567,7 +569,7 @@ """Creating feature sets, graph sets, tracks etc individually for the diagram.""" def setUp(self): """Test setup, just loads a GenBank file as a SeqRecord.""" - handle = open(os.path.join("GenBank","NC_005816.gb"), 'r') + handle = open(os.path.join("GenBank", "NC_005816.gb"), 'r') self.record = SeqIO.read(handle, "genbank") handle.close() @@ -575,21 +577,21 @@ """Check how the write methods respond to output format arguments.""" gdd = Diagram('Test Diagram') gdd.drawing = None # Hack - need the ReportLab drawing object to be created. - filename = os.path.join("Graphics","error.txt") + filename = os.path.join("Graphics", "error.txt") #We (now) allow valid formats in any case. - for output in ["XXX","xxx",None,123,5.9]: + for output in ["XXX", "xxx", None, 123, 5.9]: try: gdd.write(filename, output) assert False, \ "Should have rejected %s as an output format" % output - except ValueError, e: + except ValueError as e: #Good! pass try: gdd.write_to_string(output) assert False, \ "Should have rejected %s as an output format" % output - except ValueError, e: + except ValueError as e: #Good! pass @@ -650,15 +652,15 @@ #And draw it... gdd.draw(format='linear', orientation='landscape', - tracklines=False, pagesize=(10*cm,6*cm), fragments=1, + tracklines=False, pagesize=(10*cm, 6*cm), fragments=1, start=start, end=end) output_filename = os.path.join('Graphics', 'GD_region_linear.pdf') gdd.write(output_filename, 'PDF') #Also check the write_to_string method matches, #(Note the possible confusion over new lines on Windows) - assert open(output_filename).read().replace("\r\n","\n") \ - == gdd.write_to_string('PDF').replace("\r\n","\n") + assert open(output_filename).read().replace("\r\n", "\n") \ + == gdd.write_to_string('PDF').replace("\r\n", "\n") output_filename = os.path.join('Graphics', 'GD_region_linear.svg') gdd.write(output_filename, 'SVG') @@ -666,7 +668,7 @@ #Circular with a particular start/end is a bit odd, but by setting #circular=False (above) a sweep of 90% is used (a wedge is left out) gdd.draw(format='circular', - tracklines=False, pagesize=(10*cm,10*cm), + tracklines=False, pagesize=(10*cm, 10*cm), start=start, end=end) output_filename = os.path.join('Graphics', 'GD_region_circular.pdf') gdd.write(output_filename, 'PDF') @@ -701,10 +703,10 @@ #I want to include some strandless features, so for an example #will use EcoRI recognition sites etc. - for site, name, color in [("GAATTC","EcoRI","green"), - ("CCCGGG","SmaI","orange"), - ("AAGCTT","HindIII","red"), - ("GGATCC","BamHI","purple")]: + for site, name, color in [("GAATTC", "EcoRI", "green"), + ("CCCGGG", "SmaI", "orange"), + ("AAGCTT", "HindIII", "red"), + ("GGATCC", "BamHI", "purple")]: index = 0 while True: index = genbank_entry.seq.find(site, start=index) @@ -754,7 +756,7 @@ gdd.write(output_filename, 'PDF') gdd.draw(format='circular', tracklines=False, circle_core=0.8, - pagesize=(20*cm,20*cm), circular=True) + pagesize=(20*cm, 20*cm), circular=True) output_filename = os.path.join('Graphics', 'GD_by_meth_circular.pdf') gdd.write(output_filename, 'PDF') @@ -806,47 +808,47 @@ #Some cross links on the same linear diagram fragment, f, c = fill_and_border(colors.red) - a = gdfsA.add_feature(SeqFeature(FeatureLocation(2220,2230)), color=f, border=c) - b = gdfsB.add_feature(SeqFeature(FeatureLocation(2200,2210)), color=f, border=c) + a = gdfsA.add_feature(SeqFeature(FeatureLocation(2220, 2230)), color=f, border=c) + b = gdfsB.add_feature(SeqFeature(FeatureLocation(2200, 2210)), color=f, border=c) gdd.cross_track_links.append(CrossLink(a, b, f, c)) f, c = fill_and_border(colors.blue) - a = gdfsA.add_feature(SeqFeature(FeatureLocation(2150,2200)), color=f, border=c) - b = gdfsB.add_feature(SeqFeature(FeatureLocation(2220,2290)), color=f, border=c) + a = gdfsA.add_feature(SeqFeature(FeatureLocation(2150, 2200)), color=f, border=c) + b = gdfsB.add_feature(SeqFeature(FeatureLocation(2220, 2290)), color=f, border=c) gdd.cross_track_links.append(CrossLink(a, b, f, c, flip=True)) f, c = fill_and_border(colors.green) - a = gdfsA.add_feature(SeqFeature(FeatureLocation(2250,2560)), color=f, border=c) - b = gdfsB.add_feature(SeqFeature(FeatureLocation(2300,2860)), color=f, border=c) + a = gdfsA.add_feature(SeqFeature(FeatureLocation(2250, 2560)), color=f, border=c) + b = gdfsB.add_feature(SeqFeature(FeatureLocation(2300, 2860)), color=f, border=c) gdd.cross_track_links.append(CrossLink(a, b, f, c)) #Some cross links where both parts are saddling the linear diagram fragment boundary, f, c = fill_and_border(colors.red) - a = gdfsA.add_feature(SeqFeature(FeatureLocation(3155,3250)), color=f, border=c) - b = gdfsB.add_feature(SeqFeature(FeatureLocation(3130,3300)), color=f, border=c) + a = gdfsA.add_feature(SeqFeature(FeatureLocation(3155, 3250)), color=f, border=c) + b = gdfsB.add_feature(SeqFeature(FeatureLocation(3130, 3300)), color=f, border=c) gdd.cross_track_links.append(CrossLink(a, b, f, c)) #Nestled within that (drawn on top), f, c = fill_and_border(colors.blue) - a = gdfsA.add_feature(SeqFeature(FeatureLocation(3160,3275)), color=f, border=c) - b = gdfsB.add_feature(SeqFeature(FeatureLocation(3180,3225)), color=f, border=c) + a = gdfsA.add_feature(SeqFeature(FeatureLocation(3160, 3275)), color=f, border=c) + b = gdfsB.add_feature(SeqFeature(FeatureLocation(3180, 3225)), color=f, border=c) gdd.cross_track_links.append(CrossLink(a, b, f, c, flip=True)) #Some cross links where two features are on either side of the linear diagram fragment boundary, f, c = fill_and_border(colors.green) - a = gdfsA.add_feature(SeqFeature(FeatureLocation(6450,6550)), color=f, border=c) - b = gdfsB.add_feature(SeqFeature(FeatureLocation(6265,6365)), color=f, border=c) + a = gdfsA.add_feature(SeqFeature(FeatureLocation(6450, 6550)), color=f, border=c) + b = gdfsB.add_feature(SeqFeature(FeatureLocation(6265, 6365)), color=f, border=c) gdd.cross_track_links.append(CrossLink(a, b, color=f, border=c)) f, c = fill_and_border(colors.gold) - a = gdfsA.add_feature(SeqFeature(FeatureLocation(6265,6365)), color=f, border=c) - b = gdfsB.add_feature(SeqFeature(FeatureLocation(6450,6550)), color=f, border=c) + a = gdfsA.add_feature(SeqFeature(FeatureLocation(6265, 6365)), color=f, border=c) + b = gdfsB.add_feature(SeqFeature(FeatureLocation(6450, 6550)), color=f, border=c) gdd.cross_track_links.append(CrossLink(a, b, color=f, border=c)) f, c = fill_and_border(colors.red) - a = gdfsA.add_feature(SeqFeature(FeatureLocation(6275,6375)), color=f, border=c) - b = gdfsB.add_feature(SeqFeature(FeatureLocation(6430,6530)), color=f, border=c) + a = gdfsA.add_feature(SeqFeature(FeatureLocation(6275, 6375)), color=f, border=c) + b = gdfsB.add_feature(SeqFeature(FeatureLocation(6430, 6530)), color=f, border=c) gdd.cross_track_links.append(CrossLink(a, b, color=f, border=c, flip=True)) f, c = fill_and_border(colors.blue) - a = gdfsA.add_feature(SeqFeature(FeatureLocation(6430,6530)), color=f, border=c) - b = gdfsB.add_feature(SeqFeature(FeatureLocation(6275,6375)), color=f, border=c) + a = gdfsA.add_feature(SeqFeature(FeatureLocation(6430, 6530)), color=f, border=c) + b = gdfsB.add_feature(SeqFeature(FeatureLocation(6275, 6375)), color=f, border=c) gdd.cross_track_links.append(CrossLink(a, b, color=f, border=c, flip=True)) cds_count = 0 @@ -963,7 +965,7 @@ gdd.set_all_tracks("greytrack_labels", 2) gdd.draw(format='linear', orientation='landscape', - tracklines=0, pagesize=(30*cm,10*cm), fragments=1, + tracklines=0, pagesize=(30*cm, 10*cm), fragments=1, start=3000, end=6300) output_filename = os.path.join('Graphics', 'GD_by_obj_frag_linear.pdf') gdd.write(output_filename, 'PDF') diff -Nru python-biopython-1.62/Tests/test_GraphicsBitmaps.py python-biopython-1.63/Tests/test_GraphicsBitmaps.py --- python-biopython-1.62/Tests/test_GraphicsBitmaps.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_GraphicsBitmaps.py 2013-12-05 14:10:43.000000000 +0000 @@ -84,13 +84,13 @@ # error here. except IndexError: pass - except IOError, err: + except IOError as err: if "encoder zip not available" in str(err): raise MissingExternalDependencyError( "Check zip encoder installed for PIL and ReportLab renderPM") else: raise err - except RenderPMError, err : + except RenderPMError as err: if str(err).startswith("Can't setFont(") : #TODO - can we raise the error BEFORE the unit test function #is run? That way it can be skipped in run_tests.py diff -Nru python-biopython-1.62/Tests/test_GraphicsChromosome.py python-biopython-1.63/Tests/test_GraphicsChromosome.py --- python-biopython-1.62/Tests/test_GraphicsChromosome.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_GraphicsChromosome.py 2013-12-05 14:10:43.000000000 +0000 @@ -11,10 +11,12 @@ Graphics.DisplayRepresentation classes. """ # standard library +from __future__ import print_function + import os import sys import random -import cStringIO +from Bio._py3k import StringIO import unittest from Bio import MissingPythonDependencyError @@ -234,7 +236,7 @@ # trick to write the properties to a string save_stdout = sys.stdout - new_stdout = cStringIO.StringIO() + new_stdout = StringIO() sys.stdout = new_stdout test_widget.dumpProperties() @@ -283,19 +285,19 @@ record = SeqIO.read(filename, "gb") assert length == len(record) features = [f for f in record.features if f.type=="tRNA"] - print name + print(name) #Strip of the first three chars, AT# where # is the chr - print [(int(f.location.start), int(f.location.end), + print([(int(f.location.start), int(f.location.end), f.strand, f.qualifiers['locus_tag'][0][3:]) - for f in features] + for f in features]) #Output was copy and pasted to the script, see above. #Continue test using SeqFeature objects! #To test colours from the qualifiers, - for i,f in enumerate(features): + for i, f in enumerate(features): f.qualifiers['color'] = [str(i % 16)] else: - features = [(start,end,strand,label,color) - for (start,end,strand,label) in features] + features = [(start, end, strand, label, color) + for (start, end, strand, label) in features] #I haven't found a nice source of data for real Arabidopsis #cytobands, so these three are made up at random! cytobands = [] diff -Nru python-biopython-1.62/Tests/test_HMMCasino.py python-biopython-1.63/Tests/test_HMMCasino.py --- python-biopython-1.62/Tests/test_HMMCasino.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_HMMCasino.py 2013-12-05 14:10:43.000000000 +0000 @@ -12,6 +12,8 @@ .1. """ +from __future__ import print_function + import os if os.name == 'java': from Bio import MissingExternalDependencyError @@ -150,7 +152,7 @@ rolls, states = generate_rolls(3000) # predicted_states, prob = my_mm.viterbi(rolls, DiceTypeAlphabet()) -# print "prob:", prob +# print("prob: %f" % prob) # Utilities.pretty_print_prediction(rolls, states, predicted_states) @@ -159,7 +161,7 @@ """Tell the training model when to stop. """ if VERBOSE: - print "ll change:", log_likelihood_change + print("ll change: %f" % log_likelihood_change) if log_likelihood_change < 0.01: return 1 elif num_iterations >= 10: @@ -168,37 +170,37 @@ return 0 # -- Standard Training with known states -print "Training with the Standard Trainer..." +print("Training with the Standard Trainer...") known_training_seq = Trainer.TrainingSequence(rolls, states) trainer = Trainer.KnownStateTrainer(standard_mm) trained_mm = trainer.train([known_training_seq]) if VERBOSE: - print trained_mm.transition_prob - print trained_mm.emission_prob + print(trained_mm.transition_prob) + print(trained_mm.emission_prob) test_rolls, test_states = generate_rolls(300) predicted_states, prob = trained_mm.viterbi(test_rolls, DiceTypeAlphabet()) if VERBOSE: - print "Prediction probability:", prob + print("Prediction probability: %f" % prob) Utilities.pretty_print_prediction(test_rolls, test_states, predicted_states) # -- Baum-Welch training without known state sequences -print "Training with Baum-Welch..." +print("Training with Baum-Welch...") training_seq = Trainer.TrainingSequence(rolls, Seq("", DiceTypeAlphabet())) trainer = Trainer.BaumWelchTrainer(baum_welch_mm) trained_mm = trainer.train([training_seq], stop_training) if VERBOSE: - print trained_mm.transition_prob - print trained_mm.emission_prob + print(trained_mm.transition_prob) + print(trained_mm.emission_prob) test_rolls, test_states = generate_rolls(300) predicted_states, prob = trained_mm.viterbi(test_rolls, DiceTypeAlphabet()) if VERBOSE: - print "Prediction probability:", prob + print("Prediction probability: %f" % prob) Utilities.pretty_print_prediction(test_rolls, test_states, predicted_states) diff -Nru python-biopython-1.62/Tests/test_HMMGeneral.py python-biopython-1.63/Tests/test_HMMGeneral.py --- python-biopython-1.62/Tests/test_HMMGeneral.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_HMMGeneral.py 2013-12-05 14:10:43.000000000 +0000 @@ -4,6 +4,8 @@ Also tests Training methods. """ # standard modules +from __future__ import print_function + import unittest import math @@ -379,7 +381,7 @@ ('2', 0) : .7} s_value = self.dp._calculate_s_value(1, previous_vars) - # print s_value + # print(s_value) class AbstractTrainerTest(unittest.TestCase): diff -Nru python-biopython-1.62/Tests/test_HotRand.py python-biopython-1.63/Tests/test_HotRand.py --- python-biopython-1.62/Tests/test_HotRand.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_HotRand.py 2013-12-05 14:10:43.000000000 +0000 @@ -2,6 +2,8 @@ """Tests HotRand. """ # standard library +from __future__ import print_function + import unittest import warnings @@ -17,15 +19,15 @@ # --- helper classes and functions -def are_items_in_range( a, high, low ): - for j in range( 0, len( a ) ): - if( a[ j ] > high ): - print 'a[ %d ] is %d' % ( j , a[ j ] ) - return 0 - if( a[ j ] < low ): - print 'a[ %d ] is %d' % ( j , a[ j ] ) - return 0 - return 1 +def are_items_in_range(a, high, low): + for j in range(0, len(a)): + if a[j] > high: + print('a[ %d ] is %d' % (j, a[j])) + return False + if a[j] < low: + print('a[ %d ] is %d' % (j, a[j])) + return False + return True # --- the actual test classes @@ -37,24 +39,26 @@ def test_get_random_range(self): """Get a sequence of random numbers. """ - return rand_seq = [] hot_random = HotRandom() - for j in range( 0, 200 ): - rand_num = hot_random.hot_rand( 91, 37 ) - rand_seq.append( rand_num ) - assert are_items_in_range( rand_seq, 91, 37 ) , "Got an out of range number" + for j in range(0, 200): + rand_num = hot_random.hot_rand(91, 37) + rand_seq.append(rand_num) + self.assertTrue(are_items_in_range(rand_seq, 91, 37), + "Got an out of range number") rand_seq = [] - for j in range( 0, 200 ): - rand_num = hot_random.hot_rand( 19, 0 ) - rand_seq.append( rand_num ) - assert are_items_in_range( rand_seq, 19, 0 ) , "Got an out of range number" + for j in range(0, 200): + rand_num = hot_random.hot_rand(19, 0) + rand_seq.append(rand_num) + self.assertTrue(are_items_in_range(rand_seq, 19, 0), + "Got an out of range number") rand_seq = [] - for j in range( 0, 200 ): - rand_num = hot_random.hot_rand( 61, 4 ) - rand_seq.append( rand_num ) - assert are_items_in_range( rand_seq, 61, 4 ) , "Got an out of range number" + for j in range(0, 200): + rand_num = hot_random.hot_rand(61, 4) + rand_seq.append(rand_num ) + self.assertTrue(are_items_in_range(rand_seq, 61, 4), + "Got an out of range number") if __name__ == "__main__": - runner = unittest.TextTestRunner(verbosity = 2) + runner = unittest.TextTestRunner(verbosity=2) unittest.main(testRunner=runner) diff -Nru python-biopython-1.62/Tests/test_KEGG.py python-biopython-1.63/Tests/test_KEGG.py --- python-biopython-1.62/Tests/test_KEGG.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_KEGG.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,6 +1,13 @@ +# Copyright 2001 by Tarjei Mikkelsen. All rights reserved. +# Revisions copyright 2007 by Michiel de Hoon. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. """Tests the basic functionality of the KEGG parsers. """ +from __future__ import print_function + import os from Bio.KEGG import Enzyme @@ -17,11 +24,11 @@ """Tests Bio.KEGG.Enzyme functionality.""" for file in testfiles: fh = open(os.path.join("KEGG", file)) - print "Testing Bio.KEGG.Enzyme on " + file + "\n\n" + print("Testing Bio.KEGG.Enzyme on " + file + "\n\n") records = Enzyme.parse(fh) for record in records: - print record - print "\n" + print(record) + print("\n") fh.close() @@ -29,11 +36,11 @@ """Tests Bio.KEGG.Compound functionality.""" for file in testfiles: fh = open(os.path.join("KEGG", file)) - print "Testing Bio.KEGG.Compound on " + file + "\n\n" + print("Testing Bio.KEGG.Compound on " + file + "\n\n") records = Compound.parse(fh) for record in records: - print record - print "\n" + print(record) + print("\n") fh.close() @@ -41,7 +48,7 @@ """Tests Bio.KEGG.Map functionality.""" for file in testfiles: fh = open(os.path.join("KEGG", file)) - print "Testing Bio.KEGG.Map on " + file + "\n\n" + print("Testing Bio.KEGG.Map on " + file + "\n\n") reactions = Map.parse(fh) system = System() for reaction in reactions: @@ -56,7 +63,7 @@ # solution below proves resilient rxs.sort(key=lambda x:str(x)) for x in rxs: - print str(x) + print(str(x)) fh.close() diff -Nru python-biopython-1.62/Tests/test_KeyWList.py python-biopython-1.63/Tests/test_KeyWList.py --- python-biopython-1.62/Tests/test_KeyWList.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_KeyWList.py 2013-12-05 14:10:43.000000000 +0000 @@ -18,7 +18,7 @@ records = KeyWList.parse(handle) # Testing the first record - record = records.next() + record = next(records) self.assertEqual(record["ID"], "2Fe-2S.") self.assertEqual(record["AC"], "KW-0001") self.assertEqual(record["DE"], "Protein which contains at least one 2Fe-2S iron-sulfur cluster: 2 iron atoms complexed to 2 inorganic sulfides and 4 sulfur atoms of cysteines from the protein.") @@ -31,13 +31,13 @@ self.assertEqual(record["CA"], "Ligand.") # Testing the second record - record = records.next() + record = next(records) self.assertEqual(record["IC"], "Molecular function.") self.assertEqual(record["AC"], "KW-9992") self.assertEqual(record["DE"], "Keywords assigned to proteins due to their particular molecular function.") # Testing the third record - record = records.next() + record = next(records) self.assertEqual(record["ID"], "Zymogen.") self.assertEqual(record["AC"], "KW-0865") self.assertEqual(record["DE"], "The enzymatically inactive precursor of mostly proteolytic enzymes.") @@ -56,7 +56,7 @@ records = KeyWList.parse(handle) # Testing the first record - record = records.next() + record = next(records) self.assertEqual(record["ID"], "2Fe-2S.") self.assertEqual(record["AC"], "KW-0001") self.assertEqual(record["DE"], "Protein which contains at least one 2Fe-2S iron-sulfur cluster: 2 iron atoms complexed to 2 inorganic sulfides and 4 sulfur atoms of cysteines from the protein.") @@ -69,7 +69,7 @@ self.assertEqual(record["CA"], "Ligand.") # Testing the second record - record = records.next() + record = next(records) self.assertEqual(record["ID"], "3D-structure.") self.assertEqual(record["AC"], "KW-0002") self.assertEqual(record["DE"], "Protein, or part of a protein, whose three-dimensional structure has been resolved experimentally (for example by X-ray crystallography or NMR spectroscopy) and whose coordinates are available in the PDB database. Can also be used for theoretical models.") @@ -78,7 +78,7 @@ self.assertEqual(record["CA"], "Technical term.") # Testing the third record - record = records.next() + record = next(records) self.assertEqual(record["ID"], "3Fe-4S.") self.assertEqual(record["AC"], "KW-0003") self.assertEqual(record["DE"], "Protein which contains at least one 3Fe-4S iron-sulfur cluster: 3 iron atoms complexed to 4 inorganic sulfides and 3 sulfur atoms of cysteines from the protein. In a number of iron-sulfur proteins, the 4Fe-4S cluster can be reversibly converted by oxidation and loss of one iron ion to a 3Fe-4S cluster.") diff -Nru python-biopython-1.62/Tests/test_Location.py python-biopython-1.63/Tests/test_Location.py --- python-biopython-1.62/Tests/test_Location.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_Location.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,13 +1,20 @@ #!/usr/bin/env python +# Copyright 2001 by Brad Chapman. All rights reserved. +# Revisions copyright 2011-2013 by Peter Cock. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. """Test the Location code located in SeqFeature.py This checks to be sure fuzzy and non-fuzzy representations of locations are working properly. """ +from __future__ import print_function + from Bio import SeqFeature # --- test fuzzy representations -print "Testing fuzzy representations..." +print("Testing fuzzy representations...") # check the positions alone exact_pos = SeqFeature.ExactPosition(5) @@ -17,12 +24,12 @@ before_pos = SeqFeature.BeforePosition(15) after_pos = SeqFeature.AfterPosition(40) -print "Exact:", exact_pos -print "Within (as start, %i): %s" % (int(within_pos_s), within_pos_s) -print "Within (as end, %i): %s" % (int(within_pos_e), within_pos_e) -print "Between (as end, %i): %s" % (int(between_pos_e), between_pos_e) -print "Before:", before_pos -print "After:", after_pos +print("Exact: %s" % exact_pos) +print("Within (as start, %i): %s" % (int(within_pos_s), within_pos_s)) +print("Within (as end, %i): %s" % (int(within_pos_e), within_pos_e)) +print("Between (as end, %i): %s" % (int(between_pos_e), between_pos_e)) +print("Before: %s" % before_pos) +print("After: %s" % after_pos) # put these into Locations location1 = SeqFeature.FeatureLocation(exact_pos, within_pos_e) @@ -30,13 +37,13 @@ location3 = SeqFeature.FeatureLocation(within_pos_s, after_pos) for location in [location1, location2, location3]: - print "Location:", location - print " Start:", location.start - print " End :", location.end + print("Location: %s" % location) + print(" Start: %s" % location.start) + print(" End : %s" % location.end) # --- test non-fuzzy represenations -print "Testing non-fuzzy representations..." +print("Testing non-fuzzy representations...") for location in [location1, location2, location3]: - print "Location:", location - print " Non-Fuzzy Start:", location.nofuzzy_start - print " Non-Fuzzy End:", location.nofuzzy_end + print("Location: %s" % location) + print(" Non-Fuzzy Start: %s" % location.nofuzzy_start) + print(" Non-Fuzzy End: %s" % location.nofuzzy_end) diff -Nru python-biopython-1.62/Tests/test_LogisticRegression.py python-biopython-1.63/Tests/test_LogisticRegression.py --- python-biopython-1.62/Tests/test_LogisticRegression.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_LogisticRegression.py 2013-12-05 14:10:43.000000000 +0000 @@ -66,14 +66,14 @@ def test_classify(self): model = LogisticRegression.train(xs, ys) - result = LogisticRegression.classify(model, [6,-173.143442352]) + result = LogisticRegression.classify(model, [6, -173.143442352]) self.assertEqual(result, 1) result = LogisticRegression.classify(model, [309, -271.005880394]) self.assertEqual(result, 0) def test_calculate_probability(self): model = LogisticRegression.train(xs, ys) - q, p = LogisticRegression.calculate(model, [6,-173.143442352]) + q, p = LogisticRegression.calculate(model, [6, -173.143442352]) self.assertAlmostEqual(p, 0.993242, places=6) self.assertAlmostEqual(q, 0.006758, places=6) q, p = LogisticRegression.calculate(model, [309, -271.005880394]) diff -Nru python-biopython-1.62/Tests/test_MSAProbs_tool.py python-biopython-1.63/Tests/test_MSAProbs_tool.py --- python-biopython-1.62/Tests/test_MSAProbs_tool.py 1970-01-01 00:00:00.000000000 +0000 +++ python-biopython-1.63/Tests/test_MSAProbs_tool.py 2013-12-05 14:10:43.000000000 +0000 @@ -0,0 +1,164 @@ +# Copyright 2013 by Christian Brueffer. All rights reserved. +# +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. + +import os +import sys +import unittest +from Bio import AlignIO +from Bio import MissingExternalDependencyError +from Bio import SeqIO +from Bio.Align.Applications import MSAProbsCommandline +from Bio.Application import ApplicationError +from Bio._py3k import getoutput + +################################################################# + +#Try to avoid problems when the OS is in another language +os.environ['LANG'] = 'C' + +msaprobs_exe = None +if sys.platform == "win32": + #TODO + raise MissingExternalDependencyError("Testing this on Windows is not implemented yet") +else: + output = getoutput("msaprobs -version") + if output.startswith("MSAPROBS version"): + msaprobs_exe = "msaprobs" + +if not msaprobs_exe: + raise MissingExternalDependencyError( + "Install msaprobs if you want to use MSAProbs from Biopython.") + + +class MSAProbsTestCase(unittest.TestCase): + + def setUp(self): + self.files_to_clean = set() + + def tearDown(self): + for filename in self.files_to_clean: + if os.path.isfile(filename): + os.remove(filename) + + def standard_test_procedure(self, cline): + """Standard testing procedure used by all tests.""" + + # Mark output files for later cleanup. + self.add_file_to_clean(cline.outfile) + + input_records = SeqIO.to_dict(SeqIO.parse(cline.infile, "fasta")) + self.assertEqual(str(eval(repr(cline))), str(cline)) + output, error = cline() + + def add_file_to_clean(self, filename): + """Adds a file for deferred removal by the tearDown routine.""" + self.files_to_clean.add(filename) + +################################################################# + + +class MSAProbsTestErrorConditions(MSAProbsTestCase): + + def test_empty_file(self): + """Test an empty file.""" + input_file = "does_not_exist.fasta" + self.assertFalse(os.path.isfile(input_file)) + cline = MSAProbsCommandline(msaprobs_exe, infile=input_file) + try: + stdout, stderr = cline() + except ApplicationError as err: + self.assertTrue("Cannot open sequence file" in str(err) or + "Cannot open input file" in str(err) or + "non-zero exit status" in str(err)) + else: + self.fail("Should have failed, returned:\n%s\n%s" % (stdout, stderr)) + + def test_single_sequence(self): + """Test an input file containing a single sequence.""" + input_file = "Fasta/f001" + self.assertTrue(os.path.isfile(input_file)) + self.assertEqual(len(list(SeqIO.parse(input_file, "fasta"))), 1) + cline = MSAProbsCommandline(msaprobs_exe, infile=input_file) + try: + stdout, stderr = cline() + except ApplicationError as err: + self.assertEqual(err.returncode, 139) + else: + self.fail("Should have failed, returned:\n%s\n%s" % (stdout, stderr)) + + def test_invalid_format(self): + """Test an input file in an invalid format.""" + input_file = "Medline/pubmed_result1.txt" + self.assertTrue(os.path.isfile(input_file)) + cline = MSAProbsCommandline(msaprobs_exe, infile=input_file) + try: + stdout, stderr = cline() + except ApplicationError as err: + self.assertEqual(err.returncode, 1) + else: + self.fail("Should have failed, returned:\n%s\n%s" % (stdout, stderr)) + +################################################################# + + +class MSAProbsTestNormalConditions(MSAProbsTestCase): + + def test_simple_fasta(self): + """Test a simple fasta file.""" + input_file = "Registry/seqs.fasta" + output_file = "temp_test.aln" + + cline = MSAProbsCommandline(msaprobs_exe, + infile=input_file, + outfile=output_file, + clustalw=True) + + self.standard_test_procedure(cline) + + def test_properties(self): + """Test setting options via properties.""" + input_file = "Registry/seqs.fasta" + output_file = "temp_test.aln" + + cline = MSAProbsCommandline(msaprobs_exe) + cline.infile = input_file + cline.outfile = output_file + cline.clustalw = True + + self.standard_test_procedure(cline) + + def test_input_filename_with_space(self): + """Test an input filename containing a space.""" + input_file = "Clustalw/temp horses.fasta" + handle = open(input_file, "w") + SeqIO.write(SeqIO.parse("Phylip/hennigian.phy", "phylip"), handle, "fasta") + handle.close() + output_file = "temp_test.aln" + + cline = MSAProbsCommandline(msaprobs_exe, + infile=input_file, + outfile=output_file, + clustalw=True) + + self.add_file_to_clean(input_file) + self.standard_test_procedure(cline) + + def test_output_filename_with_spaces(self): + """Test an output filename containing spaces.""" + input_file = "Registry/seqs.fasta" + output_file = "temp with spaces.aln" + + cline = MSAProbsCommandline(msaprobs_exe, + infile=input_file, + outfile=output_file, + clustalw=True) + + self.standard_test_procedure(cline) + + +if __name__ == "__main__": + runner = unittest.TextTestRunner(verbosity=2) + unittest.main(testRunner=runner) diff -Nru python-biopython-1.62/Tests/test_Mafft_tool.py python-biopython-1.63/Tests/test_Mafft_tool.py --- python-biopython-1.62/Tests/test_Mafft_tool.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_Mafft_tool.py 2013-12-05 14:10:43.000000000 +0000 @@ -23,8 +23,8 @@ if sys.platform=="win32": raise MissingExternalDependencyError("Testing with MAFFT not implemented on Windows yet") else: - import commands - output = commands.getoutput("mafft -help") + from Bio._py3k import getoutput + output = getoutput("mafft -help") if "not found" not in output and "MAFFT" in output: mafft_exe = "mafft" if not mafft_exe: @@ -53,8 +53,8 @@ index = output.find(marker) if index == -1: continue - version = output[index+len(marker):].strip().split(None,1)[0] - major = int(version.split(".",1)[0]) + version = output[index+len(marker):].strip().split(None, 1)[0] + major = int(version.split(".", 1)[0]) if major < 6: raise MissingExternalDependencyError("Test requires MAFFT v6 or " "later (found %s)." % version) diff -Nru python-biopython-1.62/Tests/test_MarkovModel.py python-biopython-1.63/Tests/test_MarkovModel.py --- python-biopython-1.62/Tests/test_MarkovModel.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_MarkovModel.py 2013-12-05 14:10:43.000000000 +0000 @@ -215,7 +215,7 @@ states = MarkovModel.find_states(markov_model, "TTAGCAGTGCG") self.assertEqual(len(states), 1) state_list, state_float = states[0] - self.assertEqual(state_list, ['N','R','R','R','R','R','R','R','R','R','R']) + self.assertEqual(state_list, ['N', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R']) def test_topcoder5(self): # N diff -Nru python-biopython-1.62/Tests/test_Medline.py python-biopython-1.63/Tests/test_Medline.py --- python-biopython-1.62/Tests/test_Medline.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_Medline.py 2013-12-05 14:10:43.000000000 +0000 @@ -23,7 +23,7 @@ self.assertEqual(record["PUBM"], "Print") self.assertEqual(record["IS"], "1467-5463 (Print)") self.assertEqual(record["VI"], "3") - self.assertEqual(record["IP"] , "3") + self.assertEqual(record["IP"], "3") self.assertEqual(record["DP"], "2002 Sep") self.assertEqual(record["TI"], "The Bio* toolkits--a brief overview.") self.assertEqual(record["PG"], "296-302") @@ -47,7 +47,7 @@ def test_parse(self): handle = open("Medline/pubmed_result2.txt") records = Medline.parse(handle) - record = records.next() + record = next(records) self.assertEqual(record["PMID"], "16403221") self.assertEqual(record["OWN"], "NLM") self.assertEqual(record["STAT"], "MEDLINE") @@ -79,7 +79,7 @@ self.assertEqual(record["AID"], ["1471-2105-7-10 [pii]", "10.1186/1471-2105-7-10 [doi]"]) self.assertEqual(record["PST"], "epublish") self.assertEqual(record["SO"], "BMC Bioinformatics. 2006 Jan 10;7:10.") - record = records.next() + record = next(records) self.assertEqual(record["PMID"], "16377612") self.assertEqual(record["OWN"], "NLM") self.assertEqual(record["STAT"], "MEDLINE") @@ -112,7 +112,7 @@ self.assertEqual(record["AID"], ["btk021 [pii]", "10.1093/bioinformatics/btk021 [doi]"]) self.assertEqual(record["PST"], "ppublish") self.assertEqual(record["SO"], "Bioinformatics. 2006 Mar 1;22(5):616-7. Epub 2005 Dec 23.") - record = records.next() + record = next(records) self.assertEqual(record["PMID"], "14871861") self.assertEqual(record["OWN"], "NLM") self.assertEqual(record["STAT"], "MEDLINE") @@ -145,7 +145,7 @@ self.assertEqual(record["AID"], ["10.1093/bioinformatics/bth078 [doi]", "bth078 [pii]"]) self.assertEqual(record["PST"], "ppublish") self.assertEqual(record["SO"], "Bioinformatics. 2004 Jun 12;20(9):1453-4. Epub 2004 Feb 10.") - record = records.next() + record = next(records) self.assertEqual(record["PMID"], "14630660") self.assertEqual(record["OWN"], "NLM") self.assertEqual(record["STAT"], "MEDLINE") @@ -176,7 +176,7 @@ self.assertEqual(record["MHDA"], "2004/07/23 05:00") self.assertEqual(record["PST"], "ppublish") self.assertEqual(record["SO"], "Bioinformatics. 2003 Nov 22;19(17):2308-10.") - self.assertRaises(StopIteration, records.next) + self.assertRaises(StopIteration, next, records) handle.close() diff -Nru python-biopython-1.62/Tests/test_Motif.py python-biopython-1.63/Tests/test_Motif.py --- python-biopython-1.62/Tests/test_Motif.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_Motif.py 2013-12-05 14:10:43.000000000 +0000 @@ -23,7 +23,7 @@ self.FAout = "Motif/fa.out" self.PFMout = "Motif/fa.out" self.m=Motif.Motif() - self.m.add_instance(Seq("ATATA",self.m.alphabet)) + self.m.add_instance(Seq("ATATA", self.m.alphabet)) def tearDown(self): self.PFMin.close() @@ -75,7 +75,7 @@ self.assertEqual(record.motifs[0].instances[8].tostring(), "TCTACGATTGAG") self.assertEqual(record.motifs[0].instances[9].tostring(), "TCAAAGATAGAG") self.assertEqual(record.motifs[0].instances[10].tostring(), "TCTACGATTGAG") - self.assertEqual(record.motifs[0].mask, [1,1,0,1,1,1,1,1,0,1,1,1]) + self.assertEqual(record.motifs[0].mask, [1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1]) self.assertAlmostEqual(record.motifs[0].score, 57.9079) self.assertEqual(record.motifs[1].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record.motifs[1].instances), 22) @@ -101,7 +101,7 @@ self.assertEqual(record.motifs[1].instances[19].tostring(), "GGCGGGCCATCCCTGTATGAA") self.assertEqual(record.motifs[1].instances[20].tostring(), "CTCCAGGTCGCATGGAGAGAG") self.assertEqual(record.motifs[1].instances[21].tostring(), "CCTCGGATCGCTTGGGAAGAG") - self.assertEqual(record.motifs[1].mask, [1,0,1,1,0,1,0,0,1,1,1,0,0,0,1,0,0,0,1,0,1]) + self.assertEqual(record.motifs[1].mask, [1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1]) self.assertAlmostEqual(record.motifs[1].score, 19.6235) self.assertEqual(record.motifs[2].alphabet, IUPAC.unambiguous_dna) @@ -124,7 +124,7 @@ self.assertEqual(record.motifs[2].instances[15].tostring(), "GACCTGGAGGCTTAGACTTGG") self.assertEqual(record.motifs[2].instances[16].tostring(), "GCGCTCTTCCCAAGCGATCCG") self.assertEqual(record.motifs[2].instances[17].tostring(), "GGGCCGTCAGCTCTCAAGTCT") - self.assertEqual(record.motifs[2].mask, [1,0,1,1,0,1,0,0,0,1,1,0,0,0,1,0,1,0,0,1,1]) + self.assertEqual(record.motifs[2].mask, [1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1]) self.assertAlmostEqual(record.motifs[2].score, 19.1804) self.assertEqual(record.motifs[3].alphabet, IUPAC.unambiguous_dna) @@ -145,7 +145,7 @@ self.assertEqual(record.motifs[3].instances[13].tostring(), "GCGATCAGCTTGTGGGCGTGC") self.assertEqual(record.motifs[3].instances[14].tostring(), "GACAAATCGGATACTGGGGCA") self.assertEqual(record.motifs[3].instances[15].tostring(), "GCACTTAGCAGCGTATCGTTA") - self.assertEqual(record.motifs[3].mask, [1,1,1,0,0,0,0,1,1,0,0,0,0,1,0,0,1,1,1,0,1]) + self.assertEqual(record.motifs[3].mask, [1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1]) self.assertAlmostEqual(record.motifs[3].score, 18.0097) self.assertEqual(record.motifs[4].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record.motifs[4].instances), 15) @@ -164,7 +164,7 @@ self.assertEqual(record.motifs[4].instances[12].tostring(), "ATGCTTAGAGGTT") self.assertEqual(record.motifs[4].instances[13].tostring(), "AGACTTGGGCGAT") self.assertEqual(record.motifs[4].instances[14].tostring(), "CGACCTGGAGGCT") - self.assertEqual(record.motifs[4].mask, [1,1,0,1,0,1,1,1,1,1,1,0,1]) + self.assertEqual(record.motifs[4].mask, [1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1]) self.assertAlmostEqual(record.motifs[4].score, 16.8287) self.assertEqual(record.motifs[5].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record.motifs[5].instances), 18) @@ -186,7 +186,7 @@ self.assertEqual(record.motifs[5].instances[15].tostring(), "CTCTGCGTCGCATGGCGGCGTGG") self.assertEqual(record.motifs[5].instances[16].tostring(), "GGAGGCTTAGACTTGGGCGATAC") self.assertEqual(record.motifs[5].instances[17].tostring(), "GCATGGAGAGAGATCCGGAGGAG") - self.assertEqual(record.motifs[5].mask, [1,0,1,0,1,1,0,0,0,1,0,0,0,0,1,0,1,1,0,0,1,0,1]) + self.assertEqual(record.motifs[5].mask, [1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1]) self.assertAlmostEqual(record.motifs[5].score, 15.0441) self.assertEqual(record.motifs[6].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record.motifs[6].instances), 20) @@ -210,7 +210,7 @@ self.assertEqual(record.motifs[6].instances[17].tostring(), "GCTCGTCTATGGTCA") self.assertEqual(record.motifs[6].instances[18].tostring(), "GCGCATGCTGGATCC") self.assertEqual(record.motifs[6].instances[19].tostring(), "GGCCGTCAGCTCTCA") - self.assertEqual(record.motifs[6].mask, [1,1,0,1,1,1,1,0,1,0,1,0,0,1,1]) + self.assertEqual(record.motifs[6].mask, [1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1]) self.assertAlmostEqual(record.motifs[6].score, 13.3145) self.assertEqual(record.motifs[7].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record.motifs[7].instances), 20) @@ -234,7 +234,7 @@ self.assertEqual(record.motifs[7].instances[17].tostring(), "AGTCAATGACACGCGCCTGGG") self.assertEqual(record.motifs[7].instances[18].tostring(), "GGTCATGGAATCTTATGTAGC") self.assertEqual(record.motifs[7].instances[19].tostring(), "GTAGATAACAGAGGTCGGGGG") - self.assertEqual(record.motifs[7].mask, [1,0,0,1,0,0,0,1,1,0,0,1,1,0,0,0,1,1,0,1,1]) + self.assertEqual(record.motifs[7].mask, [1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1]) self.assertAlmostEqual(record.motifs[7].score, 11.6098) self.assertEqual(record.motifs[8].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record.motifs[8].instances), 14) @@ -252,7 +252,7 @@ self.assertEqual(record.motifs[8].instances[11].tostring(), "GAGATCCGGAGGAGG") self.assertEqual(record.motifs[8].instances[12].tostring(), "GCGATCCGAGGGCCG") self.assertEqual(record.motifs[8].instances[13].tostring(), "GAGTTCACATGGCTG") - self.assertEqual(record.motifs[8].mask, [1,0,1,0,0,1,1,0,1,1,1,1,1,0,1]) + self.assertEqual(record.motifs[8].mask, [1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1]) self.assertAlmostEqual(record.motifs[8].score, 11.2943) self.assertEqual(record.motifs[9].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record.motifs[9].instances), 18) @@ -274,7 +274,7 @@ self.assertEqual(record.motifs[9].instances[15].tostring(), "TCTAGGCGGGC") self.assertEqual(record.motifs[9].instances[16].tostring(), "AGTATGCTTAG") self.assertEqual(record.motifs[9].instances[17].tostring(), "TGGAGGCTTAG") - self.assertEqual(record.motifs[9].mask, [1,1,1,1,0,1,1,1,1,1,1]) + self.assertEqual(record.motifs[9].mask, [1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1]) self.assertAlmostEqual(record.motifs[9].score, 9.7924) self.assertEqual(record.motifs[10].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record.motifs[10].instances), 13) @@ -291,7 +291,7 @@ self.assertEqual(record.motifs[10].instances[10].tostring(), "ATCCTCTGCGTCGCATGGCGG") self.assertEqual(record.motifs[10].instances[11].tostring(), "GACCATAGACGAGCATCAAAG") self.assertEqual(record.motifs[10].instances[12].tostring(), "GGCCCTCGGATCGCTTGGGAA") - self.assertEqual(record.motifs[10].mask, [1,0,1,1,0,0,0,1,0,0,0,1,1,1,1,0,0,0,0,1,1]) + self.assertEqual(record.motifs[10].mask, [1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1]) self.assertAlmostEqual(record.motifs[10].score, 9.01393) self.assertEqual(record.motifs[11].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record.motifs[11].instances), 16) @@ -311,7 +311,7 @@ self.assertEqual(record.motifs[11].instances[13].tostring(), "GCGATCCGAG") self.assertEqual(record.motifs[11].instances[14].tostring(), "AGTGCGCGTC") self.assertEqual(record.motifs[11].instances[15].tostring(), "AGTGCCCGAG") - self.assertEqual(record.motifs[11].mask, [1,1,1,1,1,1,1,1,1,1]) + self.assertEqual(record.motifs[11].mask, [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) self.assertAlmostEqual(record.motifs[11].score, 7.51121) self.assertEqual(record.motifs[12].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record.motifs[12].instances), 16) @@ -331,7 +331,7 @@ self.assertEqual(record.motifs[12].instances[13].tostring(), "GCACGTAGCTGGTAAATAGG") self.assertEqual(record.motifs[12].instances[14].tostring(), "GCGGCGTGGATTTCATACAG") self.assertEqual(record.motifs[12].instances[15].tostring(), "CCTGGAGGCTTAGACTTGGG") - self.assertEqual(record.motifs[12].mask, [1,1,0,1,1,0,0,1,1,0,1,0,0,0,1,0,0,0,1,1]) + self.assertEqual(record.motifs[12].mask, [1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1]) self.assertAlmostEqual(record.motifs[12].score, 5.63667) self.assertEqual(record.motifs[13].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record.motifs[13].instances), 15) @@ -350,7 +350,7 @@ self.assertEqual(record.motifs[13].instances[12].tostring(), "ACGCACGGGACTTCAACCAG") self.assertEqual(record.motifs[13].instances[13].tostring(), "GCACGTAGCTGGTAAATAGG") self.assertEqual(record.motifs[13].instances[14].tostring(), "ATCCTCTGCGTCGCATGGCG") - self.assertEqual(record.motifs[13].mask, [1,1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,0,1,1]) + self.assertEqual(record.motifs[13].mask, [1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1]) self.assertAlmostEqual(record.motifs[13].score, 3.89842) self.assertEqual(record.motifs[14].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record.motifs[14].instances), 14) @@ -368,7 +368,7 @@ self.assertEqual(record.motifs[14].instances[11].tostring(), "TACTCCGGGTAC") self.assertEqual(record.motifs[14].instances[12].tostring(), "GACGCAGAGGAT") self.assertEqual(record.motifs[14].instances[13].tostring(), "TAGGCGGGCCAT") - self.assertEqual(record.motifs[14].mask, [1,1,1,1,1,0,1,1,1,0,1,1]) + self.assertEqual(record.motifs[14].mask, [1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1]) self.assertAlmostEqual(record.motifs[14].score, 3.33444) self.assertEqual(record.motifs[15].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record.motifs[15].instances), 21) @@ -393,20 +393,20 @@ self.assertEqual(record.motifs[15].instances[18].tostring(), "AGGCTCGCACGTAGCTGG") self.assertEqual(record.motifs[15].instances[19].tostring(), "CCACGCCGCCATGCGACG") self.assertEqual(record.motifs[15].instances[20].tostring(), "AGCCTCCAGGTCGCATGG") - self.assertEqual(record.motifs[15].mask, [1,1,0,1,0,1,0,0,1,1,0,1,1,0,0,0,1,1]) + self.assertEqual(record.motifs[15].mask, [1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1]) self.assertAlmostEqual(record.motifs[15].score, 1.0395) def test_pfm_parsing(self): """Test to be sure that Motif can parse pfm files. """ - motif= Motif.read(self.PFMin,"jaspar-pfm") - assert motif.length==12 + motif= Motif.read(self.PFMin, "jaspar-pfm") + self.assertEqual(motif.length, 12) def test_sites_parsing(self): """Test to be sure that Motif can parse sites files. """ - motif= Motif.read(self.SITESin,"jaspar-sites") - assert motif.length==6 + motif= Motif.read(self.SITESin, "jaspar-sites") + self.assertEqual(motif.length, 6) def test_FAoutput(self): """Ensure that we can write proper FASTA output files. diff -Nru python-biopython-1.62/Tests/test_Muscle_tool.py python-biopython-1.63/Tests/test_Muscle_tool.py --- python-biopython-1.62/Tests/test_Muscle_tool.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_Muscle_tool.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,6 +3,8 @@ # license. Please see the LICENSE file that should have been included # as part of this package. +from __future__ import print_function + import os import sys import subprocess @@ -32,11 +34,11 @@ #locations under Program Files... and then the full path. likely_dirs = ["", # Current dir prog_files, - os.path.join(prog_files,"Muscle3.6"), - os.path.join(prog_files,"Muscle3.7"), - os.path.join(prog_files,"Muscle3.8"), - os.path.join(prog_files,"Muscle3.9"), - os.path.join(prog_files,"Muscle")] + sys.path + os.path.join(prog_files, "Muscle3.6"), + os.path.join(prog_files, "Muscle3.7"), + os.path.join(prog_files, "Muscle3.8"), + os.path.join(prog_files, "Muscle3.9"), + os.path.join(prog_files, "Muscle")] + sys.path for folder in likely_dirs: if os.path.isdir(folder): if os.path.isfile(os.path.join(folder, "muscle.exe")): @@ -45,8 +47,8 @@ if muscle_exe: break else: - import commands - output = commands.getoutput("muscle -version") + from Bio._py3k import getoutput + output = getoutput("muscle -version") #Since "not found" may be in another language, try and be sure this is #really the MUSCLE tool's output if "not found" not in output and "MUSCLE" in output \ @@ -170,8 +172,8 @@ self.assertEqual(str(cmdline).rstrip(), "muscle -in Fasta/f002 -maxiters 2 -stable") result, out_handle, err_handle = generic_run(cmdline) #NOTE: generic_run has been removed from Biopython - print err_handle.read() - print out_handle.read() + print(err_handle.read()) + print(out_handle.read()) align = AlignIO.read(out_handle, "fasta") self.assertEqual(len(records),len(align)) for old, new in zip(records, align): @@ -183,7 +185,7 @@ """Simple muscle call using Clustal output with a MUSCLE header""" input_file = "Fasta/f002" self.assertTrue(os.path.isfile(input_file)) - records = list(SeqIO.parse(input_file,"fasta")) + records = list(SeqIO.parse(input_file, "fasta")) records.sort(key = lambda rec: rec.id) #Prepare the command... use Clustal output (with a MUSCLE header) cmdline = MuscleCommandline(muscle_exe, input=input_file, clw = True) @@ -204,16 +206,16 @@ child.stdout.close() child.stderr.close() del child - self.assertEqual(len(records),len(align)) + self.assertEqual(len(records), len(align)) for old, new in zip(records, align): self.assertEqual(old.id, new.id) - self.assertEqual(str(new.seq).replace("-",""), str(old.seq)) + self.assertEqual(str(new.seq).replace("-", ""), str(old.seq)) def test_simple_clustal_strict(self): """Simple muscle call using strict Clustal output""" input_file = "Fasta/f002" self.assertTrue(os.path.isfile(input_file)) - records = list(SeqIO.parse(input_file,"fasta")) + records = list(SeqIO.parse(input_file, "fasta")) records.sort(key = lambda rec: rec.id) #Prepare the command... cmdline = MuscleCommandline(muscle_exe) @@ -232,10 +234,10 @@ align = AlignIO.read(child.stdout, "clustal") align.sort() self.assertTrue(child.stderr.read().strip().startswith("MUSCLE")) - self.assertEqual(len(records),len(align)) + self.assertEqual(len(records), len(align)) for old, new in zip(records, align): self.assertEqual(old.id, new.id) - self.assertEqual(str(new.seq).replace("-",""), str(old.seq)) + self.assertEqual(str(new.seq).replace("-", ""), str(old.seq)) return_code = child.wait() self.assertEqual(return_code, 0) child.stdout.close() @@ -275,7 +277,7 @@ self.assertEqual(len(records), len(align)) for old, new in zip(records, align): self.assertEqual(old.id, new.id) - self.assertEqual(str(new.seq).replace("-",""), str(old.seq)) + self.assertEqual(str(new.seq).replace("-", ""), str(old.seq)) #See if quiet worked: self.assertEqual("", child.stderr.read().strip()) return_code = child.wait() @@ -289,7 +291,7 @@ """Simple alignment using stdin""" input_file = "Fasta/f002" self.assertTrue(os.path.isfile(input_file)) - records = list(SeqIO.parse(input_file,"fasta")) + records = list(SeqIO.parse(input_file, "fasta")) #Prepare the command... use Clustal output (with a MUSCLE header) cline = MuscleCommandline(muscle_exe, clw=True) self.assertEqual(str(cline).rstrip(), @@ -307,10 +309,10 @@ align = AlignIO.read(child.stdout, "clustal") align.sort() records.sort(key = lambda rec: rec.id) - self.assertEqual(len(records),len(align)) + self.assertEqual(len(records), len(align)) for old, new in zip(records, align): self.assertEqual(old.id, new.id) - self.assertEqual(str(new.seq).replace("-",""), str(old.seq)) + self.assertEqual(str(new.seq).replace("-", ""), str(old.seq)) self.assertEqual(0, child.wait()) child.stdout.close() child.stderr.close() @@ -322,7 +324,7 @@ output_html = "temp_f002.html" output_clwstrict = "temp_f002.clw" self.assertTrue(os.path.isfile(input_file)) - records = list(SeqIO.parse(input_file,"fasta")) + records = list(SeqIO.parse(input_file, "fasta")) records.sort(key = lambda rec: rec.id) #Prepare the command... use Clustal output (with a MUSCLE header) cmdline = MuscleCommandline(muscle_exe, input=input_file, @@ -344,13 +346,13 @@ self.assertTrue(child.stderr.read().strip().startswith("MUSCLE")) return_code = child.wait() self.assertEqual(return_code, 0) - self.assertEqual(len(records),len(align)) + self.assertEqual(len(records), len(align)) for old, new in zip(records, align): self.assertEqual(old.id, new.id) child.stdout.close() child.stderr.close() del child - handle = open(output_html,"rU") + handle = open(output_html, "rU") html = handle.read().strip().upper() handle.close() self.assertTrue(html.startswith("") if b[0].endswith("..."): self.assertTrue(a.title.startswith(">"+b[0][:-3])) else: self.assertEqual(a.title, ">" + b[0]) - self.assertEqual(None, records.next()) + self.assertEqual(None, next(records)) handle.close() def test_text_2220L_blastx_002(self): @@ -14247,7 +14252,7 @@ handle = open(path) records = NCBIStandalone.Iterator(handle, self.parser) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.20') self.assertEqual(record.date, "Feb-08-2009") @@ -14259,7 +14264,7 @@ self.assertEqual(len(record.descriptions), 0) self.assertEqual(len(record.alignments), 0) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.20') self.assertEqual(record.date, "Feb-08-2009") @@ -14271,7 +14276,7 @@ self.assertEqual(len(record.descriptions), 0) self.assertEqual(len(record.alignments), 0) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.20') self.assertEqual(record.date, "Feb-08-2009") @@ -14283,7 +14288,7 @@ self.assertEqual(len(record.descriptions), 0) self.assertEqual(len(record.alignments), 0) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.20') self.assertEqual(record.date, "Feb-08-2009") @@ -14303,19 +14308,19 @@ self.assertEqual(len(record.alignments[0].hsps), 2) self.assertEqual(record.alignments[0].hsps[0].expect, 8e-07) self.assertEqual(record.alignments[0].hsps[0].align_length, 40) - self.assertEqual(record.alignments[0].hsps[0].identities, (25,40)) + self.assertEqual(record.alignments[0].hsps[0].identities, (25, 40)) self.assertEqual(record.alignments[0].hsps[1].expect, 8e-07) self.assertEqual(record.alignments[0].hsps[1].align_length, 23) - self.assertEqual(record.alignments[0].hsps[1].identities, (12,23)) + self.assertEqual(record.alignments[0].hsps[1].identities, (12, 23)) self.assertEqual(len(record.alignments[1].hsps), 2) self.assertEqual(record.alignments[1].hsps[0].expect, 8e-07) self.assertEqual(record.alignments[1].hsps[0].align_length, 40) - self.assertEqual(record.alignments[1].hsps[0].identities, (25,40)) + self.assertEqual(record.alignments[1].hsps[0].identities, (25, 40)) self.assertEqual(record.alignments[1].hsps[1].expect, 8e-07) self.assertEqual(record.alignments[1].hsps[1].align_length, 23) - self.assertEqual(record.alignments[1].hsps[1].identities, (12,23)) + self.assertEqual(record.alignments[1].hsps[1].identities, (12, 23)) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.20') self.assertEqual(record.date, "Feb-08-2009") @@ -14327,7 +14332,7 @@ self.assertEqual(len(record.descriptions), 0) self.assertEqual(len(record.alignments), 0) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.20') self.assertEqual(record.date, "Feb-08-2009") @@ -14339,7 +14344,7 @@ self.assertEqual(len(record.descriptions), 0) self.assertEqual(len(record.alignments), 0) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.20') self.assertEqual(record.date, "Feb-08-2009") @@ -14351,7 +14356,7 @@ self.assertEqual(len(record.descriptions), 0) self.assertEqual(len(record.alignments), 0) - self.assertEqual(None, records.next()) + self.assertEqual(None, next(records)) handle.close() def test_text_2221L_blastp_001(self): @@ -14361,7 +14366,7 @@ handle = open(path) records = NCBIStandalone.Iterator(handle, self.parser) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTP") self.assertEqual(record.version, '2.2.21') self.assertEqual(record.date, "Jun-14-2009") @@ -14374,7 +14379,7 @@ self.assertEqual(len(record.alignments), 1) # I used -b 1 self.assertEqual(len(record.alignments[0].hsps), 1) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTP") self.assertEqual(record.version, '2.2.21') self.assertEqual(record.date, "Jun-14-2009") @@ -14387,7 +14392,7 @@ self.assertEqual(len(record.alignments), 1) # I used -b 1 self.assertEqual(len(record.alignments[0].hsps), 2) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTP") self.assertEqual(record.version, '2.2.21') self.assertEqual(record.date, "Jun-14-2009") @@ -14400,7 +14405,7 @@ self.assertEqual(len(record.alignments), 1) # I used -b 1 self.assertEqual(len(record.alignments[0].hsps), 1) - self.assertEqual(None, records.next()) + self.assertEqual(None, next(records)) handle.close() def test_text_2222L_blastx_001(self): @@ -14410,7 +14415,7 @@ handle = open(path) records = NCBIStandalone.Iterator(handle, self.parser) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.22') self.assertEqual(record.date, "Sep-27-2009") @@ -14423,7 +14428,7 @@ self.assertEqual(len(record.alignments), 1) # I used -b 1 self.assertEqual(len(record.alignments[0].hsps), 1) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.22') self.assertEqual(record.date, "Sep-27-2009") @@ -14436,7 +14441,7 @@ self.assertEqual(len(record.alignments), 1) # I used -b 1 self.assertEqual(len(record.alignments[0].hsps), 2) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.22') self.assertEqual(record.date, "Sep-27-2009") @@ -14448,7 +14453,7 @@ self.assertEqual(len(record.descriptions), 0) self.assertEqual(len(record.alignments), 0) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.22') self.assertEqual(record.date, "Sep-27-2009") @@ -14461,7 +14466,7 @@ self.assertEqual(len(record.alignments), 1) # I used -b 1 self.assertEqual(len(record.alignments[0].hsps), 1) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.22') self.assertEqual(record.date, "Sep-27-2009") @@ -14474,7 +14479,7 @@ self.assertEqual(len(record.alignments), 1) # I used -b 1 self.assertEqual(len(record.alignments[0].hsps), 2) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.22') self.assertEqual(record.date, "Sep-27-2009") @@ -14487,7 +14492,7 @@ self.assertEqual(len(record.alignments), 1) # I used -b 1 self.assertEqual(len(record.alignments[0].hsps), 1) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.22') self.assertEqual(record.date, "Sep-27-2009") @@ -14500,7 +14505,7 @@ self.assertEqual(len(record.alignments), 1) # I used -b 1 self.assertEqual(len(record.alignments[0].hsps), 1) - self.assertEqual(None, records.next()) + self.assertEqual(None, next(records)) handle.close() def test_text_2222_blastx_001(self): @@ -14510,7 +14515,7 @@ handle = open(path) records = NCBIStandalone.Iterator(handle, self.parser) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.22+') self.assertEqual(record.date, "") @@ -14523,7 +14528,7 @@ self.assertEqual(len(record.alignments), 1) # I used -b 1 self.assertEqual(len(record.alignments[0].hsps), 1) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.22+') self.assertEqual(record.date, "") @@ -14537,7 +14542,7 @@ #Two short HSPs with 2.2.22 (text_2222L_blastx_001.txt), but one with 2.2.22+ self.assertEqual(len(record.alignments[0].hsps), 1) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.22+') self.assertEqual(record.date, "") @@ -14549,7 +14554,7 @@ self.assertEqual(len(record.descriptions), 0) self.assertEqual(len(record.alignments), 0) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.22+') self.assertEqual(record.date, "") @@ -14562,7 +14567,7 @@ self.assertEqual(len(record.alignments), 1) # I used -b 1 self.assertEqual(len(record.alignments[0].hsps), 1) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.22+') self.assertEqual(record.date, "") @@ -14576,7 +14581,7 @@ #Two short HSPs with 2.2.22 (text_2222L_blastx_001.txt), but one with 2.2.22+ self.assertEqual(len(record.alignments[0].hsps), 1) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.22+') self.assertEqual(record.date, "") @@ -14589,7 +14594,7 @@ self.assertEqual(len(record.alignments), 1) # I used -b 1 self.assertEqual(len(record.alignments[0].hsps), 1) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.22+') self.assertEqual(record.date, "") @@ -14602,7 +14607,7 @@ self.assertEqual(len(record.alignments), 1) # I used -b 1 self.assertEqual(len(record.alignments[0].hsps), 1) - self.assertEqual(None, records.next()) + self.assertEqual(None, next(records)) handle.close() def test_text_2226_blastn_001(self): @@ -14612,7 +14617,7 @@ handle = open(path) records = NCBIStandalone.Iterator(handle, self.parser) - record = records.next() + record = next(records) self.assertEqual(record.application, 'BLASTN') self.assertEqual(record.version, '2.2.26+') self.assertEqual(record.query, 'random_s00') @@ -14623,7 +14628,7 @@ self.assertEqual(len(record.descriptions), 0) self.assertEqual(len(record.alignments), 0) - self.assertEqual(None, records.next()) + self.assertEqual(None, next(records)) handle.close() def test_text_2226_blastn_002(self): @@ -14633,7 +14638,7 @@ handle = open(path) records = NCBIStandalone.Iterator(handle, self.parser) - record = records.next() + record = next(records) self.assertEqual(record.application, 'BLASTN') self.assertEqual(record.version, '2.2.26+') self.assertEqual(record.query, 'gi|356995852:1-490 Mus musculus POU domain, class 5, transcription\nfactor 1 (Pou5f1), transcript variant 1, mRNA') @@ -14646,7 +14651,7 @@ for ali in record.alignments: self.assertEqual(len(ali.hsps), 1) - self.assertEqual(None, records.next()) + self.assertEqual(None, next(records)) handle.close() def test_text_2226_blastn_003(self): @@ -14656,7 +14661,7 @@ handle = open(path) records = NCBIStandalone.Iterator(handle, self.parser) - record = records.next() + record = next(records) self.assertEqual(record.application, 'BLASTN') self.assertEqual(record.version, '2.2.26+') self.assertEqual(record.query, "hg19_dna range=chr1:1207307-1207372 5'pad=0 3'pad=0 strand=+\nrepeatMasking=none") @@ -14672,7 +14677,7 @@ else: self.assertEqual(len(ali.hsps), 1) - self.assertEqual(None, records.next()) + self.assertEqual(None, next(records)) handle.close() def test_text_2226_blastp_001(self): @@ -14682,7 +14687,7 @@ handle = open(path) records = NCBIStandalone.Iterator(handle, self.parser) - record = records.next() + record = next(records) self.assertEqual(record.application, 'BLASTP') self.assertEqual(record.version, '2.2.26+') self.assertEqual(record.query, 'random_s00') @@ -14693,7 +14698,7 @@ self.assertEqual(len(record.descriptions), 0) self.assertEqual(len(record.alignments), 0) - self.assertEqual(None, records.next()) + self.assertEqual(None, next(records)) handle.close() def test_text_2226_blastp_002(self): @@ -14703,7 +14708,7 @@ handle = open(path) records = NCBIStandalone.Iterator(handle, self.parser) - record = records.next() + record = next(records) self.assertEqual(record.application, 'BLASTP') self.assertEqual(record.version, '2.2.26+') self.assertEqual(record.query, 'gi|16080617|ref|NP_391444.1| membrane bound lipoprotein [Bacillus\nsubtilis subsp. subtilis str. 168]') @@ -14716,7 +14721,7 @@ for ali in record.alignments: self.assertEqual(len(ali.hsps), 1) - self.assertEqual(None, records.next()) + self.assertEqual(None, next(records)) handle.close() def test_text_2226_blastp_003(self): @@ -14726,7 +14731,7 @@ handle = open(path) records = NCBIStandalone.Iterator(handle, self.parser) - record = records.next() + record = next(records) self.assertEqual(record.application, 'BLASTP') self.assertEqual(record.version, '2.2.26+') self.assertEqual(record.query, "gi|11464971:4-101 pleckstrin [Mus musculus]") @@ -14742,7 +14747,7 @@ else: self.assertEqual(len(ali.hsps), 2) - self.assertEqual(None, records.next()) + self.assertEqual(None, next(records)) handle.close() def test_text_2226_blastx_001(self): @@ -14752,7 +14757,7 @@ handle = open(path) records = NCBIStandalone.Iterator(handle, self.parser) - record = records.next() + record = next(records) self.assertEqual(record.application, 'BLASTX') self.assertEqual(record.version, '2.2.26+') self.assertEqual(record.query, 'random_s00') @@ -14771,7 +14776,7 @@ handle = open(path) records = NCBIStandalone.Iterator(handle, self.parser) - record = records.next() + record = next(records) self.assertEqual(record.application, 'BLASTX') self.assertEqual(record.version, '2.2.26+') self.assertEqual(record.query, 'gi|356995852:1-490 Mus musculus POU domain, class 5, transcription\nfactor 1 (Pou5f1), transcript variant 1, mRNA') @@ -14784,7 +14789,7 @@ for ali in record.alignments: self.assertEqual(len(ali.hsps), 1) - self.assertEqual(None, records.next()) + self.assertEqual(None, next(records)) handle.close() def test_text_2226_blastx_003(self): @@ -14794,7 +14799,7 @@ handle = open(path) records = NCBIStandalone.Iterator(handle, self.parser) - record = records.next() + record = next(records) self.assertEqual(record.application, 'BLASTX') self.assertEqual(record.version, '2.2.26+') self.assertEqual(record.query, "hg19_dna range=chr1:1207057-1207541 5'pad=0 3'pad=0 strand=+\nrepeatMasking=none") @@ -14810,7 +14815,7 @@ else: self.assertEqual(len(ali.hsps), 2) - self.assertEqual(None, records.next()) + self.assertEqual(None, next(records)) handle.close() def test_text_2226_tblastn_001(self): @@ -14820,7 +14825,7 @@ handle = open(path) records = NCBIStandalone.Iterator(handle, self.parser) - record = records.next() + record = next(records) self.assertEqual(record.application, 'TBLASTN') self.assertEqual(record.version, '2.2.26+') self.assertEqual(record.query, 'random_s00') @@ -14831,7 +14836,7 @@ self.assertEqual(len(record.descriptions), 0) self.assertEqual(len(record.alignments), 0) - self.assertEqual(None, records.next()) + self.assertEqual(None, next(records)) handle.close() def test_text_2226_tblastn_002(self): @@ -14841,7 +14846,7 @@ handle = open(path) records = NCBIStandalone.Iterator(handle, self.parser) - record = records.next() + record = next(records) self.assertEqual(record.application, 'TBLASTN') self.assertEqual(record.version, '2.2.26+') self.assertEqual(record.query, 'gi|16080617|ref|NP_391444.1| membrane bound lipoprotein [Bacillus\nsubtilis subsp. subtilis str. 168]') @@ -14854,7 +14859,7 @@ for ali in record.alignments: self.assertEqual(len(ali.hsps), 1) - self.assertEqual(None, records.next()) + self.assertEqual(None, next(records)) handle.close() def test_text_2226_tblastn_003(self): @@ -14864,7 +14869,7 @@ handle = open(path) records = NCBIStandalone.Iterator(handle, self.parser) - record = records.next() + record = next(records) self.assertEqual(record.application, 'TBLASTN') self.assertEqual(record.version, '2.2.26+') self.assertEqual(record.query, "gi|11464971:4-101 pleckstrin [Mus musculus]") @@ -14880,7 +14885,7 @@ else: self.assertEqual(len(ali.hsps), 2) - self.assertEqual(None, records.next()) + self.assertEqual(None, next(records)) handle.close() def test_text_2226_tblastx_001(self): @@ -14890,7 +14895,7 @@ handle = open(path) records = NCBIStandalone.Iterator(handle, self.parser) - record = records.next() + record = next(records) self.assertEqual(record.application, 'TBLASTX') self.assertEqual(record.version, '2.2.26+') self.assertEqual(record.query, 'random_s00') @@ -14901,7 +14906,7 @@ self.assertEqual(len(record.descriptions), 0) self.assertEqual(len(record.alignments), 0) - self.assertEqual(None, records.next()) + self.assertEqual(None, next(records)) handle.close() def test_text_2226_tblastx_002(self): @@ -14911,7 +14916,7 @@ handle = open(path) records = NCBIStandalone.Iterator(handle, self.parser) - record = records.next() + record = next(records) self.assertEqual(record.application, 'TBLASTX') self.assertEqual(record.version, '2.2.26+') self.assertEqual(record.query, 'gi|356995852:1-490 Mus musculus POU domain, class 5, transcription\nfactor 1 (Pou5f1), transcript variant 1, mRNA') @@ -14924,7 +14929,7 @@ for ali in record.alignments: self.assertEqual(len(ali.hsps), 1) - self.assertEqual(None, records.next()) + self.assertEqual(None, next(records)) handle.close() def test_text_2226_tblastx_003(self): @@ -14934,7 +14939,7 @@ handle = open(path) records = NCBIStandalone.Iterator(handle, self.parser) - record = records.next() + record = next(records) self.assertEqual(record.application, 'TBLASTX') self.assertEqual(record.version, '2.2.26+') self.assertEqual(record.query, "hg19_dna range=chr1:1207057-1207541 5'pad=0 3'pad=0 strand=+\nrepeatMasking=none") @@ -14950,7 +14955,7 @@ else: self.assertEqual(len(ali.hsps), 3) - self.assertEqual(None, records.next()) + self.assertEqual(None, next(records)) handle.close() diff -Nru python-biopython-1.62/Tests/test_NCBIXML.py python-biopython-1.63/Tests/test_NCBIXML.py --- python-biopython-1.62/Tests/test_NCBIXML.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_NCBIXML.py 2013-12-05 14:10:43.000000000 +0000 @@ -19,7 +19,7 @@ datafile = os.path.join("Blast", filename) handle = open(datafile) records = NCBIXML.parse(handle) - record = records.next() + record = next(records) alignments = record.alignments self.assertEqual(len(alignments), 212) @@ -1390,7 +1390,7 @@ self.assertEqual(len(alignment.hsps), 1) self.assertTrue(alignment.hsps[0].expect > E_VALUE_THRESH) - self.assertRaises(StopIteration, records.next) + self.assertRaises(StopIteration, next, records) handle.close() handle = open(datafile) @@ -1404,7 +1404,7 @@ datafile = os.path.join("Blast", filename) handle = open(datafile) records = NCBIXML.parse(handle) - record = records.next() + record = next(records) alignments = record.alignments self.assertEqual(record.query_id, "gi|1348916|gb|G26684.1|G26684") @@ -1419,7 +1419,7 @@ self.assertEqual(len(alignments[1].hsps), 1) self.assertTrue(alignments[1].hsps[0].expect > E_VALUE_THRESH) - self.assertRaises(StopIteration, records.next) + self.assertRaises(StopIteration, next, records) handle.close() handle = open(datafile) @@ -1434,12 +1434,12 @@ handle = open(datafile) records = NCBIXML.parse(handle) - record = records.next() + record = next(records) alignments = record.alignments self.assertEqual(record.query_id, "gi|1347369|gb|G25137.1|G25137") self.assertEqual(len(alignments), 78) self.assertEqual(sum([len(a.hsps) for a in alignments]), 84) - self.assertRaises(StopIteration, records.next) + self.assertRaises(StopIteration, next, records) handle.close() handle = open(datafile) @@ -1454,12 +1454,12 @@ handle = open(datafile) records = NCBIXML.parse(handle) - record = records.next() + record = next(records) alignments = record.alignments self.assertEqual(record.query_id, "gi|729325|sp|P39483|DHG2_BACME") self.assertEqual(len(alignments), 100) self.assertEqual(sum([len(a.hsps) for a in alignments]), 127) - self.assertRaises(StopIteration, records.next) + self.assertRaises(StopIteration, next, records) handle.close() handle = open(datafile) @@ -1474,12 +1474,12 @@ handle = open(datafile) records = NCBIXML.parse(handle) - record = records.next() + record = next(records) alignments = record.alignments self.assertEqual(record.query_id, "gi|1348853|gb|G26621.1|G26621") self.assertEqual(len(alignments), 10) self.assertEqual(sum([len(a.hsps) for a in alignments]), 102) - self.assertRaises(StopIteration, records.next) + self.assertRaises(StopIteration, next, records) handle.close() handle = open(datafile) @@ -1496,7 +1496,7 @@ handle = open(datafile) records = NCBIXML.parse(handle) - record = records.next() + record = next(records) alignments = record.alignments self.assertEqual(record.query_id, "31493") self.assertEqual(len(alignments), 10) @@ -1546,7 +1546,7 @@ self.assertTrue(alignments[9].hsps[0].expect > E_VALUE_THRESH) self.assertTrue(alignments[9].hsps[1].expect > E_VALUE_THRESH) - self.assertRaises(StopIteration, records.next) + self.assertRaises(StopIteration, next, records) handle.close() handle = open(datafile) @@ -1560,14 +1560,14 @@ datafile = os.path.join("Blast", filename) handle = open(datafile) records = NCBIXML.parse(handle) - record = records.next() + record = next(records) self.assertEqual(record.query_id, "gi|585505|sp|Q08386|MOPB_RHOCA") alignments = record.alignments self.assertEqual(len(record.alignments), 0) - record = records.next() + record = next(records) self.assertEqual(record.query_id, "gi|129628|sp|P07175.1|PARA_AGRTU") self.assertEqual(len(record.alignments), 0) - self.assertRaises(StopIteration, records.next) + self.assertRaises(StopIteration, next, records) handle.close() def test_xml_2218L_blastp_001(self): @@ -1578,11 +1578,11 @@ handle = open(datafile) records = NCBIXML.parse(handle) - record = records.next() + record = next(records) self.assertEqual(record.query_id, "lcl|1_0") alignments = record.alignments self.assertEqual(len(alignments), 0) - self.assertRaises(StopIteration, records.next) + self.assertRaises(StopIteration, next, records) handle.close() handle = open(datafile) @@ -1599,7 +1599,7 @@ handle = open(datafile) records = NCBIXML.parse(handle) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.22+') self.assertEqual(record.date, "") @@ -1614,7 +1614,7 @@ self.assertEqual(len(record.alignments), 1) self.assertEqual(len(record.alignments[0].hsps), 1) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.22+') self.assertEqual(record.date, "") @@ -1632,7 +1632,7 @@ self.assertEqual(len(record.alignments[1].hsps), 2) self.assertEqual(len(record.alignments[9].hsps), 2) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.22+') self.assertEqual(record.date, "") @@ -1646,7 +1646,7 @@ self.assertEqual(len(record.descriptions), 0) self.assertEqual(len(record.alignments), 0) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.22+') self.assertEqual(record.date, "") @@ -1662,7 +1662,7 @@ self.assertEqual(len(record.alignments[0].hsps), 1) self.assertEqual(len(record.alignments[9].hsps), 1) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.22+') self.assertEqual(record.date, "") @@ -1678,7 +1678,7 @@ self.assertEqual(len(record.alignments[0].hsps), 2) self.assertEqual(len(record.alignments[9].hsps), 1) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.22+') self.assertEqual(record.date, "") @@ -1694,7 +1694,7 @@ self.assertEqual(len(record.alignments[0].hsps), 1) self.assertEqual(len(record.alignments[9].hsps), 1) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTX") self.assertEqual(record.version, '2.2.22+') self.assertEqual(record.date, "") @@ -1710,7 +1710,7 @@ self.assertEqual(len(record.alignments[0].hsps), 1) self.assertEqual(len(record.alignments[9].hsps), 1) - self.assertRaises(StopIteration, records.next) + self.assertRaises(StopIteration, next, records) handle.close() def test_xml_2222_blastp_001(self): @@ -1723,7 +1723,7 @@ handle = open(datafile) records = NCBIXML.parse(handle) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTP") self.assertEqual(record.version, '2.2.22+') self.assertEqual(record.date, "") @@ -1738,19 +1738,19 @@ self.assertEqual(len(record.alignments), 10) self.assertEqual(len(record.alignments[0].hsps), 1) - record = records.next() + record = next(records) self.assertEqual(record.query, "gi|2781234|pdb|1JLY|B Chain B, Crystal Structure Of Amaranthus Caudatus Agglutinin") self.assertEqual(record.query_letters, 304) - record = records.next() + record = next(records) self.assertEqual(record.query, "gi|4959044|gb|AAD34209.1|AF069992_1 LIM domain interacting RING finger protein") self.assertEqual(record.query_letters, 600) - record = records.next() + record = next(records) self.assertEqual(record.query, "gi|671626|emb|CAA85685.1| rubisco large subunit") self.assertEqual(record.query_letters, 473) - self.assertRaises(StopIteration, records.next) + self.assertRaises(StopIteration, next, records) handle.close() def test_xml_2218L_rpsblast_001(self): @@ -1766,7 +1766,7 @@ handle = open(datafile) records = NCBIXML.parse(handle) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTP") self.assertEqual(record.version, '2.2.18') self.assertEqual(record.date, "Mar-02-2008") @@ -1807,7 +1807,7 @@ self.assertEqual(hsp.sbjct_start, 1) self.assertEqual(hsp.sbjct_end, 76) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTP") self.assertEqual(record.version, '2.2.18') self.assertEqual(record.date, "Mar-02-2008") @@ -1834,7 +1834,7 @@ self.assertEqual(hsp.sbjct_start, 1) self.assertEqual(hsp.sbjct_end, 131) - record = records.next() + record = next(records) self.assertEqual(record.application, "BLASTP") self.assertEqual(record.version, '2.2.18') self.assertEqual(record.date, "Mar-02-2008") @@ -1863,7 +1863,7 @@ #TODO - Can we detect the convergence status: #CONVERGED - self.assertRaises(StopIteration, records.next) + self.assertRaises(StopIteration, next, records) handle.close() diff -Nru python-biopython-1.62/Tests/test_NCBI_BLAST_tools.py python-biopython-1.63/Tests/test_NCBI_BLAST_tools.py --- python-biopython-1.62/Tests/test_NCBI_BLAST_tools.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_NCBI_BLAST_tools.py 2013-12-05 14:10:43.000000000 +0000 @@ -7,6 +7,8 @@ # database, and if it finds them then do some standalone blast searches # using Bio.Blast.NCBIStandalone to call the command line tool. +from __future__ import print_function + import os import sys import subprocess @@ -36,7 +38,7 @@ for folder in likely_dirs: if not os.path.isdir(folder): continue - for name in wanted : + for name in wanted: if sys.platform=="win32": exe_name = os.path.join(folder, name+".exe") else: @@ -58,8 +60,8 @@ if name == "blast_formatter" and " -archive " not in output: continue exe_names[name] = exe_name - #else : - # print "Rejecting", exe_name + #else: + # print("Rejecting %r" % exe_name) del exe_name, name #To avoid the name clash with legacy BLAST, Debian introduced rpsblast+ alias @@ -180,7 +182,7 @@ assert index != -1 name = stdoutdata[:index] if " " in name: - name = name.split(None,1)[0] + name = name.split(None, 1)[0] names_in_tool.add(name) stdoutdata = stdoutdata[index+1:] @@ -207,8 +209,8 @@ if exe_name == "tblastx": #These appear to have been removed in BLAST 2.2.23+ #(which seems a bit odd - TODO - check with NCBI?) - extra = extra.difference(["-gapextend","-gapopen", - "-xdrop_gap","-xdrop_gap_final"]) + extra = extra.difference(["-gapextend", "-gapopen", + "-xdrop_gap", "-xdrop_gap_final"]) if exe_name in ["rpsblast", "rpstblastn"]: #These appear to have been removed in BLAST 2.2.24+ #(which seems a bit odd - TODO - check with NCBI?) diff -Nru python-biopython-1.62/Tests/test_NCBI_qblast.py python-biopython-1.63/Tests/test_NCBI_qblast.py --- python-biopython-1.62/Tests/test_NCBI_qblast.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_NCBI_qblast.py 2013-12-05 14:10:43.000000000 +0000 @@ -12,10 +12,13 @@ Make sure that all retrieval is working as expected. Make sure we can parse the latest XML format being used by the NCBI. """ +from __future__ import print_function + +from Bio._py3k import HTTPError + import requires_internet requires_internet.check() from Bio import MissingExternalDependencyError -from urllib2 import HTTPError #We want to test these: from Bio.Blast import NCBIWWW @@ -35,10 +38,10 @@ #Simple protein blast filtered for rat only, using protein GI:160837788 #the actin related protein 2/3 complex, subunit 1B [Mus musculus] ("blastp", "nr", "160837788", 0.001, - "rat [ORGN]", ['9506405','13592137','37589612','149064087','56912225']), + "rat [ORGN]", ['9506405', '13592137', '37589612', '149064087', '56912225']), #This next example finds PCR primer matches in Chimpanzees, e.g. BRCA1: ("blastn", "nr", "GTACCTTGATTTCGTATTC"+("N"*30)+"GACTCTACTACCTTTACCC", - 10, "pan [ORGN]", ["37953274","51104367","51104367","51104367"]), + 10, "pan [ORGN]", ["37953274", "51104367", "51104367", "51104367"]), #Try an orchid EST (nucleotide) sequence against NR using BLASTX ("blastx", "nr", """>gi|116660609|gb|EG558220.1|EG558220 CR02019H04 Leaf CR02 cDNA library Catharanthus roseus cDNA clone CR02019H04 5', mRNA sequence CTCCATTCCCTCTCTATTTTCAGTCTAATCAAATTAGAGCTTAAAAGAATGAGATTTTTAACAAATAAAA @@ -50,12 +53,12 @@ AGCCATGGATTTCTCAGAAGAAAATGATTATACTTCTTAATCAGGCAACTGATATTATCAATTTATGGCA GCAGAGTGGTGGCTCCTTGTCCCAGCAGCAGTAATTACTTTTTTTTCTCTTTTTGTTTCCAAATTAAGAA ACATTAGTATCATATGGCTATTTGCTCAATTGCAGATTTCTTTCTTTTGTGAATG""", - 0.0000001, None, ["21554275","18409071","296087288"]), + 0.0000001, None, ["21554275", "18409071", "296087288"]), ] -print "Checking Bio.Blast.NCBIWWW.qblast() with various queries" -for program,database,query,e_value,entrez_filter,expected_hits in tests: - print "qblast('%s', '%s', %s, ...)" % (program, database, repr(query)) +print("Checking Bio.Blast.NCBIWWW.qblast() with various queries") +for program, database, query, e_value, entrez_filter, expected_hits in tests: + print("qblast('%s', '%s', %s, ...)" % (program, database, repr(query))) try: if program=="blastn": #Check the megablast parameter is accepted @@ -80,7 +83,7 @@ assert len(query) == record.query_letters elif query.startswith(">"): #We used a FASTA record as the query - assert query[1:].split("\n",1)[0] == (record.query) + assert query[1:].split("\n", 1)[0] == (record.query) else: #We used an identifier as the query assert query in record.query_id.split("|") @@ -103,9 +106,9 @@ found_result = True break if len(expected_hits)==1: - print "Update this test to have some redundancy..." + print("Update this test to have some redundancy...") for alignment in record.alignments: - print alignment.hit_id + print(alignment.hit_id) assert found_result, "Missing all of %s in alignments" \ % ", ".join(expected_hits) @@ -118,9 +121,9 @@ for expected_hit in expected_hits: for descr in record.descriptions: if expected_hit == descr.accession \ - or expected_hit in descr.title.split(None,1)[0].split("|"): + or expected_hit in descr.title.split(None, 1)[0].split("|"): found_result = True break assert found_result, "Missing all of %s in descriptions" % expected_hit -print "Done" +print("Done") diff -Nru python-biopython-1.62/Tests/test_NNExclusiveOr.py python-biopython-1.63/Tests/test_NNExclusiveOr.py --- python-biopython-1.62/Tests/test_NNExclusiveOr.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_NNExclusiveOr.py 2013-12-05 14:10:43.000000000 +0000 @@ -4,6 +4,8 @@ This is a very basic test of Neural Network functionality. """ # Neural Network code we'll be using +from __future__ import print_function + from Bio.NeuralNetwork.Training import TrainingExample from Bio.NeuralNetwork.BackPropagation import Layer from Bio.NeuralNetwork.BackPropagation.Network import BasicNetwork @@ -17,7 +19,7 @@ Since we have so few examples, we use all of them for training, validation and testing. """ - print "Setting up training examples..." + print("Setting up training examples...") # set up the training examples examples = [] examples.append(TrainingExample([0, 0], [0])) @@ -32,19 +34,19 @@ network = BasicNetwork(input, hidden, output) - print "Training the network..." + print("Training the network...") # train it learning_rate = .5 momentum = .1 network.train(examples, examples, stopping_criteria, learning_rate, momentum) - print "Predicting..." + print("Predicting...") # try predicting for example in examples: prediction = network.predict(example.inputs) if VERBOSE: - print "%s;%s=> %s" % (example.inputs, example.outputs, prediction) + print("%s;%s=> %s" % (example.inputs, example.outputs, prediction)) def stopping_criteria(num_iterations, validation_error, training_error): @@ -52,10 +54,9 @@ """ if num_iterations % 100 == 0: if VERBOSE: - print "error:", validation_error + print("error: %s" % validation_error) if num_iterations >= 2000: - return 1 - - return 0 + return True + return False main() diff -Nru python-biopython-1.62/Tests/test_NNGene.py python-biopython-1.63/Tests/test_NNGene.py --- python-biopython-1.62/Tests/test_NNGene.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_NNGene.py 2013-12-05 14:10:43.000000000 +0000 @@ -10,6 +10,8 @@ genes, as well as generic Pattern methods. """ # standard library +from __future__ import print_function + import os import unittest @@ -58,9 +60,9 @@ input_handle = open(self.test_file, "r") read_motifs = self.pattern_io.read(input_handle) input_handle.close() - assert read_motifs == motifs, \ - "Failed to get back expected motifs %s, got %s" \ - % (motifs, read_motifs) + self.assertEqual(read_motifs, motifs, + "Failed to get back expected motifs %s, got %s" + % (motifs, read_motifs)) # write seqs seq_motifs = [] @@ -74,9 +76,9 @@ input_handle = open(self.test_file, "r") read_motifs = self.pattern_io.read(input_handle) input_handle.close() - assert read_motifs == motifs, \ - "Failed to get back expected motifs %s from seqs, got %s" \ - % (motifs, read_motifs) + self.assertEqual(read_motifs, motifs, + "Failed to get back expected motifs %s from seqs, got %s" + % (motifs, read_motifs)) def test_schema(self): """Reading and writing schemas to a file. @@ -91,9 +93,9 @@ input_handle = open(self.test_file, "r") read_schemas = self.pattern_io.read(input_handle) input_handle.close() - assert schemas == read_schemas, \ - "Read incorrect schemas %s, expected %s." \ - % (read_schemas, schemas) + self.assertEqual(schemas, read_schemas, + "Read incorrect schemas %s, expected %s." + % (read_schemas, schemas)) # --- make sure inappropriate alphabets are reported schemas = ["GTR", "G*C"] # '*' not in the unambigous alphabet @@ -123,9 +125,9 @@ input_handle = open(self.test_file, "r") read_sigs = self.pattern_io.read(input_handle) input_handle.close() - assert read_sigs == signatures, \ - "Got back unexpected signatures %s, wanted %s" \ - % (read_sigs, signatures) + self.assertEqual(read_sigs, signatures, + "Got back unexpected signatures %s, wanted %s" + % (read_sigs, signatures)) class PatternRepositoryTest(unittest.TestCase): @@ -145,78 +147,83 @@ """ all_motifs = self.repository.get_all() - assert all_motifs == ["GATC", "GGGG", "GTAG", "AAAA", "ATAT"], \ - "Unexpected motifs returned %s" % all_motifs + self.assertEqual(all_motifs, + ["GATC", "GGGG", "GTAG", "AAAA", "ATAT"], + "Unexpected motifs returned %s" % all_motifs) def test_get_random(self): """Retrieve random patterns from the repository. """ for num_patterns in range(5): patterns = self.repository.get_random(num_patterns) - assert len(patterns) == num_patterns, \ - "Got unexpected number of patterns %s, expected %s" \ - % (len(patterns), num_patterns) + self.assertEqual(len(patterns), num_patterns, + "Got unexpected number of patterns %s, expected %s" + % (len(patterns), num_patterns)) for pattern in patterns: - assert pattern in self.motifs.keys(), \ - "Got unexpected pattern %s" % pattern + self.assertTrue(pattern in list(self.motifs.keys()), + "Got unexpected pattern %s" % pattern) def test_get_top_percentage(self): """Retrieve the top percentge of patterns from the repository. """ for num_patterns, percentage in ((1, 0.2), (2, .4), (5, 1.0)): patterns = self.repository.get_top_percentage(percentage) - assert len(patterns) == num_patterns, \ - "Got unexpected number of patterns %s, expected %s" \ - % (len(patterns), num_patterns) + self.assertEqual(len(patterns), num_patterns, + "Got unexpected number of patterns %s, expected %s" + % (len(patterns), num_patterns)) for pattern in patterns: - assert pattern in self.motifs.keys(), \ - "Got unexpected pattern %s" % pattern + self.assertTrue(pattern in list(self.motifs.keys()), + "Got unexpected pattern %s" % pattern) def test_get_top(self): """Retrieve a certain number of the top patterns. """ for num_patterns in range(5): patterns = self.repository.get_top(num_patterns) - assert len(patterns) == num_patterns, \ - "Got unexpected number of patterns %s, expected %s" \ - % (len(patterns), num_patterns) + self.assertEqual(len(patterns), num_patterns, + "Got unexpected number of patterns %s, expected %s" + % (len(patterns), num_patterns)) for pattern in patterns: - assert pattern in self.motifs.keys(), \ - "Got unexpected pattern %s" % pattern + self.assertTrue(pattern in list(self.motifs.keys()), + "Got unexpected pattern %s" % pattern) def test_get_differing(self): """Retrieve patterns from both sides of the list (top and bottom). """ patterns = self.repository.get_differing(2, 2) - assert patterns == ["GATC", "GGGG", "AAAA", "ATAT"], \ - "Got unexpected patterns %s" % patterns + self.assertEqual(patterns, + ["GATC", "GGGG", "AAAA", "ATAT"], + "Got unexpected patterns %s" % patterns) def test_remove_polyA(self): """Test the ability to remove A rich patterns from the repository. """ patterns = self.repository.get_all() - assert len(patterns) == 5, "Unexpected starting: %s" % patterns + self.assertEqual(len(patterns), 5, + "Unexpected starting: %s" % patterns) self.repository.remove_polyA() patterns = self.repository.get_all() - assert len(patterns) == 3, "Unexpected ending: %s" % patterns - assert patterns == ["GATC", "GGGG", "GTAG"], \ - "Unexpected patterns: %s" % patterns + self.assertEqual(len(patterns), 3, + "Unexpected ending: %s" % patterns) + self.assertEqual(patterns, + ["GATC", "GGGG", "GTAG"], + "Unexpected patterns: %s" % patterns) def test_count(self): """Retrieve counts for particular patterns in the repository. """ num_times = self.repository.count("GGGG") - assert num_times == 10, \ - "Did not count item in the respository: %s" % num_times + self.assertEqual(num_times, 10, + "Did not count item in the respository: %s" % num_times) num_times = self.repository.count("NOT_IN_THERE") - assert num_times == 0, \ - "Counted items not in repository: %s" % num_times + self.assertEqual(num_times, 0, + "Counted items not in repository: %s" % num_times) # --- Tests for motifs @@ -239,9 +246,9 @@ iterator = SeqIO.parse(handle, "fasta", alphabet=IUPAC.unambiguous_dna) - while 1: + while True: try: - seq_record = iterator.next() + seq_record = next(iterator) except StopIteration: break if seq_record is None: @@ -259,8 +266,8 @@ motif_repository = self.motif_finder.find(self.test_records, 8) top_motif = motif_repository.get_top(1) - assert top_motif[0] == 'TTGGAAAG', \ - "Got unexpected motif %s" % top_motif[0] + self.assertEqual(top_motif[0], 'TTGGAAAG', + "Got unexpected motif %s" % top_motif[0]) def test_find_differences(self): """Find the difference in motif counts between two sets of sequences. @@ -271,8 +278,10 @@ top, bottom = motif_repository.get_differing(1, 1) - assert top == "TTGGAAAG", "Got unexpected top motif %s" % top - assert bottom == "AATGGCAT", "Got unexpected bottom motif %s" % bottom + self.assertEqual(top, "TTGGAAAG", + "Got unexpected top motif %s" % top) + self.assertEqual(bottom, "AATGGCAT", + "Got unexpected bottom motif %s" % bottom) class MotifCoderTest(unittest.TestCase): @@ -293,9 +302,9 @@ seq_to_code = Seq(match_string, IUPAC.unambiguous_dna) matches = self.coder.representation(seq_to_code) - assert matches == expected, \ - "Did not match representation, expected %s, got %s" \ - % (expected, matches) + self.assertEqual(matches, expected, + "Did not match representation, expected %s, got %s" + % (expected, matches)) # --- Tests for schemas @@ -326,8 +335,9 @@ for motif, expected in self.match_info: found_matches = self.motif_coder.find_matches(motif, self.match_string) - assert found_matches == expected, "Expected %s, got %s" \ - % (expected, found_matches) + self.assertEqual(found_matches, expected, + "Expected %s, got %s" + % (expected, found_matches)) def test_num_matches(self): """Find how many matches are present in a sequence. @@ -335,8 +345,9 @@ for motif, expected in self.match_info: num_matches = self.motif_coder.num_matches(motif, self.match_string) - assert num_matches == len(expected), \ - "Expected %s, got %s" % (num_matches, len(expected)) + self.assertEqual(num_matches, len(expected), + "Expected %s, got %s" + % (num_matches, len(expected))) def test_find_ambiguous(self): """Find the positions of ambiguous items in a sequence. @@ -348,9 +359,9 @@ for motif, expected in ambig_info: found_positions = self.motif_coder.find_ambiguous(motif) - assert found_positions == expected, \ - "Expected %s, got %s for %s" % (expected, found_positions, - motif) + self.assertEqual(found_positions, expected, + "Expected %s, got %s for %s" + % (expected, found_positions, motif)) def test_num_ambiguous(self): """Find the number of ambiguous items in a sequence. @@ -362,8 +373,9 @@ for motif, expected in ambig_info: found_num = self.motif_coder.num_ambiguous(motif) - assert found_num == expected, \ - "Expected %s, got %s for %s" % (expected, found_num, motif) + self.assertEqual(found_num, expected, + "Expected %s, got %s for %s" + % (expected, found_num, motif)) def test_motif_cache(self): """Make sure motif compiled regular expressions are cached properly. @@ -373,7 +385,7 @@ self.motif_coder.find_matches(test_motif, "GATCGATC") self.assertTrue(test_motif in self.motif_coder._motif_cache, - "Did not find motif cached properly.") + "Did not find motif cached properly.") # make sure we don't bomb out if we use the same motif twice self.motif_coder.find_matches(test_motif, "GATCGATC") @@ -384,8 +396,8 @@ found_unambig = self.motif_coder.all_unambiguous() expected = ["A", "C", "G", "T"] - assert found_unambig == expected, \ - "Got %s, expected %s" % (found_unambig, expected) + self.assertEqual(found_unambig, expected, + "Got %s, expected %s" % (found_unambig, expected)) class SchemaFinderTest(unittest.TestCase): @@ -421,7 +433,8 @@ repository = self.finder.find(self.test_records + self.diff_records) schemas = repository.get_all() - assert len(schemas) >= self.num_schemas, "Got too few schemas." + self.assertTrue(len(schemas) >= self.num_schemas, + "Got too few schemas.") def test_find_differences(self): """Find schemas that differentiate between two sets of sequences. @@ -432,7 +445,8 @@ self.diff_records) schemas = repository.get_all() - assert len(schemas) >= self.num_schemas, "Got too few schemas." + self.assertTrue(len(schemas) >= self.num_schemas, + "Got too few schemas.") class SchemaCoderTest(unittest.TestCase): @@ -462,8 +476,8 @@ for match_string, expected in self.match_strings: match_seq = Seq(match_string, IUPAC.unambiguous_dna) found_rep = self.motif_coder.representation(match_seq) - assert found_rep == expected, "Got %s, expected %s" % \ - (found_rep, expected) + self.assertEqual(found_rep, expected, + "Got %s, expected %s" % (found_rep, expected)) class SchemaMatchingTest(unittest.TestCase): @@ -474,19 +488,24 @@ def runTest(self): match = Schema.matches_schema("GATC", "AAAAA") - assert match == 0, "Expected no match because of length differences" + self.assertEqual(match, 0, + "Expected no match because of length differences") match = Schema.matches_schema("GATC", "GAT*") - assert match == 1, "Expected match" + self.assertEqual(match, 1, + "Expected match") match = Schema.matches_schema("GATC", "GATC") - assert match == 1, "Expected match" + self.assertEqual(match, 1, + "Expected match") match = Schema.matches_schema("GATC", "C*TC") - assert match == 0, "Expected no match because of char mismatch." + self.assertEqual(match, 0, + "Expected no match because of char mismatch.") match = Schema.matches_schema("G*TC", "*TTC") - assert match == 1, "Expected match because of ambiguity." + self.assertEqual(match, 1, + "Expected match because of ambiguity.") class SchemaFactoryTest(unittest.TestCase): @@ -524,9 +543,9 @@ schema_bank = self.factory.from_motifs(motif_bank, .5, 2) if VERBOSE: - print "\nSchemas:" + print("\nSchemas:") for schema in schema_bank.get_all(): - print "%s: %s" % (schema, schema_bank.count(schema)) + print("%s: %s" % (schema, schema_bank.count(schema))) def test_hard_from_motifs(self): """Generating schema from a real life set of motifs. @@ -534,9 +553,9 @@ schema_bank = self._load_schema_repository() if VERBOSE: - print "\nSchemas:" + print("\nSchemas:") for schema in schema_bank.get_top(5): - print "%s: %s" % (schema, schema_bank.count(schema)) + print("%s: %s" % (schema, schema_bank.count(schema))) def _load_schema_repository(self): """Helper function to load a schema repository from a file. @@ -583,7 +602,7 @@ alphabet=IUPAC.unambiguous_dna): schema_values = schema_coder.representation(seq_record.seq) if VERBOSE: - print "Schema values:", schema_values + print("Schema values: %s" % schema_values) fasta_handle.close() @@ -610,8 +629,7 @@ repository = self.sig_finder.find(self.test_records, 6, 9) top_sig = repository.get_top(1) - assert top_sig[0] == ('TTGGAA', 'TGGAAA'), \ - "Unexpected signature %s" % top_sig[0] + self.assertEqual(top_sig[0], ('TTGGAA', 'TGGAAA')) class SignatureCoderTest(unittest.TestCase): @@ -636,9 +654,9 @@ test_seq = Seq(seq_string, IUPAC.unambiguous_dna) predicted = self.coder.representation(test_seq) - assert predicted == expected, \ - "Non-expected representation %s for %s, wanted %s" \ - % (predicted, seq_string, expected) + self.assertEqual(predicted, expected, + "Non-expected representation %s for %s, wanted %s" + % (predicted, seq_string, expected)) if __name__ == "__main__": runner = unittest.TextTestRunner(verbosity = 2) diff -Nru python-biopython-1.62/Tests/test_Nexus.py python-biopython-1.63/Tests/test_Nexus.py --- python-biopython-1.62/Tests/test_Nexus.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_Nexus.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,8 +1,17 @@ +# Copyright 2005 by Iddo Friedberg. All rights reserved. +# Revisions copyright 2006-2013 by Peter Cock. All rights reserved. +# Revisions copyright 2008 by Frank Kauff. All rights reserved. +# Revisions copyright 2009 by Michiel de Hoon. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. + import os.path import unittest import tempfile -import cStringIO import sys +from Bio._py3k import StringIO +from Bio._py3k import range from Bio.Nexus import Nexus, Trees @@ -113,7 +122,7 @@ "three": [16, 17, 18, 19, 20, 21, 22, 23], "two": [8, 9, 10, 11, 12, 13, 14, 15], }) - self.assertEqual(n.taxpartitions.keys(), ['taxpart']) + self.assertEqual(list(n.taxpartitions.keys()), ['taxpart']) self.assertEqual(n.taxpartitions['taxpart'], {"badnames": ["isn'that [a] strange name?", 'one should be punished, for (that)!', @@ -125,7 +134,7 @@ # and exporting adjusted sets f1=tempfile.NamedTemporaryFile("w+") n.write_nexus_data(f1, - delete=['t1','t7'], + delete=['t1', 't7'], exclude=n.invert(n.charsets['big'])) f1.seek(0) nf1=Nexus.Nexus(f1) @@ -187,7 +196,7 @@ 'c': [1]}) self.assertEqual(nf1.charpartitions['part'], {'one': [0, 1, 2, 3]}) - self.assertEqual(nf1.taxpartitions.keys(), ['taxpart']) + self.assertEqual(list(nf1.taxpartitions.keys()), ['taxpart']) self.assertEqual(nf1.taxpartitions['taxpart'], {"badnames": ["isn'that [a] strange name?", 'one should be punished, for (that)!', @@ -198,7 +207,7 @@ f2=tempfile.NamedTemporaryFile("w+") n.write_nexus_data(f2, delete=['t2_the_name'], - exclude=range(3,40,4)) + exclude=list(range(3, 40, 4))) f2.seek(0) nf2=Nexus.Nexus(f2) self.assertEqual(os.path.normpath(nf2.filename), @@ -283,7 +292,7 @@ "three": [12, 13, 14, 15, 16, 17], "two": [6, 7, 8, 9, 10, 11], }) - self.assertEqual(nf2.taxpartitions.keys(), ['taxpart']) + self.assertEqual(list(nf2.taxpartitions.keys()), ['taxpart']) self.assertEqual(nf2.taxpartitions['taxpart'], {"badnames": ["isn'that [a] strange name?", 'one should be punished, for (that)!', @@ -308,20 +317,16 @@ n=Nexus.Nexus(self.handle) t3=n.trees[2] t2=n.trees[2] - t3.root_with_outgroup(['t1','t5']) + t3.root_with_outgroup(['t1', 't5']) self.assertEqual(str(t3), "tree tree1 = (((((('one should be punished, for (that)!','isn''that [a] strange name?'),'t2 the name'),t8,t9),t6),t7),(t5,t1));") - self.assertEqual(t3.is_monophyletic(['t8','t9','t6','t7']), -1) - self.assertEqual(t3.is_monophyletic(['t1','t5']), 13) + self.assertEqual(t3.is_monophyletic(['t8', 't9', 't6', 't7']), -1) + self.assertEqual(t3.is_monophyletic(['t1', 't5']), 13) t3.split(parent_id=t3.search_taxon('t9')) stdout = sys.stdout try: - sys.stdout = cStringIO.StringIO() + sys.stdout = StringIO() t3.display() - if sys.version_info[0] == 3: - output = sys.stdout.getvalue() - else: - sys.stdout.reset() - output = sys.stdout.read() + output = sys.stdout.getvalue() finally: sys.stdout = stdout expected = """\ @@ -351,7 +356,7 @@ for l1, l2 in zip(output.split("\n"), expected.split("\n")): self.assertEqual(l1, l2) self.assertEqual(output, expected) - self.assertEqual(t3.is_compatible(t2,threshold=0.3), []) + self.assertEqual(t3.is_compatible(t2, threshold=0.3), []) def test_internal_node_labels(self): """Handle text labels on internal nodes. @@ -359,16 +364,20 @@ ts1b = "(Cephalotaxus:125.000000,(Taxus:100.000000,Torreya:100.000000)"\ "TT1:25.000000)Taxaceae:90.000000;" tree = Trees.Tree(ts1b) - assert self._get_flat_nodes(tree) == [('Taxaceae', 90.0, None, None), - ('Cephalotaxus', 125.0, None, None), ('TT1', 25.0, None, None), - ('Taxus', 100.0, None, None), ('Torreya', 100.0, None, None)] + self.assertEqual(self._get_flat_nodes(tree), [('Taxaceae', 90.0, None, None), + ('Cephalotaxus', 125.0, None, None), + ('TT1', 25.0, None, None), + ('Taxus', 100.0, None, None), + ('Torreya', 100.0, None, None)]) ts1c = "(Cephalotaxus:125.000000,(Taxus:100.000000,Torreya:100.000000)"\ "25.000000)90.000000;" tree = Trees.Tree(ts1c) - assert self._get_flat_nodes(tree) == [(None, 90.0, None, None), - ('Cephalotaxus', 125.0, None, None), (None, 25.0, None, None), - ('Taxus', 100.0, None, None), ('Torreya', 100.0, None, None)] + self.assertEqual(self._get_flat_nodes(tree), [(None, 90.0, None, None), + ('Cephalotaxus', 125.0, None, None), + (None, 25.0, None, None), + ('Taxus', 100.0, None, None), + ('Torreya', 100.0, None, None)]) ts2 = "(((t9:0.385832, (t8:0.445135,t4:0.41401)C:0.024032)B:0.041436,"\ "t6:0.392496)A:0.0291131, t2:0.497673, ((t0:0.301171,"\ diff -Nru python-biopython-1.62/Tests/test_PAML_baseml.py python-biopython-1.63/Tests/test_PAML_baseml.py --- python-biopython-1.62/Tests/test_PAML_baseml.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_PAML_baseml.py 2013-12-05 14:10:43.000000000 +0000 @@ -172,7 +172,8 @@ "fix_blength": None, "method": 0} self.bml.read_ctl_file(self.ctl_file) - self.assertEqual(sorted(self.bml._options.keys()), sorted(target_options.keys())) + #Compare the dictionary keys: + self.assertEqual(sorted(self.bml._options), sorted(target_options)) for key in target_options: self.assertEqual(self.bml._options[key], target_options[key], "%s: %r vs %r" @@ -193,7 +194,7 @@ self.assertRaises(ValueError, baseml.read, self.results_file) def testParseAllVersions(self): - folder = os.path.join("PAML","Results", "baseml", "versions") + folder = os.path.join("PAML", "Results", "baseml", "versions") for results_file in os.listdir(folder): file_path = os.path.join(folder, results_file) if os.path.isfile(file_path) and results_file[:6] == "baseml": diff -Nru python-biopython-1.62/Tests/test_PAML_codeml.py python-biopython-1.63/Tests/test_PAML_codeml.py --- python-biopython-1.62/Tests/test_PAML_codeml.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_PAML_codeml.py 2013-12-05 14:10:43.000000000 +0000 @@ -186,7 +186,8 @@ "rho": None, "fix_rho": None} self.cml.read_ctl_file(self.ctl_file) - self.assertEqual(sorted(self.cml._options.keys()), sorted(target_options.keys())) + #Compare the dictionary keys: + self.assertEqual(sorted(self.cml._options), sorted(target_options)) for key in target_options: self.assertEqual(self.cml._options[key], target_options[key], "%s: %r vs %r" diff -Nru python-biopython-1.62/Tests/test_PDB.py python-biopython-1.63/Tests/test_PDB.py --- python-biopython-1.62/Tests/test_PDB.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_PDB.py 2013-12-05 14:10:43.000000000 +0000 @@ -10,11 +10,13 @@ # as part of this package. """Unit tests for the Bio.PDB module.""" +from __future__ import print_function + import os import tempfile import unittest import warnings -from StringIO import StringIO +from Bio._py3k import StringIO try: import numpy @@ -34,6 +36,7 @@ from Bio.PDB import rotmat, Vector from Bio.PDB import Residue, Atom from Bio.PDB import make_dssp_dict +from Bio.PDB.NACCESS import process_asa_data, process_rsa_data # NB: the 'A_' prefix ensures this test case is run first @@ -138,7 +141,7 @@ 'release_date': '1998-10-14', 'structure_method': 'x-ray diffraction', } - for key, expect in known_strings.iteritems(): + for key, expect in known_strings.items(): self.assertEqual(struct.header[key].lower(), expect.lower()) def test_fibril(self): @@ -156,7 +159,7 @@ 'release_date': '2005-11-22', 'structure_method': 'solution nmr', } - for key, expect in known_strings.iteritems(): + for key, expect in known_strings.items(): self.assertEqual(struct.header[key].lower(), expect.lower()) @@ -936,7 +939,7 @@ N=(' NH1', ' NH2'), ) - for element, atom_names in pdb_elements.iteritems(): + for element, atom_names in pdb_elements.items(): for fullname in atom_names: e = quick_assign(fullname) #warnings.warn("%s %s" % (fullname, e)) @@ -951,7 +954,7 @@ def test_get_chains(self): """Yields chains from different models separately.""" chains = [chain.id for chain in self.struc.get_chains()] - self.assertEqual(chains, ['A','A', 'B', ' ']) + self.assertEqual(chains, ['A', 'A', 'B', ' ']) def test_get_residues(self): """Yields all residues from all models.""" @@ -977,7 +980,7 @@ # """Residues in a structure are renumbered.""" # self.structure.renumber_residues() # nums = [resi.id[1] for resi in self.structure[0]['A'].child_list] -# print nums +# print(nums) # # ------------------------------------------------------------- @@ -999,7 +1002,7 @@ """ if hasattr(o, "get_coord"): return o.get_coord(), 1 - total_pos = numpy.array((0.0,0.0,0.0)) + total_pos = numpy.array((0.0, 0.0, 0.0)) total_count = 0 for p in o.get_list(): pos, count = self.get_total_pos(p) @@ -1017,8 +1020,8 @@ def test_transform(self): """Transform entities (rotation and translation).""" for o in (self.s, self.m, self.c, self.r, self.a): - rotation = rotmat(Vector(1,3,5), Vector(1,0,0)) - translation=numpy.array((2.4,0,1), 'f') + rotation = rotmat(Vector(1, 3, 5), Vector(1, 0, 0)) + translation=numpy.array((2.4, 0, 1), 'f') oldpos = self.get_pos(o) o.transform(rotation, translation) newpos = self.get_pos(o) @@ -1060,6 +1063,28 @@ dssp, keys = make_dssp_dict("PDB/2BEG.dssp") self.assertEqual(len(dssp), 130) + def test_DSSP_noheader_file(self): + """Test parsing of pregenerated DSSP missing header information""" + # New DSSP prints a line containing only whitespace and "." + dssp, keys = make_dssp_dict("PDB/2BEG_noheader.dssp") + self.assertEqual(len(dssp), 130) + +class NACCESSTests(unittest.TestCase): + """Tests for NACCESS parsing etc which don't need the binary tool. + + See also test_NACCESS_tool.py for run time testing with the tool. + """ + def test_NACCESS_rsa_file(self): + """Test parsing of pregenerated rsa NACCESS file""" + with open("PDB/1A8O.rsa") as rsa: + naccess = process_rsa_data(rsa) + self.assertEqual(len(naccess), 66) + + def test_NACCESS_asa_file(self): + """Test parsing of pregenerated asa NACCESS file""" + with open("PDB/1A8O.asa") as asa: + naccess = process_asa_data(asa) + self.assertEqual(len(naccess), 524) if __name__ == '__main__': runner = unittest.TextTestRunner(verbosity=2) diff -Nru python-biopython-1.62/Tests/test_PDB_KDTree.py python-biopython-1.63/Tests/test_PDB_KDTree.py --- python-biopython-1.62/Tests/test_PDB_KDTree.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_PDB_KDTree.py 2013-12-05 14:10:43.000000000 +0000 @@ -48,7 +48,7 @@ hits = ns.search_all(5.0) self.assertTrue(isinstance(hits, list), hits) self.assertTrue(len(hits) >= 0, hits) - x = array([250,250,250]) # Far away from our random atoms + x = array([250, 250, 250]) # Far away from our random atoms self.assertEqual([], ns.search(x, 5.0, "A")) self.assertEqual([], ns.search(x, 5.0, "R")) self.assertEqual([], ns.search(x, 5.0, "C")) diff -Nru python-biopython-1.62/Tests/test_ParserSupport.py python-biopython-1.63/Tests/test_ParserSupport.py --- python-biopython-1.62/Tests/test_ParserSupport.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_ParserSupport.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,10 +3,17 @@ # license. Please see the LICENSE file that should have been included # as part of this package. +from __future__ import print_function + import string -from StringIO import StringIO +from Bio._py3k import StringIO from Bio import File -from Bio import ParserSupport + +import warnings +from Bio import BiopythonDeprecationWarning +with warnings.catch_warnings(): + warnings.simplefilter('ignore', BiopythonDeprecationWarning) + from Bio import ParserSupport # pyUnit @@ -18,12 +25,12 @@ ### TaggingConsumer -print "Running tests on TaggingConsumer" +print("Running tests on TaggingConsumer") class TestHandle: def write(self, s): - print s + print(s) h = TestHandle() tc = ParserSupport.TaggingConsumer(handle=h, colwidth=5) @@ -34,27 +41,27 @@ ### is_blank_line -print "Running tests on is_blank_line" +print("Running tests on is_blank_line") is_blank_line = lambda *args, **keywds: \ pb(ParserSupport.is_blank_line(*args, **keywds)) -print is_blank_line('\n') # 1 -print is_blank_line('\r\n') # 1 -print is_blank_line('\r') # 1 -print is_blank_line('') # 1 -print is_blank_line('', allow_spaces=1) # 1 -print is_blank_line('', allow_spaces=0) # 1 -print is_blank_line(string.whitespace, allow_spaces=1) # 1 -print is_blank_line('hello') # 0 -print is_blank_line('hello', allow_spaces=1) # 0 -print is_blank_line('hello', allow_spaces=0) # 0 -print is_blank_line(string.whitespace, allow_spaces=0) # 0 +print(is_blank_line('\n')) # 1 +print(is_blank_line('\r\n')) # 1 +print(is_blank_line('\r')) # 1 +print(is_blank_line('')) # 1 +print(is_blank_line('', allow_spaces=1)) # 1 +print(is_blank_line('', allow_spaces=0)) # 1 +print(is_blank_line(string.whitespace, allow_spaces=1)) # 1 +print(is_blank_line('hello')) # 0 +print(is_blank_line('hello', allow_spaces=1)) # 0 +print(is_blank_line('hello', allow_spaces=0)) # 0 +print(is_blank_line(string.whitespace, allow_spaces=0)) # 0 ### safe_readline -print "Running tests on safe_readline" +print("Running tests on safe_readline") data = """This file""" @@ -62,19 +69,19 @@ h = File.UndoHandle(StringIO(data)) safe_readline = ParserSupport.safe_readline -print safe_readline(h) # "This" -print safe_readline(h) # "file" +print(safe_readline(h)) # "This" +print(safe_readline(h)) # "file" try: safe_readline(h) except ValueError: - print "correctly failed" + print("correctly failed") else: - print "ERROR, should have failed" + print("ERROR, should have failed") ### safe_peekline -print "Running tests on safe_peekline" +print("Running tests on safe_peekline") safe_peekline = ParserSupport.safe_peekline data = """This @@ -82,23 +89,23 @@ h = File.UndoHandle(StringIO(data)) -print safe_peekline(h) # "This" +print(safe_peekline(h)) # "This" h.readline() -print safe_peekline(h) # "file" +print(safe_peekline(h)) # "file" h.readline() try: safe_peekline(h) except ValueError: - print "correctly failed" + print("correctly failed") else: - print "ERROR, should have failed" + print("ERROR, should have failed") h.saveline('hello') -print safe_peekline(h) # 'hello' +print(safe_peekline(h)) # 'hello' ### read_and_call -print "Running tests on read_and_call" +print("Running tests on read_and_call") data = """>gi|132871|sp|P19947|RL30_BACSU 50S RIBOSOMAL PROTEIN L30 (BL27) MAKLEITLKRSVIGRPEDQRVTVRTLGLKKTNQTVVHEDNAAIRGMINKVSHLVSVKEQ @@ -120,7 +127,7 @@ lines.append(line) rac(h, m) -print lines[-1][:10] # '>gi|132871' +print(lines[-1][:10]) # '>gi|132871' rac(h, m, start='MAKLE', end='KEQ', contains='SVIG') rac(h, m, blank=0) @@ -128,42 +135,42 @@ try: rac(h, m, blank=1) except ValueError: - print "correctly failed" + print("correctly failed") else: - print "ERROR, should have failed" + print("ERROR, should have failed") try: rac(h, m, start='foobar') except ValueError: - print "correctly failed" + print("correctly failed") else: - print "ERROR, should have failed" + print("ERROR, should have failed") try: rac(h, m, end='foobar') except ValueError: - print "correctly failed" + print("correctly failed") else: - print "ERROR, should have failed" + print("ERROR, should have failed") try: rac(h, m, contains='foobar') except ValueError: - print "correctly failed" + print("correctly failed") else: - print "ERROR, should have failed" + print("ERROR, should have failed") try: rac(h, m, blank=0) except ValueError: - print "correctly failed" + print("correctly failed") else: - print "ERROR, should have failed" + print("ERROR, should have failed") ### attempt_read_and_call -print "Running tests on attempt_read_and_call" +print("Running tests on attempt_read_and_call") data = """>gi|132871|sp|P19947|RL30_BACSU 50S RIBOSOMAL PROTEIN L30 (BL27) MAKLEITLKRSVIGRPEDQRVTVRTLGLKKTNQTVVHEDNAAIRGMINKVSHLVSVKEQ @@ -182,7 +189,7 @@ def m(line): lines.append(line) -print arac(h, m, contains="RIBOSOMAL PROTEIN") # 1 -print arac(h, m, start="foobar") # 0 -print arac(h, m, blank=1) # 0 -print arac(h, m, end="LVSVKEQ") # 1 +print(arac(h, m, contains="RIBOSOMAL PROTEIN")) # 1 +print(arac(h, m, start="foobar")) # 0 +print(arac(h, m, blank=1)) # 0 +print(arac(h, m, end="LVSVKEQ")) # 1 diff -Nru python-biopython-1.62/Tests/test_Pathway.py python-biopython-1.63/Tests/test_Pathway.py --- python-biopython-1.62/Tests/test_Pathway.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_Pathway.py 2013-12-05 14:10:43.000000000 +0000 @@ -15,21 +15,21 @@ class GraphTestCase(unittest.TestCase): def testEquals(self): - a = Graph(['a','b','c']) - a.add_edge('a','b','label1') - a.add_edge('b','c','label1') - a.add_edge('b','a','label2') - b = Graph(['a','b','c']) + a = Graph(['a', 'b', 'c']) + a.add_edge('a', 'b', 'label1') + a.add_edge('b', 'c', 'label1') + a.add_edge('b', 'a', 'label2') + b = Graph(['a', 'b', 'c']) self.assertNotEqual(a, b, "equal to similar nodes, no edges") - b.add_edge('a','b','label1') + b.add_edge('a', 'b', 'label1') self.assertNotEqual(a, b, "equal to similar nodes, edge subset") - b.add_edge('b','c','label1') - b.add_edge('b','a','label2') + b.add_edge('b', 'c', 'label1') + b.add_edge('b', 'a', 'label2') self.assertEqual(a, b, "not equal to similar") - c = Graph(['a','b','c']) - c.add_edge('a','b','label2') - c.add_edge('b','c','label2') - c.add_edge('b','a','label1') + c = Graph(['a', 'b', 'c']) + c.add_edge('a', 'b', 'label2') + c.add_edge('b', 'c', 'label2') + c.add_edge('b', 'a', 'label1') self.assertNotEqual(a, c, "equal to similar with different labels") self.assertNotEqual(c, Graph(), "equal to empty graph") self.assertEqual(Graph(), Graph(), "empty graph not equal to self") @@ -42,56 +42,54 @@ a.add_node('a') self.assertEqual(a.nodes(), ['a'], "duplicate node added") a.add_node('b') - l = a.nodes() - l.sort() + l = sorted(a.nodes()) self.assertEqual(l, ['a', 'b'], "second node not added") def testEdges(self): - a = Graph(['a','b','c','d']) - a.add_edge('a','b','label1') - self.assertEqual(a.child_edges('a'), [('b','label1')]) # , "incorrect child edges") - a.add_edge('b','a','label2') - self.assertEqual(a.parent_edges('a'), [('b','label2')]) # , "incorrect parent edges") - a.add_edge('b','c','label3') - self.assertEqual(a.parent_edges('c'), [('b','label3')]) # , "incorrect parent edges") - l = a.children('b') - l.sort() + a = Graph(['a', 'b', 'c', 'd']) + a.add_edge('a', 'b', 'label1') + self.assertEqual(a.child_edges('a'), [('b', 'label1')]) # , "incorrect child edges") + a.add_edge('b', 'a', 'label2') + self.assertEqual(a.parent_edges('a'), [('b', 'label2')]) # , "incorrect parent edges") + a.add_edge('b', 'c', 'label3') + self.assertEqual(a.parent_edges('c'), [('b', 'label3')]) # , "incorrect parent edges") + l = sorted(a.children('b')) self.assertEqual(l, ['a', 'c'], "incorrect children") self.assertEqual(a.children('d'), [], "incorrect children for singleton") self.assertEqual(a.parents('a'), ['b'], "incorrect parents") def testRemoveNode(self): - a = Graph(['a','b','c','d','e']) - a.add_edge('a','e','label1') - a.add_edge('b','e','label1') - a.add_edge('c','e','label2') - a.add_edge('d','e','label3') - a.add_edge('e','d','label4') - a.add_edge('a','b','label5') + a = Graph(['a', 'b', 'c', 'd', 'e']) + a.add_edge('a', 'e', 'label1') + a.add_edge('b', 'e', 'label1') + a.add_edge('c', 'e', 'label2') + a.add_edge('d', 'e', 'label3') + a.add_edge('e', 'd', 'label4') + a.add_edge('a', 'b', 'label5') a.remove_node('e') - b = Graph(['a','b','c','d']) - b.add_edge('a','b','label5') + b = Graph(['a', 'b', 'c', 'd']) + b.add_edge('a', 'b', 'label5') self.assertEqual(a, b) # , "incorrect node removal") class MultiGraphTestCase(unittest.TestCase): def testEquals(self): - a = MultiGraph(['a','b','c']) - a.add_edge('a','b','label1') - a.add_edge('b','c','label1') - a.add_edge('b','a','label2') - b = MultiGraph(['a','b','c']) + a = MultiGraph(['a', 'b', 'c']) + a.add_edge('a', 'b', 'label1') + a.add_edge('b', 'c', 'label1') + a.add_edge('b', 'a', 'label2') + b = MultiGraph(['a', 'b', 'c']) self.assertNotEqual(a, b, "equal to similar nodes, no edges") - b.add_edge('a','b','label1') + b.add_edge('a', 'b', 'label1') self.assertNotEqual(a, b, "equal to similar nodes, edge subset") - b.add_edge('b','c','label1') - b.add_edge('b','a','label2') + b.add_edge('b', 'c', 'label1') + b.add_edge('b', 'a', 'label2') self.assertEqual(a, b, "not equal to similar") - c = MultiGraph(['a','b','c']) - c.add_edge('a','b','label2') - c.add_edge('b','c','label2') - c.add_edge('b','a','label1') + c = MultiGraph(['a', 'b', 'c']) + c.add_edge('a', 'b', 'label2') + c.add_edge('b', 'c', 'label2') + c.add_edge('b', 'a', 'label1') self.assertNotEqual(a, c, "equal to similar with different labels") self.assertNotEqual(c, MultiGraph(), "equal to empty graph") self.assertEqual(MultiGraph(), MultiGraph(), "empty graph not equal to self") @@ -104,22 +102,20 @@ a.add_node('a') self.assertEqual(a.nodes(), ['a'], "duplicate node added") a.add_node('b') - l = a.nodes() - l.sort() + l = sorted(a.nodes()) self.assertEqual(l, ['a', 'b'], "second node not added") def testEdges(self): - a = MultiGraph(['a','b','c','d']) - a.add_edge('a','b','label1') - self.assertEqual(a.child_edges('a'), [('b','label1')]) # , "incorrect child edges") - a.add_edge('a','b','label2') - l = a.child_edges('a') - l.sort() - self.assertEqual(l, [('b','label1'),('b','label2')]) # , "incorrect child edges") - a.add_edge('b','a','label2') - self.assertEqual(a.parent_edges('a'), [('b','label2')]) # , "incorrect parent edges") - a.add_edge('b','c','label3') - self.assertEqual(a.parent_edges('c'), [('b','label3')]) # , "incorrect parent edges") + a = MultiGraph(['a', 'b', 'c', 'd']) + a.add_edge('a', 'b', 'label1') + self.assertEqual(a.child_edges('a'), [('b', 'label1')]) # , "incorrect child edges") + a.add_edge('a', 'b', 'label2') + l = sorted(a.child_edges('a')) + self.assertEqual(l, [('b', 'label1'), ('b', 'label2')]) # , "incorrect child edges") + a.add_edge('b', 'a', 'label2') + self.assertEqual(a.parent_edges('a'), [('b', 'label2')]) # , "incorrect parent edges") + a.add_edge('b', 'c', 'label3') + self.assertEqual(a.parent_edges('c'), [('b', 'label3')]) # , "incorrect parent edges") l = a.children('b') l.sort() self.assertEqual(l, ['a', 'c'], "incorrect children") @@ -127,19 +123,19 @@ self.assertEqual(a.parents('a'), ['b'], "incorrect parents") def testRemoveNode(self): - a = MultiGraph(['a','b','c','d','e']) - a.add_edge('a','e','label1') + a = MultiGraph(['a', 'b', 'c', 'd', 'e']) + a.add_edge('a', 'e', 'label1') self.assertEqual(repr(a), "") - a.add_edge('b','e','label1') - a.add_edge('c','e','label2') - a.add_edge('d','e','label3') - a.add_edge('e','d','label4') - a.add_edge('a','b','label5') + a.add_edge('b', 'e', 'label1') + a.add_edge('c', 'e', 'label2') + a.add_edge('d', 'e', 'label3') + a.add_edge('e', 'd', 'label4') + a.add_edge('a', 'b', 'label5') self.assertEqual(repr(a), "") a.remove_node('e') self.assertEqual(repr(a), "") - b = MultiGraph(['a','b','c','d']) - b.add_edge('a','b','label5') + b = MultiGraph(['a', 'b', 'c', 'd']) + b.add_edge('a', 'b', 'label5') self.assertEqual(repr(b), "") self.assertEqual(repr(a), repr(b)) self.assertEqual(a, b) # , "incorrect node removal") diff -Nru python-biopython-1.62/Tests/test_Phd.py python-biopython-1.63/Tests/test_Phd.py --- python-biopython-1.62/Tests/test_Phd.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_Phd.py 2013-12-05 14:10:43.000000000 +0000 @@ -19,7 +19,7 @@ """Test phd1 using parser via SeqIO.""" records = SeqIO.parse(self.handle, "phd") #Contig 1 - record = records.next() + record = next(records) self.assertEqual(record.id, "34_222_(80-A03-19).b.ab1") self.assertEqual(record.name, "34_222_(80-A03-19).b.ab1") self.assertEqual(record.description, "34_222_(80-A03-19).b.ab1") @@ -43,25 +43,25 @@ "+\n" "IIJSVe\\\\XV\n") #Contig 2 - record = records.next() + record = next(records) self.assertEqual(record.id, "425_103_(81-A03-19).g.ab1") self.assertEqual(record.name, "425_103_(81-A03-19).g.ab1") self.assertEqual(record.letter_annotations["phred_quality"][:10], [14, 17, 22, 10, 10, 10, 15, 8, 8, 9]) #Contig 3 - record = records.next() + record = next(records) self.assertEqual(record.id, '425_7_(71-A03-19).b.ab1') self.assertEqual(record.name, '425_7_(71-A03-19).b.ab1') self.assertEqual(record.letter_annotations["phred_quality"][:10], [10, 10, 10, 10, 8, 8, 6, 6, 6, 6]) # Make sure that no further records are found - self.assertRaises(StopIteration, records.next) + self.assertRaises(StopIteration, next, records) def test_check_record_parser(self): """Test phd1 file in detail.""" records = Phd.parse(self.handle) # Record 1 - record = records.next() + record = next(records) self.assertEqual(record.file_name, "34_222_(80-A03-19).b.ab1") self.assertEqual(record.comments['abi_thumbprint'], 0) self.assertEqual(record.comments['call_method'], "phred") @@ -113,7 +113,7 @@ self.assertEqual(str(record.seq_trimmed)[:10], 'cgtcggaaca') self.assertEqual(str(record.seq_trimmed)[-10:], 'tatttcggag') # Record 2 - record = records.next() + record = next(records) center = len(record.sites)//2 self.assertEqual(record.file_name, "425_103_(81-A03-19).g.ab1") self.assertEqual(record.comments['abi_thumbprint'], 0) @@ -165,7 +165,7 @@ self.assertEqual(str(record.seq_trimmed)[:10], 'cctgatccga') self.assertEqual(str(record.seq_trimmed)[-10:], 'ggggccgcca') # Record 3 - record = records.next() + record = next(records) center = len(record.sites)//2 self.assertEqual(record.file_name, '425_7_(71-A03-19).b.ab1') self.assertEqual(record.comments['abi_thumbprint'], 0) @@ -215,7 +215,7 @@ self.assertEqual(str(record.seq)[:10], 'acataaatca') self.assertEqual(str(record.seq)[-10:], 'atctgctttn') # Make sure that no further records are found - self.assertRaises(StopIteration, records.next) + self.assertRaises(StopIteration, next, records) class PhdTestTwo(unittest.TestCase): @@ -229,7 +229,7 @@ """Test phd2 using parser via SeqIO.""" records = SeqIO.parse(self.handle, "phd") #Contig 1 - record = records.next() + record = next(records) self.assertEqual(record.id, "ML4924R") self.assertEqual(record.name, "ML4924R") self.assertEqual(record.description, "ML4924R") @@ -246,7 +246,7 @@ self.assertEqual(record[:10].format("fastq-illumina"), "@ML4924R\nactttggtcg\n+\nFFFHHLRPNK\n") # Make sure that no further records are found - self.assertRaises(StopIteration, records.next) + self.assertRaises(StopIteration, next, records) class PhdTest454(unittest.TestCase): @@ -260,7 +260,7 @@ """Test phd_454 using parser via SeqIO.""" records = SeqIO.parse(self.handle, "phd") #Contig 1 - record = records.next() + record = next(records) self.assertEqual(record.id, "EBE03TV04IHLTF.77-243") self.assertEqual(record.name, "EBE03TV04IHLTF.77-243") self.assertEqual(record.description, "EBE03TV04IHLTF.77-243 1") @@ -286,7 +286,7 @@ "+\n" "eeeeeeeeee\n") # Make sure that no further records are found - self.assertRaises(StopIteration, records.next) + self.assertRaises(StopIteration, next, records) class PhdTestSolexa(unittest.TestCase): @@ -300,7 +300,7 @@ """Test phd2 using parser via SeqIO.""" records = SeqIO.parse(self.handle, "phd") #Contig 1 - record = records.next() + record = next(records) self.assertEqual(record.id, "HWI-EAS94_4_1_1_537_446") self.assertEqual(record.name, "HWI-EAS94_4_1_1_537_446") self.assertEqual(record.description, "HWI-EAS94_4_1_1_537_446 1") @@ -331,7 +331,7 @@ "+\n" "^^^^^^^^^^^^^^^^^^^^\\W^^^^^^\\VHVGOOOJJKO\n") #Contig 2 - record = records.next() + record = next(records) self.assertEqual(record.id, "HWI-EAS94_4_1_1_602_99") self.assertEqual(record.name, "HWI-EAS94_4_1_1_602_99") self.assertEqual(record.description, "HWI-EAS94_4_1_1_602_99 1") @@ -362,7 +362,7 @@ "+\n" "^^^^^^^^^^^^^^^^^^^^^^^^^^P^\\VVVNOOEJOJE\n") # Make sure that no further records are found - self.assertRaises(StopIteration, records.next) + self.assertRaises(StopIteration, next, records) if __name__ == "__main__": runner = unittest.TextTestRunner(verbosity = 2) diff -Nru python-biopython-1.62/Tests/test_Phylo.py python-biopython-1.63/Tests/test_Phylo.py --- python-biopython-1.62/Tests/test_Phylo.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_Phylo.py 2013-12-05 14:10:43.000000000 +0000 @@ -7,7 +7,8 @@ import sys import unittest -from cStringIO import StringIO +from Bio._py3k import StringIO +from io import BytesIO from Bio import Phylo from Bio.Phylo import PhyloXML, NewickIO @@ -87,12 +88,8 @@ def test_convert(self): """Convert a tree between all supported formats.""" mem_file_1 = StringIO() + mem_file_2 = BytesIO() mem_file_3 = StringIO() - if sys.version_info[0] == 3: - from io import BytesIO - mem_file_2 = BytesIO() - else: - mem_file_2 = StringIO() Phylo.convert(EX_NEWICK, 'newick', mem_file_1, 'nexus') mem_file_1.seek(0) Phylo.convert(mem_file_1, 'nexus', mem_file_2, 'phyloxml') @@ -165,8 +162,8 @@ # Root is bifurcating self.assertEqual(len(tree.root.clades), 2) # Deepest tips under each child of the root are equally deep - deep_dist_0 = max(tree.clade[0].depths().itervalues()) - deep_dist_1 = max(tree.clade[1].depths().itervalues()) + deep_dist_0 = max(tree.clade[0].depths().values()) + deep_dist_1 = max(tree.clade[1].depths().values()) self.assertAlmostEqual(deep_dist_0, deep_dist_1) # Magic method @@ -236,7 +233,7 @@ self.assertTrue(isinstance(octo[0], PhyloXML.Clade)) self.assertEqual(octo[0].taxonomies[0].code, 'OCTVU') # string filter - dee = self.phylogenies[10].find_clades('D').next() + dee = next(self.phylogenies[10].find_clades('D')) self.assertEqual(dee.name, 'D') def test_find_terminal(self): diff -Nru python-biopython-1.62/Tests/test_PhyloXML.py python-biopython-1.63/Tests/test_PhyloXML.py --- python-biopython-1.62/Tests/test_PhyloXML.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_PhyloXML.py 2013-12-05 14:10:43.000000000 +0000 @@ -236,9 +236,9 @@ #Because we short circult interation, must close handle explicitly #to avoid a ResourceWarning handle = open(EX_DOLLO) - tree = PhyloXMLIO.parse(handle).next() + tree = next(PhyloXMLIO.parse(handle)) handle.close() - bchars = tree.clade[0,0].binary_characters + bchars = tree.clade[0, 0].binary_characters self.assertTrue(isinstance(bchars, PX.BinaryCharacters)) self.assertEqual(bchars.type, 'parsimony inferred') for name, count, value in ( @@ -265,7 +265,7 @@ """Instantiation of Confidence objects.""" #Because we short circult interation, must close handle explicitly handle = open(EX_MADE) - tree = PhyloXMLIO.parse(handle).next() + tree = next(PhyloXMLIO.parse(handle)) handle.close() self.assertEqual(tree.name, 'testing confidence') for conf, type, val in zip(tree.confidences, @@ -285,8 +285,8 @@ def test_Date(self): """Instantiation of Date objects.""" tree = list(PhyloXMLIO.parse(EX_PHYLO))[11] - silurian = tree.clade[0,0].date - devonian = tree.clade[0,1].date + silurian = tree.clade[0, 0].date + devonian = tree.clade[0, 1].date ediacaran = tree.clade[1].date for date, desc, val in zip( (silurian, devonian, ediacaran), @@ -305,9 +305,9 @@ Also checks Point type and safe Unicode handling (?). """ tree = list(PhyloXMLIO.parse(EX_PHYLO))[10] - hirschweg = tree.clade[0,0].distributions[0] - nagoya = tree.clade[0,1].distributions[0] - eth_zurich = tree.clade[0,2].distributions[0] + hirschweg = tree.clade[0, 0].distributions[0] + nagoya = tree.clade[0, 1].distributions[0] + eth_zurich = tree.clade[0, 2].distributions[0] san_diego = tree.clade[1].distributions[0] for dist, desc, lati, longi, alti in zip( (hirschweg, nagoya, eth_zurich, san_diego), @@ -334,9 +334,9 @@ """ #Because we short circult interation, must close handle explicitly handle = open(EX_APAF) - tree = PhyloXMLIO.parse(handle).next() + tree = next(PhyloXMLIO.parse(handle)) handle.close() - clade = tree.clade[0,0,0,0,0,0,0,0,0,0] + clade = tree.clade[0, 0, 0, 0, 0, 0, 0, 0, 0, 0] darch = clade.sequences[0].domain_architecture self.assertTrue(isinstance(darch, PX.DomainArchitecture)) self.assertEqual(darch.length, 1249) @@ -406,9 +406,9 @@ #Because we short circult interation, must close handle explicitly #to avoid a ResourceWarning handle = open(EX_DOLLO) - tree = PhyloXMLIO.parse(handle).next() + tree = next(PhyloXMLIO.parse(handle)) handle.close() - reference = tree.clade[0,0,0,0,0,0].references[0] + reference = tree.clade[0, 0, 0, 0, 0, 0].references[0] self.assertTrue(isinstance(reference, PX.Reference)) self.assertEqual(reference.doi, '10.1038/nature06614') self.assertEqual(reference.desc, None) @@ -429,8 +429,8 @@ self.assertEqual(seq0.name, 'alcohol dehydrogenase') self.assertEqual(seq0.annotations[0].ref, 'InterPro:IPR002085') # More complete elements - seq1 = trees[5].clade[0,0].sequences[0] - seq2 = trees[5].clade[0,1].sequences[0] + seq1 = trees[5].clade[0, 0].sequences[0] + seq2 = trees[5].clade[0, 1].sequences[0] seq3 = trees[5].clade[1].sequences[0] for seq, sym, acc, name, mol_seq, ann_refs in zip( (seq1, seq2, seq3), @@ -475,7 +475,7 @@ """ trees = list(PhyloXMLIO.parse(EX_PHYLO)) # Octopus - tax5 = trees[5].clade[0,0].taxonomies[0] + tax5 = trees[5].clade[0, 0].taxonomies[0] self.assertTrue(isinstance(tax5, PX.Taxonomy)) self.assertEqual(tax5.id.value, '6645') self.assertEqual(tax5.id.provider, 'NCBI') @@ -673,8 +673,8 @@ def test_clade_getitem(self): """Clade.__getitem__: get sub-clades by extended indexing.""" tree = self.phyloxml.phylogenies[3] - self.assertEqual(tree.clade[0,0], tree.clade.clades[0].clades[0]) - self.assertEqual(tree.clade[0,1], tree.clade.clades[0].clades[1]) + self.assertEqual(tree.clade[0, 0], tree.clade.clades[0].clades[0]) + self.assertEqual(tree.clade[0, 1], tree.clade.clades[0].clades[1]) self.assertEqual(tree.clade[1], tree.clade.clades[1]) self.assertEqual(len(tree.clade[:]), len(tree.clade.clades)) self.assertEqual(len(tree.clade[0,:]), diff -Nru python-biopython-1.62/Tests/test_Phylo_CDAO.py python-biopython-1.63/Tests/test_Phylo_CDAO.py --- python-biopython-1.62/Tests/test_Phylo_CDAO.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_Phylo_CDAO.py 2013-12-05 14:10:43.000000000 +0000 @@ -56,18 +56,18 @@ def test_write(self): """Parse, rewrite and retest an example file.""" infile = open(filename, 'rb') - t1 = CDAOIO.Parser(infile).parse().next() + t1 = next(CDAOIO.Parser(infile).parse()) infile.close() outfile = open(DUMMY, 'w+b') CDAOIO.write([t1], outfile) outfile.close() - t2 = CDAOIO.Parser(open(DUMMY, 'rb')).parse().next() + t2 = next(CDAOIO.Parser(open(DUMMY, 'rb')).parse()) def assert_property(prop_name): p1 = sorted([getattr(n, prop_name) for n in t1.get_terminals()]) p2 = sorted([getattr(n, prop_name) for n in t2.get_terminals()]) - self.assertEqual(p1,p2) + self.assertEqual(p1, p2) for prop_name in ('name', 'branch_length', 'confidence'): assert_property(prop_name) diff -Nru python-biopython-1.62/Tests/test_Phylo_NeXML.py python-biopython-1.63/Tests/test_Phylo_NeXML.py --- python-biopython-1.62/Tests/test_Phylo_NeXML.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_Phylo_NeXML.py 2013-12-05 14:10:43.000000000 +0000 @@ -6,8 +6,6 @@ """Unit tests for the NeXML and NeXMLIO modules. """ -from __future__ import with_statement - import os import tempfile import unittest @@ -83,17 +81,17 @@ def test_write(self): """Parse, rewrite and retest an example file.""" with open(filename, 'rb') as infile: - t1 = NeXMLIO.Parser(infile).parse().next() + t1 = next(NeXMLIO.Parser(infile).parse()) with open(DUMMY, 'w+b') as outfile: NeXMLIO.write([t1], outfile) with open(DUMMY, 'rb') as infile: - t2 = NeXMLIO.Parser(infile).parse().next() + t2 = next(NeXMLIO.Parser(infile).parse()) def assert_property(prop_name): p1 = sorted([getattr(n, prop_name) for n in t1.get_terminals() if getattr(n, prop_name)]) p2 = sorted([getattr(n, prop_name) for n in t2.get_terminals() if getattr(n, prop_name)]) - self.assertEqual(p1,p2) + self.assertEqual(p1, p2) for prop_name in ('name', 'branch_length', 'confidence'): assert_property(prop_name) diff -Nru python-biopython-1.62/Tests/test_Phylo_depend.py python-biopython-1.63/Tests/test_Phylo_depend.py --- python-biopython-1.62/Tests/test_Phylo_depend.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_Phylo_depend.py 2013-12-05 14:10:43.000000000 +0000 @@ -41,7 +41,7 @@ # OK, we can go ahead import unittest -from cStringIO import StringIO +from Bio._py3k import StringIO from Bio import Phylo diff -Nru python-biopython-1.62/Tests/test_PopGen_DFDist.py python-biopython-1.63/Tests/test_PopGen_DFDist.py --- python-biopython-1.62/Tests/test_PopGen_DFDist.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_PopGen_DFDist.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,6 +3,8 @@ # license. Please see the LICENSE file that should have been included # as part of this package. +from __future__ import print_function + import os import shutil import tempfile @@ -119,6 +121,6 @@ if __name__ == "__main__": - print "Running fdist tests, which might take some time, please wait" + print("Running fdist tests, which might take some time, please wait") runner = unittest.TextTestRunner(verbosity = 2) unittest.main(testRunner=runner) diff -Nru python-biopython-1.62/Tests/test_PopGen_FDist.py python-biopython-1.63/Tests/test_PopGen_FDist.py --- python-biopython-1.62/Tests/test_PopGen_FDist.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_PopGen_FDist.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,6 +3,8 @@ # license. Please see the LICENSE file that should have been included # as part of this package. +from __future__ import print_function + import os import shutil import tempfile @@ -113,6 +115,6 @@ if __name__ == "__main__": - print "Running fdist tests, which might take some time, please wait" + print("Running fdist tests, which might take some time, please wait") runner = unittest.TextTestRunner(verbosity = 2) unittest.main(testRunner=runner) diff -Nru python-biopython-1.62/Tests/test_PopGen_GenePop.py python-biopython-1.63/Tests/test_PopGen_GenePop.py --- python-biopython-1.62/Tests/test_PopGen_GenePop.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_PopGen_GenePop.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,6 +3,8 @@ # license. Please see the LICENSE file that should have been included # as part of this package. +from __future__ import print_function + import os import unittest @@ -34,17 +36,17 @@ """ ctrl = GenePopController() pop_iter, locus_iter = ctrl.calc_allele_genotype_freqs("PopGen" + os.sep + "big.gen") - #print pop, loci + #print("%s %s" % (pop, loci)) #for popc in pop_iter: # pop_name, loci_content = popc - # print pop_name - # for locus in loci_content.keys(): + # print(pop_name) + # for locus in loci_content: # geno_list, hets, freq_fis = loci_content[locus] - # print locus - # print hets - # print freq_fis - # print geno_list - # print + # print(locus) + # print(hets) + # print(freq_fis) + # print(geno_list) + # print("") def test_calc_diversities_fis_with_identity(self): """Test calculations of diversities ... @@ -83,7 +85,7 @@ ctrl = GenePopController() (allFis, allFst, allFit), itr = ctrl.calc_fst_all("PopGen" + os.sep + "haplo.gen") litr = list(itr) - assert not type(allFst) == int + assert not isinstance(allFst, int) assert len(litr) == 37 assert litr[36][0] == "Locus37" diff -Nru python-biopython-1.62/Tests/test_PopGen_GenePop_EasyController.py python-biopython-1.63/Tests/test_PopGen_GenePop_EasyController.py --- python-biopython-1.62/Tests/test_PopGen_GenePop_EasyController.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_PopGen_GenePop_EasyController.py 2013-12-05 14:10:43.000000000 +0000 @@ -58,7 +58,7 @@ """Test get alleles. """ #Returns keys of a dict, so order is Python implementation dependent - self.assertEqual(set(self.ctrl.get_alleles(0,"Locus3")), set([3, 20])) + self.assertEqual(set(self.ctrl.get_alleles(0, "Locus3")), set([3, 20])) def test_get_alleles_all_pops(self): """Test get alleles for all populations. @@ -68,21 +68,21 @@ def test_get_fis(self): """Test get Fis. """ - alleles, overall = self.ctrl.get_fis(0,"Locus2") + alleles, overall = self.ctrl.get_fis(0, "Locus2") self.assertEqual(alleles[3][0], 55) self.assertEqual(overall[0], 62) def test_get_allele_frequency(self): """Test allele frequency. """ - tot_genes, alleles = self.ctrl.get_allele_frequency(0,"Locus2") + tot_genes, alleles = self.ctrl.get_allele_frequency(0, "Locus2") self.assertEqual(tot_genes, 62) self.assertTrue(abs(alleles[20] - 0.113) < 0.05) def test_get_genotype_count(self): """Test genotype count. """ - self.assertEqual(len(self.ctrl.get_genotype_count(0,"Locus2")), 3) + self.assertEqual(len(self.ctrl.get_genotype_count(0, "Locus2")), 3) def test_estimate_nm(self): """Test Nm estimation. diff -Nru python-biopython-1.62/Tests/test_PopGen_GenePop_nodepend.py python-biopython-1.63/Tests/test_PopGen_GenePop_nodepend.py --- python-biopython-1.62/Tests/test_PopGen_GenePop_nodepend.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_PopGen_GenePop_nodepend.py 2013-12-05 14:10:43.000000000 +0000 @@ -75,9 +75,9 @@ class FileParserTest(unittest.TestCase): def setUp(self): - self.files = map(lambda x: os.path.join("PopGen", x), + self.files = [os.path.join("PopGen", x) for x in ["c2line.gen", "c3line.gen", "c2space.gen", - "c3space.gen", "haplo3.gen", "haplo2.gen"]) + "c3space.gen", "haplo3.gen", "haplo2.gen"]] self.pops_indivs = [ (3, [4, 3, 5]), (3, [4, 3, 5]), diff -Nru python-biopython-1.62/Tests/test_Prank_tool.py python-biopython-1.63/Tests/test_Prank_tool.py --- python-biopython-1.62/Tests/test_Prank_tool.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_Prank_tool.py 2013-12-05 14:10:43.000000000 +0000 @@ -40,8 +40,8 @@ if prank_exe: break else: - import commands - output = commands.getoutput("prank") + from Bio._py3k import getoutput + output = getoutput("prank") if "not found" not in output and "prank" in output.lower(): prank_exe = "prank" if not prank_exe: @@ -179,7 +179,7 @@ for record in old: record.id = record.id[:10] new = AlignIO.read(filename, format) - assert len(old) == len(new) + self.assertEqual(len(old), len(new)) for old_r, new_r in zip(old, new): self.assertEqual(old_r.id, new_r.id) self.assertEqual(str(old_r.seq), str(new_r.seq)) diff -Nru python-biopython-1.62/Tests/test_Probcons_tool.py python-biopython-1.63/Tests/test_Probcons_tool.py --- python-biopython-1.62/Tests/test_Probcons_tool.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_Probcons_tool.py 2013-12-05 14:10:43.000000000 +0000 @@ -7,7 +7,7 @@ import sys import os import unittest -from cStringIO import StringIO +from Bio._py3k import StringIO from Bio import AlignIO, SeqIO, MissingExternalDependencyError from Bio.Align.Applications import ProbconsCommandline @@ -18,8 +18,8 @@ if sys.platform=="win32": raise MissingExternalDependencyError("PROBCONS not available on Windows") else: - import commands - output = commands.getoutput("probcons") + from Bio._py3k import getoutput + output = getoutput("probcons") if "not found" not in output and "probcons" in output.lower(): probcons_exe = "probcons" @@ -47,11 +47,11 @@ stdout, stderr = cmdline() self.assertTrue(stderr.startswith("\nPROBCONS")) align = AlignIO.read(StringIO(stdout), "fasta") - records = list(SeqIO.parse(self.infile1,"fasta")) - self.assertEqual(len(records),len(align)) + records = list(SeqIO.parse(self.infile1, "fasta")) + self.assertEqual(len(records), len(align)) for old, new in zip(records, align): self.assertEqual(old.id, new.id) - self.assertEqual(str(new.seq).replace("-",""), str(old.seq).replace("-","")) + self.assertEqual(str(new.seq).replace("-", ""), str(old.seq).replace("-", "")) def test_Probcons_alignment_clustalw(self): """Round-trip through app and read clustalw alignment from stdout @@ -64,11 +64,11 @@ stdout, stderr = cmdline() self.assertTrue(stderr.strip().startswith("PROBCONS")) align = AlignIO.read(StringIO(stdout), "clustal") - records = list(SeqIO.parse(self.infile1,"fasta")) - self.assertEqual(len(records),len(align)) + records = list(SeqIO.parse(self.infile1, "fasta")) + self.assertEqual(len(records), len(align)) for old, new in zip(records, align): self.assertEqual(old.id, new.id) - self.assertEqual(str(new.seq).replace("-",""), str(old.seq).replace("-","")) + self.assertEqual(str(new.seq).replace("-", ""), str(old.seq).replace("-", "")) def test_Probcons_complex_commandline(self): """Round-trip through app with complex command line and output file diff -Nru python-biopython-1.62/Tests/test_ProtParam.py python-biopython-1.63/Tests/test_ProtParam.py --- python-biopython-1.62/Tests/test_ProtParam.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_ProtParam.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,11 @@ +# Copyright 2003-2004 by Iddo Friedberg. All rights reserved. +# Revisions copyright 2008-2010 by Peter Cock. All rights reserved. +# Revisions copyright 2012 by Matt Fenwick. All rights reserved. +# Revisions copyright 2012 by Kai Blin. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. + import unittest from Bio.SeqUtils import ProtParam, ProtParamData @@ -32,7 +40,7 @@ def test_aromaticity(self): "Test calculating protein aromaticity" # Old test used a number rounded to two digits, so use the same - self.assertEqual(round(self.analysis.aromaticity(),2), 0.10) + self.assertEqual(round(self.analysis.aromaticity(), 2), 0.10) def test_instability_index(self): "Test calculating protein instability index" @@ -110,25 +118,25 @@ def test_protein_scale(self): "Test calculating the Kite Doolittle scale" - expected = [-0.0783,+0.0358,+0.1258,+0.6950,+0.8775,+0.8350,+0.2925,+0.3383, - -0.1733,-0.4142,-0.5292,-0.6108,-0.8308,-0.8100,-0.8208,-1.0283, - -1.6300,-1.8233,-2.4267,-2.2292,-1.7817,-1.4742,-0.7467,-0.1608, - +0.1108,+0.2142,+0.1792,-0.1217,-0.4808,-0.4333,-0.5167,-0.2833, - +0.3758,+0.7225,+0.4958,+0.6033,+0.5625,+0.3108,-0.2408,-0.0575, - -0.3717,-0.7800,-1.1242,-1.4083,-1.7550,-2.2642,-2.8575,-2.9175, - -2.5358,-2.5325,-1.8142,-1.4667,-0.6058,-0.4483,+0.1300,+0.1225, - +0.2825,+0.1650,+0.3317,-0.2000,+0.2683,+0.1233,+0.4092,+0.1392, - +0.4192,+0.2758,-0.2350,-0.5750,-0.5983,-1.2067,-1.3867,-1.3583, - -0.8708,-0.5383,-0.3675,+0.0667,+0.0825,-0.0150,+0.1817,+0.4692, - +0.3017,+0.3800,+0.4825,+0.4675,+0.1575,-0.1783,-0.5175,-1.2017, - -1.7033,-1.5500,-1.2375,-0.8500,-0.0583,+0.3125,+0.4242,+0.7133, - +0.5633,+0.0483,-0.7167,-1.3158,-1.9217,-2.5033,-2.4117,-2.2483, - -2.3758,-2.0633,-1.8900,-1.8667,-1.9292,-1.8625,-2.0050,-2.2708, - -2.4050,-2.3508,-2.1758,-1.5533,-1.0350,-0.1983,-0.0233,+0.1800, - +0.0317,-0.0917,-0.6375,-0.9650,-1.4500,-1.6008,-1.7558,-1.5450, - -1.7900,-1.8133,-2.0125,-2.1383,-2.3142,-2.1525,-2.1425,-1.9733, - -1.4742,-0.8083,-0.2100,+0.8067,+1.3092,+1.8367,+2.0283,+2.3558] - for i,e in zip(self.analysis.protein_scale(ProtParamData.kd, 9, 0.4), expected): + expected = [-0.0783, +0.0358, +0.1258, +0.6950, +0.8775, +0.8350, +0.2925, +0.3383, + -0.1733, -0.4142, -0.5292, -0.6108, -0.8308, -0.8100, -0.8208, -1.0283, + -1.6300, -1.8233, -2.4267, -2.2292, -1.7817, -1.4742, -0.7467, -0.1608, + +0.1108, +0.2142, +0.1792, -0.1217, -0.4808, -0.4333, -0.5167, -0.2833, + +0.3758, +0.7225, +0.4958, +0.6033, +0.5625, +0.3108, -0.2408, -0.0575, + -0.3717, -0.7800, -1.1242, -1.4083, -1.7550, -2.2642, -2.8575, -2.9175, + -2.5358, -2.5325, -1.8142, -1.4667, -0.6058, -0.4483, +0.1300, +0.1225, + +0.2825, +0.1650, +0.3317, -0.2000, +0.2683, +0.1233, +0.4092, +0.1392, + +0.4192, +0.2758, -0.2350, -0.5750, -0.5983, -1.2067, -1.3867, -1.3583, + -0.8708, -0.5383, -0.3675, +0.0667, +0.0825, -0.0150, +0.1817, +0.4692, + +0.3017, +0.3800, +0.4825, +0.4675, +0.1575, -0.1783, -0.5175, -1.2017, + -1.7033, -1.5500, -1.2375, -0.8500, -0.0583, +0.3125, +0.4242, +0.7133, + +0.5633, +0.0483, -0.7167, -1.3158, -1.9217, -2.5033, -2.4117, -2.2483, + -2.3758, -2.0633, -1.8900, -1.8667, -1.9292, -1.8625, -2.0050, -2.2708, + -2.4050, -2.3508, -2.1758, -1.5533, -1.0350, -0.1983, -0.0233, +0.1800, + +0.0317, -0.0917, -0.6375, -0.9650, -1.4500, -1.6008, -1.7558, -1.5450, + -1.7900, -1.8133, -2.0125, -2.1383, -2.3142, -2.1525, -2.1425, -1.9733, + -1.4742, -0.8083, -0.2100, +0.8067, +1.3092, +1.8367, +2.0283, +2.3558] + for i, e in zip(self.analysis.protein_scale(ProtParamData.kd, 9, 0.4), expected): # Expected values have 4 decimal places, so restrict to that exactness self.assertAlmostEqual(i, e, places=4) diff -Nru python-biopython-1.62/Tests/test_Restriction.py python-biopython-1.63/Tests/test_Restriction.py --- python-biopython-1.62/Tests/test_Restriction.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_Restriction.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Testing code for Restriction enzyme classes of Biopython. """ diff -Nru python-biopython-1.62/Tests/test_SCOP_Cla.py python-biopython-1.63/Tests/test_SCOP_Cla.py --- python-biopython-1.62/Tests/test_SCOP_Cla.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_SCOP_Cla.py 2013-12-05 14:10:43.000000000 +0000 @@ -50,7 +50,7 @@ in actual_hierarchy) self.assertEqual(len(actual_hierarchy), len(expected_hierarchy)) - for key, actual_value in actual_hierarchy.iteritems(): + for key, actual_value in actual_hierarchy.items(): self.assertEqual(actual_value, expected_hierarchy[key]) finally: f.close() @@ -67,7 +67,7 @@ record = Cla.Record(recLine) self.assertEqual(record.sid, 'd1dan.1') self.assertEqual(record.residues.pdbid, '1dan') - self.assertEqual(record.residues.fragments, (('T','',''),('U','91','106'))) + self.assertEqual(record.residues.fragments, (('T', '', ''), ('U', '91', '106'))) self.assertEqual(record.sccs, 'b.1.2.1') self.assertEqual(record.sunid, 21953) self.assertEqual(record.hierarchy, {'cl' : 48724, diff -Nru python-biopython-1.62/Tests/test_SCOP_Des.py python-biopython-1.63/Tests/test_SCOP_Des.py --- python-biopython-1.62/Tests/test_SCOP_Des.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_SCOP_Des.py 2013-12-05 14:10:43.000000000 +0000 @@ -47,7 +47,7 @@ def testRecord(self): """Test one record in detail""" recLine = '49268\tsp\tb.1.2.1\t-\tHuman (Homo sapiens) \n' - recFields = (49268,'sp','b.1.2.1','','Human (Homo sapiens)') + recFields = (49268, 'sp', 'b.1.2.1', '', 'Human (Homo sapiens)') record = Des.Record(recLine) self.assertEqual(record.sunid, recFields[0]) diff -Nru python-biopython-1.62/Tests/test_SCOP_Dom.py python-biopython-1.63/Tests/test_SCOP_Dom.py --- python-biopython-1.62/Tests/test_SCOP_Dom.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_SCOP_Dom.py 2013-12-05 14:10:43.000000000 +0000 @@ -25,7 +25,7 @@ count = 0 for record in Dom.parse(f): count +=1 - self.assertEqual(count,10) + self.assertEqual(count, 10) finally: f.close() @@ -36,7 +36,7 @@ for line in f: record = Dom.Record(line) #End of line is platform dependent. Strip it off - self.assertEqual(str(record).rstrip(),line.rstrip()) + self.assertEqual(str(record).rstrip(), line.rstrip()) finally: f.close() @@ -51,9 +51,9 @@ rec = Dom.Record(recLine) self.assertEqual(rec.sid, 'd7hbib_') - self.assertEqual(rec.residues.pdbid,'7hbi') - self.assertEqual(rec.residues.fragments,(('b','',''),) ) - self.assertEqual(rec.hierarchy,'1.001.001.001.001.001') + self.assertEqual(rec.residues.pdbid, '7hbi') + self.assertEqual(rec.residues.fragments, (('b', '', ''),) ) + self.assertEqual(rec.hierarchy, '1.001.001.001.001.001') if __name__ == '__main__': diff -Nru python-biopython-1.62/Tests/test_SCOP_Raf.py python-biopython-1.63/Tests/test_SCOP_Raf.py --- python-biopython-1.62/Tests/test_SCOP_Raf.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_SCOP_Raf.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,8 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Unit test for Raf""" diff -Nru python-biopython-1.62/Tests/test_SCOP_Residues.py python-biopython-1.63/Tests/test_SCOP_Residues.py --- python-biopython-1.62/Tests/test_SCOP_Residues.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_SCOP_Residues.py 2013-12-05 14:10:43.000000000 +0000 @@ -15,14 +15,14 @@ ( "A:", (("A", "", ""),) ), ( "1:", (("1", "", ""),) ), ( "1-100", (("", "1", "100"),) ), - ( "B:1-101", (("B", "1" ,"101"),) ), + ( "B:1-101", (("B", "1", "101"),) ), ( "1:1a-100a", (("1", "1a", "100a"),) ), ( "a:-100a--1a", (("a", "-100a", "-1a"),) ), ( "-1-100", (("", "-1", "100"),) ), ( "-1-100", (("", "-1", "100"),) ), - ( "A:12-19,A:23-25", (("A","12","19"),("A","23","25")) ), - ( "12-19,1:23-25", (("","12","19"),("1","23","25")) ), - ( "0-1,1:-1a-25a,T:", (("","0","1"),("1","-1a","25a"),("T","","")) ), + ( "A:12-19,A:23-25", (("A", "12", "19"), ("A", "23", "25")) ), + ( "12-19,1:23-25", (("", "12", "19"), ("1", "23", "25")) ), + ( "0-1,1:-1a-25a,T:", (("", "0", "1"), ("1", "-1a", "25a"), ("T", "", "")) ), ) def testParse(self): diff -Nru python-biopython-1.62/Tests/test_SCOP_Scop.py python-biopython-1.63/Tests/test_SCOP_Scop.py --- python-biopython-1.62/Tests/test_SCOP_Scop.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_SCOP_Scop.py 2013-12-05 14:10:43.000000000 +0000 @@ -7,8 +7,11 @@ """Unit test for Scop""" +from __future__ import print_function + import unittest -from StringIO import * +from Bio._py3k import StringIO +from Bio._py3k import zip from Bio.SCOP import * @@ -24,8 +27,8 @@ """ fields1 = cla_line_1.rstrip().split('\t') fields2 = cla_line_2.rstrip().split('\t') - print fields1 - print fields2 + print(fields1) + print(fields2) # compare the first five fields in a Cla line, which should be exactly # the same if fields1[:5] != fields2[:5]: diff -Nru python-biopython-1.62/Tests/test_SVDSuperimposer.py python-biopython-1.63/Tests/test_SVDSuperimposer.py --- python-biopython-1.62/Tests/test_SVDSuperimposer.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_SVDSuperimposer.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,6 +3,8 @@ # as part of this package. #TODO - Don't use "from XXX import *" +from __future__ import print_function + try: from numpy import * from numpy import dot # missing in old PyPy's micronumpy @@ -12,7 +14,7 @@ raise MissingPythonDependencyError( "Install NumPy if you want to use Bio.SVDSuperimposer.") -from Bio.SVDSuperimposer import * +from Bio.SVDSuperimposer import SVDSuperimposer # start with two coordinate sets (Nx3 arrays - Float0) @@ -60,19 +62,13 @@ versions of the underlying libraries or the compilation options they used). """ + return "[%s]" % "\n ".join("[%s]" % " ".join("% 1.4f" % v for v in row) + for row in matrix) - #This uses a fancy double nested list expression. - #If and when Biopython requires Python 2.4 or later, - #it would be slightly nicer to use generator expressions. - return "[" \ - + "\n ".join(["[" - + " ".join(["% 1.4f" % val for val in row]) - + "]" for row in matrix]) \ - + "]" # output results -print simple_matrix_print(y_on_x1) -print -print simple_matrix_print(y_on_x2) -print -print "%.2f" % rms +print(simple_matrix_print(y_on_x1)) +print("") +print(simple_matrix_print(y_on_x2)) +print("") +print("%.2f" % rms) diff -Nru python-biopython-1.62/Tests/test_SearchIO_blast_tab.py python-biopython-1.63/Tests/test_SearchIO_blast_tab.py --- python-biopython-1.62/Tests/test_SearchIO_blast_tab.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_SearchIO_blast_tab.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,9 +5,6 @@ """Tests for SearchIO BlastIO parsers.""" -# For using with statement in Python 2.5 or Jython -from __future__ import with_statement - import os import unittest @@ -29,8 +26,9 @@ def test_tab_2228_tblastx_001(self): "Test parsing TBLASTX 2.2.28+ tabular output (tab_2228_tblastx_001)" tab_file = get_file('tab_2228_tblastx_001.txt') - qresults = list(parse(tab_file, FMT, fields=all_fields.values(), - comments=True)) + qresults = list(parse(tab_file, FMT, + fields=list(all_fields.values()), + comments=True)) # this a single query, with 192 hits and 243 hsps self.assertEqual(1, len(qresults)) @@ -67,7 +65,7 @@ counter = 0 # test first qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('gi|16080617|ref|NP_391444.1|', qresult.id) @@ -112,7 +110,7 @@ self.assertEqual(31.6, hsp.bitscore) # test last qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('gi|11464971:4-101', qresult.id) @@ -152,7 +150,7 @@ self.assertEqual(32.7, hsp.bitscore) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(2, counter) def test_tab_2226_tblastn_002(self): @@ -162,7 +160,7 @@ qresults = parse(xml_file, FMT) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) def test_tab_2226_tblastn_003(self): "Test parsing TBLASTN 2.2.26+ tabular output (tab_2226_tblastn_003)" @@ -172,7 +170,7 @@ counter = 0 # test first qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('gi|16080617|ref|NP_391444.1|', qresult.id) @@ -217,7 +215,7 @@ self.assertEqual(31.6, hsp.bitscore) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_tab_2226_tblastn_004(self): @@ -227,7 +225,7 @@ qresults = parse(xml_file, FMT) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('gi|11464971:4-101', qresult.id) @@ -267,7 +265,7 @@ self.assertEqual(32.7, hsp.bitscore) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_tab_2226_tblastn_005(self): @@ -278,7 +276,7 @@ counter = 0 # test first qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('tblastn', qresult.program) @@ -288,7 +286,7 @@ self.assertEqual(0, len(qresult)) # test second qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('tblastn', qresult.program) @@ -336,7 +334,7 @@ self.assertEqual(31.6, hsp.bitscore) # test last qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('tblastn', qresult.program) @@ -379,7 +377,7 @@ self.assertEqual(32.7, hsp.bitscore) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(3, counter) def test_tab_2226_tblastn_006(self): @@ -389,7 +387,7 @@ qresults = parse(xml_file, FMT, comments=True) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('tblastn', qresult.program) @@ -399,7 +397,7 @@ self.assertEqual(0, len(qresult)) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_tab_2226_tblastn_007(self): @@ -409,7 +407,7 @@ qresults = parse(xml_file, FMT, comments=True) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('tblastn', qresult.program) @@ -457,7 +455,7 @@ self.assertEqual(31.6, hsp.bitscore) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_tab_2226_tblastn_008(self): @@ -467,7 +465,7 @@ qresults = parse(xml_file, FMT, comments=True) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('tblastn', qresult.program) @@ -510,7 +508,7 @@ self.assertEqual(32.7, hsp.bitscore) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_tab_2226_tblastn_009(self): @@ -521,7 +519,7 @@ counter = 0 # test first qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('', qresult.program) @@ -549,7 +547,7 @@ self.assertEqual('gi|16080617|ref|NP_391444.1|', hsp.query_id) # test last qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('', qresult.program) @@ -572,7 +570,7 @@ self.assertEqual('gi|11464971:4-101', hsp.query_id) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(2, counter) def test_tab_2226_tblastn_010(self): @@ -583,7 +581,7 @@ counter = 0 # test first qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('tblastn', qresult.program) @@ -593,7 +591,7 @@ self.assertEqual(0, len(qresult)) # test second qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('tblastn', qresult.program) @@ -625,7 +623,7 @@ self.assertEqual(31.6, hsp.bitscore) # test last qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('tblastn', qresult.program) @@ -652,7 +650,7 @@ self.assertEqual(32.7, hsp.bitscore) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(3, counter) def test_tab_2226_tblastn_011(self): @@ -663,7 +661,7 @@ counter = 0 # test first qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('tblastn', qresult.program) @@ -673,7 +671,7 @@ self.assertEqual(0, len(qresult)) # test second qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('tblastn', qresult.program) @@ -751,7 +749,7 @@ self.assertEqual(1, hsp.hit_frame) # test last qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('tblastn', qresult.program) @@ -822,7 +820,7 @@ self.assertEqual(2, hsp.hit_frame) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(3, counter) def test_tab_2226_tblastn_012(self): @@ -833,7 +831,7 @@ counter = 0 # test first qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('tblastn', qresult.program) @@ -844,7 +842,7 @@ self.assertEqual(0, len(qresult)) # test second qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('tblastn', qresult.program) @@ -855,7 +853,7 @@ self.assertEqual(3, len(qresult)) # test last qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('tblastn', qresult.program) @@ -866,7 +864,7 @@ self.assertEqual(5, len(qresult)) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(3, counter) def test_tab_2226_tblastn_013(self): @@ -876,7 +874,7 @@ qresults = parse(xml_file, FMT, fields="qseq std sseq") counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('', qresult.program) @@ -927,7 +925,7 @@ self.assertEqual('GLVPDHTLILPVGHYQSMLDLTEEVQTELDQFKSALRKYYLSKGKTCVIYERNFRTQHL', str(hsp.hit.seq)) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) diff -Nru python-biopython-1.62/Tests/test_SearchIO_blast_text.py python-biopython-1.63/Tests/test_SearchIO_blast_text.py --- python-biopython-1.62/Tests/test_SearchIO_blast_text.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_SearchIO_blast_text.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,9 +5,6 @@ """Tests for SearchIO BlastIO plain text parsers.""" -# For using with statement in Python 2.5 or Jython -from __future__ import with_statement - import os import unittest diff -Nru python-biopython-1.62/Tests/test_SearchIO_blast_xml.py python-biopython-1.63/Tests/test_SearchIO_blast_xml.py --- python-biopython-1.62/Tests/test_SearchIO_blast_xml.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_SearchIO_blast_xml.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,7 +5,6 @@ """Tests for SearchIO BlastIO parsers.""" - import os import unittest @@ -15,6 +14,10 @@ TEST_DIR = 'Blast' FMT = 'blast-xml' +REFERENCE = (u'Altschul, Stephen F., Thomas L. Madden, Alejandro A. Sch\xe4ffer, ' + u'Jinghui Zhang, Zheng Zhang, Webb Miller, and David J. Lipman (1997), ' + u'"Gapped BLAST and PSI-BLAST: a new generation of protein database ' + u'search programs", Nucleic Acids Res. 25:3389-3402.') def get_file(filename): """Returns the path of a test file.""" @@ -29,11 +32,11 @@ counter = 0 # test each qresult's attributes - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('2.2.12', qresult.version) - self.assertEqual(u'Altschul, Stephen F., Thomas L. Madden, Alejandro A. Sch\xe4ffer, Jinghui Zhang, Zheng Zhang, Webb Miller, and David J. Lipman (1997), "Gapped BLAST and PSI-BLAST: a new generation of protein database search programs", Nucleic Acids Res. 25:3389-3402.', qresult.reference) + self.assertEqual(REFERENCE, qresult.reference) self.assertEqual(10.0, qresult.param_evalue_threshold) self.assertEqual(1, qresult.param_score_match) self.assertEqual(-3, qresult.param_score_mismatch) @@ -107,7 +110,7 @@ self.assertRaises(IndexError, hit.__getitem__, 1) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_xml_2226_blastn_001(self): @@ -116,7 +119,7 @@ counter = 0 # test each qresult's attributes - qresult = qresults.next() + qresult = next(qresults) counter += 1 # test meta variables, only for the first one @@ -147,7 +150,7 @@ self.assertEqual(0, len(qresult)) # test parsed values of the second qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('gi|356995852:1-490', qresult.id) self.assertEqual('Mus musculus POU domain, class 5, transcription factor 1 (Pou5f1), transcript variant 1, mRNA', qresult.description) @@ -189,7 +192,7 @@ self.assertRaises(IndexError, hit.__getitem__, 1) # test parsed values of the third qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('hg19_dna', qresult.id) self.assertEqual('range=chr1:1207307-1207372 5\'pad=0 3\'pad=0 strand=+ repeatMasking=none', qresult.description) @@ -273,7 +276,7 @@ self.assertEqual('||| |||||||||||||||||||||||||||||| |||||||||||||||||||||||||||||||', hsp.aln_annotation['homology']) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(3, counter) def test_xml_2226_blastn_002(self): @@ -282,7 +285,7 @@ counter = 0 # test each qresult's attributes - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('2.2.26+', qresult.version) @@ -311,7 +314,7 @@ self.assertEqual([], list(qresult.hits)) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_xml_2226_blastn_003(self): @@ -320,7 +323,7 @@ counter = 0 # test each qresult's attributes - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('2.2.26+', qresult.version) @@ -379,7 +382,7 @@ self.assertRaises(IndexError, hit.__getitem__, 1) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_xml_2226_blastn_004(self): @@ -387,7 +390,7 @@ qresults = parse(xml_file, FMT) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('hg19_dna', qresult.id) self.assertEqual('range=chr1:1207307-1207372 5\'pad=0 3\'pad=0 ' @@ -473,7 +476,7 @@ self.assertEqual('||| |||||||||||||||||||||||||||||| |||||||||||||||||||||||||||||||', hsp.aln_annotation['homology']) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_xml_2226_blastn_005(self): @@ -482,7 +485,7 @@ counter = 0 # test each qresult's attributes - qresult = qresults.next() + qresult = next(qresults) counter += 1 # test meta variables, only for the first one @@ -513,7 +516,7 @@ self.assertEqual(0, len(qresult)) # test parsed values of the second qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('gi|356995852:1-490', qresult.id) self.assertEqual('Mus musculus POU domain, class 5, transcription ' @@ -557,7 +560,7 @@ self.assertRaises(IndexError, hit.__getitem__, 1) # test parsed values of the third qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('hg19_dna', qresult.id) self.assertEqual('range=chr1:1207307-1207372 5\'pad=0 3\'pad=0 ' @@ -622,7 +625,7 @@ self.assertEqual('||| |||| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||', hsp.aln_annotation['homology']) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(3, counter) @@ -633,11 +636,11 @@ qresults = parse(xml_file, FMT) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('2.2.12', qresult.version) - self.assertEqual(u'Altschul, Stephen F., Thomas L. Madden, Alejandro A. Sch\xe4ffer, Jinghui Zhang, Zheng Zhang, Webb Miller, and David J. Lipman (1997), "Gapped BLAST and PSI-BLAST: a new generation of protein database search programs", Nucleic Acids Res. 25:3389-3402.', qresult.reference) + self.assertEqual(REFERENCE, qresult.reference) self.assertEqual('BLOSUM62', qresult.param_matrix) self.assertEqual(10.0, qresult.param_evalue_threshold) self.assertEqual('L;', qresult.param_filter) @@ -712,7 +715,7 @@ self.assertRaises(IndexError, hit.__getitem__, 1) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_xml_2218_blastp_001(self): @@ -720,11 +723,11 @@ qresults = parse(xml_file, FMT) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('2.2.18+', qresult.version) - self.assertEqual(u'Altschul, Stephen F., Thomas L. Madden, Alejandro A. Sch\xe4ffer, Jinghui Zhang, Zheng Zhang, Webb Miller, and David J. Lipman (1997), "Gapped BLAST and PSI-BLAST: a new generation of protein database search programs", Nucleic Acids Res. 25:3389-3402.', qresult.reference) + self.assertEqual(REFERENCE, qresult.reference) self.assertEqual('BLOSUM62', qresult.param_matrix) self.assertEqual(10.0, qresult.param_evalue_threshold) self.assertEqual(11, qresult.param_gap_open) @@ -795,7 +798,7 @@ self.assertEqual('T +A C + +V I+++ +W+++ H+ V + WAP', hsp.aln_annotation['homology']) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_xml_2218_blastp_002(self): @@ -803,13 +806,12 @@ qresults = parse(xml_file, FMT) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 # test meta variables, only for the first one self.assertEqual('2.2.18+', qresult.version) - self.assertEqual(u'Altschul, Stephen F., Thomas L. Madden, Alejandro A. Sch\xe4ffer, Jinghui Zhang, Zheng Zhang, Webb Miller, and David J. Lipman (1997), "Gapped BLAST and PSI-BLAST: a new generation of protein database search programs", Nucleic Acids Res. 25:3389-3402.', - qresult.reference) + self.assertEqual(REFERENCE, qresult.reference) self.assertEqual('BLOSUM62', qresult.param_matrix) self.assertEqual(0.01, qresult.param_evalue_threshold) self.assertEqual(11, qresult.param_gap_open) @@ -831,7 +833,7 @@ self.assertEqual(0, len(qresult)) # second qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('gi|129628|sp|P07175.1|PARA_AGRTU', qresult.id) @@ -846,7 +848,7 @@ self.assertEqual(0, len(qresult)) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(2, counter) def test_xml_2218L_blastp_001(self): @@ -855,7 +857,7 @@ counter = 0 # test each qresult's attributes - qresult = qresults.next() + qresult = next(qresults) counter += 1 # test meta variables, only for the first one @@ -883,7 +885,7 @@ self.assertEqual(0, len(qresult)) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_xml_2222_blastp_001(self): @@ -891,7 +893,7 @@ qresults = parse(xml_file, FMT) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('2.2.22+', qresult.version) @@ -976,7 +978,7 @@ counter = 0 # test each qresult's attributes - qresult = qresults.next() + qresult = next(qresults) counter += 1 # test meta variables, only for the first one @@ -1008,7 +1010,7 @@ self.assertEqual(0, len(qresult)) # test parsed values of the second qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('gi|16080617|ref|NP_391444.1|', qresult.id) self.assertEqual('membrane bound lipoprotein [Bacillus subtilis ' @@ -1051,7 +1053,7 @@ self.assertRaises(IndexError, hit.__getitem__, 1) # test parsed values of the third qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('gi|11464971:4-101', qresult.id) self.assertEqual('pleckstrin [Mus musculus]', qresult.description) @@ -1131,7 +1133,7 @@ self.assertEqual('KRIREGYLVKKGS+FNTWKPMWV+LLEDGIEFYKKKSDNSPKGMIPLKGSTLTSPCQDFGKRMFV KITTTKQQDHFFQAAFLEERD WVRDIKKAIK', hsp.aln_annotation['homology']) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(3, counter) def test_xml_2226_blastp_002(self): @@ -1140,7 +1142,7 @@ counter = 0 # test each qresult's attributes - qresult = qresults.next() + qresult = next(qresults) counter += 1 # test meta variables, only for the first one @@ -1172,7 +1174,7 @@ self.assertEqual(0, len(qresult)) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_xml_2226_blastp_003(self): @@ -1181,7 +1183,7 @@ counter = 0 # test each qresult's attributes - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('2.2.26+', qresult.version) @@ -1238,7 +1240,7 @@ self.assertRaises(IndexError, hit.__getitem__, 1) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_xml_2226_blastp_004(self): @@ -1247,7 +1249,7 @@ counter = 0 # test each qresult's attributes - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('2.2.26+', qresult.version) @@ -1343,7 +1345,7 @@ self.assertEqual('KRIREGYLVKKGS+FNTWKPMWV+LLEDGIEFYKKKSDNSPKGMIPLKGSTLTSPCQDFGKRMFV KITTTKQQDHFFQAAFLEERD WVRDIKKAIK', hsp.aln_annotation['homology']) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_xml_2226_blastp_005(self): @@ -1352,7 +1354,7 @@ counter = 0 # test each qresult's attributes - qresult = qresults.next() + qresult = next(qresults) counter += 1 # test meta variables, only for the first one @@ -1384,7 +1386,7 @@ self.assertEqual(0, len(qresult)) # test parsed values of the second qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('gi|16080617|ref|NP_391444.1|', qresult.id) self.assertEqual('membrane bound lipoprotein [Bacillus subtilis subsp. subtilis str. 168]', qresult.description) @@ -1424,7 +1426,7 @@ self.assertRaises(IndexError, hit.__getitem__, 1) # test parsed values of the third qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('gi|11464971:4-101', qresult.id) self.assertEqual('pleckstrin [Mus musculus]', qresult.description) @@ -1504,7 +1506,7 @@ self.assertEqual('KRIREGYLVKKGS+FNTWKPMWV+LLEDGIEFYKKKSDNSPKGMIPLKGSTLTSPCQDFGKRMFV KITTTKQQDHFFQAAFLEERD WVRDIKKAIK', hsp.aln_annotation['homology']) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(3, counter) @@ -1515,11 +1517,11 @@ qresults = parse(xml_file, FMT) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('2.2.12', qresult.version) - self.assertEqual(u'Altschul, Stephen F., Thomas L. Madden, Alejandro A. Sch\xe4ffer, Jinghui Zhang, Zheng Zhang, Webb Miller, and David J. Lipman (1997), "Gapped BLAST and PSI-BLAST: a new generation of protein database search programs", Nucleic Acids Res. 25:3389-3402.', qresult.reference) + self.assertEqual(REFERENCE, qresult.reference) self.assertEqual('BLOSUM62', qresult.param_matrix) self.assertEqual(10.0, qresult.param_evalue_threshold) self.assertEqual('L;', qresult.param_filter) @@ -1588,7 +1590,7 @@ self.assertEqual('+ +NS + A+ N+ SSSG K++ +K +KS + + H++ IN+ +K KEH VV +', hsp.aln_annotation['homology']) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_xml_2222_blastx_001(self): @@ -1596,7 +1598,7 @@ qresults = parse(xml_file, FMT) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('2.2.22+', qresult.version) @@ -1651,7 +1653,7 @@ counter = 0 # test each qresult's attributes - qresult = qresults.next() + qresult = next(qresults) counter += 1 # test meta variables, only for the first one @@ -1683,7 +1685,7 @@ self.assertEqual(0, len(qresult)) # test parsed values of the third qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('hg19_dna', qresult.id) self.assertEqual('range=chr1:1207057-1207541 5\'pad=0 3\'pad=0 ' @@ -1764,7 +1766,7 @@ self.assertEqual('SF +AG+QW DL QPPPPGFK FS LS P+SW+YRH+P C NF VETGF+HVGQA LE SG L A ASQS GITGVSHHA+', hsp.aln_annotation['homology']) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(2, counter) def test_xml_2226_blastx_002(self): @@ -1772,7 +1774,7 @@ qresults = parse(xml_file, FMT) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('2.2.26+', qresult.version) @@ -1802,7 +1804,7 @@ self.assertEqual(0, len(qresult)) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_xml_2226_blastx_003(self): @@ -1810,7 +1812,7 @@ qresults = parse(xml_file, FMT) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('2.2.26+', qresult.version) @@ -1906,7 +1908,7 @@ self.assertEqual('SF +AG+QW DL QPPPPGFK FS LS P+SW+YRH+P C NF VETGF+HVGQA LE SG L A ASQS GITGVSHHA+', hsp.aln_annotation['homology']) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_xml_2226_blastx_004(self): @@ -1915,7 +1917,7 @@ counter = 0 # test each qresult's attributes - qresult = qresults.next() + qresult = next(qresults) counter += 1 # test meta variables, only for the first one @@ -1947,7 +1949,7 @@ self.assertEqual(0, len(qresult)) # test parsed values of the second qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('hg19_dna', qresult.id) self.assertEqual('range=chr1:1207057-1207541 5\'pad=0 3\'pad=0 ' @@ -2029,7 +2031,7 @@ self.assertEqual('V AGVQW +L QPPP FK FS LS SSWD R PPCL+ FVFL+ETGF HVGQAGL+ SG+ A ASQS GI GVSH P C+', hsp.aln_annotation['homology']) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(2, counter) @@ -2040,11 +2042,11 @@ qresults = parse(xml_file, FMT) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('2.2.12', qresult.version) - self.assertEqual(u'Altschul, Stephen F., Thomas L. Madden, Alejandro A. Sch\xe4ffer, Jinghui Zhang, Zheng Zhang, Webb Miller, and David J. Lipman (1997), "Gapped BLAST and PSI-BLAST: a new generation of protein database search programs", Nucleic Acids Res. 25:3389-3402.', qresult.reference) + self.assertEqual(REFERENCE, qresult.reference) self.assertEqual('BLOSUM62', qresult.param_matrix) self.assertEqual(0.001, qresult.param_evalue_threshold) self.assertEqual(11, qresult.param_gap_open) @@ -2116,7 +2118,7 @@ self.assertEqual('L KV +VTG +G+G A+AV GQ +KVVVNY ++ E A +V EI+ AI ++ DV + V L++ AV+ FG LD++ +NAG+ + VPS +E +E +++V N G F +REA ++ E G +I SS + P Y+ SKG + LA++ K I VN + PGAI T + N E F D +', hsp.aln_annotation['homology']) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_xml_2226_tblastn_001(self): @@ -2125,7 +2127,7 @@ counter = 0 # test each qresult's attributes - qresult = qresults.next() + qresult = next(qresults) counter += 1 # test meta variables, only for the first one @@ -2156,7 +2158,7 @@ self.assertEqual(0, len(qresult)) # test parsed values of the second qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('gi|16080617|ref|NP_391444.1|', qresult.id) self.assertEqual('membrane bound lipoprotein [Bacillus subtilis ' @@ -2196,7 +2198,7 @@ self.assertRaises(IndexError, hit.__getitem__, 1) # test parsed values of the third qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('gi|11464971:4-101', qresult.id) self.assertEqual('pleckstrin [Mus musculus]', qresult.description) @@ -2276,7 +2278,7 @@ self.assertEqual('GS F TW +++ +L E E K D + KG++ L S TS', hsp.aln_annotation['homology']) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(3, counter) def test_xml_2226_tblastn_002(self): @@ -2284,7 +2286,7 @@ qresults = parse(xml_file, FMT) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('2.2.26+', qresult.version) @@ -2312,7 +2314,7 @@ self.assertEqual(-1, qresult.stat_entropy) self.assertEqual(0, len(qresult)) - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_xml_2226_tblastn_003(self): @@ -2320,7 +2322,7 @@ qresults = parse(xml_file, FMT) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('2.2.26+', qresult.version) @@ -2374,7 +2376,7 @@ self.assertRaises(IndexError, hit.__getitem__, 1) - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_xml_2226_tblastn_004(self): @@ -2382,7 +2384,7 @@ qresults = parse(xml_file, FMT) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('2.2.26+', qresult.version) @@ -2476,7 +2478,7 @@ self.assertEqual('GSCFPTWDLIFIEVLNPFLKEKLWEADNEEISKFVDLTLKGLVDLYPSHFTS', str(hsp.hit.seq)) self.assertEqual('GS F TW +++ +L E E K D + KG++ L S TS', hsp.aln_annotation['homology']) - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_xml_2226_tblastn_005(self): @@ -2485,7 +2487,7 @@ counter = 0 # test each qresult's attributes - qresult = qresults.next() + qresult = next(qresults) counter += 1 # test meta variables, only for the first one @@ -2516,7 +2518,7 @@ self.assertEqual(0, len(qresult)) # test parsed values of the second qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('gi|16080617|ref|NP_391444.1|', qresult.id) self.assertEqual('membrane bound lipoprotein [Bacillus subtilis subsp. subtilis str. 168]', qresult.description) @@ -2555,7 +2557,7 @@ self.assertRaises(IndexError, hit.__getitem__, 1) # test parsed values of the third qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('gi|11464971:4-101', qresult.id) self.assertEqual('pleckstrin [Mus musculus]', qresult.description) @@ -2635,7 +2637,7 @@ self.assertEqual('KRIREGYLVKKGS+FNTWKPMWVVLLEDGIEFYKKKSDNSPKGMIPLKGSTLTSPCQDFGKRMFV KITTTKQQDHFFQAAFLEERDAWVRDIKKAIK', hsp.aln_annotation['homology']) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(3, counter) @@ -2647,12 +2649,12 @@ counter = 0 # test the first qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 # test meta variables, only for the first one self.assertEqual('2.2.12', qresult.version) - self.assertEqual(u'Altschul, Stephen F., Thomas L. Madden, Alejandro A. Sch\xe4ffer, Jinghui Zhang, Zheng Zhang, Webb Miller, and David J. Lipman (1997), "Gapped BLAST and PSI-BLAST: a new generation of protein database search programs", Nucleic Acids Res. 25:3389-3402.', qresult.reference) + self.assertEqual(REFERENCE, qresult.reference) self.assertEqual('BLOSUM80', qresult.param_matrix) self.assertEqual(1, qresult.param_evalue_threshold) self.assertEqual('L;', qresult.param_filter) @@ -2723,7 +2725,7 @@ self.assertEqual('PL K H +FQ S+ FY+ C+ + +QLL', hsp.aln_annotation['homology']) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_xml_2226_tblastx_001(self): @@ -2732,7 +2734,7 @@ counter = 0 # test each qresult's attributes - qresult = qresults.next() + qresult = next(qresults) counter += 1 # test meta variables, only for the first one @@ -2763,7 +2765,7 @@ self.assertEqual(0, len(qresult)) # test parsed values of the second qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('gi|296147483:1-350', qresult.id) self.assertEqual('Saccharomyces cerevisiae S288c Mon2p (MON2) mRNA, complete cds', qresult.description) @@ -2843,7 +2845,7 @@ self.assertEqual('IR+ASDKSIEILK VHS+EEL RHPDF +P V++C S+NAK+TT++MQC Q L+TVP IP +LS++LDAFIEA LAM+I+LK', hsp.aln_annotation['homology']) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(2, counter) def test_xml_2226_tblastx_002(self): @@ -2851,7 +2853,7 @@ qresults = parse(xml_file, FMT) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('2.2.26+', qresult.version) @@ -2879,7 +2881,7 @@ self.assertEqual(-1, qresult.stat_entropy) self.assertEqual(0, len(qresult)) - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_xml_2226_tblastx_003(self): @@ -2887,7 +2889,7 @@ qresults = parse(xml_file, FMT) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('2.2.26+', qresult.version) @@ -2982,7 +2984,7 @@ self.assertEqual('IR+ASDKSIEILK VHS+EEL RHPDF +P V++C S+NAK+TT++MQC Q L+TVP IP +LS++LDAFIEA LAM+I+LK', hsp.aln_annotation['homology']) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_xml_2226_tblastx_004(self): @@ -2991,7 +2993,7 @@ counter = 0 # test each qresult's attributes - qresult = qresults.next() + qresult = next(qresults) counter += 1 # test meta variables, only for the first one @@ -3022,7 +3024,7 @@ self.assertEqual(0, len(qresult)) # test parsed values of the second qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('gi|296147483:1-350', qresult.id) self.assertEqual('Saccharomyces cerevisiae S288c Mon2p (MON2) mRNA, complete cds', qresult.description) @@ -3106,7 +3108,7 @@ self.assertEqual('IR+ASDKSIEILK VHS+EEL RHPDF +P V++C S+NAK+TT++MQC Q L+TVP IP +LS++LDAFIEA LAM+I+LK', hsp.aln_annotation['homology']) # check if we've finished iteration over qresults - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(2, counter) @@ -3118,7 +3120,7 @@ counter = 0 # test each qresult's attributes - qresult = qresults.next() + qresult = next(qresults) counter += 1 # test the Hit IDs only, since this is a special case diff -Nru python-biopython-1.62/Tests/test_SearchIO_exonerate.py python-biopython-1.63/Tests/test_SearchIO_exonerate.py --- python-biopython-1.62/Tests/test_SearchIO_exonerate.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_SearchIO_exonerate.py 2013-12-05 14:10:43.000000000 +0000 @@ -1383,7 +1383,7 @@ """Test parsing exonerate output (exn_22_q_none.exn)""" exn_file = get_file('exn_22_q_none.exn') qresults = parse(exn_file, 'exonerate-text') - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) class ExonerateVulgarCases(unittest.TestCase): diff -Nru python-biopython-1.62/Tests/test_SearchIO_fasta_m10.py python-biopython-1.63/Tests/test_SearchIO_fasta_m10.py --- python-biopython-1.62/Tests/test_SearchIO_fasta_m10.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_SearchIO_fasta_m10.py 2013-12-05 14:10:43.000000000 +0000 @@ -70,6 +70,7 @@ self.assertEqual(103, hsp.hit_end) self.assertEqual('SQRSTRRKPENQPTRVILFNKPYDVLPQFTDEAGRKTLKEFIPVQGVYAAGRLDRDSEGLLVLTNNGALQARLTQPGKRTGKIYYVQV', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({}, hsp.aln_annotation) # first qresult, second hit hit = qresult[1] self.assertEqual('gi|15831859|ref|NP_310632.1|', hit.id) @@ -95,6 +96,7 @@ self.assertEqual(219, hsp.hit_end) self.assertEqual('EIKPRGTSKGEAIAAFMQEAPFIGRTPVFLGDDLTDESGFAVVNRLGGMSVKI', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({}, hsp.aln_annotation) # test second qresult qresult = qresults[1] @@ -130,6 +132,7 @@ self.assertEqual(384, hsp.hit_end) self.assertEqual('TELNSELAKAMKVDAQRG-AFVSQVLPNSSAAKAGIKAGDVITSLNGKPISSFAALRA-QVGTMPVGSKLTLGLLRDG-KQVNVNLELQQSS', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({}, hsp.aln_annotation) # second qresult, second hit hit = qresult[1] self.assertEqual('gi|15832592|ref|NP_311365.1|', hit.id) @@ -155,6 +158,7 @@ self.assertEqual(185, hsp.hit_end) self.assertEqual('LFDLFLKNDAMHDPMVNESYC-ETFGWVSKENLARMKE---LTYKANDVLKKLFDDAGLILVDFKLEFGLYKG', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({}, hsp.aln_annotation) # test third qresult qresult = qresults[2] @@ -190,6 +194,7 @@ self.assertEqual(76, hsp.hit_end) self.assertEqual('IDPKKIEQIARQVHESMPKGIREFGEDVEKKIRQTLQAQLTRLDLVSREEFDVQTQVLLRTRE', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({}, hsp.aln_annotation) # third qresult, second hit hit = qresult[1] self.assertEqual('gi|15833861|ref|NP_312634.1|', hit.id) @@ -215,6 +220,7 @@ self.assertEqual(155, hsp.hit_end) self.assertEqual('EFIRLLSDHDQFEKDQISELTVAANALKLEVAK--NNY-----NMKYSFDTQTERRMIELIREQKDLIPEKYLHQSGIKKL-KLHED---EFSSLLVDAERQVLEGSSFVLCCGEKINSTISELLSKKITDLTHPTESFTLSEYFSYDVYEEIFKKV', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({}, hsp.aln_annotation) def test_output003(self): """Test parsing fasta34 output (output003.m10)""" @@ -264,6 +270,7 @@ self.assertEqual(69, hsp.hit_end) self.assertEqual('VRLTAEEDQ--EIRKRAAECG-KTVSGFLRAAALGKKVNSLTDDRVLKEVMRLGA', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({}, hsp.aln_annotation) # test second qresult qresult = qresults[1] @@ -319,6 +326,7 @@ self.assertEqual(123, hsp.hit_end) self.assertEqual('DDRANLFEFLSEEGITITEDNN', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({}, hsp.aln_annotation) # test fifth qresult qresult = qresults[4] @@ -354,6 +362,7 @@ self.assertEqual(124, hsp.hit_end) self.assertEqual('VYTSFN---GEKFSSYTLNKVTKTDEYNDLSELSASFFKKNFDKINVNLLSKATSF-ALKKGI', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({}, hsp.aln_annotation) class Fasta35Cases(unittest.TestCase): @@ -406,6 +415,7 @@ self.assertEqual(195, hsp.hit_end) self.assertEqual('AGSGAPRRRGSGLASRISEQSEALLQEAAKHAAEFGRS------EVDTEHLLLALADSDVVKTILGQFKIKVDDLKRQIESEAKR-GDKPF-EGEIGVSPRVKDALSR', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({}, hsp.aln_annotation) # first qresult, second hit hit = qresult[1] self.assertEqual('gi|152973588|ref|YP_001338639.1|', hit.id) @@ -431,6 +441,7 @@ self.assertEqual(248, hsp.hit_end) self.assertEqual('ASRQGCTVGG--KMDSVQDKASDKDKERVMKNINIMWNALSKNRLFDG----NKELKEFIMTLT', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({}, hsp.aln_annotation) # test second qresult qresult = qresults[1] @@ -466,6 +477,7 @@ self.assertEqual(81, hsp.hit_end) self.assertEqual('IKKDLGVSFLKLKNREKTLIVDALKKKYPVAELLSVLQ', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({}, hsp.aln_annotation) # test third qresult qresult = qresults[2] @@ -501,6 +513,7 @@ self.assertEqual(94, hsp.hit_end) self.assertEqual('SRINSDVARRIPGIHRDPKDRLSSLKQVEEALDMLISSHGEYC', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({}, hsp.aln_annotation) def test_output004(self): """Test parsing fasta35 output (output004.m10)""" @@ -559,6 +572,7 @@ self.assertEqual(414, hsp.hit_end) self.assertEqual('AGAGAAAATAAAACAAGTAATAAAATATTAATGGAAAAAATAAATTCTTGTTTATTTAGACCTGATTCTAATCACTTTTCTTGCCCGGAGTCATTTTTGACA', str(hsp.hit.seq)) self.assertEqual(1, hsp.query_strand) + self.assertEqual({'homology': ': : :: :::::: : : : : : : ::: :::: : : :: :::::::: :: ::: : : ::: : ::::: :::::: ::'}, hsp.aln_annotation) # test third qresult qresult = qresults[2] @@ -626,6 +640,7 @@ self.assertEqual(148, hsp.hit_end) self.assertEqual('IKDELPVAFCSWASLDLECEVKYINDVTSLYAKDWMSGERKWFIDWIAPFGHNMELYKYMRKKYPYELFRAIRLDESSKTGKIAEFHGGGIDKKLASKIFRQYHHELMSE', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({}, hsp.aln_annotation) # test third qresult qresult = qresults[2] @@ -684,6 +699,7 @@ self.assertEqual(490, hsp.hit_end) self.assertEqual('GCAACGCTTCAAGAACTGGAATTAGGAACCGTGACAACGATTAATGAGGAGATTTATGAAGAGGGTTCTTCGATTTTAGGCCAATCGGAAGGAATTATGTAGCAAGTCCATCAGAAAATGGAAGTAGTCAT', str(hsp.hit.seq)) self.assertEqual(-1, hsp.query_strand) + self.assertEqual({'homology': ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::'}, hsp.aln_annotation) class Fasta36Cases(unittest.TestCase): @@ -736,6 +752,7 @@ self.assertEqual(195, hsp.hit_end) self.assertEqual('AGSGAPRRRGSGLASRISEQSEALLQEAAKHAAEFGRS------EVDTEHLLLALADSDVVKTILGQFKIKVDDLKRQIESEAKR-GDKPF-EGEIGVSPRVKDALSR', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({'homology': '.::..-:::. . :.. . .---:: :.::: :..------ . . . .:.:. :.: ..-----.. :.... ..::-::. .-: :... . :::'}, hsp.aln_annotation) # first qresult, second hit hit = qresult[1] self.assertEqual('gi|152973588|ref|YP_001338639.1|', hit.id) @@ -761,6 +778,7 @@ self.assertEqual(248, hsp.hit_end) self.assertEqual('ASRQGCTVGG--KMDSVQDKASDKDKERVMKNINIMWNALSKNRLFDG----NKELKEFIMTLT', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({'homology': ':.. : ::.:--. .. :... .::.:..-. .::.:. ..::----..: : ....:'}, hsp.aln_annotation) # first qresult, third hit hit = qresult[2] self.assertEqual('gi|152973480|ref|YP_001338531.1|', hit.id) @@ -786,6 +804,7 @@ self.assertEqual(87, hsp.hit_end) self.assertEqual('ELVKLIADMGISVRALLRKNVEPYEELGLEEDKFTDDQLIDFMLQ', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({'homology': ':. : :. : .: ..:: .-----:: . ...:::... ...'}, hsp.aln_annotation) # test second qresult qresult = qresults[1] @@ -821,6 +840,7 @@ self.assertEqual(81, hsp.hit_end) self.assertEqual('IKKDLGVSFLKLKNREKTLIVDALKKKYPVAELLSVLQ', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({'homology': '.::: .. .::..:::.. : .:..: ..'}, hsp.aln_annotation) # second qresult, second hit hit = qresult[1] self.assertEqual('gi|152973509|ref|YP_001338560.1|', hit.id) @@ -846,6 +866,7 @@ self.assertEqual(418, hsp.hit_end) self.assertEqual('FFDLVIENPGK', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({'homology': '::::.: : ::'}, hsp.aln_annotation) # second qresult, third hit hit = qresult[2] self.assertEqual('gi|152973581|ref|YP_001338632.1|', hit.id) @@ -871,6 +892,7 @@ self.assertEqual(84, hsp.hit_end) self.assertEqual('ESVVFILMAGFAMSVCYLFFSVLEKVINARKSKDESIYHD', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({'homology': '....::..: .: -::: .:. .. .::: .-.. :'}, hsp.aln_annotation) # second qresult, fourth hit hit = qresult[3] self.assertEqual('gi|152973536|ref|YP_001338587.1|', hit.id) @@ -896,6 +918,7 @@ self.assertEqual(36, hsp.hit_end) self.assertEqual('ASFSKEEQDKVAVDKVAADVAWQERMNKPV', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({'homology': '::: :.. ::. :. .. ... . . :.'}, hsp.aln_annotation) # test third qresult qresult = qresults[2] @@ -931,6 +954,7 @@ self.assertEqual(94, hsp.hit_end) self.assertEqual('SRINSDVARRIPGIHRDPKDRLSSLKQVEEALDMLISSHGEYC', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({'homology': ':...: . . : ::.: : .:: -. . . .:. . ... ::'}, hsp.aln_annotation) # third qresult, second hit hit = qresult[1] self.assertEqual('gi|152973505|ref|YP_001338556.1|', hit.id) @@ -956,6 +980,7 @@ self.assertEqual(281, hsp.hit_end) self.assertEqual('IDGVITAFD-LRTGMNISKDKVVAQIQGMDPVW---ISAAVPESIAYLLKDTSQFEISVPAYPD', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({'homology': ':.:. ..:-: : . . .... .:.. ..---:. . :. :--.::..:: ..: . :'}, hsp.aln_annotation) def test_output008(self): """Test parsing tfastx36 output (output008.m10)""" @@ -1015,6 +1040,7 @@ self.assertEqual(317, hsp.hit_end) self.assertEqual('IPHQLPHALRHRPAQEAAHASQLHPAQPGCGQPLHGLWRLHHHPVYLYAWILRLRGHGMQSGGLL', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({'homology': '. :. :: ... :. . .: . : : :---. ::: : .. :. :. .:'}, hsp.aln_annotation) # second qresult, second hit hit = qresult[1] self.assertEqual('gi|57163782|ref|NM_001009242.1|', hit.id) @@ -1040,6 +1066,7 @@ self.assertEqual(595, hsp.hit_end) self.assertEqual('GPELLRALLQQNGCGTQPLRVPTVLPG*AMAVLHAGRLHVPAHRAWLPHQLPHALRHGPAQEAAHASQLHPAQPGRG*PLHGLRWLHHHPLH/PLCMDTLSLGPQDAIWRASLPHWAVKLPCGLWWSWPLSGTWWCVSP*ATSA------LGRTMP*WASLSPGSWHWPALHPPSLVGPGTSLKACSVHAGSTTTHSSQKS', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({'homology': ':::.:---: :-: :: . :: .. . .::-------: :. :: .. :. . .: . : . :-----::: :- : .:. : : . .. . -: ... : .. . . : .:------:.. .: . :: : :.::. .:: :-.: . ...:...:'}, hsp.aln_annotation) # test third qresult qresult = qresults[2] @@ -1085,6 +1112,7 @@ self.assertEqual(1044, hsp.hit_end) self.assertEqual('MNGTEGPNFYVPFSNKTGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQHKKLRTPLNYILLNLAVADLFMVFGGFTTTLYTSLHGYFVFGPTGCNLEGFFATLGGEIALWSLVVLAIERYVVVCKPMSNFRFGENHAIMGVAFTWVMALACAAPPLVGWSRYIPEGMQCSCGIDYYTLKPEVNNESFVIYMFVVHFTIPMIVIFFCYGQLVFTVKEAAAQQQESATTQKAEKEVTRMVIIMVIAFLICWVPYASVAFYIFTHQGSNFGPIFMTLPAFFAKSSSIYNPVIYIMMNKQFRNCMLTTLCCGKNPLGDDEASTTGSKTETSQVAPA', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({'homology': '::::::::::::::: :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::.::::.:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::.:::::::::.::::::::::::::::::::::::::::::::::.:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::.:::::::..:::::::::::::::::::::.:::::::::::::.: :::::::::::'}, hsp.aln_annotation) # fourth qresult, second hit hit = qresult[1] self.assertEqual('gi|18148870|dbj|AB062417.1|', hit.id) @@ -1116,6 +1144,7 @@ self.assertEqual('Myotis ricketti voucher GQX10 rhodopsin (RHO) mRNA, partial cds', hit.description) self.assertEqual(983, hit.seq_len) self.assertEqual(2, len(hit)) + self.assertEqual({'homology': '::::::::::::::: ::::::::: ::::::::::::::::::::::.::::::::::::::::::::::::::::::::::::::.::::.:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::.:::::::::.:::::::::: . :.:::::::::::::: ::.:.:::::::::::::::::::::::::::::::::::::::::::::::.:::.:::::::::::.::::::::::::::..:.:::::::::::::::::.::.:::::::::::::.:::::::::::::'}, hsp.aln_annotation) # fourth qresult, third hit, first hsp hsp = qresult[2].hsps[0] self.assertEqual(2138, hsp.initn_score) @@ -1135,6 +1164,7 @@ self.assertEqual(978, hsp.hit_end) self.assertEqual('VPFSNKTGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQHKKLRTPLNYILLNLAVANLFMVFGGFTTTLYTSMHGYFVFGATGCNLEGFFATLGGEIALWSLVVLAIERYVVVCKPMSNFRFGENHAIMGLAFTWVMALACAAPPLAGWSRYIPEGMQCSCGIDYYTLKPEVNNESFVIYMFVVHFTIPMIVIFFCYGQLVFTVKEAAAQQQESATTQKAEKEVTRMVIIMVVAFLICWLPYASVAFYIFTHQGSNFGPVFMTIPAFFAKSSSIYNPVIYIMMNKQFRNCMLTTLCCGKNPLGDDEASTT', str(hsp.hit.seq)) self.assertEqual(0, hsp.query_strand) + self.assertEqual({'homology': '::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::.::::.::::.:::::.::::::: :::::::::::::::::::::::::::::::::::::::::::::::::.:::::::::::::::::::::::::.::::::::::::::::::::::::::::::::::.::::::::::::::::::::::::::::::::::::::::.::::::.:::::::::::::::::::.:::::::::::..:::::::::::::::::::::.:::::::::::::.:'}, hsp.aln_annotation) # fourth qresult, third hit, second hsp hsp = qresult[2].hsps[1] self.assertEqual(74, hsp.initn_score) diff -Nru python-biopython-1.62/Tests/test_SearchIO_hmmer2_text.py python-biopython-1.63/Tests/test_SearchIO_hmmer2_text.py --- python-biopython-1.62/Tests/test_SearchIO_hmmer2_text.py 2013-08-28 21:34:03.000000000 +0000 +++ python-biopython-1.63/Tests/test_SearchIO_hmmer2_text.py 2013-12-05 14:10:43.000000000 +0000 @@ -17,7 +17,7 @@ def test_hmmpfam_21(self): """Test parsing hmmpfam 2.1 file (text_21_hmmpfam_001.out)""" results = parse(path.join("Hmmer", "text_21_hmmpfam_001.out"), self.fmt) - res = results.next() + res = next(results) self.assertEqual('roa1_drome', res.id) self.assertEqual('', res.description) self.assertEqual('hmmpfam', res.program) @@ -70,7 +70,7 @@ def test_hmmpfam_22(self): """Test parsing hmmpfam 2.2 file (text_22_hmmpfam_001.out)""" results = parse(path.join("Hmmer", "text_22_hmmpfam_001.out"), self.fmt) - res = results.next() + res = next(results) self.assertEqual('gi|1522636|gb|AAC37060.1|', res.id) self.assertEqual('M. jannaschii predicted coding region MJECS02 [Methanococcus jannaschii]', res.description) self.assertEqual('[none]', res.accession) @@ -108,7 +108,7 @@ def test_hmmpfam_23(self): """Test parsing hmmpfam 2.3 file (text_23_hmmpfam_001.out)""" results = parse(path.join("Hmmer", "text_23_hmmpfam_001.out"), self.fmt) - res = results.next() + res = next(results) self.assertEqual('gi|90819130|dbj|BAE92499.1|', res.id) self.assertEqual('glutamate synthase [Porphyra yezoensis]', res.description) self.assertEqual('[none]', res.accession) @@ -156,12 +156,12 @@ def test_hmmpfam_23_no_match(self): """Test parsing hmmpfam 2.3 file (text_23_hmmpfam_002.out)""" results = parse(path.join("Hmmer", "text_23_hmmpfam_002.out"), self.fmt) - res = results.next() + res = next(results) self.assertEqual('SEQ0001', res.id) self.assertEqual(0, len(res.hits)) - res = results.next() + res = next(results) self.assertEqual('SEQ0002', res.id) self.assertEqual(0, len(res.hits)) @@ -169,7 +169,7 @@ def test_hmmpfam_23_missing_consensus(self): """Test parsing hmmpfam 2.3 file (text_23_hmmpfam_003.out)""" results = parse(path.join("Hmmer", "text_23_hmmpfam_003.out"), self.fmt) - res = results.next() + res = next(results) self.assertEqual('small_input', res.id) self.assertEqual('[none]', res.description) @@ -418,7 +418,7 @@ self.assertEqual(337, hsp.query_end) self.assertEqual('[]', hsp.query_endtype) self.assertEqual('lPesfDWReWkggaVtpVKdQGiqCGSCWAFSavgalEgr', str(hsp.query.seq)[:40]) - self.assertEqual('IVKNSWGtdWGEnGYfriaRgknksgkneCGIaseasypi',str(hsp.query.seq)[-40:]) + self.assertEqual('IVKNSWGtdWGEnGYfriaRgknksgkneCGIaseasypi', str(hsp.query.seq)[-40:]) self.assertEqual(337, len(hsp.query.seq)) self.assertEqual('+P+++DWRe kg VtpVK+QG qCGSCWAFSa g lEg+', str(hsp.aln_annotation['homology'])[:40]) @@ -428,7 +428,7 @@ self.assertEqual(332, hsp.hit_end) self.assertEqual('..', hsp.hit_endtype) self.assertEqual('IPKTVDWRE-KG-CVTPVKNQG-QCGSCWAFSASGCLEGQ', str(hsp.hit.seq)[:40]) - self.assertEqual('LVKNSWGKEWGMDGYIKIAKDRN----NHCGLATAASYPI',str(hsp.hit.seq)[-40:]) + self.assertEqual('LVKNSWGKEWGMDGYIKIAKDRN----NHCGLATAASYPI', str(hsp.hit.seq)[-40:]) self.assertEqual(337, len(hsp.hit.seq)) # last hit @@ -453,7 +453,7 @@ self.assertEqual(337, hsp.query_end) self.assertEqual('[]', hsp.query_endtype) self.assertEqual('lPesfDWReWkggaVtpVKdQGiqCGSCWAFSavgalEgr', str(hsp.query.seq)[:40]) - self.assertEqual('IVKNSWGtdWGEnGYfriaRgknksgkneCGIaseasypi',str(hsp.query.seq)[-40:]) + self.assertEqual('IVKNSWGtdWGEnGYfriaRgknksgkneCGIaseasypi', str(hsp.query.seq)[-40:]) self.assertEqual(337, len(hsp.query.seq)) self.assertEqual('+Pe +DWR+ kg aVtpVK+QG +CGSCWAFSav ++Eg+', str(hsp.aln_annotation['homology'])[:40]) @@ -463,7 +463,7 @@ self.assertEqual(343, hsp.hit_end) self.assertEqual('..', hsp.hit_endtype) self.assertEqual('IPEYVDWRQ-KG-AVTPVKNQG-SCGSCWAFSAVVTIEGI', str(hsp.hit.seq)[:40]) - self.assertEqual('LIKNSWGTGWGENGYIRIKRGTGNS-YGVCGLYTSSFYPV',str(hsp.hit.seq)[-40:]) + self.assertEqual('LIKNSWGTGWGENGYIRIKRGTGNS-YGVCGLYTSSFYPV', str(hsp.hit.seq)[-40:]) self.assertEqual(337, len(hsp.hit.seq)) diff -Nru python-biopython-1.62/Tests/test_SearchIO_hmmer3_domtab.py python-biopython-1.63/Tests/test_SearchIO_hmmer3_domtab.py --- python-biopython-1.62/Tests/test_SearchIO_hmmer3_domtab.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_SearchIO_hmmer3_domtab.py 2013-12-05 14:10:43.000000000 +0000 @@ -32,7 +32,7 @@ counter = 0 # first qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual(1, len(qresult)) self.assertEqual('gi|4885477|ref|NP_005359.1|', qresult.id) @@ -65,7 +65,7 @@ self.assertEqual(0.97, hsp.acc_avg) # second qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual(2, len(qresult)) self.assertEqual('gi|126362951:116-221', qresult.id) @@ -123,7 +123,7 @@ self.assertEqual(0.71, hsp.acc_avg) # third qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual(2, len(qresult)) self.assertEqual('gi|22748937|ref|NP_065801.1|', qresult.id) @@ -212,7 +212,7 @@ self.assertEqual(0.85, hsp.acc_avg) # fourth qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual(5, len(qresult)) self.assertEqual('gi|125490392|ref|NP_038661.2|', qresult.id) @@ -365,7 +365,7 @@ self.assertEqual(0.77, hsp.acc_avg) # test if we've properly finished iteration - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(4, counter) def test_domtab_30_hmmscan_002(self): @@ -374,7 +374,7 @@ tab_file = get_file('domtab_30_hmmscan_002.out') qresults = parse(tab_file, self.fmt) - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) def test_domtab_30_hmmscan_003(self): "Test parsing hmmscan-domtab, hmmscan 3.0, multiple queries (domtab_30_hmmscan_003)" @@ -383,7 +383,7 @@ qresults = parse(tab_file, self.fmt) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual(1, len(qresult)) self.assertEqual('gi|4885477|ref|NP_005359.1|', qresult.id) @@ -416,7 +416,7 @@ self.assertEqual(0.97, hsp.acc_avg) # test if we've properly finished iteration - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_domtab_30_hmmscan_004(self): @@ -426,7 +426,7 @@ qresults = parse(tab_file, self.fmt) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual(2, len(qresult)) self.assertEqual('gi|126362951:116-221', qresult.id) @@ -484,7 +484,7 @@ self.assertEqual(0.71, hsp.acc_avg) # test if we've properly finished iteration - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) @@ -501,7 +501,7 @@ # first qresult # we only want to check the coordinate switch actually # so checking the first hsp of the first hit of the qresult is enough - qresult = qresults.next() + qresult = next(qresults) self.assertEqual(7, len(qresult)) self.assertEqual('Pkinase', qresult.id) self.assertEqual('PF00069.17', qresult.accession) diff -Nru python-biopython-1.62/Tests/test_SearchIO_hmmer3_tab.py python-biopython-1.63/Tests/test_SearchIO_hmmer3_tab.py --- python-biopython-1.62/Tests/test_SearchIO_hmmer3_tab.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_SearchIO_hmmer3_tab.py 2013-12-05 14:10:43.000000000 +0000 @@ -31,7 +31,7 @@ counter = 0 # first qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual(1, len(qresult)) self.assertEqual('gi|4885477|ref|NP_005359.1|', qresult.id) @@ -58,7 +58,7 @@ self.assertEqual(0.2, hsp.bias) # second qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual(2, len(qresult)) self.assertEqual('gi|126362951:116-221', qresult.id) @@ -105,7 +105,7 @@ self.assertEqual(0.1, hsp.bias) # third qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual(2, len(qresult)) self.assertEqual('gi|22748937|ref|NP_065801.1|', qresult.id) @@ -152,7 +152,7 @@ self.assertEqual(0.0, hsp.bias) # last qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual(5, len(qresult)) self.assertEqual('gi|125490392|ref|NP_038661.2|', qresult.id) @@ -264,7 +264,7 @@ self.assertEqual(0.1, hsp.bias) # test if we've properly finished iteration - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(4, counter) def test_30_hmmscan_002(self): @@ -273,7 +273,7 @@ tab_file = get_file('tab_30_hmmscan_002.out') qresults = parse(tab_file, FMT) - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) def test_30_hmmscan_003(self): "Test parsing hmmer3-tab, hmmscan 3.0, single query, single hit, single hsp (tab_30_hmmscan_003)" @@ -282,7 +282,7 @@ qresults = parse(tab_file, FMT) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual(1, len(qresult)) self.assertEqual('gi|4885477|ref|NP_005359.1|', qresult.id) @@ -309,7 +309,7 @@ self.assertEqual(0.2, hsp.bias) # test if we've properly finished iteration - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_30_hmmscan_004(self): @@ -319,7 +319,7 @@ qresults = parse(tab_file, FMT) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual(2, len(qresult)) self.assertEqual('gi|126362951:116-221', qresult.id) @@ -366,7 +366,7 @@ self.assertEqual(0.1, hsp.bias) # test if we've properly finished iteration - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) diff -Nru python-biopython-1.62/Tests/test_SearchIO_hmmer3_text.py python-biopython-1.63/Tests/test_SearchIO_hmmer3_text.py --- python-biopython-1.62/Tests/test_SearchIO_hmmer3_text.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_SearchIO_hmmer3_text.py 2013-12-05 14:10:43.000000000 +0000 @@ -31,7 +31,7 @@ counter = 0 # test first qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('hmmscan', qresult.program) @@ -42,7 +42,7 @@ self.assertEqual(0, len(qresult)) # test second result - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('hmmscan', qresult.program) @@ -91,7 +91,7 @@ hsp.aln_annotation['PP']) # test third result - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('hmmscan', qresult.program) @@ -172,7 +172,7 @@ hsp.aln_annotation['PP']) # test fourth result - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('hmmscan', qresult.program) @@ -310,7 +310,7 @@ hsp.aln_annotation['PP']) # test fifth result - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('hmmscan', qresult.program) @@ -523,7 +523,7 @@ hsp.aln_annotation['PP']) # test if we've properly finished iteration - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(5, counter) def test_30_hmmscan_002(self): @@ -534,7 +534,7 @@ counter = 0 # test first qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('hmmscan', qresult.program) @@ -545,7 +545,7 @@ self.assertEqual(0, len(qresult)) # test if we've properly finished iteration - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_30_hmmscan_003(self): @@ -556,7 +556,7 @@ counter = 0 # test first qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('hmmscan', qresult.program) @@ -605,7 +605,7 @@ hsp.aln_annotation['PP']) # test if we've properly finished iteration - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_30_hmmscan_004(self): @@ -616,7 +616,7 @@ counter = 0 # test first qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('hmmscan', qresult.program) @@ -697,7 +697,7 @@ hsp.aln_annotation['PP']) # test if we've properly finished iteration - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_30_hmmscan_005(self): @@ -708,7 +708,7 @@ counter = 0 # test first result - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('hmmscan', qresult.program) @@ -846,7 +846,7 @@ hsp.aln_annotation['PP']) # test if we've properly finished iteration - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_30_hmmscan_006(self): @@ -857,7 +857,7 @@ counter = 0 # test first qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('hmmscan', qresult.program) @@ -1070,7 +1070,7 @@ hsp.aln_annotation['PP']) # test if we've properly finished iteration - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_30_hmmscan_007(self): @@ -1081,7 +1081,7 @@ counter = 0 # test first qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('hmmscan', qresult.program) @@ -1256,7 +1256,7 @@ self.assertEqual(0.77, hsp.acc_avg) # test if we've properly finished iteration - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_30_hmmscan_008(self): @@ -1267,7 +1267,7 @@ counter = 0 # test first result - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('hmmscan', qresult.program) @@ -1405,7 +1405,7 @@ hsp.aln_annotation['PP']) # test if we've properly finished iteration - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) @@ -1416,7 +1416,7 @@ counter = 0 # test first qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('SCO3574', qresult.id) self.assertEqual(5, len(qresult.hits)) @@ -1451,7 +1451,7 @@ qresults = parse(xml_file, FMT) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('hmmsearch', qresult.program) @@ -1462,7 +1462,7 @@ self.assertEqual(0, len(qresult)) # test if we've properly finished iteration - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(1, counter) def test_30_hmmsearch_002(self): @@ -1472,7 +1472,7 @@ qresults = parse(xml_file, FMT) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('hmmsearch', qresult.program) @@ -1611,7 +1611,7 @@ hsp.aln_annotation['PP']) # test if we've properly finished iteration - #self.assertRaises(StopIteration, qresults.next, ) + #self.assertRaises(StopIteration, next, qresults) #self.assertEqual(1, counter) def test_30_hmmsearch_003(self): @@ -1621,7 +1621,7 @@ qresults = parse(xml_file, FMT) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('hmmsearch', qresult.program) @@ -1728,7 +1728,7 @@ self.assertEqual(0.97, hsp.acc_avg) # test if we've properly finished iteration - #self.assertRaises(StopIteration, qresults.next, ) + #self.assertRaises(StopIteration, next, qresults) #self.assertEqual(1, counter) def test_30_hmmsearch_004(self): @@ -1738,7 +1738,7 @@ qresults = parse(xml_file, FMT) counter = 0 - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('hmmsearch', qresult.program) @@ -1877,7 +1877,7 @@ hsp.aln_annotation['PP']) # test if we've properly finished iteration - #self.assertRaises(StopIteration, qresults.next, ) + #self.assertRaises(StopIteration, next, qresults) #self.assertEqual(1, counter) def test_30_hmmsearch_005(self): @@ -1888,7 +1888,7 @@ counter = 0 # test first qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('hmmsearch', qresult.program) @@ -1899,7 +1899,7 @@ self.assertEqual(0, len(qresult)) # test second qresult - qresult = qresults.next() + qresult = next(qresults) counter += 1 self.assertEqual('hmmsearch', qresult.program) @@ -2038,7 +2038,7 @@ hsp.aln_annotation['PP']) # test if we've properly finished iteration - self.assertRaises(StopIteration, qresults.next, ) + self.assertRaises(StopIteration, next, qresults) self.assertEqual(2, counter) diff -Nru python-biopython-1.62/Tests/test_SearchIO_model.py python-biopython-1.63/Tests/test_SearchIO_model.py --- python-biopython-1.62/Tests/test_SearchIO_model.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_SearchIO_model.py 2013-12-05 14:10:43.000000000 +0000 @@ -1126,7 +1126,7 @@ self.assertRaises(TypeError, len, self) # len is a shorthand for .aln_span, and it can be set manually self.fragment.aln_span = 5 - self.assertEqual(5,len(self.fragment)) + self.assertEqual(5, len(self.fragment)) def test_repr(self): """Test HSPFragment.__repr__, no alignments""" diff -Nru python-biopython-1.62/Tests/test_SeqIO.py python-biopython-1.63/Tests/test_SeqIO.py --- python-biopython-1.62/Tests/test_SeqIO.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_SeqIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,25 +3,30 @@ # license. Please see the LICENSE file that should have been included # as part of this package. +from __future__ import print_function +from Bio._py3k import basestring + import os +import warnings + +try: + from StringIO import StringIO # Python 2 + # Can't use cStringIO, quoting the documentation, + # "Unlike the StringIO module, this module is not able to accept + # Unicode strings that cannot be encoded as plain ASCII strings." + # Therefore can't use from Bio._py3k import StringIO +except ImportError: + from io import StringIO # Python 3 +from io import BytesIO from Bio import BiopythonWarning from Bio import SeqIO from Bio import AlignIO from Bio.SeqRecord import SeqRecord from Bio.Seq import Seq, UnknownSeq -from StringIO import StringIO from Bio import Alphabet from Bio.Align import MultipleSeqAlignment -try: - #This is in Python 2.6+, but we need it on Python 3 - from io import BytesIO -except ImportError: - BytesIO = StringIO - -import warnings - # TODO - Convert this to using unittest, and check desired warnings # are issued. Used to do that by capturing warnings to stdout and # verifying via the print-and-compare check. However, there was some @@ -33,16 +38,16 @@ rna_alphas = [Alphabet.generic_rna] nucleotide_alphas = [Alphabet.generic_nucleotide, Alphabet.Gapped(Alphabet.generic_nucleotide)] -no_alpha_formats = ["fasta","clustal","phylip","phylip-relaxed", - "phylip-sequential","tab","ig", - "stockholm","emboss", "fastq","fastq-solexa", - "fastq-illumina","qual"] +no_alpha_formats = ["fasta", "clustal", "phylip", "phylip-relaxed", + "phylip-sequential", "tab", "ig", + "stockholm", "emboss", "fastq", "fastq-solexa", + "fastq-illumina", "qual"] possible_unknown_seq_formats = ["qual", "genbank", "gb", "embl", "imgt"] #List of formats including alignment only file formats we can read AND write. #The list is initially hard coded to preserve the original order of the unit #test output, with any new formats added since appended to the end. -test_write_read_alignment_formats = ["fasta","clustal","phylip","stockholm", +test_write_read_alignment_formats = ["fasta", "clustal", "phylip", "stockholm", "phylip-relaxed"] for format in sorted(SeqIO._FormatToWriter): if format not in test_write_read_alignment_formats: @@ -62,10 +67,10 @@ test_files = [ ("sff", False, 'Roche/E3MFGYR02_random_10_reads.sff', 10), #Following examples are also used in test_Clustalw.py - ("clustal",True, 'Clustalw/cw02.aln', 2), - ("clustal",True, 'Clustalw/opuntia.aln', 7), - ("clustal",True, 'Clustalw/hedgehog.aln', 5), - ("clustal",True, 'Clustalw/odd_consensus.aln', 2), + ("clustal", True, 'Clustalw/cw02.aln', 2), + ("clustal", True, 'Clustalw/opuntia.aln', 7), + ("clustal", True, 'Clustalw/hedgehog.aln', 5), + ("clustal", True, 'Clustalw/odd_consensus.aln', 2), #Following nucleic examples are also used in test_SeqIO_FastaIO.py ("fasta", False, 'Fasta/lupine.nu', 1), ("fasta", False, 'Fasta/elderberry.nu', 1), @@ -123,32 +128,33 @@ ("uniprot-xml", False, 'SwissProt/Q13639.xml', 1), ("swiss", False, 'SwissProt/Q13639.txt', 1), #Following examples are also used in test_GenBank.py - ("genbank",False, 'GenBank/noref.gb', 1), - ("genbank",False, 'GenBank/cor6_6.gb', 6), - ("genbank",False, 'GenBank/iro.gb', 1), - ("genbank",False, 'GenBank/pri1.gb', 1), - ("genbank",False, 'GenBank/arab1.gb', 1), - ("genbank",False, 'GenBank/protein_refseq.gb', 1), # Old version - ("genbank",False, 'GenBank/protein_refseq2.gb', 1), # Revised version - ("genbank",False, 'GenBank/extra_keywords.gb', 1), - ("genbank",False, 'GenBank/one_of.gb', 1), - ("genbank",False, 'GenBank/NT_019265.gb', 1), # contig, no sequence - ("genbank",False, 'GenBank/origin_line.gb', 1), - ("genbank",False, 'GenBank/blank_seq.gb', 1), - ("genbank",False, 'GenBank/dbsource_wrap.gb', 1), - ("genbank",False, 'GenBank/NC_005816.gb', 1), # See also AE017046.embl - ("genbank",False, 'GenBank/NC_000932.gb', 1), - ("genbank",False, 'GenBank/pBAD30.gb', 1), # Odd LOCUS line from Vector NTI + ("genbank", False, 'GenBank/noref.gb', 1), + ("genbank", False, 'GenBank/cor6_6.gb', 6), + ("genbank", False, 'GenBank/iro.gb', 1), + ("genbank", False, 'GenBank/pri1.gb', 1), + ("genbank", False, 'GenBank/arab1.gb', 1), + ("genbank", False, 'GenBank/protein_refseq.gb', 1), # Old version + ("genbank", False, 'GenBank/protein_refseq2.gb', 1), # Revised version + ("genbank", False, 'GenBank/extra_keywords.gb', 1), + ("genbank", False, 'GenBank/one_of.gb', 1), + ("genbank", False, 'GenBank/NT_019265.gb', 1), # contig, no sequence + ("genbank", False, 'GenBank/origin_line.gb', 1), + ("genbank", False, 'GenBank/blank_seq.gb', 1), + ("genbank", False, 'GenBank/dbsource_wrap.gb', 1), + ("genbank", False, 'GenBank/NC_005816.gb', 1), # See also AE017046.embl + ("genbank", False, 'GenBank/NC_000932.gb', 1), + ("genbank", False, 'GenBank/pBAD30.gb', 1), # Odd LOCUS line from Vector NTI # The next example is a truncated copy of gbvrl1.seq from # ftp://ftp.ncbi.nih.gov/genbank/gbvrl1.seq.gz # This includes an NCBI header, and the first three records: - ("genbank",False, 'GenBank/gbvrl1_start.seq', 3), + ("genbank", False, 'GenBank/gbvrl1_start.seq', 3), #Following files are also used in test_GFF.py - ("genbank",False, 'GFF/NC_001422.gbk', 1), + ("genbank", False, 'GFF/NC_001422.gbk', 1), #Generated with Entrez.efetch("protein", id="16130152", rettype="gbwithparts") - ("genbank",False, 'GenBank/NP_416719.gbwithparts', 1), + ("genbank", False, 'GenBank/NP_416719.gbwithparts', 1), #Following files are currently only used here or in test_SeqIO_index.py: ("embl", False, 'EMBL/epo_prt_selection.embl', 9), # proteins + ("embl", False, 'EMBL/patents.embl', 4), # more proteins, but no seq ("embl", False, 'EMBL/TRBG361.embl', 1), ("embl", False, 'EMBL/DD231055_edited.embl', 1), ("embl", False, 'EMBL/DD231055_edited2.embl', 1), #Partial ID line @@ -199,12 +205,13 @@ ("pir", True, 'NBRF/clustalw.pir', 2), #Following quality files are also used in the Bio.SeqIO.QualityIO doctests: ("fasta", True, 'Quality/example.fasta', 3), - ("qual", False,'Quality/example.qual', 3), - ("fastq", True, 'Quality/example.fastq', 3), + ("qual", False, 'Quality/example.qual', 3), + ("fastq", True, 'Quality/example.fastq', 3), #Unix new lines + ("fastq", True, 'Quality/example_dos.fastq', 3), #DOS/Windows new lines ("fastq", True, 'Quality/tricky.fastq', 4), - ("fastq", False,'Quality/sanger_faked.fastq', 1), - ("fastq", False,'Quality/sanger_93.fastq', 1), - ("fastq-illumina", False,'Quality/illumina_faked.fastq', 1), + ("fastq", False, 'Quality/sanger_faked.fastq', 1), + ("fastq", False, 'Quality/sanger_93.fastq', 1), + ("fastq-illumina", False, 'Quality/illumina_faked.fastq', 1), ("fastq-solexa", False, 'Quality/solexa_faked.fastq', 1), ("fastq-solexa", True, 'Quality/solexa_example.fastq', 5), #Following examples are also used in test_SeqXML.py @@ -299,7 +306,7 @@ answer = [] alignment_len = alignment.get_alignment_length() rec_count = len(alignment) - for i in range(min(5,alignment_len)): + for i in range(min(5, alignment_len)): answer.append(index + col_summary(alignment.get_column(i)) + " alignment column %i" % i) if alignment_len > 5: @@ -312,7 +319,7 @@ def check_simple_write_read(records, indent=" "): - #print indent+"Checking we can write and then read back these records" + #print(indent+"Checking we can write and then read back these records") for format in test_write_read_alignment_formats: if format not in possible_unknown_seq_formats \ and isinstance(records[0].seq, UnknownSeq) \ @@ -320,7 +327,7 @@ #Skipping for speed. Some of the unknown sequences are #rather long, and it seems a bit pointless to record them. continue - print indent+"Checking can write/read as '%s' format" % format + print(indent+"Checking can write/read as '%s' format" % format) #Going to write to a handle... if format in SeqIO._BinaryFormats: @@ -331,7 +338,7 @@ try: c = SeqIO.write(sequences=records, handle=handle, format=format) assert c == len(records) - except (TypeError, ValueError), e: + except (TypeError, ValueError) as e: #This is often expected to happen, for example when we try and #write sequences of different lengths to an alignment file. if "len()" in str(e): @@ -344,9 +351,9 @@ #>>> len(None) #... #TypeError: object of type 'NoneType' has no len() - print "Failed: Probably len() of None" + print("Failed: Probably len() of None") else: - print indent+"Failed: %s" % str(e) + print(indent+"Failed: %s" % str(e)) if records[0].seq.alphabet.letters is not None: assert format != t_format, \ "Should be able to re-write in the original format!" @@ -358,7 +365,7 @@ #Now ready to read back from the handle... try: records2 = list(SeqIO.parse(handle=handle, format=format)) - except ValueError, e: + except ValueError as e: #This is BAD. We can't read our own output. #I want to see the output when called from the test harness, #run_tests.py (which can be funny about new lines on Windows) @@ -390,16 +397,16 @@ #Beware of different quirks and limitations in the #valid character sets and the identifier lengths! if format in ["phylip", "phylip-sequential"]: - assert r1.id.replace("[","").replace("]","")[:10] == r2.id, \ + assert r1.id.replace("[", "").replace("]", "")[:10] == r2.id, \ "'%s' vs '%s'" % (r1.id, r2.id) elif format=="phylip-relaxed": assert r1.id.replace(" ", "").replace(':', '|') == r2.id, \ "'%s' vs '%s'" % (r1.id, r2.id) elif format=="clustal": - assert r1.id.replace(" ","_")[:30] == r2.id, \ + assert r1.id.replace(" ", "_")[:30] == r2.id, \ "'%s' vs '%s'" % (r1.id, r2.id) elif format=="stockholm": - assert r1.id.replace(" ","_") == r2.id, \ + assert r1.id.replace(" ", "_") == r2.id, \ "'%s' vs '%s'" % (r1.id, r2.id) elif format=="fasta": assert r1.id.split()[0] == r2.id @@ -433,11 +440,11 @@ else: mode = "r" - print "Testing reading %s format file %s" % (t_format, t_filename) + print("Testing reading %s format file %s" % (t_format, t_filename)) assert os.path.isfile(t_filename), t_filename #Try as an iterator using handle - h = open(t_filename,mode) + h = open(t_filename, mode) records = list(SeqIO.parse(handle=h, format=t_format)) h.close() assert len(records) == t_count, \ @@ -451,11 +458,11 @@ #Try using the iterator with the next() method records3 = [] - h = open(t_filename,mode) + h = open(t_filename, mode) seq_iterator = SeqIO.parse(handle=h, format=t_format) while True: try: - record = seq_iterator.next() + record = next(seq_iterator) except StopIteration: break assert record is not None, "Should raise StopIteration not return None" @@ -463,10 +470,10 @@ h.close() #Try a mixture of next() and list (a torture test!) - h = open(t_filename,mode) + h = open(t_filename, mode) seq_iterator = SeqIO.parse(handle=h, format=t_format) try: - record = seq_iterator.next() + record = next(seq_iterator) except StopIteration: record = None if record is not None: @@ -486,7 +493,7 @@ h = ForwardOnlyHandle(open(t_filename, mode)) seq_iterator = SeqIO.parse(h, format=t_format) try: - record = seq_iterator.next() + record = next(seq_iterator) except StopIteration: record = None if record is not None: @@ -534,12 +541,12 @@ assert compare_record(record, records5[i]) if i < 3: - print record_summary(record) + print(record_summary(record)) # Only printed the only first three records: 0,1,2 if t_count > 4: - print " ..." + print(" ...") if t_count > 3: - print record_summary(records[-1]) + print(record_summary(records[-1])) # Check Bio.SeqIO.read(...) if t_count == 1: @@ -585,21 +592,21 @@ for given_alpha in good: #These should all work... given_base = Alphabet._get_base_alphabet(given_alpha) - for record in SeqIO.parse(t_filename,t_format,given_alpha): + for record in SeqIO.parse(t_filename, t_format, given_alpha): base_alpha = Alphabet._get_base_alphabet(record.seq.alphabet) assert isinstance(base_alpha, given_base.__class__) assert base_alpha == given_base if t_count == 1: - h = open(t_filename,mode) - record = SeqIO.read(h,t_format,given_alpha) + h = open(t_filename, mode) + record = SeqIO.read(h, t_format, given_alpha) h.close() assert isinstance(base_alpha, given_base.__class__) assert base_alpha == given_base for given_alpha in bad: #These should all fail... - h = open(t_filename,mode) + h = open(t_filename, mode) try: - print SeqIO.parse(h,t_format,given_alpha).next() + print(next(SeqIO.parse(h, t_format, given_alpha))) h.close() assert False, "Forcing wrong alphabet, %s, should fail (%s)" \ % (repr(given_alpha), t_filename) @@ -610,8 +617,8 @@ del good, bad, given_alpha, base_alpha if t_alignment: - print "Testing reading %s format file %s as an alignment" \ - % (t_format, t_filename) + print("Testing reading %s format file %s as an alignment" \ + % (t_format, t_filename)) alignment = MultipleSeqAlignment(SeqIO.parse( handle=t_filename, format=t_format)) @@ -625,7 +632,7 @@ assert compare_record(records[i], alignment[i]) assert len(records[i].seq) == alignment_len - print alignment_summary(alignment) + print(alignment_summary(alignment)) #Some alignment file formats have magic characters which mean #use the letter in this position in the first sequence. @@ -634,4 +641,4 @@ records.reverse() check_simple_write_read(records) -print "Finished tested reading files" +print("Finished tested reading files") diff -Nru python-biopython-1.62/Tests/test_SeqIO_AbiIO.py python-biopython-1.63/Tests/test_SeqIO_AbiIO.py --- python-biopython-1.62/Tests/test_SeqIO_AbiIO.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_SeqIO_AbiIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -104,7 +104,7 @@ """Test if the extracted seqrecords data are equal to expected values.""" for trace in test_data: record = SeqIO.read(test_data[trace]['handle'], 'abi') - self.assertEqual(basename(test_data[trace]["path"][-1]).replace('.ab1',''), record.name) + self.assertEqual(basename(test_data[trace]["path"][-1]).replace('.ab1', ''), record.name) self.assertEqual(test_data[trace]['seq'], str(record.seq)) self.assertEqual(test_data[trace]['qual'], record.letter_annotations['phred_quality']) self.assertEqual(test_data[trace]['sample'], record.id) diff -Nru python-biopython-1.62/Tests/test_SeqIO_FastaIO.py python-biopython-1.63/Tests/test_SeqIO_FastaIO.py --- python-biopython-1.62/Tests/test_SeqIO_FastaIO.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_SeqIO_FastaIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -4,10 +4,10 @@ # license. Please see the LICENSE file that should have been included # as part of this package. -from __future__ import with_statement +from __future__ import print_function import unittest -from StringIO import StringIO +from Bio._py3k import StringIO from Bio import SeqIO from Bio.SeqIO.FastaIO import FastaIterator @@ -46,9 +46,9 @@ global title_to_ids handle = open(filename) iterator = FastaIterator(handle, alphabet, title_to_ids) - record = iterator.next() + record = next(iterator) try: - second = iterator.next() + second = next(iterator) except StopIteration: second = None handle.close() @@ -91,7 +91,7 @@ self.assertEqual(str(record.seq), seq) self.assertEqual(record.seq.alphabet, alphabet) #Uncomment this for testing the methods are calling the right files: - #print "{%s done}" % filename, + #print("{%s done}" % filename) def multi_check(self, filename, alphabet): """Basic test for parsing multi-record FASTA files.""" @@ -107,7 +107,7 @@ self.assertEqual(str(new.seq), str(old.seq)) self.assertEqual(new.seq.alphabet, old.seq.alphabet) #Uncomment this for testing the methods are calling the right files: - #print "{%s done}" % filename, + #print("{%s done}" % filename) def test_no_name(self): """Test FASTA record with no identifier.""" diff -Nru python-biopython-1.62/Tests/test_SeqIO_Insdc.py python-biopython-1.63/Tests/test_SeqIO_Insdc.py --- python-biopython-1.62/Tests/test_SeqIO_Insdc.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_SeqIO_Insdc.py 2013-12-05 14:10:43.000000000 +0000 @@ -4,7 +4,7 @@ # as part of this package. import unittest -from StringIO import StringIO +from Bio._py3k import StringIO from Bio import SeqIO diff -Nru python-biopython-1.62/Tests/test_SeqIO_QualityIO.py python-biopython-1.63/Tests/test_SeqIO_QualityIO.py --- python-biopython-1.62/Tests/test_SeqIO_QualityIO.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_SeqIO_QualityIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,18 +5,15 @@ """Additional unit tests for Bio.SeqIO.QualityIO (covering FASTQ and QUAL).""" -from __future__ import with_statement +from __future__ import print_function import os import unittest import warnings -from StringIO import StringIO -try: - #This is in Python 2.6+, but we need it on Python 3 - from io import BytesIO -except ImportError: - BytesIO = StringIO +from Bio._py3k import range +from Bio._py3k import StringIO +from io import BytesIO from Bio import BiopythonWarning from Bio.Alphabet import generic_dna @@ -55,7 +52,7 @@ SeqIO.write(records, handle, out_format) handle.seek(0) #Now load it back and check it agrees, - records2 = list(SeqIO.parse(handle,out_format)) + records2 = list(SeqIO.parse(handle, out_format)) compare_records(records, records2, truncation_expected(out_format)) @@ -82,16 +79,16 @@ if "phred_quality" in old.letter_annotations \ and "phred_quality" in new.letter_annotations \ and old.letter_annotations["phred_quality"] != new.letter_annotations["phred_quality"]: - if truncate and [min(q,truncate) for q in old.letter_annotations["phred_quality"]] == \ - [min(q,truncate) for q in new.letter_annotations["phred_quality"]]: + if truncate and [min(q, truncate) for q in old.letter_annotations["phred_quality"]] == \ + [min(q, truncate) for q in new.letter_annotations["phred_quality"]]: pass else: raise ValuerError("Mismatch in phred_quality") if "solexa_quality" in old.letter_annotations \ and "solexa_quality" in new.letter_annotations \ and old.letter_annotations["solexa_quality"] != new.letter_annotations["solexa_quality"]: - if truncate and [min(q,truncate) for q in old.letter_annotations["solexa_quality"]] == \ - [min(q,truncate) for q in new.letter_annotations["solexa_quality"]]: + if truncate and [min(q, truncate) for q in old.letter_annotations["solexa_quality"]] == \ + [min(q, truncate) for q in new.letter_annotations["solexa_quality"]]: pass else: raise ValueError("Mismatch in phred_quality") @@ -102,12 +99,12 @@ converted = [round(QualityIO.solexa_quality_from_phred(q)) for q in old.letter_annotations["phred_quality"]] if truncate: - converted = [min(q,truncate) for q in converted] + converted = [min(q, truncate) for q in converted] if converted != new.letter_annotations["solexa_quality"]: - print - print old.letter_annotations["phred_quality"] - print converted - print new.letter_annotations["solexa_quality"] + print("") + print(old.letter_annotations["phred_quality"]) + print(converted) + print(new.letter_annotations["solexa_quality"]) raise ValueError("Mismatch in phred_quality vs solexa_quality") if "solexa_quality" in old.letter_annotations \ and "phred_quality" in new.letter_annotations: @@ -116,11 +113,11 @@ converted = [round(QualityIO.phred_quality_from_solexa(q)) for q in old.letter_annotations["solexa_quality"]] if truncate: - converted = [min(q,truncate) for q in converted] + converted = [min(q, truncate) for q in converted] if converted != new.letter_annotations["phred_quality"]: - print old.letter_annotations["solexa_quality"] - print converted - print new.letter_annotations["phred_quality"] + print(old.letter_annotations["solexa_quality"]) + print(converted) + print(new.letter_annotations["phred_quality"]) raise ValueError("Mismatch in solexa_quality vs phred_quality") return True @@ -130,7 +127,7 @@ if len(old_list) != len(new_list): raise ValueError("%i vs %i records" % (len(old_list), len(new_list))) for old, new in zip(old_list, new_list): - if not compare_record(old,new,truncate_qual): + if not compare_record(old, new, truncate_qual): return False return True @@ -144,17 +141,17 @@ handle = open(filename, "rU") records = SeqIO.parse(handle, format) for i in range(good_count): - record = records.next() # Make sure no errors! + record = next(records) # Make sure no errors! self.assertTrue(isinstance(record, SeqRecord)) - self.assertRaises(ValueError, records.next) + self.assertRaises(ValueError, next, records) handle.close() def check_general_fails(self, filename, good_count): handle = open(filename, "rU") tuples = QualityIO.FastqGeneralIterator(handle) for i in range(good_count): - title, seq, qual = tuples.next() # Make sure no errors! - self.assertRaises(ValueError, tuples.next) + title, seq, qual = next(tuples) # Make sure no errors! + self.assertRaises(ValueError, next, tuples) handle.close() def check_general_passes(self, filename, record_count): @@ -195,9 +192,9 @@ ("trunc_at_plus", 4), ("trunc_at_qual", 4)] for base_name, good_count in tests: - def funct(name,c): - f = lambda x : x.check_all_fail("Quality/error_%s.fastq" % name,c) - f.__doc__ = "Reject FASTQ with %s" % name.replace("_"," ") + def funct(name, c): + f = lambda x : x.check_all_fail("Quality/error_%s.fastq" % name, c) + f.__doc__ = "Reject FASTQ with %s" % name.replace("_", " ") return f setattr(TestFastqErrors, "test_%s" % (base_name), funct(base_name, good_count)) @@ -213,9 +210,9 @@ ("tab", 4, 5), ("null", 0, 5)] for base_name, good_count, full_count in tests: - def funct(name,c1,c2): - f = lambda x : x.check_qual_char("Quality/error_qual_%s.fastq"%name,c1,c2) - f.__doc__ = "Reject FASTQ with %s in quality" % name.replace("_"," ") + def funct(name, c1, c2): + f = lambda x : x.check_qual_char("Quality/error_qual_%s.fastq"%name, c1, c2) + f.__doc__ = "Reject FASTQ with %s in quality" % name.replace("_", " ") return f setattr(TestFastqErrors, "test_qual_%s" % (base_name), funct(base_name, good_count, full_count)) @@ -313,8 +310,8 @@ for base_name, variant in tests: assert variant in ["sanger", "solexa", "illumina"] - def funct(bn,var): - f = lambda x : x.simple_check(bn,var) + def funct(bn, var): + f = lambda x : x.simple_check(bn, var) f.__doc__ = "Reference conversions of %s file %s" % (var, bn) return f @@ -329,7 +326,7 @@ """Check FASTQ parsing matches FASTA+QUAL parsing""" with open("Quality/example.fasta") as f: with open("Quality/example.qual") as q: - records1 = list(QualityIO.PairedFastaQualIterator(f,q )) + records1 = list(QualityIO.PairedFastaQualIterator(f, q )) records2 = list(SeqIO.parse("Quality/example.fastq", "fastq")) self.assertTrue(compare_records(records1, records2)) @@ -343,7 +340,7 @@ def test_qual_out(self): """Check FASTQ to QUAL output""" records = SeqIO.parse("Quality/example.fastq", "fastq") - h = StringIO("") + h = StringIO() SeqIO.write(records, h, "qual") with open("Quality/example.qual") as expected: self.assertEqual(h.getvalue(), expected.read()) @@ -357,7 +354,7 @@ def test_fasta_out(self): """Check FASTQ to FASTA output""" records = SeqIO.parse("Quality/example.fastq", "fastq") - h = StringIO("") + h = StringIO() SeqIO.write(records, h, "fasta") with open("Quality/example.fasta") as expected: self.assertEqual(h.getvalue(), expected.read()) @@ -400,7 +397,7 @@ """Read and write back simple example with upper case 2000bp read""" data = "@%s\n%s\n+\n%s\n" \ % ("id descr goes here", "ACGT"*500, "!@a~"*500) - handle = StringIO("") + handle = StringIO() self.assertEqual(1, SeqIO.write(SeqIO.parse(StringIO(data), "fastq"), handle, "fastq")) self.assertEqual(data, handle.getvalue()) @@ -408,7 +405,7 @@ """Read and write back simple example with mixed case 1000bp read""" data = "@%s\n%s\n+\n%s\n" \ % ("id descr goes here", "ACGTNncgta"*100, "abcd!!efgh"*100) - handle = StringIO("") + handle = StringIO() self.assertEqual(1, SeqIO.write(SeqIO.parse(StringIO(data), "fastq"), handle, "fastq")) self.assertEqual(data, handle.getvalue()) @@ -419,7 +416,7 @@ % ("id descr goes here", ambiguous_dna_letters.upper(), "".join(chr(33+q) for q in range(len(ambiguous_dna_letters)))) - handle = StringIO("") + handle = StringIO() self.assertEqual(1, SeqIO.write(SeqIO.parse(StringIO(data), "fastq"), handle, "fastq")) self.assertEqual(data, handle.getvalue()) #Now in lower case... @@ -427,7 +424,7 @@ % ("id descr goes here", ambiguous_dna_letters.lower(), "".join(chr(33+q) for q in range(len(ambiguous_dna_letters)))) - handle = StringIO("") + handle = StringIO() self.assertEqual(1, SeqIO.write(SeqIO.parse(StringIO(data), "fastq"), handle, "fastq")) self.assertEqual(data, handle.getvalue()) @@ -438,7 +435,7 @@ % ("id descr goes here", ambiguous_rna_letters.upper(), "".join(chr(33+q) for q in range(len(ambiguous_rna_letters)))) - handle = StringIO("") + handle = StringIO() self.assertEqual(1, SeqIO.write(SeqIO.parse(StringIO(data), "fastq"), handle, "fastq")) self.assertEqual(data, handle.getvalue()) #Now in lower case... @@ -446,7 +443,7 @@ % ("id descr goes here", ambiguous_rna_letters.lower(), "".join(chr(33+q) for q in range(len(ambiguous_rna_letters)))) - handle = StringIO("") + handle = StringIO() self.assertEqual(1, SeqIO.write(SeqIO.parse(StringIO(data), "fastq"), handle, "fastq")) self.assertEqual(data, handle.getvalue()) @@ -456,21 +453,21 @@ def test_generated(self): """Write and read back odd SeqRecord objects""" record1 = SeqRecord(Seq("ACGT"*500, generic_dna), id="Test", description="Long "*500, - letter_annotations={"phred_quality":[40,30,20,10]*500}) + letter_annotations={"phred_quality":[40, 30, 20, 10]*500}) record2 = SeqRecord(MutableSeq("NGGC"*1000), id="Mut", description="very "*1000+"long", - letter_annotations={"phred_quality":[0,5,5,10]*1000}) - record3 = SeqRecord(UnknownSeq(2000,character="N"), id="Unk", description="l"+("o"*1000)+"ng", - letter_annotations={"phred_quality":[0,1]*1000}) + letter_annotations={"phred_quality":[0, 5, 5, 10]*1000}) + record3 = SeqRecord(UnknownSeq(2000, character="N"), id="Unk", description="l"+("o"*1000)+"ng", + letter_annotations={"phred_quality":[0, 1]*1000}) record4 = SeqRecord(Seq("ACGT"*500), id="no_descr", description="", name="", - letter_annotations={"phred_quality":[40,50,60,62]*500}) - record5 = SeqRecord(Seq("",generic_dna), id="empty_p", description="(could have been trimmed lots)", + letter_annotations={"phred_quality":[40, 50, 60, 62]*500}) + record5 = SeqRecord(Seq("", generic_dna), id="empty_p", description="(could have been trimmed lots)", letter_annotations={"phred_quality":[]}) record6 = SeqRecord(Seq(""), id="empty_s", description="(could have been trimmed lots)", letter_annotations={"solexa_quality":[]}) record7 = SeqRecord(Seq("ACNN"*500), id="Test_Sol", description="Long "*500, - letter_annotations={"solexa_quality":[40,30,0,-5]*500}) + letter_annotations={"solexa_quality":[40, 30, 0, -5]*500}) record8 = SeqRecord(Seq("ACGT"), id="HighQual", description="With very large qualities that even Sanger FASTQ can't hold!", - letter_annotations={"solexa_quality":[0,10,100,1000]}) + letter_annotations={"solexa_quality":[0, 10, 100, 1000]}) #TODO - Record with no identifier? records = [record1, record2, record3, record4, record5, record6, record7, record8] #TODO - Have a Biopython defined "DataLossWarning?" @@ -503,7 +500,7 @@ #TODO - On Python 2.6+ we can check this warning is really triggered warnings.simplefilter('ignore', BiopythonWarning) self.check(os.path.join("Quality", "sanger_93.fastq"), "fastq", - ["fastq-solexa","fastq-illumina"]) + ["fastq-solexa", "fastq-illumina"]) warnings.filters.pop() def test_sanger_faked(self): @@ -621,7 +618,7 @@ self.assertEqual(6, round(QualityIO.solexa_quality_from_phred(7))) self.assertEqual(7, round(QualityIO.solexa_quality_from_phred(8))) self.assertEqual(8, round(QualityIO.solexa_quality_from_phred(9))) - for i in range(10,100): + for i in range(10, 100): self.assertEqual(i, round(QualityIO.solexa_quality_from_phred(i))) def test_phred_quality_from_solexa(self): @@ -641,7 +638,7 @@ self.assertEqual(8, round(QualityIO.phred_quality_from_solexa(7))) self.assertEqual(9, round(QualityIO.phred_quality_from_solexa(8))) self.assertEqual(10, round(QualityIO.phred_quality_from_solexa(9))) - for i in range(10,100): + for i in range(10, 100): self.assertEqual(i, round(QualityIO.phred_quality_from_solexa(i))) def test_sanger_to_solexa(self): @@ -650,11 +647,11 @@ #solexa_quality_from_phred function directly. For speed it uses a #cached dictionary of the mappings. seq = "N"*94 - qual = "".join(chr(33+q) for q in range(0,94)) - expected_sol = [min(62,int(round(QualityIO.solexa_quality_from_phred(q)))) - for q in range(0,94)] - in_handle = StringIO("@Test\n%s\n+\n%s" % (seq,qual)) - out_handle = StringIO("") + qual = "".join(chr(33+q) for q in range(0, 94)) + expected_sol = [min(62, int(round(QualityIO.solexa_quality_from_phred(q)))) + for q in range(0, 94)] + in_handle = StringIO("@Test\n%s\n+\n%s" % (seq, qual)) + out_handle = StringIO() #Want to ignore the data loss warning #(on Python 2.6 we could check for it!) warnings.simplefilter('ignore', BiopythonWarning) @@ -673,11 +670,11 @@ #solexa_quality_from_phred function directly. For speed it uses a #cached dictionary of the mappings. seq = "N"*68 - qual = "".join(chr(64+q) for q in range(-5,63)) + qual = "".join(chr(64+q) for q in range(-5, 63)) expected_phred = [round(QualityIO.phred_quality_from_solexa(q)) - for q in range(-5,63)] - in_handle = StringIO("@Test\n%s\n+\n%s" % (seq,qual)) - out_handle = StringIO("") + for q in range(-5, 63)] + in_handle = StringIO("@Test\n%s\n+\n%s" % (seq, qual)) + out_handle = StringIO() #Want to ignore the data loss warning #(on Python 2.6 we could check for it!) warnings.simplefilter('ignore', BiopythonWarning) @@ -693,10 +690,10 @@ def test_sanger_to_illumina(self): """Mapping check for FASTQ Sanger (0 to 93) to Illumina (0 to 62)""" seq = "N"*94 - qual = "".join(chr(33+q) for q in range(0,94)) - expected_phred = [min(62,q) for q in range(0,94)] - in_handle = StringIO("@Test\n%s\n+\n%s" % (seq,qual)) - out_handle = StringIO("") + qual = "".join(chr(33+q) for q in range(0, 94)) + expected_phred = [min(62, q) for q in range(0, 94)] + in_handle = StringIO("@Test\n%s\n+\n%s" % (seq, qual)) + out_handle = StringIO() #Want to ignore the data loss warning #(on Python 2.6 we could check for it!) warnings.simplefilter('ignore', BiopythonWarning) @@ -712,10 +709,10 @@ def test_illumina_to_sanger(self): """Mapping check for FASTQ Illumina (0 to 62) to Sanger (0 to 62)""" seq = "N"*63 - qual = "".join(chr(64+q) for q in range(0,63)) - expected_phred = range(63) - in_handle = StringIO("@Test\n%s\n+\n%s" % (seq,qual)) - out_handle = StringIO("") + qual = "".join(chr(64+q) for q in range(0, 63)) + expected_phred = list(range(63)) + in_handle = StringIO("@Test\n%s\n+\n%s" % (seq, qual)) + out_handle = StringIO() SeqIO.write(SeqIO.parse(in_handle, "fastq-illumina"), out_handle, "fastq-sanger") out_handle.seek(0) diff -Nru python-biopython-1.62/Tests/test_SeqIO_SeqXML.py python-biopython-1.63/Tests/test_SeqIO_SeqXML.py --- python-biopython-1.62/Tests/test_SeqIO_SeqXML.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_SeqIO_SeqXML.py 2013-12-05 14:10:43.000000000 +0000 @@ -8,13 +8,13 @@ from Bio import SeqIO from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord -from StringIO import StringIO +from Bio._py3k import StringIO test_files = { - "dna" : ["SeqXML/dna_example.xml",4], - "rna" : ["SeqXML/rna_example.xml",5], - "protein" : ["SeqXML/protein_example.xml",5], - "globalSpecies" : ["SeqXML/global_species_example.xml",2], + "dna": ["SeqXML/dna_example.xml", 4], + "rna": ["SeqXML/rna_example.xml", 5], + "protein": ["SeqXML/protein_example.xml", 5], + "globalSpecies": ["SeqXML/global_species_example.xml", 2], } corrupt_files = ["SeqXML/corrupt_example1.xml", @@ -22,13 +22,13 @@ ] -def assert_equal_records(testCase,record_a,record_b): - testCase.assertEqual(record_a.id,record_b.id) - testCase.assertEqual(record_a.name,record_b.name) - testCase.assertEqual(record_a.description,record_b.description) +def assert_equal_records(testCase, record_a, record_b): + testCase.assertEqual(record_a.id, record_b.id) + testCase.assertEqual(record_a.name, record_b.name) + testCase.assertEqual(record_a.description, record_b.description) testCase.assertEqual(str(record_a.seq), str(record_b.seq)) - testCase.assertEqual(record_a.dbxrefs,record_b.dbxrefs) - testCase.assertEqual(record_a.annotations,record_a.annotations) + testCase.assertEqual(record_a.dbxrefs, record_b.dbxrefs) + testCase.assertEqual(record_a.annotations, record_a.annotations) class TestSimpleRead(unittest.TestCase): @@ -36,8 +36,8 @@ def test_check_SeqIO(self): """Files readable using parser via SeqIO.""" for key in test_files: - records = list(SeqIO.parse(test_files[key][0],"seqxml")) - self.assertEqual(len(records),test_files[key][1]) + records = list(SeqIO.parse(test_files[key][0], "seqxml")) + self.assertEqual(len(records), test_files[key][1]) class TestDetailedRead(unittest.TestCase): @@ -46,7 +46,7 @@ def setUp(self): for key in test_files: - self.records[key] = list(SeqIO.parse(test_files[key][0],"seqxml")) + self.records[key] = list(SeqIO.parse(test_files[key][0], "seqxml")) def test_special_characters_desc(self): """Read special XML characters in description.""" @@ -60,88 +60,88 @@ def test_full_characters_set_read(self): """Read full characters set for each type""" - self.assertEqual(str(self.records["dna"][1].seq),"ACGTMRWSYKVHDBXN.-" ) - self.assertEqual(str(self.records["rna"][1].seq),"ACGUMRWSYKVHDBXN.-" ) - self.assertEqual(str(self.records["protein"][1].seq),"ABCDEFGHIJKLMNOPQRSTUVWXYZ.-*") + self.assertEqual(str(self.records["dna"][1].seq), "ACGTMRWSYKVHDBXN.-" ) + self.assertEqual(str(self.records["rna"][1].seq), "ACGUMRWSYKVHDBXN.-" ) + self.assertEqual(str(self.records["protein"][1].seq), "ABCDEFGHIJKLMNOPQRSTUVWXYZ.-*") def test_duplicated_property(self): """Read property with multiple values""" - self.assertEqual(self.records["protein"][2].annotations["test"],[u"1",u"2",u"3"]) + self.assertEqual(self.records["protein"][2].annotations["test"], [u"1", u"2", u"3"]) def test_duplicated_dbxref(self): """Read multiple cross references to a single source""" - self.assertEqual(self.records["protein"][2].dbxrefs,[u"someDB:G001",u"someDB:G002"]) + self.assertEqual(self.records["protein"][2].dbxrefs, [u"someDB:G001", u"someDB:G002"]) def test_read_minimal_required(self): """Check minimal record.""" - minimalRecord = SeqRecord(id="test",seq=Seq("abc")) + minimalRecord = SeqRecord(id="test", seq=Seq("abc")) minimalRecord.annotations["source"] = u"Ensembl" - self.assertEqual(self.records["rna"][3].name,minimalRecord.name) - self.assertEqual(self.records["dna"][3].annotations,minimalRecord.annotations) - self.assertEqual(self.records["rna"][3].dbxrefs,minimalRecord.dbxrefs) - self.assertEqual(self.records["protein"][3].description,minimalRecord.description) + self.assertEqual(self.records["rna"][3].name, minimalRecord.name) + self.assertEqual(self.records["dna"][3].annotations, minimalRecord.annotations) + self.assertEqual(self.records["rna"][3].dbxrefs, minimalRecord.dbxrefs) + self.assertEqual(self.records["protein"][3].description, minimalRecord.description) def test_local_species(self): """Check local species.""" - self.assertEqual(self.records["rna"][1].annotations["organism"],"Mus musculus") - self.assertEqual(self.records["rna"][1].annotations["ncbi_taxid"],"10090") + self.assertEqual(self.records["rna"][1].annotations["organism"], "Mus musculus") + self.assertEqual(self.records["rna"][1].annotations["ncbi_taxid"], "10090") - self.assertEqual(self.records["rna"][0].annotations["organism"],"Gallus gallus") - self.assertEqual(self.records["rna"][0].annotations["ncbi_taxid"],"9031") + self.assertEqual(self.records["rna"][0].annotations["organism"], "Gallus gallus") + self.assertEqual(self.records["rna"][0].annotations["ncbi_taxid"], "9031") def test_global_species(self): """Check global species.""" - self.assertEqual(self.records["globalSpecies"][0].annotations["organism"],"Mus musculus") - self.assertEqual(self.records["globalSpecies"][0].annotations["ncbi_taxid"],"10090") + self.assertEqual(self.records["globalSpecies"][0].annotations["organism"], "Mus musculus") + self.assertEqual(self.records["globalSpecies"][0].annotations["ncbi_taxid"], "10090") - self.assertEqual(self.records["globalSpecies"][1].annotations["organism"],"Homo sapiens") - self.assertEqual(self.records["globalSpecies"][1].annotations["ncbi_taxid"],"9606") + self.assertEqual(self.records["globalSpecies"][1].annotations["organism"], "Homo sapiens") + self.assertEqual(self.records["globalSpecies"][1].annotations["ncbi_taxid"], "9606") def test_local_source_definition(self): """Check local source.""" - self.assertEqual(self.records["protein"][4].annotations["source"],u"Uniprot") + self.assertEqual(self.records["protein"][4].annotations["source"], u"Uniprot") def test_empty_description(self): """Check empty description.""" - self.assertEqual(self.records["rna"][4].description,SeqRecord(id="",seq=Seq("")).description) + self.assertEqual(self.records["rna"][4].description, SeqRecord(id="", seq=Seq("")).description) class TestReadAndWrite(unittest.TestCase): def test_read_write_rna(self): """Read and write RNA.""" - read1_records = list(SeqIO.parse(test_files["rna"][0],"seqxml")) + read1_records = list(SeqIO.parse(test_files["rna"][0], "seqxml")) self._write_parse_and_compare(read1_records) def test_read_write_dna(self): """Read and write DNA.""" - read1_records = list(SeqIO.parse(test_files["dna"][0],"seqxml")) + read1_records = list(SeqIO.parse(test_files["dna"][0], "seqxml")) self._write_parse_and_compare(read1_records) def test_read_write_protein(self): """Read and write protein.""" - read1_records = list(SeqIO.parse(test_files["protein"][0],"seqxml")) + read1_records = list(SeqIO.parse(test_files["protein"][0], "seqxml")) self._write_parse_and_compare(read1_records) def test_read_write_globalSpecies(self): """Read and write global species.""" - read1_records = list(SeqIO.parse(test_files["globalSpecies"][0],"seqxml")) + read1_records = list(SeqIO.parse(test_files["globalSpecies"][0], "seqxml")) self._write_parse_and_compare(read1_records) - def _write_parse_and_compare(self,read1_records): + def _write_parse_and_compare(self, read1_records): handle = StringIO() - SeqIO.write(read1_records,handle,"seqxml") + SeqIO.write(read1_records, handle, "seqxml") handle.seek(0) - read2_records = list(SeqIO.parse(handle,"seqxml")) + read2_records = list(SeqIO.parse(handle, "seqxml")) - self.assertEqual(len(read1_records),len(read2_records)) + self.assertEqual(len(read1_records), len(read2_records)) - for record1,record2 in zip(read1_records,read2_records): - assert_equal_records(self,record1,record2) + for record1, record2 in zip(read1_records, read2_records): + assert_equal_records(self, record1, record2) class TestReadCorruptFiles(unittest.TestCase): @@ -149,8 +149,8 @@ def test_for_errors(self): """Handling of corrupt files.""" for filename in corrupt_files: - iterator = SeqIO.parse(filename,"seqxml") - self.assertRaises(ValueError,iterator.next) + iterator = SeqIO.parse(filename, "seqxml") + self.assertRaises(ValueError, next, iterator) if __name__ == "__main__": diff -Nru python-biopython-1.62/Tests/test_SeqIO_convert.py python-biopython-1.63/Tests/test_SeqIO_convert.py --- python-biopython-1.62/Tests/test_SeqIO_convert.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_SeqIO_convert.py 2013-12-05 14:10:43.000000000 +0000 @@ -4,13 +4,15 @@ # as part of this package. """Unit tests for Bio.SeqIO.convert(...) function.""" +from __future__ import print_function + import unittest import warnings from Bio.Seq import UnknownSeq from Bio import SeqIO from Bio.SeqIO import QualityIO from Bio.SeqIO._convert import _converter as converter_dict -from StringIO import StringIO +from Bio._py3k import StringIO from Bio.Alphabet import generic_protein, generic_nucleotide, generic_dna @@ -26,7 +28,7 @@ #Top level function as this makes it easier to use for debugging: def check_convert(in_filename, in_format, out_format, alphabet=None): - records = list(SeqIO.parse(in_filename,in_format, alphabet)) + records = list(SeqIO.parse(in_filename, in_format, alphabet)) #Write it out... handle = StringIO() qual_truncate = truncation_expected(out_format) @@ -55,7 +57,7 @@ #We want the SAME error message from parse/write as convert! err1 = None try: - records = list(SeqIO.parse(in_filename,in_format, alphabet)) + records = list(SeqIO.parse(in_filename, in_format, alphabet)) handle = StringIO() if qual_truncate: warnings.simplefilter('ignore', UserWarning) @@ -64,7 +66,7 @@ warnings.filters.pop() handle.seek(0) assert False, "Parse or write should have failed!" - except ValueError, err: + except ValueError as err: err1 = err #Now do the conversion... try: @@ -75,11 +77,10 @@ if qual_truncate: warnings.filters.pop() assert False, "Convert should have failed!" - except ValueError, err2: + except ValueError as err2: assert str(err1) == str(err2), \ "Different failures, parse/write:\n%s\nconvert:\n%s" \ % (err1, err2) - #print err #TODO - move this to a shared test module... @@ -108,16 +109,16 @@ if "phred_quality" in old.letter_annotations \ and "phred_quality" in new.letter_annotations \ and old.letter_annotations["phred_quality"] != new.letter_annotations["phred_quality"]: - if truncate and [min(q,truncate) for q in old.letter_annotations["phred_quality"]] == \ - [min(q,truncate) for q in new.letter_annotations["phred_quality"]]: + if truncate and [min(q, truncate) for q in old.letter_annotations["phred_quality"]] == \ + [min(q, truncate) for q in new.letter_annotations["phred_quality"]]: pass else: raise ValuerError("Mismatch in phred_quality") if "solexa_quality" in old.letter_annotations \ and "solexa_quality" in new.letter_annotations \ and old.letter_annotations["solexa_quality"] != new.letter_annotations["solexa_quality"]: - if truncate and [min(q,truncate) for q in old.letter_annotations["solexa_quality"]] == \ - [min(q,truncate) for q in new.letter_annotations["solexa_quality"]]: + if truncate and [min(q, truncate) for q in old.letter_annotations["solexa_quality"]] == \ + [min(q, truncate) for q in new.letter_annotations["solexa_quality"]]: pass else: raise ValueError("Mismatch in phred_quality") @@ -128,12 +129,12 @@ converted = [round(QualityIO.solexa_quality_from_phred(q)) for q in old.letter_annotations["phred_quality"]] if truncate: - converted = [min(q,truncate) for q in converted] + converted = [min(q, truncate) for q in converted] if converted != new.letter_annotations["solexa_quality"]: - print - print old.letter_annotations["phred_quality"] - print converted - print new.letter_annotations["solexa_quality"] + print("") + print(old.letter_annotations["phred_quality"]) + print(converted) + print(new.letter_annotations["solexa_quality"]) raise ValueError("Mismatch in phred_quality vs solexa_quality") if "solexa_quality" in old.letter_annotations \ and "phred_quality" in new.letter_annotations: @@ -142,11 +143,11 @@ converted = [round(QualityIO.phred_quality_from_solexa(q)) for q in old.letter_annotations["solexa_quality"]] if truncate: - converted = [min(q,truncate) for q in converted] + converted = [min(q, truncate) for q in converted] if converted != new.letter_annotations["phred_quality"]: - print old.letter_annotations["solexa_quality"] - print converted - print new.letter_annotations["phred_quality"] + print(old.letter_annotations["solexa_quality"]) + print(converted) + print(new.letter_annotations["phred_quality"]) raise ValueError("Mismatch in solexa_quality vs phred_quality") return True @@ -156,7 +157,7 @@ if len(old_list) != len(new_list): raise ValueError("%i vs %i records" % (len(old_list), len(new_list))) for old, new in zip(old_list, new_list): - if not compare_record(old,new,truncate_qual): + if not compare_record(old, new, truncate_qual): return False return True @@ -187,13 +188,13 @@ if in_format != format: continue - def funct(fn,fmt1, fmt2, alpha): + def funct(fn, fmt1, fmt2, alpha): f = lambda x : x.simple_check(fn, fmt1, fmt2, alpha) f.__doc__ = "Convert %s from %s to %s" % (fn, fmt1, fmt2) return f setattr(ConvertTests, "test_%s_%s_to_%s" - % (filename.replace("/","_").replace(".","_"), in_format, out_format), + % (filename.replace("/", "_").replace(".", "_"), in_format, out_format), funct(filename, in_format, out_format, alphabet)) del funct @@ -232,13 +233,13 @@ #and in order to pass this strict test they should. continue - def funct(fn,fmt1, fmt2, alpha): + def funct(fn, fmt1, fmt2, alpha): f = lambda x : x.failure_check(fn, fmt1, fmt2, alpha) f.__doc__ = "Convert %s from %s to %s" % (fn, fmt1, fmt2) return f setattr(ConvertTests, "test_%s_%s_to_%s" - % (filename.replace("/","_").replace(".","_"), in_format, out_format), + % (filename.replace("/", "_").replace(".", "_"), in_format, out_format), funct(filename, in_format, out_format, alphabet)) del funct diff -Nru python-biopython-1.62/Tests/test_SeqIO_features.py python-biopython-1.63/Tests/test_SeqIO_features.py --- python-biopython-1.62/Tests/test_SeqIO_features.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_SeqIO_features.py 2013-12-05 14:10:43.000000000 +0000 @@ -8,10 +8,12 @@ Initially this takes matched tests of GenBank and FASTA files from the NCBI and confirms they are consistent using our different parsers. """ -from __future__ import with_statement +from __future__ import print_function import os import unittest +from Bio._py3k import StringIO + from Bio.Alphabet import generic_dna, generic_rna, generic_protein from Bio import SeqIO from Bio.Data.CodonTable import TranslationError @@ -20,7 +22,7 @@ from Bio.SeqFeature import SeqFeature, FeatureLocation, CompoundLocation from Bio.SeqFeature import ExactPosition, BeforePosition, AfterPosition, \ OneOfPosition, WithinPosition -from StringIO import StringIO + from Bio.SeqIO.InsdcIO import _insdc_feature_location_string @@ -33,7 +35,7 @@ SeqIO.write(gb_records, handle, out_format) handle.seek(0) #Now load it back and check it agrees, - gb_records2 = list(SeqIO.parse(handle,out_format)) + gb_records2 = list(SeqIO.parse(handle, out_format)) compare_records(gb_records, gb_records2) @@ -42,7 +44,7 @@ if not expect_minor_diffs \ and old.id != new.id and old.name != new.name \ and (old.id not in new.id) and (new.id not in old.id) \ - and (old.id.replace(" ","_") != new.id.replace(" ","_")): + and (old.id.replace(" ", "_") != new.id.replace(" ", "_")): raise ValueError("'%s' or '%s' vs '%s' or '%s' records" % (old.id, old.name, new.id, new.name)) if len(old.seq) != len(new.seq): @@ -109,7 +111,7 @@ if len(old_list) != len(new_list): raise ValueError("%i vs %i records" % (len(old_list), len(new_list))) for old, new in zip(old_list, new_list): - if not compare_record(old,new,expect_minor_diffs): + if not compare_record(old, new, expect_minor_diffs): return False return True @@ -142,14 +144,14 @@ #Using private variable to avoid deprecation warnings, if len(old._sub_features) != len(new._sub_features): raise ValueError("Different sub features") - for a,b in zip(old._sub_features, new._sub_features): - if not compare_feature(a,b): + for a, b in zip(old._sub_features, new._sub_features): + if not compare_feature(a, b): return False #This only checks key shared qualifiers #Would a white list be easier? #for key in ["name","gene","translation","codon_table","codon_start","locus_tag"]: for key in set(old.qualifiers).intersection(new.qualifiers): - if key in ["db_xref","protein_id","product","note"]: + if key in ["db_xref", "protein_id", "product", "note"]: #EMBL and GenBank files are use different references/notes/etc continue if old.qualifiers[key] != new.qualifiers[key]: @@ -164,7 +166,7 @@ raise ValueError("%i vs %i features" % (len(old_list), len(new_list))) for old, new in zip(old_list, new_list): #This assumes they are in the same order - if not compare_feature(old,new,ignore_sub_features): + if not compare_feature(old, new, ignore_sub_features): return False return True @@ -215,7 +217,7 @@ def check(self, parent_seq, feature, answer_str, location_str): self.assertEqual(location_str, - _insdc_feature_location_string(feature,len(parent_seq))) + _insdc_feature_location_string(feature, len(parent_seq))) new = feature.extract(parent_seq) self.assertTrue(isinstance(new, Seq)) @@ -253,7 +255,7 @@ self.assertEqual(rec.features[1].type, "misc_feature") new_f = rec.features[1] self.assertEqual(location_str, - _insdc_feature_location_string(new_f,1326)) + _insdc_feature_location_string(new_f, 1326)) #Checking the strand is tricky - on parsing a GenBank file #strand +1 is assumed, but our constructed features for the @@ -264,7 +266,7 @@ if f1.strand is None: f1.strand = f2.strand # hack as described above self.assertEqual(f1.strand, f2.strand) - self.assertTrue(compare_feature(f1,f2)) + self.assertTrue(compare_feature(f1, f2)) feature.type = "misc_feature" # hack as may not be misc_feature if not feature.strand: feature.strand = new_f.strand # hack as above @@ -289,7 +291,7 @@ def test_simple_rna(self): """Feature on RNA (simple, default strand)""" s = Seq("GAUCRYWSMKHBVDN", generic_rna) - f = SeqFeature(FeatureLocation(5,10)) + f = SeqFeature(FeatureLocation(5, 10)) self.assertEqual(f.strand, None) self.assertEqual(f.location.strand, None) self.check(s, f, "YWSMK", "6..10") @@ -297,43 +299,43 @@ def test_simple_dna(self): """Feature on DNA (simple, default strand)""" s = Seq("GATCRYWSMKHBVDN", generic_dna) - f = SeqFeature(FeatureLocation(5,10)) + f = SeqFeature(FeatureLocation(5, 10)) self.check(s, f, "YWSMK", "6..10") def test_single_letter_dna(self): """Feature on DNA (single letter, default strand)""" s = Seq("GATCRYWSMKHBVDN", generic_dna) - f = SeqFeature(FeatureLocation(5,6)) + f = SeqFeature(FeatureLocation(5, 6)) self.check(s, f, "Y", "6") def test_zero_len_dna(self): """Feature on DNA (between location, zero length, default strand)""" s = Seq("GATCRYWSMKHBVDN", generic_dna) - f = SeqFeature(FeatureLocation(5,5)) + f = SeqFeature(FeatureLocation(5, 5)) self.check(s, f, "", "5^6") def test_zero_len_dna_end(self): """Feature on DNA (between location at end, zero length, default strand)""" s = Seq("GATCRYWSMKHBVDN", generic_dna) - f = SeqFeature(FeatureLocation(15,15)) + f = SeqFeature(FeatureLocation(15, 15)) self.check(s, f, "", "15^1") def test_simple_dna_strand0(self): """Feature on DNA (simple, strand 0)""" s = Seq("GATCRYWSMKHBVDN", generic_dna) - f = SeqFeature(FeatureLocation(5,10), strand=0) + f = SeqFeature(FeatureLocation(5, 10), strand=0) self.check(s, f, "YWSMK", "6..10") def test_simple_dna_strand_none(self): """Feature on DNA (simple, strand None)""" s = Seq("GATCRYWSMKHBVDN", generic_dna) - f = SeqFeature(FeatureLocation(5,10), strand=None) + f = SeqFeature(FeatureLocation(5, 10), strand=None) self.check(s, f, "YWSMK", "6..10") def test_simple_dna_strand1(self): """Feature on DNA (simple, strand +1)""" s = Seq("GATCRYWSMKHBVDN", generic_dna) - f = SeqFeature(FeatureLocation(5,10), strand=1) + f = SeqFeature(FeatureLocation(5, 10), strand=1) self.assertEqual(f.strand, +1) self.assertEqual(f.location.strand, +1) self.check(s, f, "YWSMK", "6..10") @@ -341,7 +343,7 @@ def test_simple_dna_strand_minus(self): """Feature on DNA (simple, strand -1)""" s = Seq("GATCRYWSMKHBVDN", generic_dna) - f = SeqFeature(FeatureLocation(5,10), strand=-1) + f = SeqFeature(FeatureLocation(5, 10), strand=-1) self.assertEqual(f.strand, -1) self.assertEqual(f.location.strand, -1) self.check(s, f, "MKSWR", "complement(6..10)") @@ -349,111 +351,111 @@ def test_simple_dna_join(self): """Feature on DNA (join, strand +1)""" s = Seq("GATCRYWSMKHBVDN", generic_dna) - f1 = SeqFeature(FeatureLocation(5,10), strand=1) - f2 = SeqFeature(FeatureLocation(12,15), strand=1) - f = make_join_feature([f1,f2]) + f1 = SeqFeature(FeatureLocation(5, 10), strand=1) + f2 = SeqFeature(FeatureLocation(12, 15), strand=1) + f = make_join_feature([f1, f2]) self.check(s, f, "YWSMKVDN", "join(6..10,13..15)") def test_simple_dna_join(self): """Feature on DNA (join, strand -1)""" s = Seq("AAAAACCCCCTTTTTGGGGG", generic_dna) - f1 = SeqFeature(FeatureLocation(5,10), strand=-1) - f2 = SeqFeature(FeatureLocation(12,15), strand=-1) - f = make_join_feature([f1,f2]) + f1 = SeqFeature(FeatureLocation(5, 10), strand=-1) + f2 = SeqFeature(FeatureLocation(12, 15), strand=-1) + f = make_join_feature([f1, f2]) self.check(s, f, reverse_complement("CCCCC"+"TTT"), "complement(join(6..10,13..15))") def test_simple_dna_join(self): """Feature on DNA (join, strand -1, before position)""" s = Seq("AAAAACCCCCTTTTTGGGGG", generic_dna) - f1 = SeqFeature(FeatureLocation(BeforePosition(5),10), strand=-1) - f2 = SeqFeature(FeatureLocation(12,15), strand=-1) - f = make_join_feature([f1,f2]) + f1 = SeqFeature(FeatureLocation(BeforePosition(5), 10), strand=-1) + f2 = SeqFeature(FeatureLocation(12, 15), strand=-1) + f = make_join_feature([f1, f2]) self.check(s, f, reverse_complement("CCCCC"+"TTT"), "complement(join(<6..10,13..15))") def test_simple_dna_join_after(self): """Feature on DNA (join, strand -1, after position)""" s = Seq("AAAAACCCCCTTTTTGGGGG", generic_dna) - f1 = SeqFeature(FeatureLocation(5,10), strand=-1) - f2 = SeqFeature(FeatureLocation(12,AfterPosition(15)), strand=-1) - f = make_join_feature([f1,f2]) + f1 = SeqFeature(FeatureLocation(5, 10), strand=-1) + f2 = SeqFeature(FeatureLocation(12, AfterPosition(15)), strand=-1) + f = make_join_feature([f1, f2]) self.check(s, f, reverse_complement("CCCCC"+"TTT"), "complement(join(6..10,13..>15))") def test_mixed_strand_dna_join(self): """Feature on DNA (join, mixed strand)""" s = Seq("AAAAACCCCCTTTTTGGGGG", generic_dna) - f1 = SeqFeature(FeatureLocation(5,10), strand=+1) - f2 = SeqFeature(FeatureLocation(12,15), strand=-1) - f = make_join_feature([f1,f2]) + f1 = SeqFeature(FeatureLocation(5, 10), strand=+1) + f2 = SeqFeature(FeatureLocation(12, 15), strand=-1) + f = make_join_feature([f1, f2]) self.check(s, f, "CCCCC"+reverse_complement("TTT"), "join(6..10,complement(13..15))") def test_mixed_strand_dna_multi_join(self): """Feature on DNA (multi-join, mixed strand)""" s = Seq("AAAAACCCCCTTTTTGGGGG", generic_dna) - f1 = SeqFeature(FeatureLocation(5,10), strand=+1) - f2 = SeqFeature(FeatureLocation(12,15), strand=-1) - f3 = SeqFeature(FeatureLocation(BeforePosition(0),5), strand=+1) - f = make_join_feature([f1,f2,f3]) + f1 = SeqFeature(FeatureLocation(5, 10), strand=+1) + f2 = SeqFeature(FeatureLocation(12, 15), strand=-1) + f3 = SeqFeature(FeatureLocation(BeforePosition(0), 5), strand=+1) + f = make_join_feature([f1, f2, f3]) self.check(s, f, "CCCCC"+reverse_complement("TTT")+"AAAAA", "join(6..10,complement(13..15),<1..5)") def test_protein_simple(self): """Feature on protein (simple)""" s = Seq("ABCDEFGHIJKLMNOPQRSTUVWXYZ", generic_protein) - f = SeqFeature(FeatureLocation(5,10)) + f = SeqFeature(FeatureLocation(5, 10)) self.check(s, f, "FGHIJ", "6..10") def test_protein_join(self): """Feature on protein (join)""" s = Seq("ABCDEFGHIJKLMNOPQRSTUVWXYZ", generic_protein) - f1 = SeqFeature(FeatureLocation(5,10)) - f2 = SeqFeature(FeatureLocation(15,20)) - f = make_join_feature([f1,f2]) + f1 = SeqFeature(FeatureLocation(5, 10)) + f2 = SeqFeature(FeatureLocation(15, 20)) + f = make_join_feature([f1, f2]) self.check(s, f, "FGHIJ"+"PQRST", "join(6..10,16..20)") def test_protein_join_fuzzy(self): """Feature on protein (fuzzy join)""" s = Seq("ABCDEFGHIJKLMNOPQRSTUVWXYZ", generic_protein) - f1 = SeqFeature(FeatureLocation(BeforePosition(5),10)) + f1 = SeqFeature(FeatureLocation(BeforePosition(5), 10)) f2 = SeqFeature(FeatureLocation(OneOfPosition(15, (ExactPosition(15), ExactPosition(16))), AfterPosition(20))) - f = make_join_feature([f1,f2]) + f = make_join_feature([f1, f2]) self.check(s, f, "FGHIJ"+"PQRST", "join(<6..10,one-of(16,17)..>20)") def test_protein_multi_join(self): """Feature on protein (multi-join)""" s = Seq("ABCDEFGHIJKLMNOPQRSTUVWXYZ", generic_protein) - f1 = SeqFeature(FeatureLocation(1,2)) - f2 = SeqFeature(FeatureLocation(8,9)) - f3 = SeqFeature(FeatureLocation(14,16)) - f4 = SeqFeature(FeatureLocation(24,25)) - f5 = SeqFeature(FeatureLocation(19,20)) - f6 = SeqFeature(FeatureLocation(7,8)) - f7 = SeqFeature(FeatureLocation(14,15)) - f8 = SeqFeature(FeatureLocation(13,14)) - f = make_join_feature([f1,f2,f3,f4,f5,f6,f7,f8]) + f1 = SeqFeature(FeatureLocation(1, 2)) + f2 = SeqFeature(FeatureLocation(8, 9)) + f3 = SeqFeature(FeatureLocation(14, 16)) + f4 = SeqFeature(FeatureLocation(24, 25)) + f5 = SeqFeature(FeatureLocation(19, 20)) + f6 = SeqFeature(FeatureLocation(7, 8)) + f7 = SeqFeature(FeatureLocation(14, 15)) + f8 = SeqFeature(FeatureLocation(13, 14)) + f = make_join_feature([f1, f2, f3, f4, f5, f6, f7, f8]) self.check(s, f, "BIOPYTHON", "join(2,9,15..16,25,20,8,15,14)") def test_protein_between(self): """Feature on protein (between location, zero length)""" s = Seq("ABCDEFGHIJKLMNOPQRSTUVWXYZ", generic_protein) - f = SeqFeature(FeatureLocation(5,5)) + f = SeqFeature(FeatureLocation(5, 5)) self.check(s, f, "", "5^6") def test_protein_oneof(self): """Feature on protein (one-of positions)""" s = Seq("ABCDEFGHIJKLMNOPQRSTUVWXYZ", generic_protein) - start = OneOfPosition(5, (ExactPosition(5),ExactPosition(7))) - end = OneOfPosition(11, (ExactPosition(10),ExactPosition(11))) - f = SeqFeature(FeatureLocation(start,10)) + start = OneOfPosition(5, (ExactPosition(5), ExactPosition(7))) + end = OneOfPosition(11, (ExactPosition(10), ExactPosition(11))) + f = SeqFeature(FeatureLocation(start, 10)) self.check(s, f, "FGHIJ", "one-of(6,8)..10") - f = SeqFeature(FeatureLocation(start,end)) + f = SeqFeature(FeatureLocation(start, end)) self.check(s, f, "FGHIJK", "one-of(6,8)..one-of(10,11)") - f = SeqFeature(FeatureLocation(5,end)) + f = SeqFeature(FeatureLocation(5, end)) self.check(s, f, "FGHIJK", "6..one-of(10,11)") @@ -464,9 +466,9 @@ def test_qualifiers(self): """Pass in qualifiers to SeqFeatures. """ - f = SeqFeature(FeatureLocation(10,20), strand=+1, type="CDS") + f = SeqFeature(FeatureLocation(10, 20), strand=+1, type="CDS") self.assertEqual(f.qualifiers, {}) - f = SeqFeature(FeatureLocation(10,20), strand=+1, type="CDS", + f = SeqFeature(FeatureLocation(10, 20), strand=+1, type="CDS", qualifiers={"test": ["a test"]}) self.assertEqual(f.qualifiers["test"], ["a test"]) @@ -491,33 +493,33 @@ """GenBank/EMBL write/read simple exact locations.""" #Note we don't have to explicitly give an ExactPosition object, #an integer will also work: - f = SeqFeature(FeatureLocation(10,20), strand=+1, type="CDS") - self.assertEqual(_insdc_feature_location_string(f,100), + f = SeqFeature(FeatureLocation(10, 20), strand=+1, type="CDS") + self.assertEqual(_insdc_feature_location_string(f, 100), "11..20") - self.assertEqual(_insdc_feature_location_string(f._flip(20),20), + self.assertEqual(_insdc_feature_location_string(f._flip(20), 20), "complement(1..10)") - self.assertEqual(_insdc_feature_location_string(f._flip(100),100), + self.assertEqual(_insdc_feature_location_string(f._flip(100), 100), "complement(81..90)") self.assertEqual(f._flip(100).strand, -1) self.record.features.append(f) - f = SeqFeature(FeatureLocation(30,40), strand=-1, type="CDS") - self.assertEqual(_insdc_feature_location_string(f,100), + f = SeqFeature(FeatureLocation(30, 40), strand=-1, type="CDS") + self.assertEqual(_insdc_feature_location_string(f, 100), "complement(31..40)") - self.assertEqual(_insdc_feature_location_string(f._flip(40),40), + self.assertEqual(_insdc_feature_location_string(f._flip(40), 40), "1..10") - self.assertEqual(_insdc_feature_location_string(f._flip(100),100), + self.assertEqual(_insdc_feature_location_string(f._flip(100), 100), "61..70") self.assertEqual(f._flip(100).strand, +1) self.record.features.append(f) - f = SeqFeature(FeatureLocation(ExactPosition(50),ExactPosition(60)), + f = SeqFeature(FeatureLocation(ExactPosition(50), ExactPosition(60)), strand=+1, type="CDS") - self.assertEqual(_insdc_feature_location_string(f,100), + self.assertEqual(_insdc_feature_location_string(f, 100), "51..60") - self.assertEqual(_insdc_feature_location_string(f._flip(60),60), + self.assertEqual(_insdc_feature_location_string(f._flip(60), 60), "complement(1..10)") - self.assertEqual(_insdc_feature_location_string(f._flip(100),100), + self.assertEqual(_insdc_feature_location_string(f._flip(100), 100), "complement(41..50)") self.assertEqual(f._flip(100).strand, -1) self.record.features.append(f) @@ -527,33 +529,33 @@ #limitations of the GenBank (and EMBL) feature location scheme for s in [0, None] : #Check flipping of a simple strand 0 feature: - f = SeqFeature(FeatureLocation(0,100), strand=s, type="source") - self.assertEqual(_insdc_feature_location_string(f,100), + f = SeqFeature(FeatureLocation(0, 100), strand=s, type="source") + self.assertEqual(_insdc_feature_location_string(f, 100), "1..100") - self.assertEqual(_insdc_feature_location_string(f._flip(100),100), + self.assertEqual(_insdc_feature_location_string(f._flip(100), 100), "1..100") - self.assertEqual(_insdc_feature_location_string(f._flip(200),200), + self.assertEqual(_insdc_feature_location_string(f._flip(200), 200), "101..200") self.assertEqual(f._flip(100).strand, f.strand) def test_between(self): """GenBank/EMBL write/read simple between locations.""" #Note we don't use the BetweenPosition any more! - f = SeqFeature(FeatureLocation(10,10), strand=+1, type="variation") - self.assertEqual(_insdc_feature_location_string(f,100), + f = SeqFeature(FeatureLocation(10, 10), strand=+1, type="variation") + self.assertEqual(_insdc_feature_location_string(f, 100), "10^11") - self.assertEqual(_insdc_feature_location_string(f._flip(20),20), + self.assertEqual(_insdc_feature_location_string(f._flip(20), 20), "complement(10^11)") - self.assertEqual(_insdc_feature_location_string(f._flip(100),100), + self.assertEqual(_insdc_feature_location_string(f._flip(100), 100), "complement(90^91)") self.assertEqual(f._flip(100).strand, -1) self.record.features.append(f) - f = SeqFeature(FeatureLocation(20,20), strand=-1, type="variation") - self.assertEqual(_insdc_feature_location_string(f,100), + f = SeqFeature(FeatureLocation(20, 20), strand=-1, type="variation") + self.assertEqual(_insdc_feature_location_string(f, 100), "complement(20^21)") - self.assertEqual(_insdc_feature_location_string(f._flip(40),40), + self.assertEqual(_insdc_feature_location_string(f._flip(40), 40), "20^21") - self.assertEqual(_insdc_feature_location_string(f._flip(100),100), + self.assertEqual(_insdc_feature_location_string(f._flip(100), 100), "80^81") self.assertEqual(f._flip(100).strand, +1) self.record.features.append(f) @@ -561,49 +563,49 @@ def test_join(self): """GenBank/EMBL write/read simple join locations.""" - f1 = SeqFeature(FeatureLocation(10,20), strand=+1) - f2 = SeqFeature(FeatureLocation(25,40), strand=+1) - f = make_join_feature([f1,f2]) + f1 = SeqFeature(FeatureLocation(10, 20), strand=+1) + f2 = SeqFeature(FeatureLocation(25, 40), strand=+1) + f = make_join_feature([f1, f2]) self.record.features.append(f) - self.assertEqual(_insdc_feature_location_string(f,500), + self.assertEqual(_insdc_feature_location_string(f, 500), "join(11..20,26..40)") - self.assertEqual(_insdc_feature_location_string(f._flip(60),60), + self.assertEqual(_insdc_feature_location_string(f._flip(60), 60), "complement(join(21..35,41..50))") - self.assertEqual(_insdc_feature_location_string(f._flip(100),100), + self.assertEqual(_insdc_feature_location_string(f._flip(100), 100), "complement(join(61..75,81..90))") for sub_f in f._flip(100)._sub_features : self.assertEqual(sub_f.strand, -1) self.assertEqual(f._flip(100).strand, -1) - f1 = SeqFeature(FeatureLocation(110,120), strand=+1) - f2 = SeqFeature(FeatureLocation(125,140), strand=+1) - f3 = SeqFeature(FeatureLocation(145,150), strand=+1) - f = make_join_feature([f1,f2,f3], "CDS") - self.assertEqual(_insdc_feature_location_string(f,500), + f1 = SeqFeature(FeatureLocation(110, 120), strand=+1) + f2 = SeqFeature(FeatureLocation(125, 140), strand=+1) + f3 = SeqFeature(FeatureLocation(145, 150), strand=+1) + f = make_join_feature([f1, f2, f3], "CDS") + self.assertEqual(_insdc_feature_location_string(f, 500), "join(111..120,126..140,146..150)") - self.assertEqual(_insdc_feature_location_string(f._flip(150),150), + self.assertEqual(_insdc_feature_location_string(f._flip(150), 150), "complement(join(1..5,11..25,31..40))") for sub_f in f._flip(100)._sub_features : - self.assertEqual(sub_f.strand,-1) + self.assertEqual(sub_f.strand, -1) self.assertEqual(f._flip(100).strand, -1) self.record.features.append(f) - f1 = SeqFeature(FeatureLocation(210,220), strand=-1) - f2 = SeqFeature(FeatureLocation(225,240), strand=-1) - f = make_join_feature([f1,f2], ftype="gene") - self.assertEqual(_insdc_feature_location_string(f,500), + f1 = SeqFeature(FeatureLocation(210, 220), strand=-1) + f2 = SeqFeature(FeatureLocation(225, 240), strand=-1) + f = make_join_feature([f1, f2], ftype="gene") + self.assertEqual(_insdc_feature_location_string(f, 500), "complement(join(211..220,226..240))") - self.assertEqual(_insdc_feature_location_string(f._flip(300),300), + self.assertEqual(_insdc_feature_location_string(f._flip(300), 300), "join(61..75,81..90)") for sub_f in f._flip(100)._sub_features : self.assertEqual(sub_f.strand, +1) self.assertEqual(f._flip(100).strand, +1) self.record.features.append(f) - f1 = SeqFeature(FeatureLocation(310,320), strand=-1) - f2 = SeqFeature(FeatureLocation(325,340), strand=-1) - f3 = SeqFeature(FeatureLocation(345,350), strand=-1) - f = make_join_feature([f1,f2,f3], "CDS") - self.assertEqual(_insdc_feature_location_string(f,500), + f1 = SeqFeature(FeatureLocation(310, 320), strand=-1) + f2 = SeqFeature(FeatureLocation(325, 340), strand=-1) + f3 = SeqFeature(FeatureLocation(345, 350), strand=-1) + f = make_join_feature([f1, f2, f3], "CDS") + self.assertEqual(_insdc_feature_location_string(f, 500), "complement(join(311..320,326..340,346..350))") - self.assertEqual(_insdc_feature_location_string(f._flip(350),350), + self.assertEqual(_insdc_feature_location_string(f._flip(350), 350), "join(1..5,11..25,31..40)") for sub_f in f._flip(100)._sub_features : self.assertEqual(sub_f.strand, +1) @@ -614,13 +616,13 @@ def test_fuzzy_join(self): """Features: write/read fuzzy join locations.""" s = "N"*500 - f1 = SeqFeature(FeatureLocation(BeforePosition(10),20), strand=+1) - f2 = SeqFeature(FeatureLocation(25,AfterPosition(40)), strand=+1) - f = make_join_feature([f1,f2]) + f1 = SeqFeature(FeatureLocation(BeforePosition(10), 20), strand=+1) + f2 = SeqFeature(FeatureLocation(25, AfterPosition(40)), strand=+1) + f = make_join_feature([f1, f2]) self.record.features.append(f) - self.assertEqual(_insdc_feature_location_string(f,500), + self.assertEqual(_insdc_feature_location_string(f, 500), "join(<11..20,26..>40)") - self.assertEqual(_insdc_feature_location_string(f._flip(100),100), + self.assertEqual(_insdc_feature_location_string(f._flip(100), 100), "complement(join(<61..75,81..>90))") self.assertEqual(f.strand, +1) for sub_loc in f.location.parts: @@ -636,13 +638,13 @@ ExactPosition(110)]), 120), strand=+1) - f2 = SeqFeature(FeatureLocation(125,140), strand=+1) - f3 = SeqFeature(FeatureLocation(145,WithinPosition(160, left=150, right=160)), strand=+1) - f = make_join_feature([f1,f2,f3], "CDS") - self.assertEqual(_insdc_feature_location_string(f,500), + f2 = SeqFeature(FeatureLocation(125, 140), strand=+1) + f3 = SeqFeature(FeatureLocation(145, WithinPosition(160, left=150, right=160)), strand=+1) + f = make_join_feature([f1, f2, f3], "CDS") + self.assertEqual(_insdc_feature_location_string(f, 500), "join(one-of(108,111)..120,126..140,146..(150.160))") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(200),200), + self.assertEqual(_insdc_feature_location_string(f._flip(200), 200), "complement(join((41.51)..55,61..75,81..one-of(90,93)))") self.assertEqual(f.strand, +1) for sub_loc in f.location.parts: @@ -655,13 +657,13 @@ self.assertEqual(sub_f.strand, -1) self.record.features.append(f) - f1 = SeqFeature(FeatureLocation(BeforePosition(210),220), strand=-1) - f2 = SeqFeature(FeatureLocation(225,WithinPosition(244, left=240, right=244)), strand=-1) - f = make_join_feature([f1,f2], "gene") - self.assertEqual(_insdc_feature_location_string(f,500), + f1 = SeqFeature(FeatureLocation(BeforePosition(210), 220), strand=-1) + f2 = SeqFeature(FeatureLocation(225, WithinPosition(244, left=240, right=244)), strand=-1) + f = make_join_feature([f1, f2], "gene") + self.assertEqual(_insdc_feature_location_string(f, 500), "complement(join(<211..220,226..(240.244)))") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(300),300), + self.assertEqual(_insdc_feature_location_string(f._flip(300), 300), "join((57.61)..75,81..>90)") self.assertEqual(f.strand, -1) for sub_loc in f.location.parts: @@ -674,17 +676,17 @@ self.assertEqual(sub_f.strand, +1) self.record.features.append(f) - f1 = SeqFeature(FeatureLocation(AfterPosition(310),320), strand=-1) + f1 = SeqFeature(FeatureLocation(AfterPosition(310), 320), strand=-1) #Note - is one-of(340,337) allowed or should it be one-of(337,340)? - f2 = SeqFeature(FeatureLocation(325,OneOfPosition(340, [ExactPosition(340), + f2 = SeqFeature(FeatureLocation(325, OneOfPosition(340, [ExactPosition(340), ExactPosition(337)])), strand=-1) - f3 = SeqFeature(FeatureLocation(345,WithinPosition(355, left=350, right=355)), strand=-1) - f = make_join_feature([f1,f2,f3], "CDS") - self.assertEqual(_insdc_feature_location_string(f,500), + f3 = SeqFeature(FeatureLocation(345, WithinPosition(355, left=350, right=355)), strand=-1) + f = make_join_feature([f1, f2, f3], "CDS") + self.assertEqual(_insdc_feature_location_string(f, 500), "complement(join(>311..320,326..one-of(340,337),346..(350.355)))") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(400),400), + self.assertEqual(_insdc_feature_location_string(f._flip(400), 400), "join((46.51)..55,one-of(64,61)..75,81..<90)") self.assertEqual(f.strand, -1) tmp = f._flip(100) @@ -700,67 +702,67 @@ def test_before(self): """Features: write/read simple before locations.""" s = "N"*200 - f = SeqFeature(FeatureLocation(BeforePosition(5),10), + f = SeqFeature(FeatureLocation(BeforePosition(5), 10), strand=+1, type="CDS") - self.assertEqual(_insdc_feature_location_string(f,100), + self.assertEqual(_insdc_feature_location_string(f, 100), "<6..10") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(20),20), + self.assertEqual(_insdc_feature_location_string(f._flip(20), 20), "complement(11..>15)") self.assertEqual(f.strand, +1) self.assertEqual(f._flip(100).strand, -1) self.record.features.append(f) - f = SeqFeature(FeatureLocation(BeforePosition(15),BeforePosition(20)), + f = SeqFeature(FeatureLocation(BeforePosition(15), BeforePosition(20)), strand=+1, type="CDS") - self.assertEqual(_insdc_feature_location_string(f,100), + self.assertEqual(_insdc_feature_location_string(f, 100), "<16..<20") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(20),20), + self.assertEqual(_insdc_feature_location_string(f._flip(20), 20), "complement(>1..>5)") self.assertEqual(f.strand, +1) self.assertEqual(f._flip(100).strand, -1) self.record.features.append(f) - f = SeqFeature(FeatureLocation(25,BeforePosition(30)), + f = SeqFeature(FeatureLocation(25, BeforePosition(30)), strand=+1, type="CDS") - self.assertEqual(_insdc_feature_location_string(f,100), + self.assertEqual(_insdc_feature_location_string(f, 100), "26..<30") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(40),40), + self.assertEqual(_insdc_feature_location_string(f._flip(40), 40), "complement(>11..15)") self.assertEqual(f.strand, +1) self.assertEqual(f._flip(100).strand, -1) self.record.features.append(f) - f = SeqFeature(FeatureLocation(BeforePosition(35),40), + f = SeqFeature(FeatureLocation(BeforePosition(35), 40), strand=-1, type="CDS") - self.assertEqual(_insdc_feature_location_string(f,100), + self.assertEqual(_insdc_feature_location_string(f, 100), "complement(<36..40)") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(40),40), + self.assertEqual(_insdc_feature_location_string(f._flip(40), 40), "1..>5") self.assertEqual(f.strand, -1) self.assertEqual(f._flip(100).strand, +1) self.record.features.append(f) - f = SeqFeature(FeatureLocation(BeforePosition(45),BeforePosition(50)), + f = SeqFeature(FeatureLocation(BeforePosition(45), BeforePosition(50)), strand=-1, type="CDS") - self.assertEqual(_insdc_feature_location_string(f,100), + self.assertEqual(_insdc_feature_location_string(f, 100), "complement(<46..<50)") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(100),100), + self.assertEqual(_insdc_feature_location_string(f._flip(100), 100), ">51..>55") self.assertEqual(f.strand, -1) self.assertEqual(f._flip(100).strand, +1) self.record.features.append(f) - f = SeqFeature(FeatureLocation(55,BeforePosition(60)), + f = SeqFeature(FeatureLocation(55, BeforePosition(60)), strand=-1, type="CDS") - self.assertEqual(_insdc_feature_location_string(f,100), + self.assertEqual(_insdc_feature_location_string(f, 100), "complement(56..<60)") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(100),100), + self.assertEqual(_insdc_feature_location_string(f._flip(100), 100), ">41..45") self.assertEqual(f.strand, -1) self.assertEqual(f._flip(100).strand, +1) @@ -771,67 +773,67 @@ def test_after(self): """Features: write/read simple after locations.""" s = "N" * 200 - f = SeqFeature(FeatureLocation(AfterPosition(5),10), + f = SeqFeature(FeatureLocation(AfterPosition(5), 10), strand=+1, type="CDS") - self.assertEqual(_insdc_feature_location_string(f,100), + self.assertEqual(_insdc_feature_location_string(f, 100), ">6..10") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(100),100), + self.assertEqual(_insdc_feature_location_string(f._flip(100), 100), "complement(91..<95)") self.assertEqual(f.strand, +1) self.assertEqual(f._flip(100).strand, -1) self.record.features.append(f) - f = SeqFeature(FeatureLocation(AfterPosition(15),AfterPosition(20)), + f = SeqFeature(FeatureLocation(AfterPosition(15), AfterPosition(20)), strand=+1, type="CDS") - self.assertEqual(_insdc_feature_location_string(f,100), + self.assertEqual(_insdc_feature_location_string(f, 100), ">16..>20") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(20),20), + self.assertEqual(_insdc_feature_location_string(f._flip(20), 20), "complement(<1..<5)") self.assertEqual(f.strand, +1) self.assertEqual(f._flip(100).strand, -1) self.record.features.append(f) - f = SeqFeature(FeatureLocation(25,AfterPosition(30)), + f = SeqFeature(FeatureLocation(25, AfterPosition(30)), strand=+1, type="CDS") - self.assertEqual(_insdc_feature_location_string(f,100), + self.assertEqual(_insdc_feature_location_string(f, 100), "26..>30") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(30),30), + self.assertEqual(_insdc_feature_location_string(f._flip(30), 30), "complement(<1..5)") self.assertEqual(f.strand, +1) self.assertEqual(f._flip(100).strand, -1) self.record.features.append(f) - f = SeqFeature(FeatureLocation(AfterPosition(35),40), + f = SeqFeature(FeatureLocation(AfterPosition(35), 40), strand=-1, type="CDS") - self.assertEqual(_insdc_feature_location_string(f,100), + self.assertEqual(_insdc_feature_location_string(f, 100), "complement(>36..40)") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(100),100), + self.assertEqual(_insdc_feature_location_string(f._flip(100), 100), "61..<65") self.assertEqual(f.strand, -1) self.assertEqual(f._flip(100).strand, +1) self.record.features.append(f) - f = SeqFeature(FeatureLocation(AfterPosition(45),AfterPosition(50)), + f = SeqFeature(FeatureLocation(AfterPosition(45), AfterPosition(50)), strand=-1, type="CDS") - self.assertEqual(_insdc_feature_location_string(f,100), + self.assertEqual(_insdc_feature_location_string(f, 100), "complement(>46..>50)") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(100),100), + self.assertEqual(_insdc_feature_location_string(f._flip(100), 100), "<51..<55") self.assertEqual(f.strand, -1) self.assertEqual(f._flip(100).strand, +1) self.record.features.append(f) - f = SeqFeature(FeatureLocation(55,AfterPosition(60)), + f = SeqFeature(FeatureLocation(55, AfterPosition(60)), strand=-1, type="CDS") - self.assertEqual(_insdc_feature_location_string(f,100), + self.assertEqual(_insdc_feature_location_string(f, 100), "complement(56..>60)") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(100),100), + self.assertEqual(_insdc_feature_location_string(f._flip(100), 100), "<41..45") self.assertEqual(f.strand, -1) self.assertEqual(f._flip(100).strand, +1) @@ -842,69 +844,69 @@ def test_oneof(self): """Features: write/read simple one-of locations.""" s = "N" * 100 - start = OneOfPosition(0, [ExactPosition(0),ExactPosition(3),ExactPosition(6)]) - f = SeqFeature(FeatureLocation(start,21), strand=+1, type="CDS") - self.assertEqual(_insdc_feature_location_string(f,100), + start = OneOfPosition(0, [ExactPosition(0), ExactPosition(3), ExactPosition(6)]) + f = SeqFeature(FeatureLocation(start, 21), strand=+1, type="CDS") + self.assertEqual(_insdc_feature_location_string(f, 100), "one-of(1,4,7)..21") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(100),100), + self.assertEqual(_insdc_feature_location_string(f._flip(100), 100), "complement(80..one-of(94,97,100))") self.assertEqual(f.strand, +1) self.assertEqual(f._flip(100).strand, -1) self.record.features.append(f) - start = OneOfPosition(10, [ExactPosition(x) for x in [10,13,16]]) - end = OneOfPosition(50, [ExactPosition(x) for x in [41,44,50]]) - f = SeqFeature(FeatureLocation(start,end), strand=+1, type="gene") - self.assertEqual(_insdc_feature_location_string(f,100), + start = OneOfPosition(10, [ExactPosition(x) for x in [10, 13, 16]]) + end = OneOfPosition(50, [ExactPosition(x) for x in [41, 44, 50]]) + f = SeqFeature(FeatureLocation(start, end), strand=+1, type="gene") + self.assertEqual(_insdc_feature_location_string(f, 100), "one-of(11,14,17)..one-of(41,44,50)") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(50),50), + self.assertEqual(_insdc_feature_location_string(f._flip(50), 50), "complement(one-of(1,7,10)..one-of(34,37,40))") self.assertEqual(f.strand, +1) self.assertEqual(f._flip(100).strand, -1) self.record.features.append(f) - end = OneOfPosition(33, [ExactPosition(x) for x in [30,33]]) - f = SeqFeature(FeatureLocation(27,end), strand=+1, type="gene") - self.assertEqual(_insdc_feature_location_string(f,100), + end = OneOfPosition(33, [ExactPosition(x) for x in [30, 33]]) + f = SeqFeature(FeatureLocation(27, end), strand=+1, type="gene") + self.assertEqual(_insdc_feature_location_string(f, 100), "28..one-of(30,33)") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(40),40), + self.assertEqual(_insdc_feature_location_string(f._flip(40), 40), "complement(one-of(8,11)..13)") self.assertEqual(f.strand, +1) self.assertEqual(f._flip(100).strand, -1) self.record.features.append(f) - start = OneOfPosition(36, [ExactPosition(x) for x in [36,40]]) - f = SeqFeature(FeatureLocation(start,46), strand=-1, type="CDS") - self.assertEqual(_insdc_feature_location_string(f,100), + start = OneOfPosition(36, [ExactPosition(x) for x in [36, 40]]) + f = SeqFeature(FeatureLocation(start, 46), strand=-1, type="CDS") + self.assertEqual(_insdc_feature_location_string(f, 100), "complement(one-of(37,41)..46)") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(50),50), + self.assertEqual(_insdc_feature_location_string(f._flip(50), 50), "5..one-of(10,14)") self.assertEqual(f.strand, -1) self.assertEqual(f._flip(100).strand, +1) self.record.features.append(f) - start = OneOfPosition(45, [ExactPosition(x) for x in [45,60]]) - end = OneOfPosition(90, [ExactPosition(x) for x in [70,90]]) - f = SeqFeature(FeatureLocation(start,end), strand=-1, type="CDS") - self.assertEqual(_insdc_feature_location_string(f,100), + start = OneOfPosition(45, [ExactPosition(x) for x in [45, 60]]) + end = OneOfPosition(90, [ExactPosition(x) for x in [70, 90]]) + f = SeqFeature(FeatureLocation(start, end), strand=-1, type="CDS") + self.assertEqual(_insdc_feature_location_string(f, 100), "complement(one-of(46,61)..one-of(70,90))") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(100),100), + self.assertEqual(_insdc_feature_location_string(f._flip(100), 100), "one-of(11,31)..one-of(40,55)") self.assertEqual(f.strand, -1) self.assertEqual(f._flip(100).strand, +1) self.record.features.append(f) - end = OneOfPosition(63, [ExactPosition(x) for x in [60,63]]) - f = SeqFeature(FeatureLocation(55,end), strand=-1, type="tRNA") - self.assertEqual(_insdc_feature_location_string(f,100), + end = OneOfPosition(63, [ExactPosition(x) for x in [60, 63]]) + f = SeqFeature(FeatureLocation(55, end), strand=-1, type="tRNA") + self.assertEqual(_insdc_feature_location_string(f, 100), "complement(56..one-of(60,63))") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(100),100), + self.assertEqual(_insdc_feature_location_string(f._flip(100), 100), "one-of(38,41)..45") self.assertEqual(f.strand, -1) self.assertEqual(f._flip(100).strand, +1) @@ -915,12 +917,12 @@ def test_within(self): """Features: write/read simple within locations.""" s = "N" * 100 - f = SeqFeature(FeatureLocation(WithinPosition(2, left=2, right=8),10), + f = SeqFeature(FeatureLocation(WithinPosition(2, left=2, right=8), 10), strand=+1, type="CDS") - self.assertEqual(_insdc_feature_location_string(f,100), + self.assertEqual(_insdc_feature_location_string(f, 100), "(3.9)..10") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(20),20), + self.assertEqual(_insdc_feature_location_string(f._flip(20), 20), "complement(11..(12.18))") self.assertEqual(f.strand, +1) self.assertEqual(f._flip(100).strand, -1) @@ -929,31 +931,31 @@ f = SeqFeature(FeatureLocation(WithinPosition(12, left=12, right=18), WithinPosition(28, left=20, right=28)), strand=+1, type="CDS") - self.assertEqual(_insdc_feature_location_string(f,100), + self.assertEqual(_insdc_feature_location_string(f, 100), "(13.19)..(20.28)") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(30),30), + self.assertEqual(_insdc_feature_location_string(f._flip(30), 30), "complement((3.11)..(12.18))") self.assertEqual(f.strand, +1) self.assertEqual(f._flip(100).strand, -1) self.record.features.append(f) - f = SeqFeature(FeatureLocation(25,WithinPosition(33, left=30, right=33)), + f = SeqFeature(FeatureLocation(25, WithinPosition(33, left=30, right=33)), strand=+1, type="misc_feature") - self.assertEqual(_insdc_feature_location_string(f,100), + self.assertEqual(_insdc_feature_location_string(f, 100), "26..(30.33)") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(40),40), + self.assertEqual(_insdc_feature_location_string(f._flip(40), 40), "complement((8.11)..15)") self.assertEqual(f.strand, +1) self.assertEqual(f._flip(100).strand, -1) self.record.features.append(f) - f = SeqFeature(FeatureLocation(WithinPosition(35, left=35, right=39),40), + f = SeqFeature(FeatureLocation(WithinPosition(35, left=35, right=39), 40), strand=-1, type="rRNA") - self.assertEqual(_insdc_feature_location_string(f,100), + self.assertEqual(_insdc_feature_location_string(f, 100), "complement((36.40)..40)") - self.assertEqual(_insdc_feature_location_string(f._flip(40),40), + self.assertEqual(_insdc_feature_location_string(f._flip(40), 40), "1..(1.5)") self.assertEqual(f.strand, -1) self.assertEqual(f._flip(100).strand, +1) @@ -962,21 +964,21 @@ f = SeqFeature(FeatureLocation(WithinPosition(45, left=45, right=47), WithinPosition(53, left=50, right=53)), strand=-1, type="repeat_region") - self.assertEqual(_insdc_feature_location_string(f,100), + self.assertEqual(_insdc_feature_location_string(f, 100), "complement((46.48)..(50.53))") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(60),60), + self.assertEqual(_insdc_feature_location_string(f._flip(60), 60), "(8.11)..(13.15)") self.assertEqual(f.strand, -1) self.assertEqual(f._flip(100).strand, +1) self.record.features.append(f) - f = SeqFeature(FeatureLocation(55,WithinPosition(65, left=60, right=65)), + f = SeqFeature(FeatureLocation(55, WithinPosition(65, left=60, right=65)), strand=-1, type="CDS") - self.assertEqual(_insdc_feature_location_string(f,100), + self.assertEqual(_insdc_feature_location_string(f, 100), "complement(56..(60.65))") self.assertEqual(len(f), len(f.extract(s))) - self.assertEqual(_insdc_feature_location_string(f._flip(100),100), + self.assertEqual(_insdc_feature_location_string(f._flip(100), 100), "(36.41)..45") self.assertEqual(f.strand, -1) self.assertEqual(f._flip(100).strand, +1) @@ -998,12 +1000,12 @@ #TODO - neat way to change the docstrings... def setUp(self): - self.gb_filename = os.path.join("GenBank",self.basename+".gb") - self.ffn_filename = os.path.join("GenBank",self.basename+".ffn") - self.faa_filename = os.path.join("GenBank",self.basename+".faa") - self.fna_filename = os.path.join("GenBank",self.basename+".fna") + self.gb_filename = os.path.join("GenBank", self.basename+".gb") + self.ffn_filename = os.path.join("GenBank", self.basename+".ffn") + self.faa_filename = os.path.join("GenBank", self.basename+".faa") + self.fna_filename = os.path.join("GenBank", self.basename+".fna") if self.emblname: - self.embl_filename = os.path.join("EMBL",self.emblname+".embl") + self.embl_filename = os.path.join("EMBL", self.emblname+".embl") #These tests only need the GenBank file and the FAA file: def test_CDS(self): @@ -1022,10 +1024,10 @@ self.assertEqual(len(nuc), len(f)) try: pro = nuc.translate(table=self.table, cds=True) - except TranslationError, e: - print e - print r.id, nuc, self.table - print f + except TranslationError as e: + print(e) + print("%r, %r, %r" % ( r.id, nuc, self.table)) + print(f) raise if pro[-1] == "*": self.assertEqual(str(pro)[:-1], str(r.seq)) @@ -1058,7 +1060,7 @@ #"""Checking translation of FASTA features (faa vs ffn).""" faa_records = list(SeqIO.parse(self.faa_filename, "fasta")) ffn_records = list(SeqIO.parse(self.ffn_filename, "fasta")) - self.assertEqual(len(faa_records),len(ffn_records)) + self.assertEqual(len(faa_records), len(ffn_records)) for faa, fna in zip(faa_records, ffn_records): translation = fna.seq.translate(self.table, cds=True) if faa.id in self.skip_trans_test: diff -Nru python-biopython-1.62/Tests/test_SeqIO_index.py python-biopython-1.63/Tests/test_SeqIO_index.py --- python-biopython-1.62/Tests/test_SeqIO_index.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_SeqIO_index.py 2013-12-05 14:10:43.000000000 +0000 @@ -17,14 +17,10 @@ import unittest import tempfile import gzip -from StringIO import StringIO -try: - #This is in Python 2.6+, but we need it on Python 3 - from io import BytesIO -except ImportError: - BytesIO = StringIO -from Bio._py3k import _as_bytes, _bytes_to_string +import warnings +from io import BytesIO +from Bio._py3k import _as_bytes, _bytes_to_string, StringIO from Bio.SeqRecord import SeqRecord from Bio import SeqIO @@ -33,6 +29,7 @@ from seq_tests_common import compare_record +from Bio import BiopythonParserWarning from Bio import MissingPythonDependencyError try: from test_bgzf import _have_bug17666 @@ -238,7 +235,7 @@ self.assertEqual(len(keys), len(rec_dict)) #Make sure boolean evaluation works self.assertEqual(bool(keys), bool(rec_dict)) - for key,id in zip(keys, ids): + for key, id in zip(keys, ids): self.assertTrue(key in rec_dict) self.assertEqual(id, rec_dict[key].id) self.assertEqual(id, rec_dict.get(key).id) @@ -253,21 +250,18 @@ self.assertEqual(rec_dict.get(chr(0), chr(1)), chr(1)) if hasattr(dict, "iteritems"): #Python 2.x - for key, rec in rec_dict.iteritems(): + for key, rec in rec_dict.items(): self.assertTrue(key in keys) self.assertTrue(isinstance(rec, SeqRecord)) self.assertTrue(rec.id in ids) - #Now check non-defined methods... - self.assertRaises(NotImplementedError, rec_dict.items) - self.assertRaises(NotImplementedError, rec_dict.values) else: #Python 3 assert not hasattr(rec_dict, "iteritems") - for key, rec in rec_dict.iteritems(): + for key, rec in rec_dict.items(): self.assertTrue(key in keys) self.assertTrue(isinstance(rec, SeqRecord)) self.assertTrue(rec.id in ids) - for rec in rec_dict.itervalues(): + for rec in rec_dict.values(): self.assertTrue(key in keys) self.assertTrue(isinstance(rec, SeqRecord)) self.assertTrue(rec.id in ids) @@ -296,8 +290,16 @@ h.close() id_list = [rec.id.lower() for rec in SeqIO.parse(filename, format, alphabet)] - rec_dict = SeqIO.index(filename, format, alphabet, - key_function = lambda x : x.lower()) + + if format in ["sff"]: + with warnings.catch_warnings(): + warnings.simplefilter('ignore', BiopythonParserWarning) + rec_dict = SeqIO.index(filename, format, alphabet, + key_function = lambda x : x.lower()) + else: + rec_dict = SeqIO.index(filename, format, alphabet, + key_function = lambda x : x.lower()) + self.assertEqual(set(id_list), set(rec_dict.keys())) self.assertEqual(len(id_list), len(rec_dict)) for key in id_list: @@ -371,8 +373,9 @@ ("Ace/consed_sample.ace", "ace", None), ("Ace/seq.cap.ace", "ace", generic_dna), ("Quality/wrapping_original_sanger.fastq", "fastq", None), - ("Quality/example.fastq", "fastq", None), + ("Quality/example.fastq", "fastq", None), #Unix newlines ("Quality/example.fastq", "fastq-sanger", generic_dna), + ("Quality/example_dos.fastq", "fastq", None), #DOS/Windows newlines ("Quality/tricky.fastq", "fastq", generic_nucleotide), ("Quality/sanger_faked.fastq", "fastq-sanger", generic_dna), ("Quality/solexa_faked.fastq", "fastq-solexa", generic_dna), @@ -422,33 +425,33 @@ assert format in _FormatToRandomAccess tasks = [(filename, None)] if do_bgzf and os.path.isfile(filename + ".bgz"): - tasks.append((filename + ".bgz","bgzf")) + tasks.append((filename + ".bgz", "bgzf")) for filename, comp in tasks: - def funct(fn,fmt,alpha,c): + def funct(fn, fmt, alpha, c): f = lambda x : x.simple_check(fn, fmt, alpha, c) f.__doc__ = "Index %s file %s defaults" % (fmt, fn) return f setattr(IndexDictTests, "test_%s_%s_simple" - % (format, filename.replace("/","_").replace(".","_")), + % (format, filename.replace("/", "_").replace(".", "_")), funct(filename, format, alphabet, comp)) del funct - def funct(fn,fmt,alpha,c): + def funct(fn, fmt, alpha, c): f = lambda x : x.key_check(fn, fmt, alpha, c) f.__doc__ = "Index %s file %s with key function" % (fmt, fn) return f setattr(IndexDictTests, "test_%s_%s_keyf" - % (format, filename.replace("/","_").replace(".","_")), + % (format, filename.replace("/", "_").replace(".", "_")), funct(filename, format, alphabet, comp)) del funct - def funct(fn,fmt,alpha,c): + def funct(fn, fmt, alpha, c): f = lambda x : x.get_raw_check(fn, fmt, alpha, c) f.__doc__ = "Index %s file %s get_raw" % (fmt, fn) return f setattr(IndexDictTests, "test_%s_%s_get_raw" - % (format, filename.replace("/","_").replace(".","_")), + % (format, filename.replace("/", "_").replace(".", "_")), funct(filename, format, alphabet, comp)) del funct diff -Nru python-biopython-1.62/Tests/test_SeqIO_online.py python-biopython-1.63/Tests/test_SeqIO_online.py --- python-biopython-1.62/Tests/test_SeqIO_online.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_SeqIO_online.py 2013-12-05 14:10:43.000000000 +0000 @@ -24,7 +24,7 @@ #In order to check any sequences returned from Bio import SeqIO -from StringIO import StringIO +from Bio._py3k import StringIO from Bio.SeqUtils.CheckSum import seguid from Bio.File import UndoHandle diff -Nru python-biopython-1.62/Tests/test_SeqIO_write.py python-biopython-1.63/Tests/test_SeqIO_write.py --- python-biopython-1.62/Tests/test_SeqIO_write.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_SeqIO_write.py 2013-12-05 14:10:43.000000000 +0000 @@ -5,25 +5,20 @@ import os import unittest +from io import BytesIO +from Bio._py3k import StringIO from Bio import SeqIO from Bio import AlignIO from Bio.SeqRecord import SeqRecord from Bio.Seq import Seq, UnknownSeq -from StringIO import StringIO from Bio import Alphabet from Bio.Align import MultipleSeqAlignment -try: - #This is in Python 2.6+, but we need it on Python 3 - from io import BytesIO -except ImportError: - BytesIO = StringIO - #List of formats including alignment only file formats we can read AND write. #We don't care about the order -test_write_read_alignment_formats = sorted(SeqIO._FormatToWriter.keys()) +test_write_read_alignment_formats = sorted(SeqIO._FormatToWriter) for format in sorted(AlignIO._FormatToWriter): if format not in test_write_read_alignment_formats: test_write_read_alignment_formats.append(format) @@ -37,32 +32,32 @@ # list of formats, exception type, exception message). test_records = [ ([], "zero records", {}), - ([SeqRecord(Seq("CHSMAIKLSSEHNIPSGIANAL",Alphabet.generic_protein), id="Alpha"), - SeqRecord(Seq("HNGFTALEGEIHHLTHGEKVAF",Alphabet.generic_protein), id="Gamma"), - SeqRecord(Seq("DITHGVG",Alphabet.generic_protein), id="delta")], + ([SeqRecord(Seq("CHSMAIKLSSEHNIPSGIANAL", Alphabet.generic_protein), id="Alpha"), + SeqRecord(Seq("HNGFTALEGEIHHLTHGEKVAF", Alphabet.generic_protein), id="Gamma"), + SeqRecord(Seq("DITHGVG", Alphabet.generic_protein), id="delta")], "three peptides of different lengths", []), - ([SeqRecord(Seq("CHSMAIKLSSEHNIPSGIANAL",Alphabet.generic_protein), id="Alpha"), - SeqRecord(Seq("VHGMAHPLGAFYNTPHGVANAI",Alphabet.generic_protein), id="Beta"), - SeqRecord(Seq("HNGFTALEGEIHHLTHGEKVAF",Alphabet.generic_protein), id="Gamma")], + ([SeqRecord(Seq("CHSMAIKLSSEHNIPSGIANAL", Alphabet.generic_protein), id="Alpha"), + SeqRecord(Seq("VHGMAHPLGAFYNTPHGVANAI", Alphabet.generic_protein), id="Beta"), + SeqRecord(Seq("HNGFTALEGEIHHLTHGEKVAF", Alphabet.generic_protein), id="Gamma")], "three proteins alignment", []), - ([SeqRecord(Seq("AATAAACCTTGCTGGCCATTGTGATCCATCCA",Alphabet.generic_dna), id="X"), - SeqRecord(Seq("ACTCAACCTTGCTGGTCATTGTGACCCCAGCA",Alphabet.generic_dna), id="Y"), - SeqRecord(Seq("TTTCCTCGGAGGCCAATCTGGATCAAGACCAT",Alphabet.generic_dna), id="Z")], + ([SeqRecord(Seq("AATAAACCTTGCTGGCCATTGTGATCCATCCA", Alphabet.generic_dna), id="X"), + SeqRecord(Seq("ACTCAACCTTGCTGGTCATTGTGACCCCAGCA", Alphabet.generic_dna), id="Y"), + SeqRecord(Seq("TTTCCTCGGAGGCCAATCTGGATCAAGACCAT", Alphabet.generic_dna), id="Z")], "three DNA sequence alignment", []), - ([SeqRecord(Seq("AATAAACCTTGCTGGCCATTGTGATCCATCCA",Alphabet.generic_dna), id="X", + ([SeqRecord(Seq("AATAAACCTTGCTGGCCATTGTGATCCATCCA", Alphabet.generic_dna), id="X", name="The\nMystery\rSequece:\r\nX"), - SeqRecord(Seq("ACTCAACCTTGCTGGTCATTGTGACCCCAGCA",Alphabet.generic_dna), id="Y", + SeqRecord(Seq("ACTCAACCTTGCTGGTCATTGTGACCCCAGCA", Alphabet.generic_dna), id="Y", description="an%sevil\rdescription right\nhere" % os.linesep), - SeqRecord(Seq("TTTCCTCGGAGGCCAATCTGGATCAAGACCAT",Alphabet.generic_dna), id="Z")], + SeqRecord(Seq("TTTCCTCGGAGGCCAATCTGGATCAAGACCAT", Alphabet.generic_dna), id="Z")], "3 DNA seq alignment with CR/LF in name/descr", [(["genbank"], ValueError, r"Locus identifier 'The\nMystery\rSequece:\r\nX' is too long")]), - ([SeqRecord(Seq("CHSMAIKLSSEHNIPSGIANAL",Alphabet.generic_protein), id="Alpha"), - SeqRecord(Seq("VHGMAHPLGAFYNTPHGVANAI",Alphabet.generic_protein), id="Beta"), - SeqRecord(Seq("VHGMAHPLGAFYNTPHGVANAI",Alphabet.generic_protein), id="Beta"), - SeqRecord(Seq("HNGFTALEGEIHHLTHGEKVAF",Alphabet.generic_protein), id="Gamma")], + ([SeqRecord(Seq("CHSMAIKLSSEHNIPSGIANAL", Alphabet.generic_protein), id="Alpha"), + SeqRecord(Seq("VHGMAHPLGAFYNTPHGVANAI", Alphabet.generic_protein), id="Beta"), + SeqRecord(Seq("VHGMAHPLGAFYNTPHGVANAI", Alphabet.generic_protein), id="Beta"), + SeqRecord(Seq("HNGFTALEGEIHHLTHGEKVAF", Alphabet.generic_protein), id="Gamma")], "alignment with repeated record", - [(["stockholm"],ValueError,"Duplicate record identifier: Beta"), - (["phylip","phylip-relaxed","phylip-sequential"],ValueError,"Repeated name 'Beta' (originally 'Beta'), possibly due to truncation")]), + [(["stockholm"], ValueError, "Duplicate record identifier: Beta"), + (["phylip", "phylip-relaxed", "phylip-sequential"], ValueError, "Repeated name 'Beta' (originally 'Beta'), possibly due to truncation")]), ] # Meddle with the annotation too: assert test_records[4][1] == "3 DNA seq alignment with CR/LF in name/descr" @@ -135,7 +130,7 @@ if err_msg: try: SeqIO.write(records, handle, format) - except err_type, err: + except err_type as err: self.assertEqual(str(err), err_msg) else: self.assertRaises(err_type, SeqIO.write, records, handle, format) @@ -149,7 +144,7 @@ f.__doc__ = "%s for %s" % (format, descr) return f setattr(WriterTests, - "test_%s_%s" % (format, descr.replace(" ","_")), + "test_%s_%s" % (format, descr.replace(" ", "_")), funct(records, format, descr)) #Replace the method with an error specific one? for err_formats, err_type, err_msg in errs: @@ -160,7 +155,7 @@ f.__doc__ = "%s for %s" % (format, descr) return f setattr(WriterTests, - "test_%s_%s" % (format, descr.replace(" ","_")), + "test_%s_%s" % (format, descr.replace(" ", "_")), funct_e(records, format, descr, err_type, err_msg)) break del funct diff -Nru python-biopython-1.62/Tests/test_SeqRecord.py python-biopython-1.63/Tests/test_SeqRecord.py --- python-biopython-1.62/Tests/test_SeqRecord.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_SeqRecord.py 2013-12-05 14:10:43.000000000 +0000 @@ -42,7 +42,7 @@ try: rec.letter_annotations["bad"] = "abc" self.assertTrue(False, "Adding a bad letter_annotation should fail!") - except (TypeError, ValueError), e: + except (TypeError, ValueError) as e: pass #Now try setting it afterwards to a bad value... rec = SeqRecord(Seq("ACGT", generic_dna), @@ -50,7 +50,7 @@ try: rec.letter_annotations={"test" : [1, 2, 3]} self.assertTrue(False, "Changing to bad letter_annotations should fail!") - except (TypeError, ValueError), e: + except (TypeError, ValueError) as e: pass #Now try setting it at creation time to a bad value... try: @@ -58,7 +58,7 @@ id="Test", name="Test", description="Test", letter_annotations={"test" : [1, 2, 3]}) self.assertTrue(False, "Wrong length letter_annotations should fail!") - except (TypeError, ValueError), e: + except (TypeError, ValueError) as e: pass @@ -66,22 +66,22 @@ """Test SeqRecord methods.""" def setUp(self) : - f0 = SeqFeature(FeatureLocation(0,26), type="source", + f0 = SeqFeature(FeatureLocation(0, 26), type="source", qualifiers={"mol_type":["fake protein"]}) - f1 = SeqFeature(FeatureLocation(0,ExactPosition(10))) - f2 = SeqFeature(FeatureLocation(WithinPosition(12, left=12,right=15),BeforePosition(22))) + f1 = SeqFeature(FeatureLocation(0, ExactPosition(10))) + f2 = SeqFeature(FeatureLocation(WithinPosition(12, left=12, right=15), BeforePosition(22))) f3 = SeqFeature(FeatureLocation(AfterPosition(16), - OneOfPosition(26, [ExactPosition(25),AfterPosition(26)]))) + OneOfPosition(26, [ExactPosition(25), AfterPosition(26)]))) self.record = SeqRecord(Seq("ABCDEFGHIJKLMNOPQRSTUVWZYX", generic_protein), id="TestID", name="TestName", description="TestDescr", dbxrefs=["TestXRef"], annotations={"k":"v"}, letter_annotations = {"fake":"X"*26}, - features = [f0,f1,f2,f3]) + features = [f0, f1, f2, f3]) def test_slice_variantes(self): """Simple slices using different start/end values""" - for start in range(-30,30)+[None] : - for end in range(-30,30)+[None] : + for start in list(range(-30, 30)) + [None] : + for end in list(range(-30, 30)) + [None] : if start is None and end is None: continue rec = self.record[start:end] @@ -163,7 +163,7 @@ self.assertEqual(rec.description, "") self.assertEqual(rec.dbxrefs, ["TestXRef", "dummy"]) self.assertEqual(len(rec.annotations), 0) - self.assertEqual(len(rec.letter_annotations),0) + self.assertEqual(len(rec.letter_annotations), 0) self.assertEqual(len(rec.features), len(self.record.features) + len(other.features)) self.assertEqual(rec.features[0].type, "source") diff -Nru python-biopython-1.62/Tests/test_SeqUtils.py python-biopython-1.63/Tests/test_SeqUtils.py --- python-biopython-1.62/Tests/test_SeqUtils.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_SeqUtils.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,8 +3,6 @@ # license. Please see the LICENSE file that should have been included # as part of this package. -from __future__ import with_statement - import os import unittest @@ -31,7 +29,7 @@ def windowed_LCC(s): - return ", ".join(["%0.2f" % v for v in lcc_mult(s, 20)]) + return ", ".join("%0.2f" % v for v in lcc_mult(s, 20)) class SeqUtilsTests(unittest.TestCase): diff -Nru python-biopython-1.62/Tests/test_Seq_objs.py python-biopython-1.63/Tests/test_Seq_objs.py --- python-biopython-1.62/Tests/test_Seq_objs.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_Seq_objs.py 2013-12-05 14:10:43.000000000 +0000 @@ -4,6 +4,8 @@ # as part of this package. """Unittests for the Seq objects.""" +from __future__ import print_function + import unittest import sys if sys.version_info[0] == 3: @@ -109,8 +111,8 @@ continue str2 = str(example2) - i = getattr(example1,method_name)(str2) - j = getattr(str1,method_name)(str2) + i = getattr(example1, method_name)(str2) + j = getattr(str1, method_name)(str2) if pre_comp_function: i = pre_comp_function(i) j = pre_comp_function(j) @@ -123,8 +125,8 @@ j)) try: - i = getattr(example1,method_name)(example2) - j = getattr(str1,method_name)(str2) + i = getattr(example1, method_name)(example2) + j = getattr(str1, method_name)(str2) if pre_comp_function: i = pre_comp_function(i) j = pre_comp_function(j) @@ -141,8 +143,8 @@ if start_end: for start in self._start_end_values: - i = getattr(example1,method_name)(str2, start) - j = getattr(str1,method_name)(str2, start) + i = getattr(example1, method_name)(str2, start) + j = getattr(str1, method_name)(str2, start) if pre_comp_function: i = pre_comp_function(i) j = pre_comp_function(j) @@ -156,8 +158,8 @@ j)) for end in self._start_end_values: - i = getattr(example1,method_name)(str2, start, end) - j = getattr(str1,method_name)(str2, start, end) + i = getattr(example1, method_name)(str2, start, end) + j = getattr(str1, method_name)(str2, start, end) if pre_comp_function: i = pre_comp_function(i) j = pre_comp_function(j) @@ -186,12 +188,7 @@ def test_str_startswith(self): """Check matches the python string startswith method.""" self._test_method("startswith", start_end=True) - - try: - self.assertTrue("ABCDE".startswith(("ABE","OBE","ABC"))) - except TypeError: - #Base string only supports this on Python 2.5+, skip this - return + self.assertTrue("ABCDE".startswith(("ABE", "OBE", "ABC"))) #Now check with a tuple of sub sequences for example1 in self._examples: @@ -199,27 +196,22 @@ #e.g. MutableSeq does not support this continue subs = tuple([example1[start:start+2] for start - in range(0, len(example1)-2,3)]) + in range(0, len(example1)-2, 3)]) subs_str = tuple([str(s) for s in subs]) self.assertEqual(str(example1).startswith(subs_str), example1.startswith(subs)) self.assertEqual(str(example1).startswith(subs_str), example1.startswith(subs_str)) # strings! - self.assertEqual(str(example1).startswith(subs_str,3), - example1.startswith(subs,3)) - self.assertEqual(str(example1).startswith(subs_str,2,6), - example1.startswith(subs,2,6)) + self.assertEqual(str(example1).startswith(subs_str, 3), + example1.startswith(subs, 3)) + self.assertEqual(str(example1).startswith(subs_str, 2, 6), + example1.startswith(subs, 2, 6)) def test_str_endswith(self): """Check matches the python string endswith method.""" self._test_method("endswith", start_end=True) - - try: - self.assertTrue("ABCDE".endswith(("ABE","OBE","CDE"))) - except TypeError: - #Base string only supports this on Python 2.5+, skip this - return + self.assertTrue("ABCDE".endswith(("ABE", "OBE", "CDE"))) #Now check with a tuple of sub sequences for example1 in self._examples: @@ -227,17 +219,17 @@ #e.g. MutableSeq does not support this continue subs = tuple([example1[start:start+2] for start - in range(0, len(example1)-2,3)]) + in range(0, len(example1)-2, 3)]) subs_str = tuple([str(s) for s in subs]) self.assertEqual(str(example1).endswith(subs_str), example1.endswith(subs)) self.assertEqual(str(example1).startswith(subs_str), example1.startswith(subs_str)) # strings! - self.assertEqual(str(example1).endswith(subs_str,3), - example1.endswith(subs,3)) - self.assertEqual(str(example1).endswith(subs_str,2,6), - example1.endswith(subs,2,6)) + self.assertEqual(str(example1).endswith(subs_str, 3), + example1.endswith(subs, 3)) + self.assertEqual(str(example1).endswith(subs_str, 2, 6), + example1.endswith(subs, 2, 6)) def test_str_strip(self): """Check matches the python string strip method.""" @@ -251,19 +243,22 @@ """Check matches the python string rstrip method.""" #Calling (r)split should return a list of Seq-like objects, we'll #just apply str() to each of them so it matches the string method - self._test_method("rstrip", pre_comp_function=lambda x : map(str,x)) + self._test_method("rstrip", + pre_comp_function=lambda x: [str(y) for y in x]) def test_str_rsplit(self): """Check matches the python string rstrip method.""" #Calling (r)split should return a list of Seq-like objects, we'll #just apply str() to each of them so it matches the string method - self._test_method("rstrip", pre_comp_function=lambda x : map(str,x)) + self._test_method("rstrip", + pre_comp_function=lambda x: [str(y) for y in x]) def test_str_lsplit(self): """Check matches the python string rstrip method.""" #Calling (r)split should return a list of Seq-like objects, we'll #just apply str() to each of them so it matches the string method - self._test_method("rstrip", pre_comp_function=lambda x : map(str,x)) + self._test_method("rstrip", + pre_comp_function=lambda x: [str(y) for y in x]) def test_str_length(self): """Check matches the python string __len__ method.""" @@ -298,10 +293,10 @@ self.assertEqual(str(example1[i:]), str1[i:]) for j in self._start_end_values: self.assertEqual(str(example1[i:j]), str1[i:j]) - for step in range(-3,4): + for step in range(-3, 4): if step == 0: try: - print example1[i:j:step] + print(example1[i:j:step]) self._assert(False) # Should fail! except ValueError: pass @@ -345,20 +340,20 @@ continue try : comp = example1.complement() - except ValueError, e: + except ValueError as e: self.assertEqual(str(e), "Proteins do not have complements!") continue str1 = str(example1) #This only does the unambiguous cases if "U" in str1 or "u" in str1 \ or example1.alphabet==generic_rna: - mapping = maketrans("ACGUacgu","UGCAugca") + mapping = maketrans("ACGUacgu", "UGCAugca") elif "T" in str1 or "t" in str1 \ or example1.alphabet==generic_dna \ or example1.alphabet==generic_nucleotide: - mapping = maketrans("ACGTacgt","TGCAtgca") + mapping = maketrans("ACGTacgt", "TGCAtgca") elif "A" not in str1 and "a" not in str1: - mapping = maketrans("CGcg","GCgc") + mapping = maketrans("CGcg", "GCgc") else : #TODO - look at alphabet? raise ValueError(example1) @@ -373,20 +368,20 @@ continue try : comp = example1.reverse_complement() - except ValueError, e: + except ValueError as e: self.assertEqual(str(e), "Proteins do not have complements!") continue str1 = str(example1) #This only does the unambiguous cases if "U" in str1 or "u" in str1 \ or example1.alphabet==generic_rna: - mapping = maketrans("ACGUacgu","UGCAugca") + mapping = maketrans("ACGUacgu", "UGCAugca") elif "T" in str1 or "t" in str1 \ or example1.alphabet==generic_dna \ or example1.alphabet==generic_nucleotide: - mapping = maketrans("ACGTacgt","TGCAtgca") + mapping = maketrans("ACGTacgt", "TGCAtgca") elif "A" not in str1 and "a" not in str1: - mapping = maketrans("CGcg","GCgc") + mapping = maketrans("CGcg", "GCgc") else : #TODO - look at alphabet? continue @@ -401,7 +396,7 @@ continue try : tran = example1.transcribe() - except ValueError, e: + except ValueError as e: if str(e) == "Proteins cannot be transcribed!": continue if str(e) == "RNA cannot be transcribed!": @@ -411,7 +406,7 @@ if len(str1) % 3 != 0: #TODO - Check for or silence the expected warning? continue - self.assertEqual(str1.replace("T","U").replace("t","u"), str(tran)) + self.assertEqual(str1.replace("T", "U").replace("t", "u"), str(tran)) self.assertEqual(tran.alphabet, generic_rna) # based on limited examples def test_the_back_transcription(self): @@ -422,14 +417,14 @@ continue try : tran = example1.back_transcribe() - except ValueError, e: + except ValueError as e: if str(e) == "Proteins cannot be back transcribed!": continue if str(e) == "DNA cannot be back transcribed!": continue raise e str1 = str(example1) - self.assertEqual(str1.replace("U","T").replace("u","t"), str(tran)) + self.assertEqual(str1.replace("U", "T").replace("u", "t"), str(tran)) self.assertEqual(tran.alphabet, generic_dna) # based on limited examples def test_the_translate(self): @@ -443,13 +438,13 @@ continue try : tran = example1.translate() - except ValueError, e: + except ValueError as e: if str(e) == "Proteins cannot be translated!": continue raise e #This is based on the limited example not having stop codons: if tran.alphabet not in [extended_protein, protein, generic_protein]: - print tran.alphabet + print(tran.alphabet) self.assertTrue(False) #TODO - check the actual translation, and all the optional args @@ -503,7 +498,7 @@ Seq(codon, generic_dna), Seq(codon, unambiguous_dna)]: try : - print nuc.translate() + print(nuc.translate()) self.assertTrue(False, "Transating %s should fail" % codon) except TranslationError : pass diff -Nru python-biopython-1.62/Tests/test_SffIO.py python-biopython-1.63/Tests/test_SffIO.py --- python-biopython-1.62/Tests/test_SffIO.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_SffIO.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,5 +1,12 @@ +# Copyright 2012 by Jeff Hussmann. All rights reserved. +# Revisions copyright 2013 by Peter Cock. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. + import re import unittest + from Bio import SeqIO # sffinfo E3MFGYR02_random_10_reads.sff | sed -n '/>\|Run Prefix\|Region\|XY/p' @@ -56,13 +63,13 @@ current_name = fields[0].lstrip('>') self.test_annotations[current_name] = {} elif 'Prefix' in line: - time_list = map(int, fields[2].split('_')[1:-1]) + time_list = [int(v) for v in fields[2].split('_')[1:-1]] self.test_annotations[current_name]["time"] = time_list elif 'Region' in line: region = int(fields[-1]) self.test_annotations[current_name]["region"] = region elif 'XY' in line: - x, y = map(int, fields[-1].split('_')) + x, y = [int(v) for v in fields[-1].split('_')] self.test_annotations[current_name]["coords"] = (x, y) def test_time(self): @@ -77,5 +84,58 @@ for record in self.records: self.assertEqual(record.annotations["coords"], self.test_annotations[record.name]["coords"]) -if __name__ == '__main__': - unittest.main() +class TestConcatenated(unittest.TestCase): + def test_parse1(self): + count = 0 + caught = False + try: + for record in SeqIO.parse("Roche/invalid_greek_E3MFGYR02.sff", "sff"): + count += 1 + except ValueError as err: + self.assertTrue("Additional data at end of SFF file, perhaps " + "multiple SFF files concatenated? " + "See offset 65296" in str(err), err) + caught = True + self.assertTrue(caught, "Didn't spot concatenation") + self.assertEqual(count, 24) + + def test_index1(self): + try: + d = SeqIO.index("Roche/invalid_greek_E3MFGYR02.sff", "sff") + except ValueError as err: + self.assertTrue("Additional data at end of SFF file, perhaps " + "multiple SFF files concatenated? " + "See offset 65296" in str(err), err) + else: + raise ValueError("Indxing Roche/invalid_greek_E3MFGYR02.sff should fail") + + def test_parse2(self): + count = 0 + caught = False + try: + for record in SeqIO.parse("Roche/invalid_paired_E3MFGYR02.sff", "sff"): + count += 1 + except ValueError as err: + self.assertTrue("Your SFF file is invalid, post index 5 byte " + "null padding region ended '.sff' which could " + "be the start of a concatenated SFF file? " + "See offset 54371" in str(err), err) + caught = True + self.assertTrue(caught, "Didn't spot concatenation") + self.assertEqual(count, 20) + + def test_index2(self): + try: + d = SeqIO.index("Roche/invalid_paired_E3MFGYR02.sff", "sff") + except ValueError as err: + self.assertTrue("Your SFF file is invalid, post index 5 byte " + "null padding region ended '.sff' which could " + "be the start of a concatenated SFF file? " + "See offset 54371" in str(err), err) + else: + raise ValueError("Indxing Roche/invalid_paired_E3MFGYR02.sff should fail") + + +if __name__ == "__main__": + runner = unittest.TextTestRunner(verbosity = 2) + unittest.main(testRunner=runner) diff -Nru python-biopython-1.62/Tests/test_SubsMat.py python-biopython-1.63/Tests/test_SubsMat.py --- python-biopython-1.62/Tests/test_SubsMat.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_SubsMat.py 2013-12-05 14:10:43.000000000 +0000 @@ -2,8 +2,6 @@ # license. Please see the LICENSE file that should have been included # as part of this package. -from __future__ import with_statement - try: from numpy import corrcoef del corrcoef @@ -12,7 +10,11 @@ raise MissingExternalDependencyError( "Install NumPy if you want to use Bio.SubsMat.") -import cPickle +try: + import cPickle as pickle # Only available on Python 3 +except ImportError: + import pickle + import sys import os from Bio import SubsMat @@ -33,41 +35,37 @@ pickle_file = os.path.join('SubsMat', 'acc_rep_mat.pik') #Don't want to use text mode on Python 3, with open(pickle_file, 'rb') as handle: - acc_rep_mat = cPickle.load(handle) + acc_rep_mat = pickle.load(handle) acc_rep_mat = SubsMat.AcceptedReplacementsMatrix(acc_rep_mat) obs_freq_mat = SubsMat._build_obs_freq_mat(acc_rep_mat) ftab_prot2 = SubsMat._exp_freq_table_from_obs_freq(obs_freq_mat) -obs_freq_mat.print_mat(f=f,format=" %4.3f") +obs_freq_mat.print_mat(f=f, format=" %4.3f") f.write("Diff between supplied and matrix-derived frequencies, should be small\n") -ks = ftab_prot.keys() -ks.sort() -for i in ks: - f.write("%s %.2f\n" % (i,abs(ftab_prot[i] - ftab_prot2[i]))) +for i in sorted(ftab_prot): + f.write("%s %.2f\n" % (i, abs(ftab_prot[i] - ftab_prot2[i]))) s = 0. f.write("Calculating sum of letters for an observed frequency matrix\n") counts = obs_freq_mat.sum() -keys = counts.keys() -keys.sort() -for key in keys: +for key in sorted(counts): f.write("%s\t%.2f\n" % (key, counts[key])) s += counts[key] f.write("Total sum %.2f should be 1.0\n" % (s)) lo_mat_prot = \ -SubsMat.make_log_odds_matrix(acc_rep_mat=acc_rep_mat,round_digit=1) # ,ftab_prot +SubsMat.make_log_odds_matrix(acc_rep_mat=acc_rep_mat, round_digit=1) # ,ftab_prot f.write("\nLog odds matrix\n") f.write("\nLog odds half matrix\n") # Was %.1f. Let us see if this is OK -lo_mat_prot.print_mat(f=f,format=" %d",alphabet='AVILMCFWYHSTNQKRDEGP') +lo_mat_prot.print_mat(f=f, format=" %d", alphabet='AVILMCFWYHSTNQKRDEGP') f.write("\nLog odds full matrix\n") # Was %.1f. Let us see if this is OK -lo_mat_prot.print_full_mat(f=f,format=" %d",alphabet='AVILMCFWYHSTNQKRDEGP') +lo_mat_prot.print_full_mat(f=f, format=" %d", alphabet='AVILMCFWYHSTNQKRDEGP') f.write("\nTesting MatrixInfo\n") for i in MatrixInfo.available_matrices: - mat = SubsMat.SeqMat(getattr(MatrixInfo,i)) + mat = SubsMat.SeqMat(getattr(MatrixInfo, i)) f.write("\n%s\n------------\n" % i) mat.print_mat(f=f) f.write("\nTesting Entropy\n") diff -Nru python-biopython-1.62/Tests/test_SwissProt.py python-biopython-1.63/Tests/test_SwissProt.py --- python-biopython-1.62/Tests/test_SwissProt.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_SwissProt.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,4 +1,9 @@ #!/usr/bin/env python +# Copyright 2009 by Michiel de Hoon. All rights reserved. +# Revisions copyright 2010 by Peter Cock. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. """Test for the SwissProt parser on SwissProt files. """ import os diff -Nru python-biopython-1.62/Tests/test_TCoffee_tool.py python-biopython-1.63/Tests/test_TCoffee_tool.py --- python-biopython-1.62/Tests/test_TCoffee_tool.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_TCoffee_tool.py 2013-12-05 14:10:43.000000000 +0000 @@ -18,8 +18,8 @@ raise MissingExternalDependencyError( "Testing TCOFFEE on Windows not supported yet") else: - import commands - output = commands.getoutput("t_coffee -version") + from Bio._py3k import getoutput + output = getoutput("t_coffee -version") if "not found" not in output \ and ("t_coffee" in output.lower() or "t-coffee" in output.lower()): t_coffee_exe = "t_coffee" @@ -57,10 +57,10 @@ self.assertTrue(stderr.strip().startswith("PROGRAM: T-COFFEE")) align = AlignIO.read(self.outfile1, "clustal") records = list(SeqIO.parse(self.infile1, "fasta")) - self.assertEqual(len(records),len(align)) + self.assertEqual(len(records), len(align)) for old, new in zip(records, align): self.assertEqual(old.id, new.id) - self.assertEqual(str(new.seq).replace("-",""), str(old.seq).replace("-","")) + self.assertEqual(str(new.seq).replace("-", ""), str(old.seq).replace("-", "")) def test_TCoffee_2(self): """Round-trip through app and read pir alignment from file @@ -75,11 +75,11 @@ #Can get warnings in stderr output self.assertTrue("error" not in stderr.lower(), stderr) align = AlignIO.read(self.outfile3, "pir") - records = list(SeqIO.parse(self.infile1,"fasta")) - self.assertEqual(len(records),len(align)) + records = list(SeqIO.parse(self.infile1, "fasta")) + self.assertEqual(len(records), len(align)) for old, new in zip(records, align): self.assertEqual(old.id, new.id) - self.assertEqual(str(new.seq).replace("-",""), str(old.seq).replace("-","")) + self.assertEqual(str(new.seq).replace("-", ""), str(old.seq).replace("-", "")) def test_TCoffee_3(self): """Round-trip through app and read clustalw alignment from file @@ -98,10 +98,10 @@ self.assertTrue(stderr.strip().startswith("PROGRAM: T-COFFEE")) align = AlignIO.read(self.outfile4, "clustal") records = list(SeqIO.parse(self.infile1, "fasta")) - self.assertEqual(len(records),len(align)) + self.assertEqual(len(records), len(align)) for old, new in zip(records, align): self.assertEqual(old.id, new.id) - self.assertEqual(str(new.seq).replace("-",""), str(old.seq).replace("-","")) + self.assertEqual(str(new.seq).replace("-", ""), str(old.seq).replace("-", "")) if __name__ == "__main__": runner = unittest.TextTestRunner(verbosity = 2) diff -Nru python-biopython-1.62/Tests/test_TogoWS.py python-biopython-1.63/Tests/test_TogoWS.py --- python-biopython-1.62/Tests/test_TogoWS.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_TogoWS.py 2013-12-05 14:10:43.000000000 +0000 @@ -6,10 +6,10 @@ """Testing Bio.TogoWS online code. """ -from __future__ import with_statement +from __future__ import print_function import unittest -from StringIO import StringIO +from Bio._py3k import StringIO import requires_internet requires_internet.check() @@ -51,7 +51,7 @@ """Check supported fields for pubmed database""" fields = set(TogoWS._get_entry_fields("pubmed")) self.assertTrue(fields.issuperset(['abstract', 'au', 'authors', - 'doi', 'mesh', 'so', 'ti', + 'doi', 'mesh', 'so', 'title']), fields) def test_ncbi_protein(self): @@ -112,8 +112,8 @@ 'Hirakawa M']) def test_pubmed_16381885_ti(self): - """Bio.TogoWS.entry("pubmed", "16381885", field="ti")""" - handle = TogoWS.entry("pubmed", "16381885", field="ti") + """Bio.TogoWS.entry("pubmed", "16381885", field="title")""" + handle = TogoWS.entry("pubmed", "16381885", field="title") data = handle.read().strip() handle.close() self.assertEqual(data, @@ -345,7 +345,7 @@ def test_uniprot_swiss(self): """Bio.TogoWS.entry("uniprot", ["A1AG1_HUMAN","A1AG1_MOUSE"])""" #Returns "swiss" format: - handle = TogoWS.entry("uniprot", ["A1AG1_HUMAN","A1AG1_MOUSE"]) + handle = TogoWS.entry("uniprot", ["A1AG1_HUMAN", "A1AG1_MOUSE"]) record1, record2 = SeqIO.parse(handle, "swiss") handle.close() @@ -465,7 +465,7 @@ raise ValueError("Only %i matches, expected at least %i" % (search_count, len(expected_matches))) if search_count > 5000 and not limit: - print "%i results, skipping" % search_count + print("%i results, skipping" % search_count) return if limit: count = min(search_count, limit) diff -Nru python-biopython-1.62/Tests/test_Tutorial.py python-biopython-1.63/Tests/test_Tutorial.py --- python-biopython-1.62/Tests/test_Tutorial.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_Tutorial.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,3 +1,11 @@ +# Copyright 2011-2013 by Peter Cock. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. + +# This will apply to all the doctests too: +from __future__ import print_function + import unittest import doctest import os @@ -9,9 +17,15 @@ if sys.version_info[0] >= 3: from lib2to3 import refactor - rt = refactor.RefactoringTool(refactor.get_fixers_from_package("lib2to3.fixes")) - assert rt.refactor_docstring(">>> print 2+2\n4\n", "example") == \ - ">>> print(2+2)\n4\n" + fixers = refactor.get_fixers_from_package("lib2to3.fixes") + fixers.remove("lib2to3.fixes.fix_print") # Already using print function + rt = refactor.RefactoringTool(fixers) + assert rt.refactor_docstring(">>> print(2+2)\n4\n", "example1") == \ + ">>> print(2+2)\n4\n" + assert rt.refactor_docstring('>>> print("Two plus two is", 2+2)\n' + 'Two plus two is 4\n', "example2") == \ + '>>> print("Two plus two is", 2+2)\nTwo plus two is 4\n' + tutorial = os.path.join(os.path.dirname(sys.argv[0]), "../Doc/Tutorial.tex") if not os.path.isfile(tutorial) and sys.version_info[0] >= 3: @@ -33,7 +47,7 @@ line = handle.readline() if not line: if lines: - print "".join(lines[:30]) + print("".join(lines[:30])) raise ValueError("Didn't find end of test starting: %r", lines[0]) else: raise ValueError("Didn't find end of test!") @@ -112,6 +126,7 @@ continue if sys.version_info[0] >= 3: + example = ">>> from __future__ import print_function\n" + example example = rt.refactor_docstring(example, name) def funct(n, d, f): @@ -127,7 +142,7 @@ return method setattr(TutorialDocTestHolder, - "doctest_%s" % name.replace(" ","_"), + "doctest_%s" % name.replace(" ", "_"), funct(name, example, folder)) del funct @@ -159,13 +174,13 @@ #This is to run the doctests if the script is called directly: if __name__ == "__main__": if missing_deps: - print "Skipping tests needing the following:" + print("Skipping tests needing the following:") for dep in sorted(missing_deps): - print " - %s" % dep - print "Running Tutorial doctests..." + print(" - %s" % dep) + print("Running Tutorial doctests...") import doctest tests = doctest.testmod() if tests[0]: #Note on Python 2.5+ can use tests.failed rather than tests[0] raise RuntimeError("%i/%i tests failed" % tests) - print "Tests done" + print("Tests done") diff -Nru python-biopython-1.62/Tests/test_UniGene.py python-biopython-1.63/Tests/test_UniGene.py --- python-biopython-1.62/Tests/test_UniGene.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_UniGene.py 2013-12-05 14:10:43.000000000 +0000 @@ -17,7 +17,7 @@ records = UniGene.parse(handle) # First record - record = records.next() + record = next(records) self.assertEqual(record.ID, "Eca.1") self.assertEqual(record.title, "Ribosomal protein L3") self.assertEqual(record.symbol, "RPL3") @@ -690,7 +690,7 @@ self.assertEqual(record.sequence[68].trace, "891192160") # Second record - record = records.next() + record = next(records) self.assertEqual(record.ID, "Eca.2425") self.assertEqual(record.title, "Immunoglobulin-like transcript 11 protein") @@ -810,7 +810,7 @@ self.assertEqual(record.sequence[8].trace, "891191801") # Make sure that there are no more records - self.assertRaises(StopIteration, records.next) + self.assertRaises(StopIteration, next, records) handle.close() diff -Nru python-biopython-1.62/Tests/test_Uniprot.py python-biopython-1.63/Tests/test_Uniprot.py --- python-biopython-1.62/Tests/test_Uniprot.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_Uniprot.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,8 +1,11 @@ #!/usr/bin/env python +# Copyright 2010 by Andrea Pierleoni +# Revisions copyright 2010-2013 by Peter Cock. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. """Test for the Uniprot parser on Uniprot XML files. """ -from __future__ import with_statement - import os import unittest diff -Nru python-biopython-1.62/Tests/test_Wise.py python-biopython-1.63/Tests/test_Wise.py --- python-biopython-1.62/Tests/test_Wise.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_Wise.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,9 +3,6 @@ # license. Please see the LICENSE file that should have been included # as part of this package. -__version__ = "$Revision: 1.11 $" - -import cStringIO import doctest import sys import unittest @@ -14,13 +11,15 @@ del sys.modules['requires_wise'] import requires_wise +from Bio._py3k import StringIO + from Bio import Wise class TestWiseDryRun(unittest.TestCase): def setUp(self): self.old_stdout = sys.stdout - sys.stdout = cStringIO.StringIO() + sys.stdout = StringIO() def test_dnal(self): """Call dnal, and do a trivial check on its output.""" diff -Nru python-biopython-1.62/Tests/test_XXmotif_tool.py python-biopython-1.63/Tests/test_XXmotif_tool.py --- python-biopython-1.62/Tests/test_XXmotif_tool.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_XXmotif_tool.py 2013-12-05 14:10:43.000000000 +0000 @@ -23,8 +23,8 @@ # TODO raise MissingExternalDependencyError("Testing this on Windows is not implemented yet") else: - import commands - output = commands.getoutput("XXmotif") + from Bio._py3k import getoutput + output = getoutput("XXmotif") if output.find("== XXmotif version") != -1: xxmotif_exe = "XXmotif" @@ -92,7 +92,7 @@ try: stdout, stderr = cline() - except ApplicationError, err: + except ApplicationError as err: self.assertEqual(err.returncode, 255) else: self.fail("Should have failed, returned:\n%s\n%s" % (stdout, stderr)) @@ -106,7 +106,7 @@ try: stdout, stderr = cline() - except ApplicationError, err: + except ApplicationError as err: self.assertEqual(err.returncode, 255) else: self.fail("Should have failed, returned:\n%s\n%s" % (stdout, stderr)) diff -Nru python-biopython-1.62/Tests/test_align.py python-biopython-1.63/Tests/test_align.py --- python-biopython-1.62/Tests/test_align.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_align.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,5 +1,10 @@ - #!/usr/bin/env python +# Copyright 2000-2001 by Brad Chapman. All rights reserved. +# Revisions copyright 2007-2003 by Peter Cock. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. + """test_align.py A script to test alignment stuff. @@ -10,6 +15,8 @@ o Converting between formats""" # standard library +from __future__ import print_function + import os # biopython @@ -43,7 +50,7 @@ assert alignment[1].id == "lower" assert alignment[2].id == "upper" for (col, letter) in enumerate(letters): - assert alignment[:,col] == letter + letter.lower() + letter.upper() + assert alignment[:, col] == letter + letter.lower() + letter.upper() #Check row extractions: assert alignment[0].id == "mixed" assert alignment[-1].id == "upper" @@ -55,7 +62,7 @@ del alignment del letters -print "testing reading and writing clustal format..." +print("testing reading and writing clustal format...") test_dir = os.path.join(os.getcwd(), 'Clustalw') test_names = ['opuntia.aln', 'cw02.aln'] @@ -68,49 +75,48 @@ alignment = AlignIO.read(test_file, "clustal") # print the alignment back out - print alignment.format("clustal") + print(alignment.format("clustal")) alignment = AlignIO.read(os.path.join(test_dir, test_names[0]), "clustal", alphabet = Alphabet.Gapped(IUPAC.unambiguous_dna)) # test the base alignment stuff -print 'all_seqs...' +print('all_seqs...') for seq_record in alignment: - print 'description:', seq_record.description - print 'seq:', repr(seq_record.seq) -print 'length:', alignment.get_alignment_length() + print('description: %s' % seq_record.description) + print('seq: %r' % seq_record.seq) +print('length: %i' % alignment.get_alignment_length()) -print 'Calculating summary information...' +print('Calculating summary information...') align_info = AlignInfo.SummaryInfo(alignment) consensus = align_info.dumb_consensus() assert isinstance(consensus, Seq) -print 'consensus:', repr(consensus) +print('consensus: %r' % consensus) -print 'Replacement dictionary' -ks = align_info.replacement_dictionary(['N']).keys() -ks.sort() +print('Replacement dictionary') +ks = sorted(align_info.replacement_dictionary(['N'])) for key in ks: - print "%s : %s" % (key, align_info.replacement_dictionary(['N'])[key]) + print("%s : %s" % (key, align_info.replacement_dictionary(['N'])[key])) -print 'position specific score matrix.' -print 'with a supplied consensus sequence...' -print align_info.pos_specific_score_matrix(consensus, ['N']) +print('position specific score matrix.') +print('with a supplied consensus sequence...') +print(align_info.pos_specific_score_matrix(consensus, ['N'])) -print 'defaulting to a consensus sequence...' -print align_info.pos_specific_score_matrix(chars_to_ignore = ['N']) +print('defaulting to a consensus sequence...') +print(align_info.pos_specific_score_matrix(chars_to_ignore = ['N'])) -print 'with a selected sequence...' +print('with a selected sequence...') second_seq = alignment[1].seq -print align_info.pos_specific_score_matrix(second_seq, ['N']) +print(align_info.pos_specific_score_matrix(second_seq, ['N'])) -print 'information content' -print 'part of alignment: %0.2f' \ - % align_info.information_content(5, 50, chars_to_ignore = ['N']) -print 'entire alignment: %0.2f' \ - % align_info.information_content(chars_to_ignore = ['N']) +print('information content') +print('part of alignment: %0.2f' \ + % align_info.information_content(5, 50, chars_to_ignore = ['N'])) +print('entire alignment: %0.2f' \ + % align_info.information_content(chars_to_ignore = ['N'])) -print 'relative information content' +print('relative information content') e_freq = {'G' : 0.25, 'C' : 0.25, 'A' : 0.25, @@ -119,17 +125,17 @@ e_freq_table = FreqTable.FreqTable(e_freq, FreqTable.FREQ, IUPAC.unambiguous_dna) -print 'relative information: %0.2f' \ +print('relative information: %0.2f' \ % align_info.information_content(e_freq_table = e_freq_table, - chars_to_ignore = ['N']) + chars_to_ignore = ['N'])) -print 'Column 1:', align_info.get_column(1) -print 'IC for column 1: %0.2f' % align_info.ic_vector[1] -print 'Column 7:', align_info.get_column(7) -print 'IC for column 7: %0.2f' % align_info.ic_vector[7] -print 'test print_info_content' +print('Column 1: %s' % align_info.get_column(1)) +print('IC for column 1: %0.2f' % align_info.ic_vector[1]) +print('Column 7: %s' % align_info.get_column(7)) +print('IC for column 7: %0.2f' % align_info.ic_vector[7]) +print('test print_info_content') AlignInfo.print_info_content(align_info) -print "testing reading and writing fasta format..." +print("testing reading and writing fasta format...") to_parse = os.path.join(os.curdir, 'Quality', 'example.fasta') @@ -137,35 +143,35 @@ alphabet = Alphabet.Gapped(IUPAC.ambiguous_dna)) # test the base alignment stuff -print 'all_seqs...' +print('all_seqs...') for seq_record in alignment: - print 'description:', seq_record.description - print 'seq:', repr(seq_record.seq) + print('description: %s' % seq_record.description) + print('seq: %r' % seq_record.seq) -print 'length:', alignment.get_alignment_length() +print('length: %i' % alignment.get_alignment_length()) align_info = AlignInfo.SummaryInfo(alignment) consensus = align_info.dumb_consensus(ambiguous="N", threshold=0.6) assert isinstance(consensus, Seq) -print 'consensus:', repr(consensus) +print('consensus: %r' % consensus) -print alignment +print(alignment) -print "Test format conversion..." +print("Test format conversion...") # parse the alignment file and get an aligment object alignment = AlignIO.read(os.path.join(os.curdir, 'Clustalw', 'opuntia.aln'), 'clustal') -print "As FASTA:" -print alignment.format("fasta") -print "As Clustal:" -print alignment.format("clustal") +print("As FASTA:") +print(alignment.format("fasta")) +print("As Clustal:") +print(alignment.format("clustal")) """ # test to find a position in an original sequence given a # column position in an alignment -print "Testing finding column positions..." +print("Testing finding column positions...") alignment_info = ["GATC--CGATC--G", "GA--CCCG-TC--G", "GAT--CC--TC--G"] diff -Nru python-biopython-1.62/Tests/test_bgzf.py python-biopython-1.63/Tests/test_bgzf.py --- python-biopython-1.62/Tests/test_bgzf.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_bgzf.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,4 +1,4 @@ -# Copyright 2010-2011 by Peter Cock. +# Copyright 2010-2013 by Peter Cock. # All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included @@ -24,18 +24,14 @@ Checks for http://bugs.python.org/issue17666 expected in Python 2.7.4, 3.2.4 and 3.3.1 only. """ - try: - #This is in Python 2.6+, but we need it on Python 3 - from io import BytesIO - except ImportError: - from StringIO import StringIO as BytesIO + from io import BytesIO h = gzip.GzipFile(fileobj=BytesIO(bgzf._bgzf_eof)) try: data = h.read() h.close() assert not data, "Should be zero length, not %i" % len(data) return False - except TypeError, err: + except TypeError as err: #TypeError: integer argument expected, got 'tuple' return True @@ -116,7 +112,7 @@ old = _as_string(old) h.close() - for cache in [1,10]: + for cache in [1, 10]: h = bgzf.BgzfReader(new_file, mode, max_cache=cache) if "b" in mode: new = _empty_bytes_string.join(line for line in h) @@ -132,7 +128,7 @@ def check_by_char(self, old_file, new_file, old_gzip=False): for mode in ["r", "rb"]: if old_gzip: - h = gzip.open(old_file,mode) + h = gzip.open(old_file, mode) else: h = open(old_file, mode) old = h.read() @@ -144,7 +140,7 @@ old = _as_string(old) h.close() - for cache in [1,10]: + for cache in [1, 10]: h = bgzf.BgzfReader(new_file, mode, max_cache=cache) temp = [] while True: @@ -182,8 +178,7 @@ self.assertFalse(h.isatty()) self.assertEqual(h.fileno(), h._handle.fileno()) for start, raw_len, data_start, data_len in blocks: - #print start, raw_len, data_start, data_len - h.seek(bgzf.make_virtual_offset(start,0)) + h.seek(bgzf.make_virtual_offset(start, 0)) data = h.read(data_len) self.assertEqual(len(data), data_len) #self.assertEqual(start + raw_len, h._handle.tell()) @@ -197,8 +192,7 @@ new = _empty_bytes_string h = bgzf.BgzfReader(filename, "rb") for start, raw_len, data_start, data_len in blocks[::-1]: - #print start, raw_len, data_start, data_len - h.seek(bgzf.make_virtual_offset(start,0)) + h.seek(bgzf.make_virtual_offset(start, 0)) data = h.read(data_len) self.assertEqual(len(data), data_len) #self.assertEqual(start + raw_len, h._handle.tell()) @@ -270,9 +264,13 @@ self.check_random("Blast/wnts.xml.bgz") def test_random_example_fastq(self): - """Check random access to Quality/example.fastq.bgz""" + """Check random access to Quality/example.fastq.bgz (Unix newlines)""" self.check_random("Quality/example.fastq.bgz") + def test_random_example_dos_fastq(self): + """Check random access to Quality/example_dos.fastq.bgz (DOS newlines)""" + self.check_random("Quality/example_dos.fastq.bgz") + def test_random_example_cor6(self): """Check random access to GenBank/cor6_6.gb.bgz""" self.check_random("GenBank/cor6_6.gb.bgz") diff -Nru python-biopython-1.62/Tests/test_geo.py python-biopython-1.63/Tests/test_geo.py --- python-biopython-1.62/Tests/test_geo.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_geo.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,6 +1,13 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + """Tests the basic functionality of the GEO parsers. """ +from __future__ import print_function + import os import sys @@ -24,9 +31,9 @@ fh = open(os.path.join("Geo", file), encoding="latin") else: fh = open(os.path.join("Geo", file)) - print "Testing Bio.Geo on " + file + "\n\n" + print("Testing Bio.Geo on " + file + "\n\n") records = Bio.Geo.parse(fh) for record in records: - print record - print "\n" + print(record) + print("\n") fh.close() diff -Nru python-biopython-1.62/Tests/test_kNN.py python-biopython-1.63/Tests/test_kNN.py --- python-biopython-1.62/Tests/test_kNN.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_kNN.py 2013-12-05 14:10:43.000000000 +0000 @@ -61,18 +61,18 @@ def test_calculate_model(self): k = 3 model = kNN.train(xs, ys, k) - self.assertEqual(model.classes, set([0,1])) + self.assertEqual(model.classes, set([0, 1])) n = len(xs) for i in range(n): - self.assertAlmostEqual(model.xs[i,0], xs[i][0], places=4) - self.assertAlmostEqual(model.xs[i,1], xs[i][1], places=4) + self.assertAlmostEqual(model.xs[i, 0], xs[i][0], places=4) + self.assertAlmostEqual(model.xs[i, 1], xs[i][1], places=4) self.assertEqual(model.ys[i], ys[i]) self.assertEqual(model.k, k) def test_classify(self): k = 3 model = kNN.train(xs, ys, k) - result = kNN.classify(model, [6,-173.143442352]) + result = kNN.classify(model, [6, -173.143442352]) self.assertEqual(result, 1) result = kNN.classify(model, [309, -271.005880394]) self.assertEqual(result, 0) @@ -80,7 +80,7 @@ def test_calculate_probability(self): k = 3 model = kNN.train(xs, ys, k) - weights = kNN.calculate(model, [6,-173.143442352]) + weights = kNN.calculate(model, [6, -173.143442352]) self.assertAlmostEqual(weights[0], 0.0, places=6) self.assertAlmostEqual(weights[1], 3.0, places=6) weights = kNN.calculate(model, [309, -271.005880394]) diff -Nru python-biopython-1.62/Tests/test_motifs.py python-biopython-1.63/Tests/test_motifs.py --- python-biopython-1.62/Tests/test_motifs.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_motifs.py 2013-12-05 14:10:43.000000000 +0000 @@ -73,7 +73,7 @@ self.assertEqual(str(record[0].instances[8]), "TCTACGATTGAG") self.assertEqual(str(record[0].instances[9]), "TCAAAGATAGAG") self.assertEqual(str(record[0].instances[10]), "TCTACGATTGAG") - self.assertEqual(record[0].mask, (1,1,0,1,1,1,1,1,0,1,1,1)) + self.assertEqual(record[0].mask, (1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1)) self.assertAlmostEqual(record[0].score, 57.9079) self.assertEqual(record[1].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record[1].instances), 22) @@ -99,7 +99,7 @@ self.assertEqual(str(record[1].instances[19]), "GGCGGGCCATCCCTGTATGAA") self.assertEqual(str(record[1].instances[20]), "CTCCAGGTCGCATGGAGAGAG") self.assertEqual(str(record[1].instances[21]), "CCTCGGATCGCTTGGGAAGAG") - self.assertEqual(record[1].mask, (1,0,1,1,0,1,0,0,1,1,1,0,0,0,1,0,0,0,1,0,1)) + self.assertEqual(record[1].mask, (1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1)) self.assertAlmostEqual(record[1].score, 19.6235) self.assertEqual(record[2].alphabet, IUPAC.unambiguous_dna) @@ -122,7 +122,7 @@ self.assertEqual(str(record[2].instances[15]), "GACCTGGAGGCTTAGACTTGG") self.assertEqual(str(record[2].instances[16]), "GCGCTCTTCCCAAGCGATCCG") self.assertEqual(str(record[2].instances[17]), "GGGCCGTCAGCTCTCAAGTCT") - self.assertEqual(record[2].mask, (1,0,1,1,0,1,0,0,0,1,1,0,0,0,1,0,1,0,0,1,1)) + self.assertEqual(record[2].mask, (1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1)) self.assertAlmostEqual(record[2].score, 19.1804) self.assertEqual(record[3].alphabet, IUPAC.unambiguous_dna) @@ -143,7 +143,7 @@ self.assertEqual(str(record[3].instances[13]), "GCGATCAGCTTGTGGGCGTGC") self.assertEqual(str(record[3].instances[14]), "GACAAATCGGATACTGGGGCA") self.assertEqual(str(record[3].instances[15]), "GCACTTAGCAGCGTATCGTTA") - self.assertEqual(record[3].mask, (1,1,1,0,0,0,0,1,1,0,0,0,0,1,0,0,1,1,1,0,1)) + self.assertEqual(record[3].mask, (1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1)) self.assertAlmostEqual(record[3].score, 18.0097) self.assertEqual(record[4].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record[4].instances), 15) @@ -162,7 +162,7 @@ self.assertEqual(str(record[4].instances[12]), "ATGCTTAGAGGTT") self.assertEqual(str(record[4].instances[13]), "AGACTTGGGCGAT") self.assertEqual(str(record[4].instances[14]), "CGACCTGGAGGCT") - self.assertEqual(record[4].mask, (1,1,0,1,0,1,1,1,1,1,1,0,1)) + self.assertEqual(record[4].mask, (1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1)) self.assertAlmostEqual(record[4].score, 16.8287) self.assertEqual(record[5].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record[5].instances), 18) @@ -184,7 +184,7 @@ self.assertEqual(str(record[5].instances[15]), "CTCTGCGTCGCATGGCGGCGTGG") self.assertEqual(str(record[5].instances[16]), "GGAGGCTTAGACTTGGGCGATAC") self.assertEqual(str(record[5].instances[17]), "GCATGGAGAGAGATCCGGAGGAG") - self.assertEqual(record[5].mask, (1,0,1,0,1,1,0,0,0,1,0,0,0,0,1,0,1,1,0,0,1,0,1)) + self.assertEqual(record[5].mask, (1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1)) self.assertAlmostEqual(record[5].score, 15.0441) self.assertEqual(record[6].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record[6].instances), 20) @@ -208,7 +208,7 @@ self.assertEqual(str(record[6].instances[17]), "GCTCGTCTATGGTCA") self.assertEqual(str(record[6].instances[18]), "GCGCATGCTGGATCC") self.assertEqual(str(record[6].instances[19]), "GGCCGTCAGCTCTCA") - self.assertEqual(record[6].mask, (1,1,0,1,1,1,1,0,1,0,1,0,0,1,1)) + self.assertEqual(record[6].mask, (1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1)) self.assertAlmostEqual(record[6].score, 13.3145) self.assertEqual(record[7].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record[7].instances), 20) @@ -232,7 +232,7 @@ self.assertEqual(str(record[7].instances[17]), "AGTCAATGACACGCGCCTGGG") self.assertEqual(str(record[7].instances[18]), "GGTCATGGAATCTTATGTAGC") self.assertEqual(str(record[7].instances[19]), "GTAGATAACAGAGGTCGGGGG") - self.assertEqual(record[7].mask, (1,0,0,1,0,0,0,1,1,0,0,1,1,0,0,0,1,1,0,1,1)) + self.assertEqual(record[7].mask, (1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1)) self.assertAlmostEqual(record[7].score, 11.6098) self.assertEqual(record[8].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record[8].instances), 14) @@ -250,7 +250,7 @@ self.assertEqual(str(record[8].instances[11]), "GAGATCCGGAGGAGG") self.assertEqual(str(record[8].instances[12]), "GCGATCCGAGGGCCG") self.assertEqual(str(record[8].instances[13]), "GAGTTCACATGGCTG") - self.assertEqual(record[8].mask, (1,0,1,0,0,1,1,0,1,1,1,1,1,0,1)) + self.assertEqual(record[8].mask, (1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1)) self.assertAlmostEqual(record[8].score, 11.2943) self.assertEqual(record[9].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record[9].instances), 18) @@ -272,7 +272,7 @@ self.assertEqual(str(record[9].instances[15]), "TCTAGGCGGGC") self.assertEqual(str(record[9].instances[16]), "AGTATGCTTAG") self.assertEqual(str(record[9].instances[17]), "TGGAGGCTTAG") - self.assertEqual(record[9].mask, (1,1,1,1,0,1,1,1,1,1,1)) + self.assertEqual(record[9].mask, (1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1)) self.assertAlmostEqual(record[9].score, 9.7924) self.assertEqual(record[10].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record[10].instances), 13) @@ -289,7 +289,7 @@ self.assertEqual(str(record[10].instances[10]), "ATCCTCTGCGTCGCATGGCGG") self.assertEqual(str(record[10].instances[11]), "GACCATAGACGAGCATCAAAG") self.assertEqual(str(record[10].instances[12]), "GGCCCTCGGATCGCTTGGGAA") - self.assertEqual(record[10].mask, (1,0,1,1,0,0,0,1,0,0,0,1,1,1,1,0,0,0,0,1,1)) + self.assertEqual(record[10].mask, (1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1)) self.assertAlmostEqual(record[10].score, 9.01393) self.assertEqual(record[11].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record[11].instances), 16) @@ -309,7 +309,7 @@ self.assertEqual(str(record[11].instances[13]), "GCGATCCGAG") self.assertEqual(str(record[11].instances[14]), "AGTGCGCGTC") self.assertEqual(str(record[11].instances[15]), "AGTGCCCGAG") - self.assertEqual(record[11].mask, (1,1,1,1,1,1,1,1,1,1)) + self.assertEqual(record[11].mask, (1, 1, 1, 1, 1, 1, 1, 1, 1, 1)) self.assertAlmostEqual(record[11].score, 7.51121) self.assertEqual(record[12].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record[12].instances), 16) @@ -329,7 +329,7 @@ self.assertEqual(str(record[12].instances[13]), "GCACGTAGCTGGTAAATAGG") self.assertEqual(str(record[12].instances[14]), "GCGGCGTGGATTTCATACAG") self.assertEqual(str(record[12].instances[15]), "CCTGGAGGCTTAGACTTGGG") - self.assertEqual(record[12].mask, (1,1,0,1,1,0,0,1,1,0,1,0,0,0,1,0,0,0,1,1)) + self.assertEqual(record[12].mask, (1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1)) self.assertAlmostEqual(record[12].score, 5.63667) self.assertEqual(record[13].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record[13].instances), 15) @@ -348,7 +348,7 @@ self.assertEqual(str(record[13].instances[12]), "ACGCACGGGACTTCAACCAG") self.assertEqual(str(record[13].instances[13]), "GCACGTAGCTGGTAAATAGG") self.assertEqual(str(record[13].instances[14]), "ATCCTCTGCGTCGCATGGCG") - self.assertEqual(record[13].mask, (1,1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,0,1,1)) + self.assertEqual(record[13].mask, (1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1)) self.assertAlmostEqual(record[13].score, 3.89842) self.assertEqual(record[14].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record[14].instances), 14) @@ -366,7 +366,7 @@ self.assertEqual(str(record[14].instances[11]), "TACTCCGGGTAC") self.assertEqual(str(record[14].instances[12]), "GACGCAGAGGAT") self.assertEqual(str(record[14].instances[13]), "TAGGCGGGCCAT") - self.assertEqual(record[14].mask, (1,1,1,1,1,0,1,1,1,0,1,1)) + self.assertEqual(record[14].mask, (1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1)) self.assertAlmostEqual(record[14].score, 3.33444) self.assertEqual(record[15].alphabet, IUPAC.unambiguous_dna) self.assertEqual(len(record[15].instances), 21) @@ -391,7 +391,7 @@ self.assertEqual(str(record[15].instances[18]), "AGGCTCGCACGTAGCTGG") self.assertEqual(str(record[15].instances[19]), "CCACGCCGCCATGCGACG") self.assertEqual(str(record[15].instances[20]), "AGCCTCCAGGTCGCATGG") - self.assertEqual(record[15].mask, (1,1,0,1,0,1,0,0,1,1,0,1,1,0,0,0,1,1)) + self.assertEqual(record[15].mask, (1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1)) self.assertAlmostEqual(record[15].score, 1.0395) def test_pfm_parsing(self): @@ -403,7 +403,7 @@ def test_sites_parsing(self): """Test if Bio.motifs can parse JASPAR-style sites files. """ - m = motifs.read(self.SITESin,"sites") + m = motifs.read(self.SITESin, "sites") self.assertEqual(m.length, 6) def test_TFoutput(self): @@ -1511,8 +1511,8 @@ self.assertEqual(motif.counts['A', 7], 0) self.assertEqual(motif.counts['A', 8], 0) self.assertEqual(motif.counts['A', 9], 0) - self.assertEqual(motif.counts['A',10], 0) - self.assertEqual(motif.counts['A',11], 1) + self.assertEqual(motif.counts['A', 10], 0) + self.assertEqual(motif.counts['A', 11], 1) self.assertEqual(motif.counts['C', 0], 2) self.assertEqual(motif.counts['C', 1], 1) self.assertEqual(motif.counts['C', 2], 0) @@ -1523,8 +1523,8 @@ self.assertEqual(motif.counts['C', 7], 0) self.assertEqual(motif.counts['C', 8], 0) self.assertEqual(motif.counts['C', 9], 1) - self.assertEqual(motif.counts['C',10], 2) - self.assertEqual(motif.counts['C',11], 0) + self.assertEqual(motif.counts['C', 10], 2) + self.assertEqual(motif.counts['C', 11], 0) self.assertEqual(motif.counts['G', 0], 2) self.assertEqual(motif.counts['G', 1], 2) self.assertEqual(motif.counts['G', 2], 1) @@ -1535,8 +1535,8 @@ self.assertEqual(motif.counts['G', 7], 0) self.assertEqual(motif.counts['G', 8], 5) self.assertEqual(motif.counts['G', 9], 2) - self.assertEqual(motif.counts['G',10], 0) - self.assertEqual(motif.counts['G',11], 3) + self.assertEqual(motif.counts['G', 10], 0) + self.assertEqual(motif.counts['G', 11], 3) self.assertEqual(motif.counts['T', 0], 0) self.assertEqual(motif.counts['T', 1], 0) self.assertEqual(motif.counts['T', 2], 1) @@ -1547,8 +1547,8 @@ self.assertEqual(motif.counts['T', 7], 5) self.assertEqual(motif.counts['T', 8], 0) self.assertEqual(motif.counts['T', 9], 2) - self.assertEqual(motif.counts['T',10], 3) - self.assertEqual(motif.counts['T',11], 1) + self.assertEqual(motif.counts['T', 10], 3) + self.assertEqual(motif.counts['T', 11], 1) self.assertEqual(str(motif.counts.degenerate_consensus), "SRACAGGTGKYG") motif = record[1] self.assertEqual(motif['ID'], 'motif2') diff -Nru python-biopython-1.62/Tests/test_pairwise2.py python-biopython-1.63/Tests/test_pairwise2.py --- python-biopython-1.62/Tests/test_pairwise2.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_pairwise2.py 2013-12-05 14:10:43.000000000 +0000 @@ -36,8 +36,7 @@ class TestPairwiseLocal(unittest.TestCase): def test_localxs(self): - aligns = pairwise2.align.localxs("AxBx", "zABz", -0.1, 0) - aligns.sort() + aligns = sorted(pairwise2.align.localxs("AxBx", "zABz", -0.1, 0)) seq1, seq2, score, begin, end = aligns[0] alignment = pairwise2.format_alignment(seq1, seq2, score, begin, end) self.assertEqual(alignment, """\ diff -Nru python-biopython-1.62/Tests/test_phyml_tool.py python-biopython-1.63/Tests/test_phyml_tool.py --- python-biopython-1.62/Tests/test_phyml_tool.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_phyml_tool.py 2013-12-05 14:10:43.000000000 +0000 @@ -21,8 +21,8 @@ raise MissingExternalDependencyError( "Testing PhyML on Windows not supported yet") else: - import commands - output = commands.getoutput("phyml --version") + from Bio._py3k import getoutput + output = getoutput("phyml --version") if "not found" not in output and "20" in output: phyml_exe = "phyml" diff -Nru python-biopython-1.62/Tests/test_prodoc.py python-biopython-1.63/Tests/test_prodoc.py --- python-biopython-1.62/Tests/test_prodoc.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_prodoc.py 2013-12-05 14:10:43.000000000 +0000 @@ -842,7 +842,7 @@ records = Prodoc.parse(handle) # Testing the first parsed record - record = records.next() + record = next(records) self.assertEqual(record.accession, "PDOC00000") self.assertEqual(len(record.prosite_refs), 0) self.assertEqual(record.text, """\ @@ -904,7 +904,7 @@ """) # Testing the second parsed record" - record = records.next() + record = next(records) self.assertEqual(record.accession, "PDOC00001") self.assertEqual(len(record.prosite_refs), 1) self.assertEqual(record.prosite_refs[0], ("PS00001", "ASN_GLYCOSYLATION")) @@ -968,7 +968,7 @@ PubMed=1694179""") # Testing the third parsed record" - record = records.next() + record = next(records) self.assertEqual(record.accession, "PDOC00004") self.assertEqual(len(record.prosite_refs), 1) self.assertEqual(record.prosite_refs[0], ("PS00004", "CAMP_PHOSPHO_SITE")) @@ -1010,7 +1010,7 @@ PubMed=3005275""") # Testing the fourth parsed record" - record = records.next() + record = next(records) self.assertEqual(record.accession, "PDOC60030") self.assertEqual(len(record.prosite_refs), 1) self.assertEqual(record.prosite_refs[0], ("PS60030", "BACTERIOCIN_IIA")) diff -Nru python-biopython-1.62/Tests/test_psw.py python-biopython-1.63/Tests/test_psw.py --- python-biopython-1.62/Tests/test_psw.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_psw.py 2013-12-05 14:10:43.000000000 +0000 @@ -3,8 +3,6 @@ # license. Please see the LICENSE file that should have been included # as part of this package. -__version__ = "$Revision: 1.6 $" - import doctest import unittest import random diff -Nru python-biopython-1.62/Tests/test_py3k.py python-biopython-1.63/Tests/test_py3k.py --- python-biopython-1.62/Tests/test_py3k.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_py3k.py 2013-12-05 14:10:43.000000000 +0000 @@ -16,7 +16,7 @@ d[5] = "five" d[1] = "one" d[3] = "three" - self.assertEqual(d.keys(), [5, 1, 3]) + self.assertEqual(list(d.keys()), [5, 1, 3]) if __name__ == "__main__": runner = unittest.TextTestRunner(verbosity = 2) diff -Nru python-biopython-1.62/Tests/test_raxml_tool.py python-biopython-1.63/Tests/test_raxml_tool.py --- python-biopython-1.62/Tests/test_raxml_tool.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_raxml_tool.py 2013-12-05 14:10:43.000000000 +0000 @@ -18,8 +18,8 @@ raise MissingExternalDependencyError( "Testing RAxML on Windows not supported yet") else: - import commands - output = commands.getoutput("raxmlHPC -v") + from Bio._py3k import getoutput + output = getoutput("raxmlHPC -v") if "not found" not in output and "This is RAxML" in output: raxml_exe = "raxmlHPC" if not raxml_exe: diff -Nru python-biopython-1.62/Tests/test_seq.py python-biopython-1.63/Tests/test_seq.py --- python-biopython-1.62/Tests/test_seq.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_seq.py 2013-12-05 14:10:43.000000000 +0000 @@ -2,6 +2,8 @@ # license. Please see the LICENSE file that should have been included # as part of this package. +from __future__ import print_function + import sys from Bio import Seq from Bio.Alphabet import IUPAC @@ -16,126 +18,126 @@ else: array_indicator = "c" -print -print "Testing Seq" -print "===========" +print("") +print("Testing Seq") +print("===========") s = Seq.Seq("TCAAAAGGATGCATCATG", IUPAC.unambiguous_dna) -print str(s) -print len(s) -print s[0] -print s[-1] -print str(s[3:5]) - -print "Reverse using -1 stride:", repr(s[::-1]) - -print "Extract every third nucleotide (slicing with stride 3):" -print repr(s[0::3]) -print repr(s[1::3]) -print repr(s[2::3]) +print(str(s)) +print(len(s)) +print(s[0]) +print(s[-1]) +print(str(s[3:5])) + +print("Reverse using -1 stride: %r" % s[::-1]) + +print("Extract every third nucleotide (slicing with stride 3):") +print(repr(s[0::3])) +print(repr(s[1::3])) +print(repr(s[2::3])) -print s.alphabet.letters +print(s.alphabet.letters) t = Seq.Seq("T", IUPAC.unambiguous_dna) u = s + t -print str(u.alphabet) -print len(u) +print(str(u.alphabet)) +print(len(u)) assert str(s) + "T" == str(u) t = Seq.Seq("T", IUPAC.protein) try: u = s + t except TypeError: - print "expected error, and got it" + print("expected error, and got it") else: - print "huh? ERROR" + print("huh? ERROR") t = Seq.Seq("T", IUPAC.ambiguous_dna) u = s + t -print str(u.alphabet) +print(str(u.alphabet)) from Bio.Seq import MutableSeq import array -print -print "Testing MutableSeq" -print "==================" +print("") +print("Testing MutableSeq") +print("==================") -print "Testing creating MutableSeqs in multiple ways" +print("Testing creating MutableSeqs in multiple ways") string_seq = MutableSeq("TCAAAAGGATGCATCATG", IUPAC.ambiguous_dna) array_seq = MutableSeq(array.array(array_indicator, "TCAAAAGGATGCATCATG"), IUPAC.ambiguous_dna) converted_seq = s.tomutable() for test_seq in [string_seq]: - print repr(test_seq) - print str(test_seq) - print len(test_seq) - print repr(test_seq.toseq()) + print(repr(test_seq)) + print(str(test_seq)) + print(len(test_seq)) + print("%r" % test_seq.toseq()) - print test_seq[0] - print repr(test_seq[1:5]) + print(test_seq[0]) + print("%r" % test_seq[1:5]) test_seq[1:3] = "GAT" - print "Set slice with string:", repr(test_seq) + print("Set slice with string: %r" % test_seq) test_seq[1:3] = test_seq[5:7] - print "Set slice with MutableSeq:", repr(test_seq) + print("Set slice with MutableSeq: %r" % test_seq) test_seq[1:3] = array.array(array_indicator, "GAT") - print "Set slice with array:", repr(test_seq) + print("Set slice with array: %r" % test_seq) test_seq[3] = "G" - print "Set item:", repr(test_seq) + print("Set item: %r" % test_seq) del test_seq[4:5] - print "Delete slice:", repr(test_seq) + print("Delete slice: %r" % test_seq) del test_seq[3] - print "Delete item:", repr(test_seq) + print("Delete item: %r" % test_seq) test_seq.append("C") - print "Append:", repr(test_seq) + print("Append: %r" % test_seq) test_seq.insert(4, "G") - print "Insert:", repr(test_seq) + print("Insert: %r" % test_seq) - print "Pop off the last item:", test_seq.pop() + print("Pop off the last item: %s" % test_seq.pop()) test_seq.remove("G") - print "Removed Gs:", repr(test_seq) + print("Removed Gs: %r" % test_seq) try: test_seq.remove("Z") raise AssertionError("Did not get expected value error.") except ValueError: - print "Expected value error and got it" + print("Expected value error and got it") - print "A count:", test_seq.count("A") - print "A index:", test_seq.index("A") + print("A count: %i" % test_seq.count("A")) + print("A index: %i" % test_seq.index("A")) test_seq.reverse() - print "Reversed Seq:", repr(test_seq) + print("Reversed Seq: %r" % test_seq) - print "Reverse using -1 stride:", repr(test_seq[::-1]) + print("Reverse using -1 stride: %r" % test_seq[::-1]) test_seq.extend("GAT") test_seq.extend(MutableSeq("TTT", IUPAC.ambiguous_dna)) - print "Extended Seq:", repr(test_seq) + print("Extended Seq: %r" % test_seq) del test_seq[4:6:-1] - print "Delete stride slice:", repr(test_seq) + print("Delete stride slice: %r" % test_seq) - print "Extract every third nucleotide (slicing with stride 3):" - print repr(test_seq[0::3]) - print repr(test_seq[1::3]) - print repr(test_seq[2::3]) + print("Extract every third nucleotide (slicing with stride 3):") + print(repr(test_seq[0::3])) + print(repr(test_seq[1::3])) + print(repr(test_seq[2::3])) - print "Setting wobble codon to N (set slice with stride 3):" + print("Setting wobble codon to N (set slice with stride 3):") test_seq[2::3] = "N" * len(test_seq[2::3]) - print repr(test_seq) + print(repr(test_seq)) ########################################################################### -print -print "Testing Seq addition" -print "====================" +print("") +print("Testing Seq addition") +print("====================") dna = [Seq.Seq("ATCG", IUPAC.ambiguous_dna), Seq.Seq("gtca", Alphabet.generic_dna), Seq.MutableSeq("GGTCA", Alphabet.generic_dna), @@ -147,7 +149,7 @@ Seq.MutableSeq("UC-AG", Alphabet.Gapped(Alphabet.generic_rna, "-")), Seq.Seq("U.CAG", Alphabet.Gapped(Alphabet.generic_rna, ".")), "UGCAU"] -nuc = [Seq.Seq("ATCG", Alphabet.generic_nucleotide),"UUUTTTACG"] +nuc = [Seq.Seq("ATCG", Alphabet.generic_nucleotide), "UUUTTTACG"] protein = [Seq.Seq("ATCGPK", IUPAC.protein), Seq.Seq("atcGPK", Alphabet.generic_protein), Seq.Seq("T.CGPK", Alphabet.Gapped(IUPAC.protein, ".")), @@ -167,25 +169,25 @@ try: c=a+b assert str(c) == str(a) + str(b) - except ValueError, e: - print "%s + %s\n-> %s" % (repr(a.alphabet), repr(b.alphabet), str(e)) + except ValueError as e: + print("%s + %s\n-> %s" % (repr(a.alphabet), repr(b.alphabet), str(e))) for a in dna: for b in dna: try: c=a+b assert str(c) == str(a) + str(b) - except ValueError, e: - print "%s + %s\n-> %s" % (repr(a.alphabet), repr(b.alphabet), str(e)) + except ValueError as e: + print("%s + %s\n-> %s" % (repr(a.alphabet), repr(b.alphabet), str(e))) for b in rna: try: c=a+b - assert (isinstance(a,str) or isinstance(b,str)), \ + assert (isinstance(a, str) or isinstance(b, str)), \ "DNA+RNA addition should fail!" except TypeError: pass try: c=b+a - assert (isinstance(a,str) or isinstance(b,str)), \ + assert (isinstance(a, str) or isinstance(b, str)), \ "RNA+DNA addition should fail!" except TypeError: pass @@ -194,12 +196,12 @@ try: c=a+b assert str(c) == str(a) + str(b) - except ValueError, e: - print "%s + %s\n-> %s" % (repr(a.alphabet), repr(b.alphabet), str(e)) + except ValueError as e: + print("%s + %s\n-> %s" % (repr(a.alphabet), repr(b.alphabet), str(e))) for b in nuc+dna+rna: try: c=a+b - assert (isinstance(a,str) or isinstance(b,str)), \ + assert (isinstance(a, str) or isinstance(b, str)), \ "Protein+Nucleotide addition should fail!" except TypeError: pass @@ -211,15 +213,15 @@ for b in protein: try: c=a+b - assert (isinstance(a,str) or isinstance(b,str)), \ + assert (isinstance(a, str) or isinstance(b, str)), \ "Nucleotide+Protein addition should fail!" except TypeError: pass ########################################################################### -print -print "Testing Seq string methods" -print "==========================" +print("") +print("Testing Seq string methods") +print("==========================") for a in dna + rna + nuc + protein: if not isinstance(a, Seq.Seq): continue @@ -238,14 +240,14 @@ test_chars.append(Seq.Seq("A", Alphabet.generic_nucleotide)) if isinstance(alpha, Alphabet.ProteinAlphabet): test_chars.append(Seq.Seq("K", Alphabet.generic_protein)) - test_chars.append(Seq.Seq("K-", Alphabet.Gapped(Alphabet.generic_protein,"-"))) - test_chars.append(Seq.Seq("K@", Alphabet.Gapped(IUPAC.protein,"@"))) + test_chars.append(Seq.Seq("K-", Alphabet.Gapped(Alphabet.generic_protein, "-"))) + test_chars.append(Seq.Seq("K@", Alphabet.Gapped(IUPAC.protein, "@"))) #Setup a clashing alphabet sequence b = Seq.Seq("-", Alphabet.generic_nucleotide) else: b = Seq.Seq("-", Alphabet.generic_protein) try: - print str(a.strip(b)) + print(str(a.strip(b))) assert False, "Alphabet should have clashed!" except TypeError: pass # Good! @@ -256,17 +258,17 @@ assert str(a.lstrip(chars)) == str(a).lstrip(str_chars) assert str(a.rstrip(chars)) == str(a).rstrip(str_chars) assert a.find(chars) == str(a).find(str_chars) - assert a.find(chars,2,-2) == str(a).find(str_chars,2,-2) + assert a.find(chars, 2, -2) == str(a).find(str_chars, 2, -2) assert a.rfind(chars) == str(a).rfind(str_chars) - assert a.rfind(chars,2,-2) == str(a).rfind(str_chars,2,-2) + assert a.rfind(chars, 2, -2) == str(a).rfind(str_chars, 2, -2) assert a.count(chars) == str(a).count(str_chars) - assert a.count(chars,2,-2) == str(a).count(str_chars,2,-2) + assert a.count(chars, 2, -2) == str(a).count(str_chars, 2, -2) #Now check splits assert [str(x) for x in a.split(chars)] \ == str(a).split(str(chars)) assert [str(x) for x in a.rsplit(chars)] \ == str(a).rsplit(str(chars)) - for max_sep in [0,1,2,999]: + for max_sep in [0, 1, 2, 999]: assert [str(x) for x in a.split(chars, max_sep)] \ == str(a).split(str(chars), max_sep) assert [str(x) for x in a.rsplit(chars, max_sep)] \ @@ -274,9 +276,9 @@ del a, alpha, chars, str_chars, test_chars del dna, rna, nuc, protein ########################################################################### -print -print "Checking ambiguous complements" -print "==============================" +print("") +print("Checking ambiguous complements") +print("==============================") #See bug 2380, Bio.Nexus was polluting the dictionary. assert "-" not in ambiguous_dna_values @@ -291,46 +293,46 @@ def sorted_dict(d): """A sorted repr of a dictionary.""" - return "{%s}" % ", ".join("%s: %s" % (repr(k),repr(v)) - for k,v in sorted(d.iteritems())) + return "{%s}" % ", ".join("%s: %s" % (repr(k), repr(v)) + for k, v in sorted(d.items())) -print -print "DNA Ambiguity mapping:", sorted_dict(ambiguous_dna_values) -print "DNA Complement mapping:", sorted_dict(ambiguous_dna_complement) -for ambig_char, values in sorted(ambiguous_dna_values.iteritems()): +print("") +print("DNA Ambiguity mapping: %s" % sorted_dict(ambiguous_dna_values)) +print("DNA Complement mapping: %s" % sorted_dict(ambiguous_dna_complement)) +for ambig_char, values in sorted(ambiguous_dna_values.items()): compl_values = complement(values) - print "%s={%s} --> {%s}=%s" % \ - (ambig_char, values, compl_values, ambiguous_dna_complement[ambig_char]) + print("%s={%s} --> {%s}=%s" % \ + (ambig_char, values, compl_values, ambiguous_dna_complement[ambig_char])) assert set(compl_values) == set(ambiguous_dna_values[ambiguous_dna_complement[ambig_char]]) -print -print "RNA Ambiguity mapping:", sorted_dict(ambiguous_rna_values) -print "RNA Complement mapping:", sorted_dict(ambiguous_rna_complement) -for ambig_char, values in sorted(ambiguous_rna_values.iteritems()): - compl_values = complement(values).replace("T","U") # need to help as no alphabet - print "%s={%s} --> {%s}=%s" % \ - (ambig_char, values, compl_values, ambiguous_rna_complement[ambig_char]) +print("") +print("RNA Ambiguity mapping: %s" % sorted_dict(ambiguous_rna_values)) +print("RNA Complement mapping: %s" % sorted_dict(ambiguous_rna_complement)) +for ambig_char, values in sorted(ambiguous_rna_values.items()): + compl_values = complement(values).replace("T", "U") # need to help as no alphabet + print("%s={%s} --> {%s}=%s" % \ + (ambig_char, values, compl_values, ambiguous_rna_complement[ambig_char])) assert set(compl_values) == set(ambiguous_rna_values[ambiguous_rna_complement[ambig_char]]) -print -print "Reverse complements:" +print("") +print("Reverse complements:") for sequence in [Seq.Seq("".join(sorted(ambiguous_rna_values))), Seq.Seq("".join(sorted(ambiguous_dna_values))), Seq.Seq("".join(sorted(ambiguous_rna_values)), Alphabet.generic_rna), Seq.Seq("".join(sorted(ambiguous_dna_values)), Alphabet.generic_dna), - Seq.Seq("".join(sorted(ambiguous_rna_values)).replace("X",""), IUPAC.IUPACAmbiguousRNA()), - Seq.Seq("".join(sorted(ambiguous_dna_values)).replace("X",""), IUPAC.IUPACAmbiguousDNA()), + Seq.Seq("".join(sorted(ambiguous_rna_values)).replace("X", ""), IUPAC.IUPACAmbiguousRNA()), + Seq.Seq("".join(sorted(ambiguous_dna_values)).replace("X", ""), IUPAC.IUPACAmbiguousDNA()), Seq.Seq("AWGAARCKG")]: # Note no U or T - print "%s -> %s" \ - % (repr(sequence), repr(Seq.reverse_complement(sequence))) + print("%s -> %s" \ + % (repr(sequence), repr(Seq.reverse_complement(sequence)))) assert str(sequence) \ == str(Seq.reverse_complement(Seq.reverse_complement(sequence))), \ "Dobule reverse complement didn't preserve the sequence!" -print +print("") ########################################################################### -test_seqs = [s,t,u, +test_seqs = [s, t, u, Seq.Seq("ATGAAACTG"), "ATGAAACtg", #TODO - Fix ambiguous translation @@ -348,7 +350,7 @@ Seq.Seq("ATGAAA-CTG", Alphabet.Gapped(IUPAC.unambiguous_dna)), Seq.Seq("ATGAAACTGWN", IUPAC.ambiguous_dna), Seq.Seq("AUGAAACUG", Alphabet.generic_rna), - Seq.Seq("AUGAAA==CUG", Alphabet.Gapped(Alphabet.generic_rna,"=")), + Seq.Seq("AUGAAA==CUG", Alphabet.Gapped(Alphabet.generic_rna, "=")), Seq.Seq("AUGAAACUG", IUPAC.unambiguous_rna), Seq.Seq("AUGAAACUGWN", IUPAC.ambiguous_rna), Seq.Seq("ATGAAACTG", Alphabet.generic_nucleotide), @@ -373,19 +375,19 @@ if "T" in str(nucleotide_seq).upper(): assert not isinstance(nucleotide_seq.alphabet, Alphabet.RNAAlphabet) -print -print "Transcribe DNA into RNA" -print "=======================" +print("") +print("Transcribe DNA into RNA") +print("=======================") for nucleotide_seq in test_seqs: try: expected = Seq.transcribe(nucleotide_seq) - assert str(nucleotide_seq).replace("t","u").replace("T","U") == str(expected) - print "%s -> %s" \ - % (repr(nucleotide_seq) , repr(expected)) - except ValueError, e: + assert str(nucleotide_seq).replace("t", "u").replace("T", "U") == str(expected) + print("%s -> %s" \ + % (repr(nucleotide_seq), repr(expected))) + except ValueError as e: expected = None - print "%s -> %s" \ - % (repr(nucleotide_seq) , str(e)) + print("%s -> %s" \ + % (repr(nucleotide_seq), str(e))) #Now test the Seq object's method if isinstance(nucleotide_seq, Seq.Seq): try: @@ -395,31 +397,31 @@ for s in protein_seqs: try: - print Seq.transcribe(s) + print(Seq.transcribe(s)) assert False, "Transcription shouldn't work on a protein!" except ValueError: pass if not isinstance(s, Seq.Seq): continue # Only Seq has this method try: - print s.transcribe() + print(s.transcribe()) assert False, "Transcription shouldn't work on a protein!" except ValueError: pass -print -print "Back-transcribe RNA into DNA" -print "============================" +print("") +print("Back-transcribe RNA into DNA") +print("============================") for nucleotide_seq in test_seqs: try: expected = Seq.back_transcribe(nucleotide_seq) - assert str(nucleotide_seq).replace("u","t").replace("U","T") == str(expected) - print "%s -> %s" \ - % (repr(nucleotide_seq) , repr(expected)) - except ValueError, e: + assert str(nucleotide_seq).replace("u", "t").replace("U", "T") == str(expected) + print("%s -> %s" \ + % (repr(nucleotide_seq), repr(expected))) + except ValueError as e: expected = None - print "%s -> %s" \ - % (repr(nucleotide_seq) , str(e)) + print("%s -> %s" \ + % (repr(nucleotide_seq), str(e))) #Now test the Seq object's method if isinstance(nucleotide_seq, Seq.Seq): try: @@ -429,30 +431,30 @@ for s in protein_seqs: try: - print Seq.back_transcribe(s) + print(Seq.back_transcribe(s)) assert False, "Back transcription shouldn't work on a protein!" except ValueError: pass if not isinstance(s, Seq.Seq): continue # Only Seq has this method try: - print s.back_transcribe() + print(s.back_transcribe()) assert False, "Back transcription shouldn't work on a protein!" except ValueError: pass -print -print "Reverse Complement" -print "==================" +print("") +print("Reverse Complement") +print("==================") for nucleotide_seq in test_seqs: try: expected = Seq.reverse_complement(nucleotide_seq) - print "%s\n-> %s" \ - % (repr(nucleotide_seq) , repr(expected)) - except ValueError, e: + print("%s\n-> %s" \ + % (repr(nucleotide_seq), repr(expected))) + except ValueError as e: expected = None - print "%s\n-> %s" \ - % (repr(nucleotide_seq) , str(e)) + print("%s\n-> %s" \ + % (repr(nucleotide_seq), str(e))) #Now test the Seq object's method #(The MutualSeq object acts in place) if isinstance(nucleotide_seq, Seq.Seq): @@ -464,34 +466,34 @@ for s in protein_seqs: try: - print Seq.reverse_complement(s) + print(Seq.reverse_complement(s)) assert False, "Reverse complement shouldn't work on a protein!" except ValueError: pass #Note that these methods are "in place" for the MutableSeq: try: - print s.complement() + print(s.complement()) assert False, "Complement shouldn't work on a protein!" except ValueError: pass try: - print s.reverse_complement() + print(s.reverse_complement()) assert False, "Reverse complement shouldn't work on a protein!" except ValueError: pass -print -print "Translating" -print "===========" +print("") +print("Translating") +print("===========") for nucleotide_seq in test_seqs: #Truncate to a whole number of codons to avoid translation warning nucleotide_seq = nucleotide_seq[:3 * (len(nucleotide_seq) // 3)] try: expected = Seq.translate(nucleotide_seq) - print "%s\n-> %s" % (repr(nucleotide_seq), repr(expected)) - except (ValueError, TranslationError), e: + print("%s\n-> %s" % (repr(nucleotide_seq), repr(expected))) + except (ValueError, TranslationError) as e: expected = None - print "%s\n-> %s" % (repr(nucleotide_seq), str(e)) + print("%s\n-> %s" % (repr(nucleotide_seq), str(e))) #Now test the Seq object's method if isinstance(nucleotide_seq, Seq.Seq): try: @@ -501,7 +503,7 @@ #Now check translate(..., to_stop=True) try: short = Seq.translate(nucleotide_seq, to_stop=True) - except (ValueError, TranslationError), e: + except (ValueError, TranslationError) as e: short = None if expected is not None: assert short is not None @@ -514,14 +516,14 @@ for s in protein_seqs: try: - print Seq.translate(s) + print(Seq.translate(s)) assert False, "Translation shouldn't work on a protein!" except ValueError: pass if not isinstance(s, Seq.Seq): continue # Only Seq has this method try: - print s.translate() + print(s.translate()) assert False, "Translation shouldn't work on a protein!" except ValueError: pass @@ -548,7 +550,7 @@ for s in protein_seqs: try: - print Seq.translate(s) + print(Seq.translate(s)) assert False, "Shouldn't work on a protein!" except ValueError: pass @@ -570,7 +572,7 @@ for codon in ["TA?", "N-N", "AC_", "Ac_"]: try: - print Seq.translate(codon) + print(Seq.translate(codon)) assert "Translating %s should have failed" % repr(codon) except TranslationError: pass @@ -600,34 +602,34 @@ assert values == set(t) #TODO - Use the Bio.Data.IUPACData module for the #ambiguous protein mappings? -del t,c1,c2,c3,ambig +del t, c1, c2, c3, ambig -print -print "Seq's .complement() method" -print "==========================" +print("") +print("Seq's .complement() method") +print("==========================") for nucleotide_seq in test_seqs: if isinstance(nucleotide_seq, Seq.Seq): try: - print "%s -> %s" \ - % (repr(nucleotide_seq) , repr(nucleotide_seq.complement())) + print("%s -> %s" \ + % (repr(nucleotide_seq), repr(nucleotide_seq.complement()))) assert str(nucleotide_seq.complement()) \ == str(Seq.reverse_complement(nucleotide_seq))[::-1], \ "Bio.Seq function and method disagree!" - except ValueError, e: - print "%s -> %s" \ - % (repr(nucleotide_seq) , str(e)) - -print -print "Seq's .reverse_complement() method" -print "==================================" + except ValueError as e: + print("%s -> %s" \ + % (repr(nucleotide_seq), str(e))) + +print("") +print("Seq's .reverse_complement() method") +print("==================================") for nucleotide_seq in test_seqs: if isinstance(nucleotide_seq, Seq.Seq): try: - print "%s -> %s" \ - % (repr(nucleotide_seq) , repr(nucleotide_seq.reverse_complement())) + print("%s -> %s" \ + % (repr(nucleotide_seq), repr(nucleotide_seq.reverse_complement()))) assert str(nucleotide_seq.reverse_complement()) \ == str(Seq.reverse_complement(nucleotide_seq)), \ "Bio.Seq function and method disagree!" - except ValueError, e: - print "%s -> %s" \ - % (repr(nucleotide_seq) , str(e)) + except ValueError as e: + print("%s -> %s" \ + % (repr(nucleotide_seq), str(e))) diff -Nru python-biopython-1.62/Tests/test_translate.py python-biopython-1.63/Tests/test_translate.py --- python-biopython-1.62/Tests/test_translate.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_translate.py 2013-12-05 14:10:43.000000000 +0000 @@ -1,6 +1,8 @@ # Make sure the translation functions work. # Start simple - unambiguous DNA to unambiguous protein +from __future__ import print_function + from Bio import Seq from Bio import Alphabet from Bio.Alphabet import IUPAC @@ -59,59 +61,57 @@ # use the standard table s = "TCAAAAAGGTGCATCTAGATG" -print "Starting with", s +print("Starting with %s" % s) dna = Seq.Seq(s, IUPAC.unambiguous_dna) protein = dna.translate(to_stop=True) assert isinstance(protein.alphabet, IUPAC.IUPACProtein) -print len(protein), "ungapped residues translated" +print("%i ungapped residues translated" % len(protein)) gapped_protein = dna.translate() assert isinstance(gapped_protein.alphabet, Alphabet.HasStopCodon) -print str(protein) +print(str(protein)) -print len(gapped_protein), "residues translated, including gaps" -print str(gapped_protein) +print("%i residues translated, including gaps" % len(gapped_protein)) +print(str(gapped_protein)) # This has "AGG" as a stop codon p2 = dna.translate(table=2, to_stop=True) -print len(p2), "SGC1 has a stop codon" -print str(p2) +print("%i SGC1 has a stop codon" % len(p2)) +print(str(p2)) p2 = dna.translate(table=2) -print "Actually, there are", p2.count("*"), "stops." -print str(p2) +print("Actually, there are %i stops." % p2.count("*")) +print(str(p2)) # Make sure I can change the stop character p2 = dna.translate(table=2, stop_symbol="+") -print "Yep,", p2.count("+"), "stops." -print str(p2) +print("Yep, %i stops." % p2.count("+")) +print(str(p2)) # Some of the same things, with RNA # (The code is the same, so I'm not doing all of the tests.) rna = Seq.Seq(s.replace("T", "U"), IUPAC.unambiguous_rna) -print "RNA translation ...", protein_from_rna = rna.translate(to_stop=True) assert protein.alphabet is protein_from_rna.alphabet assert str(protein) == str(protein_from_rna) -print "works." +print("RNA translation ... works.") -print "RNA translation to stop ...", gapped_protein_from_rna = rna.translate() assert len(gapped_protein) == len(gapped_protein_from_rna) assert str(gapped_protein) == str(gapped_protein_from_rna) -print "works." +print("RNA translation to stop ... works.") # some tests for "by name" # How about some forward ambiguity? -print "Forward ambiguous" +print("Forward ambiguous") s = "RATGATTARAATYTA" # B D * N L dna = Seq.Seq(s, IUPAC.ambiguous_dna) protein = dna.translate('Vertebrate Mitochondrial') -print str(protein) +print(str(protein)) stop_protein = dna.translate('SGC1', to_stop=True) -print str(stop_protein) +print(str(stop_protein)) # XXX (Backwards with ambiguity code is unfinished!) diff -Nru python-biopython-1.62/Tests/test_trie.py python-biopython-1.63/Tests/test_trie.py --- python-biopython-1.62/Tests/test_trie.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/Tests/test_trie.py 2013-12-05 14:10:43.000000000 +0000 @@ -17,6 +17,7 @@ message = "Could not import Bio.trie, check C code was compiled." raise MissingPythonDependencyError(message) +from Bio._py3k import StringIO class TestTrie(unittest.TestCase): @@ -43,21 +44,19 @@ trieobj["he"] = 7 trieobj["hej"] = 9 trieobj["foo"] = "bar" - k = trieobj.keys() - k.sort() + k = sorted(trieobj.keys()) self.assertEqual(k, ["foo", "he", "hej", "hello"]) self.assertEqual(trieobj["hello"], 5) self.assertEqual(trieobj.get("bye"), None) - self.assertEqual(trieobj.has_key("hello"), True) - self.assertEqual(trieobj.has_key("he"), True) - self.assertEqual(trieobj.has_key("bye"), False) - self.assertEqual(trieobj.has_prefix("h"), True) - self.assertEqual(trieobj.has_prefix("hel"), True) - self.assertEqual(trieobj.has_prefix("foa"), False) - self.assertEqual(trieobj.has_prefix("hello world"), False) + self.assertTrue("hello" in trieobj) + self.assertTrue("he" in trieobj) + self.assertFalse("bye" in trieobj) + self.assertTrue(trieobj.has_prefix("h")) + self.assertTrue(trieobj.has_prefix("hel")) + self.assertFalse(trieobj.has_prefix("foa")) + self.assertFalse(trieobj.has_prefix("hello world")) self.assertEqual(len(trieobj), 4) - k = trieobj.with_prefix("he") - k.sort() + k = sorted(trieobj.with_prefix("he")) self.assertEqual(k, ["he", "hej", "hello"]) k = trieobj.with_prefix("l") self.assertEqual(k, []) @@ -67,12 +66,11 @@ self.assertEqual(k, []) def test_save(self): - import StringIO trieobj = trie.trie() trieobj["foo"] = 1 - k = trieobj.keys() + k = list(trieobj.keys()) self.assertEqual(k, ["foo"]) - v = trieobj.values() + v = list(trieobj.values()) self.assertEqual(v, [1]) self.assertEqual(trieobj.get("bar", 99), 99) trieobj["hello"] = '55a' @@ -80,8 +78,7 @@ self.assertEqual(trieobj.get_approximate("foo", 1), [("foo", 1, 0)]) self.assertEqual(trieobj.get_approximate("foa", 0), []) self.assertEqual(trieobj.get_approximate("foa", 1), [("foo", 1, 1)]) - x = trieobj.get_approximate("foa", 2) - x.sort() + x = sorted(trieobj.get_approximate("foa", 2)) self.assertEqual(x, [("foo", 1, 1), ("foo", 1, 2), ("foo", 1, 2)]) # foo foo- foo- # foa f-oa fo-a @@ -92,14 +89,13 @@ y = {} for z in x: y[z] = y.get(z, 0) + 1 - x = y.items() - x.sort() - self.assertEqual(x,[(('foo', 1, 0), 1), (('hello', '55a', 4), 6)]) - h = StringIO.StringIO() + x = sorted(y.items()) + self.assertEqual(x, [(('foo', 1, 0), 1), (('hello', '55a', 4), 6)]) + h = StringIO() trie.save(h, trieobj) h.seek(0) trieobj = trie.load(h) - k = trieobj.keys() + k = list(trieobj.keys()) self.assertTrue("foo" in k) self.assertTrue("hello" in k) self.assertEqual(repr(trieobj["foo"]), '1') @@ -145,21 +141,16 @@ trieobj["foo"] = "bar" trieobj["wor"] = "ld" self.assertEqual(triefind.match("hello world!", trieobj), "hello") - k = triefind.match_all("hello world!", trieobj) - k.sort() + k = sorted(triefind.match_all("hello world!", trieobj)) self.assertEqual(k, ["he", "hello"]) - k = triefind.find("hello world!", trieobj) - k.sort() + k = sorted(triefind.find("hello world!", trieobj)) self.assertEqual(k, [("he", 0, 2), ("hello", 0, 5), ("wor", 6, 9)]) - k = triefind.find_words("hello world!", trieobj) - k.sort() + k = sorted(triefind.find_words("hello world!", trieobj)) self.assertEqual(k, [("hello", 0, 5)]) trieobj["world"] = "full" - k = triefind.find("hello world!", trieobj) - k.sort() + k = sorted(triefind.find("hello world!", trieobj)) self.assertEqual(k, [("he", 0, 2), ("hello", 0, 5), ("wor", 6, 9), ("world", 6, 11)]) - k = triefind.find_words("hello world!", trieobj) - k.sort() + k = sorted(triefind.find_words("hello world!", trieobj)) self.assertEqual(k, [("hello", 0, 5), ("world", 6, 11)]) diff -Nru python-biopython-1.62/debian/changelog python-biopython-1.63/debian/changelog --- python-biopython-1.62/debian/changelog 2013-09-15 19:00:17.000000000 +0000 +++ python-biopython-1.63/debian/changelog 2014-01-09 14:38:26.000000000 +0000 @@ -1,3 +1,9 @@ +python-biopython (1.63-1) unstable; urgency=low + + * New upstream release + + -- Philipp Benner Thu, 09 Jan 2014 15:38:19 +0100 + python-biopython (1.62-1) unstable; urgency=low * New upstream release diff -Nru python-biopython-1.62/do2to3.py python-biopython-1.63/do2to3.py --- python-biopython-1.62/do2to3.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/do2to3.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,181 +0,0 @@ -"""Helper script for building and installing Biopython on Python 3. - -Note that we can't just use distutils.command.build_py function build_py_2to3 -in setup.py since (as far as I can see) that does not allow us to alter the -2to3 options. In particular, we need to turn off the long fixer for some of -our files. - -This code is intended to be called from setup.py automatically under Python 3, -and is not intended for end users. The basic idea follows the approach taken -by NumPy with their setup.py file calling tools/py3tool.py to do the 2to3 -conversion automatically. - -This calls the lib2to3 library functions to convert the Biopython source code -from Python 2 to Python 3, tracking changes to files so that unchanged files -need not be reconverted making development much easier (i.e. if you edit one -source file, doing 'python setup.py install' will only reconvert the one file). -This is done by the last modified date stamps (which will be updated by git if -you switch branches). - -NOTE - This is intended to be run under Python 3 (not under Python 2), but -care has been taken to make it run under Python 2 enough to give a clear error -message. In particular, this meant avoiding with statements etc. -""" -import sys -if sys.version_info[0] < 3: - sys.stderr.write("Please run this under Python 3\n") - sys.exit(1) - -import shutil -import os -import lib2to3.main -from io import StringIO - - -def run2to3(filenames): - stderr = sys.stderr - handle = StringIO() - try: - #Want to capture stderr (otherwise too noisy) - sys.stderr = handle - while filenames: - filename = filenames.pop(0) - print("Converting %s" % filename) - #TODO - Configurable options per file? - args = ["--nofix=long", "--no-diffs", "-n", "-w"] - e = lib2to3.main.main("lib2to3.fixes", args + [filename]) - if e != 0: - sys.stderr = stderr - sys.stderr.write(handle.getvalue()) - os.remove(filename) # Don't want a half edited file! - raise RuntimeError("Error %i from 2to3 on %s" - % (e, filename)) - #And again for any doctests, - e = lib2to3.main.main("lib2to3.fixes", args + ["-d", filename]) - if e != 0: - sys.stderr = stderr - sys.stderr.write(handle.getvalue()) - os.remove(filename) # Don't want a half edited file! - raise RuntimeError("Error %i from 2to3 (doctests) on %s" - % (e, filename)) - except KeyboardInterrupt: - sys.stderr = stderr - sys.stderr.write("Interrupted during %s\n" % filename) - os.remove(filename) # Don't want a half edited file! - for filename in filenames: - if os.path.isfile(filename): - #Don't want uncoverted files left behind: - os.remove(filename) - sys.exit(1) - finally: - #Restore stderr - sys.stderr = stderr - - -def do_update(py2folder, py3folder, verbose=False): - if not os.path.isdir(py2folder): - raise ValueError("Python 2 folder %r does not exist" % py2folder) - if not os.path.isdir(py3folder): - os.mkdir(py3folder) - #First remove any files from the 3to2 conversion which no - #longer existing the Python 2 origin (only expected to happen - #on a development machine). - for dirpath, dirnames, filenames in os.walk(py3folder): - relpath = os.path.relpath(dirpath, py3folder) - for d in dirnames: - new = os.path.join(py3folder, relpath, d) - old = os.path.join(py2folder, relpath, d) - if not os.path.isdir(old): - print("Removing %s" % new) - shutil.rmtree(new) - for f in filenames: - new = os.path.join(py3folder, relpath, f) - old = os.path.join(py2folder, relpath, f) - if not os.path.isfile(old): - print("Removing %s" % new) - os.remove(new) - #Check all the Python 2 original files have been copied/converted - #Note we need to do all the conversions *after* copying the files - #so that 2to3 can detect local imports successfully. - to_convert = [] - for dirpath, dirnames, filenames in os.walk(py2folder): - if verbose: - print("Processing %s" % dirpath) - relpath = os.path.relpath(dirpath, py2folder) - #This is just to give cleaner filenames - if relpath[:2] == "/.": - relpath = relpath[2:] - elif relpath == ".": - relpath = "" - for d in dirnames: - new = os.path.join(py3folder, relpath, d) - if not os.path.isdir(new): - os.mkdir(new) - for f in filenames: - if f.startswith("."): - #Ignore hidden files - continue - elif f.endswith("~") or f.endswith(".bak") \ - or f.endswith(".swp"): - #Ignore backup files - continue - elif f.endswith(".pyc") or f.endswith("$py.class"): - #Ignore compiled python - continue - old = os.path.join(py2folder, relpath, f) - new = os.path.join(py3folder, relpath, f) - #The filesystem can (in Linux) record nanoseconds, but - #when copying only microsecond accuracy is used. - #See http://bugs.python.org/issue10148 - #Compare modified times down to milliseconds only. In theory - #might able to use times down to microseconds (10^-6), but - #that doesn't work on this Windows machine I'm testing on. - if os.path.isfile(new) and\ - round(os.stat(new).st_mtime * 1000) >= \ - round(os.stat(old).st_mtime * 1000): - if verbose: - print("Current: %s" % new) - continue - #Python, C code, data files, etc - copy with date stamp etc - shutil.copy2(old, new) - assert abs(os.stat(old).st_mtime - os.stat(new).st_mtime) < 0.0001, \ - "Modified time not copied! %0.8f vs %0.8f, diff %f" \ - % (os.stat(old).st_mtime, os.stat(new).st_mtime, - abs(os.stat(old).st_mtime - os.stat(new).st_mtime)) - if f.endswith(".py"): - #Also run 2to3 on it - to_convert.append(new) - if verbose: - print("Will convert %s" % new) - else: - if verbose: - print("Updated %s" % new) - if to_convert: - print("Have %i python files to convert" % len(to_convert)) - run2to3(to_convert) - - -def main(python2_source, python3_source, - children=["Bio", "BioSQL", "Tests", "Scripts", "Doc"]): - #Note want to use different folders for Python 3.1, 3.2, etc - #since the 2to3 libraries have changed so the conversion - #may differ slightly. - print("The 2to3 library will be called automatically now,") - print("and the converted files cached under %s" % python3_source) - if not os.path.isdir("build"): - os.mkdir("build") - if not os.path.isdir(python3_source): - os.mkdir(python3_source) - for child in children: - print("Processing %s" % child) - do_update(os.path.join(python2_source, child), - os.path.join(python3_source, child)) - print("Python 2to3 processing done.") - -if __name__ == "__main__": - python2_source = "." - python3_source = "build/py%i.%i" % sys.version_info[:2] - children = ["Bio", "BioSQL", "Tests", "Scripts", "Doc"] - if len(sys.argv) > 1: - children = [x for x in sys.argv[1:] if x in children] - main(python2_source, python3_source, children) diff -Nru python-biopython-1.62/setup.py python-biopython-1.63/setup.py --- python-biopython-1.62/setup.py 2013-08-28 21:34:04.000000000 +0000 +++ python-biopython-1.63/setup.py 2013-12-05 14:10:43.000000000 +0000 @@ -21,6 +21,8 @@ http://biopython.org/wiki/Mailing_lists """ +from __future__ import print_function + import sys import os import shutil @@ -60,7 +62,7 @@ default_str = 'n' while True: - print ("%s %s:" % (question, option_str)) + print("%s %s:" % (question, option_str)) if sys.version_info[0] == 3: response = input().lower() else: @@ -69,50 +71,19 @@ response = default_str if response[0] in ['y', 'n']: break - print ("Please answer y or n.") + print("Please answer y or n.") return response[0] == 'y' # Make sure we have the right Python version. -if sys.version_info[:2] < (2, 5): - print("Biopython requires Python 2.5 or better (but not Python 3 " - "yet). Python %d.%d detected" % sys.version_info[:2]) - sys.exit(-1) -elif sys.version_info[:2] == (2, 5): - print("WARNING - Biopython is dropping support for Python 2.5 after this release") -elif sys.version_info[:2] == (3, 0): - print("Biopython will not work on Python 3.0, please try Python 3.3 or later") +if sys.version_info[:2] < (2, 6): + print("Biopython requires Python 2.6 or 2.7 (or Python 3.3 or later). " + "Python %d.%d detected" % sys.version_info[:2]) + sys.exit(1) +elif sys.version_info[0] == 3 and sys.version_info[:2] < (3, 3): + print("Biopython requires Python 3.3 or later (or Python 2.6 or 2.7). " + "Python %d.%d detected" % sys.version_info[:2]) sys.exit(1) -elif sys.version_info[0] == 3: - if sys.version_info[:2] < (3, 3): - #TODO - Turn off old buildbots/travis and make this an error? - print("WARNING - For Python 3, we strongly recommend Python 3.3 or later.") - if sys.version_info == (3, 3, 1) and sys.implementation == "cpython": - print("WARNING - Rather than Python 3.3.1, we recommend Python 3.3.0, or 3.3.2, or later.") - import do2to3 - python3_source = "build/py%i.%i" % sys.version_info[:2] - if "clean" in sys.argv: - if os.path.isdir(python3_source): - shutil.rmtree(python3_source) - del python3_source # so we don't try to change to it below - else: - if not os.path.isdir("build"): - os.mkdir("build") - do2to3.main(".", python3_source) - # Ugly hack to make pip work with Python 3, from 2to3 numpy setup: - # https://github.com/numpy/numpy/blob/bb726ca19f434f5055c0efceefe48d89469fcbbe/setup.py#L172 - # Explanation: pip messes with __file__ which interacts badly with the - # change in directory due to the 2to3 conversion. Therefore we restore - # __file__ to what it would have been otherwise. - local_path = os.path.dirname(os.path.abspath(sys.argv[0])) - global __file__ - __file__ = os.path.join(os.curdir, os.path.basename(__file__)) - if '--egg-base' in sys.argv: - # Change pip-egg-info entry to absolute path, so pip can find it - # after changing directory. - idx = sys.argv.index('--egg-base') - if sys.argv[idx + 1] == 'pip-egg-info': - sys.argv[idx + 1] = os.path.join(local_path, 'pip-egg-info') def check_dependencies_once(): @@ -171,7 +142,7 @@ if is_ironpython(): return True # We're ignoring NumPy under IronPython (for now) - print (""" + print(""" Numerical Python (NumPy) is not installed. This package is required for many Biopython features. Please install @@ -179,7 +150,7 @@ anything dependent on NumPy will not work. If you do this, and later install NumPy, you should then re-install Biopython. -You can find NumPy at http://numpy.scipy.org +You can find NumPy at http://www.numpy.org """) # exit automatically if running as part of some script # (e.g. PyPM, ActiveState's Python Package Manager) @@ -334,7 +305,6 @@ 'Bio.PopGen.GenePop', 'Bio.PopGen.SimCoal', 'Bio.Restriction', - 'Bio.Restriction._Update', 'Bio.SCOP', 'Bio.SearchIO', 'Bio.SearchIO._model',