rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
self.assertAlmostEqual(markov_model.p_transition[0][0], 0.02460365, 4) self.assertAlmostEqual(markov_model.p_transition[0][1], 0.97539634, 4) self.assertAlmostEqual(markov_model.p_transition[1][0], 1.0, 4) self.assertAlmostEqual(markov_model.p_transition[1][1], 0.0, 4) | self.assertAlmostEqual(markov_model.p_transition[0][0], 0.02460365, places=4) self.assertAlmostEqual(markov_model.p_transition[0][1], 0.97539634, places=4) self.assertAlmostEqual(markov_model.p_transition[1][0], 1.0, places=4) self.assertAlmostEqual(markov_model.p_transition[1][1], 0.0, places=4) | def test_baum_welch(self): states = ["CP", "IP"] alphabet = ["cola", "ice_t", "lem"] outputs = [ (2, 1, 0) ] p_initial = [1.0, 0.0000001] p_transition = [[0.7, 0.3], [0.5, 0.5]] p_emission = [[0.6, 0.1, 0.3], [0.1, 0.7, 0.2]] N, M = len(states), len(alphabet) x = MarkovModel._baum_welch(N, M, outputs, p_initial=p_initi... |
if organism_element.text: sci_name=organism_element.text if (organism_element.attrib['type']== 'common') and not sci_name: if organism_element.text: com_name=organism_element.text if (sci_name == '') and (com_name == ''): | sci_name=organism_element.text elif organism_element.attrib['type']== 'common': com_name=organism_element.text else: | def _parse_organism(element): com_name=sci_name='' for organism_element in element.getchildren(): if organism_element.tag==NS + 'name': if organism_element.attrib['type']== 'scientific': if organism_element.text: sci_name=organism_element.text if (organism_element.attrib['type']== 'common') and not sci_name: if organis... |
if file_handle == filename == none: | if file_handle == filename == None: | def getAstralDomainsFromFile(self,filename=None,file_handle=None): """Get the scop domains from a file containing a list of sids""" if file_handle == filename == none: raise RuntimeError("You must provide a filename or handle") if not file_handle: file_handle = open(filename) doms = [] while 1: line = file_handle.readl... |
if __debug__: warnings.warn("WARNING: Chain %s is discontinuous at line %i." % (chain_id, self.line_counter), PDBConstructionWarning) | warnings.warn("WARNING: Chain %s is discontinuous at line %i." % (chain_id, self.line_counter), PDBConstructionWarning) | def init_chain(self, chain_id): """Initiate a new Chain object with given id. |
if __debug__: warnings.warn("WARNING: Residue ('%s', %i, '%s') " "redefined at line %i." % (field, resseq, icode, self.line_counter), PDBConstructionWarning) | warnings.warn("WARNING: Residue ('%s', %i, '%s') " "redefined at line %i." % (field, resseq, icode, self.line_counter), PDBConstructionWarning) | def init_residue(self, resname, field, resseq, icode): """ Initiate a new Residue object. |
if __debug__: warnings.warn("WARNING: atom names %s and %s differ " "only in spaces at line %i." % (duplicate_fullname, fullname, self.line_counter), PDBConstructionWarning) | warnings.warn("WARNING: atom names %s and %s differ " "only in spaces at line %i." % (duplicate_fullname, fullname, self.line_counter), PDBConstructionWarning) | def init_atom(self, name, coord, b_factor, occupancy, altloc, fullname, serial_number=None, element=None): """ Initiate a new Atom object. |
if __debug__: warnings.warn("WARNING: disordered atom found " "with blank altloc before line %i.\n" % self.line_counter, PDBConstructionWarning) | warnings.warn("WARNING: disordered atom found " "with blank altloc before line %i.\n" % self.line_counter, PDBConstructionWarning) | def init_atom(self, name, coord, b_factor, occupancy, altloc, fullname, serial_number=None, element=None): """ Initiate a new Atom object. |
class PDBExceptionTest(unittest.TestCase): def test_strict(self): """Check error: Parse a flawed PDB file in strict mode.""" warnings.resetwarnings() parser = PDBParser(PERMISSIVE=False) self.assertRaises(PDBConstructionException, parser.get_structure, "example", "PDB/a_structure.pdb") def test_bad_xyz(self): """Ch... | def get_coord(self): return self.coord | |
self.assertAlmostEqual(result[0], -29.18363571, 5) self.assertAlmostEqual(result[1], -38.3365097, 5) self.assertAlmostEqual(result[2], -29.17756271, 5) self.assertAlmostEqual(result[3], -38.04542542, 5) self.assertAlmostEqual(result[4], -20.3014183, 5) self.assertAlmostEqual(result[5], -25.18009186, 5) | self.assertAlmostEqual(result[0], -29.18363571, places=5) self.assertAlmostEqual(result[1], -38.3365097, places=5) self.assertAlmostEqual(result[2], -29.17756271, places=5) self.assertAlmostEqual(result[3], -38.04542542, places=5) self.assertAlmostEqual(result[4], -20.3014183, places=5) self.assertAlmostEqual(result[5]... | def test_simple(self): """Test if Motif PWM scoring works.""" result = self.m.scanPWM(self.s) self.assertEqual(6, len(result)) # The fast C-code in Bio/Motif/_pwm.c stores all results as 32-bit # floats; the slower Python code in Bio/Motif/_Motif.py uses 64-bit # doubles. The C-code and Python code results will therefo... |
raise TypeError("Need a file handle, not a string (i.e. not a filename)") | raise TypeError(\ "Need a file handle, not a string (i.e. not a filename)") | def write(sequences, handle, format): """Write complete set of sequences to a file. - sequences - A list (or iterator) of SeqRecord objects. - handle - File handle object to write to. - format - lower case string describing the file format to write. You should close the handle after calling this function. Retu... |
if isinstance(sequences,SeqRecord): raise ValueError("Use a SeqRecord list/iterator, not just a single SeqRecord") | if isinstance(sequences, SeqRecord): raise ValueError(\ "Use a SeqRecord list/iterator, not just a single SeqRecord") | def write(sequences, handle, format): """Write complete set of sequences to a file. - sequences - A list (or iterator) of SeqRecord objects. - handle - File handle object to write to. - format - lower case string describing the file format to write. You should close the handle after calling this function. Retu... |
raise TypeError("Need a file handle, not a string (i.e. not a filename)") | raise TypeError(\ "Need a file handle, not a string (i.e. not a filename)") | def parse(handle, format, alphabet=None): r"""Turns a sequence file into an iterator returning SeqRecords. - handle - handle to the file. - format - lower case string describing the file format. - alphabet - optional Alphabet object, useful when the sequence type cannot be automatically inferred from the file itse... |
from Bio.Alphabet import generic_alphabet | from Bio.Alphabet import Gapped | def to_alignment(sequences, alphabet=None, strict=True): """Returns a multiple sequence alignment (OBSOLETE). - sequences -An iterator that returns SeqRecord objects, or simply a list of SeqRecord objects. All the record sequences must be the same length. - alphabet - Optional alphabet. Stongly recommended. - strict... |
alphabet = _consensus_alphabet([rec.seq.alphabet for rec in sequences \ | alphabet = _consensus_alphabet([rec.seq.alphabet \ for rec in sequences \ | def to_alignment(sequences, alphabet=None, strict=True): """Returns a multiple sequence alignment (OBSOLETE). - sequences -An iterator that returns SeqRecord objects, or simply a list of SeqRecord objects. All the record sequences must be the same length. - alphabet - Optional alphabet. Stongly recommended. - strict... |
if not (isinstance(alphabet, Alphabet) or isinstance(alphabet, AlphabetEncoder)): | if not (isinstance(alphabet, Alphabet) \ or isinstance(alphabet, AlphabetEncoder)): | def to_alignment(sequences, alphabet=None, strict=True): """Returns a multiple sequence alignment (OBSOLETE). - sequences -An iterator that returns SeqRecord objects, or simply a list of SeqRecord objects. All the record sequences must be the same length. - alphabet - Optional alphabet. Stongly recommended. - strict... |
raise ValueError("Sequence has a gapped alphabet, alignment does not") | raise ValueError(\ "Sequence has a gapped alphabet, alignment does not") | def to_alignment(sequences, alphabet=None, strict=True): """Returns a multiple sequence alignment (OBSOLETE). - sequences -An iterator that returns SeqRecord objects, or simply a list of SeqRecord objects. All the record sequences must be the same length. - alphabet - Optional alphabet. Stongly recommended. - strict... |
raise ValueError("Sequence gap characters != alignment gap char") | raise ValueError("Sequence gap char != alignment gap char") | def to_alignment(sequences, alphabet=None, strict=True): """Returns a multiple sequence alignment (OBSOLETE). - sequences -An iterator that returns SeqRecord objects, or simply a list of SeqRecord objects. All the record sequences must be the same length. - alphabet - Optional alphabet. Stongly recommended. - strict... |
raise TypeError("SeqRecord (id=%s) has None for its sequence." % record.id) | raise TypeError(\ "SeqRecord (id=%s) has None for its sequence." % record.id) | def to_alignment(sequences, alphabet=None, strict=True): """Returns a multiple sequence alignment (OBSOLETE). - sequences -An iterator that returns SeqRecord objects, or simply a list of SeqRecord objects. All the record sequences must be the same length. - alphabet - Optional alphabet. Stongly recommended. - strict... |
_Option(["-w"], ["input"], None, 0, | _Option(["-w", "frame_shit_penalty"], ["input"], None, 0, | def __init__(self, cmd="blastall",**kwargs): self.parameters = [ \ #Sorted in the same order as the output from blastall --help #which should make it easier to keep them up to date in future. #Note that some arguments are defined the the base clases (above). _Option(["-p", "program"], ["input"], None, 1, "The blast pro... |
_Option(["-t"], ["input"], None, 0, | _Option(["-t", "largest_intron"], ["input"], None, 0, | def __init__(self, cmd="blastall",**kwargs): self.parameters = [ \ #Sorted in the same order as the output from blastall --help #which should make it easier to keep them up to date in future. #Note that some arguments are defined the the base clases (above). _Option(["-p", "program"], ["input"], None, 1, "The blast pro... |
_Option(["-B"], ["input"], None, 0, | _Option(["-B", "num_concatenated_queries"], ["input"], None, 0, | def __init__(self, cmd="blastall",**kwargs): self.parameters = [ \ #Sorted in the same order as the output from blastall --help #which should make it easier to keep them up to date in future. #Note that some arguments are defined the the base clases (above). _Option(["-p", "program"], ["input"], None, 1, "The blast pro... |
_Option(["-C"], ["input"], None, 0, | _Option(["-C", "composition_based"], ["input"], None, 0, | def __init__(self, cmd="blastall",**kwargs): self.parameters = [ \ #Sorted in the same order as the output from blastall --help #which should make it easier to keep them up to date in future. #Note that some arguments are defined the the base clases (above). _Option(["-p", "program"], ["input"], None, 1, "The blast pro... |
_Option(["-s"], ["input"], None, 0, | _Option(["-s", "smith_waterman"], ["input"], None, 0, | def __init__(self, cmd="blastall",**kwargs): self.parameters = [ \ #Sorted in the same order as the output from blastall --help #which should make it easier to keep them up to date in future. #Note that some arguments are defined the the base clases (above). _Option(["-p", "program"], ["input"], None, 1, "The blast pro... |
warnings.warn("Accessing the .data attribute is deprecated. Please use str(my_seq) or my_seq_tostring() instead of my_seq.data.", DeprecationWarning) | warnings.warn("Accessing the .data attribute is deprecated. Please " "use str(my_seq) or my_seq.tostring() instead of " "my_seq.data.", DeprecationWarning) | def data(self) : """Sequence as a string (DEPRECATED). |
assert len(x) == 2, "I don't understand RX line %s" % line | assert len(x) == 2, "I don't understand RX line %s" % value | def _read_rx(reference, value): # The basic (older?) RX line is of the form: # RX MEDLINE; 85132727. # but there are variants of this that need to be dealt with (see below) # CLD1_HUMAN in Release 39 and DADR_DIDMA in Release 33 # have extraneous information in the RX line. Check for # this and chop it out of the l... |
assert len(cols) == 2, "I don't understand RX line %s" % line | assert len(cols) == 2, "I don't understand RX line %s" % value | def _read_rx(reference, value): # The basic (older?) RX line is of the form: # RX MEDLINE; 85132727. # but there are variants of this that need to be dealt with (see below) # CLD1_HUMAN in Release 39 and DADR_DIDMA in Release 33 # have extraneous information in the RX line. Check for # this and chop it out of the l... |
cline = Applications.NcbiblastpCommandline(exe_names["blastn"], | cline = Applications.NcbiblastnCommandline(exe_names["blastn"], | def test_blastn(self): """Pairwise BLASTN search""" global exe_names cline = Applications.NcbiblastpCommandline(exe_names["blastn"], query="GenBank/NC_005816.ffn", subject="GenBank/NC_005816.fna", evalue="0.000001") self.assertEqual(str(cline), exe_names["blastn"] \ + " -query GenBank/NC_005816.ffn -evalue 0.000001" \ ... |
cline = Applications.NcbiblastpCommandline(exe_names["tblastn"], | cline = Applications.NcbitblastnCommandline(exe_names["tblastn"], | def test_tblastn(self): """Pairwise TBLASTN search""" global exe_names cline = Applications.NcbiblastpCommandline(exe_names["tblastn"], query="GenBank/NC_005816.faa", subject="GenBank/NC_005816.fna", evalue="1e-6") self.assertEqual(str(cline), exe_names["tblastn"] \ + " -query GenBank/NC_005816.faa -evalue 1e-6" \ + " ... |
raise PDBContructionError("Invalid or missing coordinate(s) at line %i." \ % global_line_counter) | raise PDBContructionException(\ "Invalid or missing coordinate(s) at line %i." \ % global_line_counter) | def _parse_coordinates(self, coords_trailer): "Parse the atomic data in the PDB file." local_line_counter=0 structure_builder=self.structure_builder current_model_id=0 # Flag we have an open model model_open=0 current_chain_id=None current_segid=None current_residue_id=None current_resname=None for i in range(0, len(co... |
raise NexusError('Taxon %s: Illegal character %s in line: %s (check dimensions / interleaving)'\ % (id,c,l[i-10:i+10])) | raise NexusError( \ ('Taxon %s: Illegal character %s in sequence %s ' + \ '(check dimensions/interleaving)') % (id,c, iupac_seq)) | 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 #eliminate empty lines and leading/trailing whitespace lines=[l.strip() for l in options.split('\n') if l.strip()!=''] lineiter=iter(lines) wh... |
for val in occupied_levels: if val >= track: | for val in occupied_levels: if val >= track.track_level: | def add_track(self, track, track_level): """ add_track(self, track, track_level) |
if feature.location.start == feature.location.end \ and isinstance(feature.location.end, SeqFeature.ExactPosition): | if isinstance(feature.location.start, SeqFeature.ExactPosition) \ and isinstance(feature.location.end, SeqFeature.ExactPosition) \ and feature.location.start.position == feature.location.end.position: | def _insdc_location_string_ignoring_strand_and_subfeatures(feature): if feature.ref: ref = "%s:" % feature.ref else: ref = "" assert not feature.ref_db if feature.location.start == feature.location.end \ and isinstance(feature.location.end, SeqFeature.ExactPosition): #Special case, 12^13 gets mapped to location 12:12 #... |
if len(self.__fst_pair_locus) == 0 | if len(self.__fst_pair_locus) == 0: | def get_avg_fst_pair_locus(self, locus): if len(self.__fst_pair_locus) == 0 iter = self._controller.calc_fst_pair(self._fname)[0] for locus_info in iter: self.__fst_pair_locus[locus_info[0]] = locus_info[1] return self.__fst_pair_locus[locus] |
gene_choices = new_org.genome.alphabet.letters | gene_choices = list(new_org.genome.alphabet.letters) | def mutate(self, organism): """Mutate the genome trying to put in 'helpful' mutations. """ new_org = organism.copy() gene_choices = new_org.genome.alphabet.letters |
gene_choices = copy.copy(new_org.genome.alphabet.letters) | gene_choices = list(new_org.genome.alphabet.letters) | def mutate(self, organism): """Mutate the genome trying to put in 'helpful' mutations. """ new_org = organism.copy() gene_choices = new_org.genome.alphabet.letters |
if zipfile.is_zipfile(source): source = unzip(source) | def _test_read_factory(source, count): """Generate a test method for read()ing the given source. The generated function reads an example file to produce a phyloXML object, then tests for existence of the root node, and counts the number of phylogenies under the root. """ fname = os.path.basename(source) if zipfile.is_... | |
if zipfile.is_zipfile(source): source = unzip(source) | def _test_parse_factory(source, count): """Generate a test method for parse()ing the given source. The generated function extracts each phylogenetic tree using the parse() function and counts the total number of trees extracted. """ fname = os.path.basename(source) if zipfile.is_zipfile(source): source = unzip(source)... | |
if zipfile.is_zipfile(source): source = unzip(source) | def _test_shape_factory(source, shapes): """Generate a test method for checking tree shapes. Counts the branches at each level of branching in a phylogenetic tree, 3 clades deep. """ fname = os.path.basename(source) if zipfile.is_zipfile(source): source = unzip(source) def test_shape(self): trees = PhyloXMLIO.parse(so... | |
test_read_mollusca = _test_read_factory(EX_MOLLUSCA, (1, 0)) | def test_shape(self): trees = PhyloXMLIO.parse(source) for tree, shape_expect in izip(trees, shapes): self.assertEquals(len(tree.clade), len(shape_expect)) for clade, sub_expect in izip(tree.clade, shape_expect): self.assertEquals(len(clade), sub_expect[0]) for subclade, len_expect in izip(clade, sub_expect[1]): self.a... | |
test_parse_mollusca = _test_parse_factory(EX_MOLLUSCA, 1) | def test_shape(self): trees = PhyloXMLIO.parse(source) for tree, shape_expect in izip(trees, shapes): self.assertEquals(len(tree.clade), len(shape_expect)) for clade, sub_expect in izip(tree.clade, shape_expect): self.assertEquals(len(clade), sub_expect[0]) for subclade, len_expect in izip(clade, sub_expect[1]): self.a... | |
test_shape_zip = _test_shape_factory(EX_MOLLUSCA, ( ( (3, (5, 1, 4)), (5, (6, 2, 2, 2, 1)), (2, (1, 1)), (1, (2,)), (2, (4, 4)), (2, (2, 2)), (1, (1,)), ), ), ) | def test_shape(self): trees = PhyloXMLIO.parse(source) for tree, shape_expect in izip(trees, shapes): self.assertEquals(len(tree.clade), len(shape_expect)) for clade, sub_expect in izip(tree.clade, shape_expect): self.assertEquals(len(clade), sub_expect[0]) for subclade, len_expect in izip(clade, sub_expect[1]): self.a... | |
def _stash_rewrite_and_call(self, fname, test_cases): """Safely run a series of tests on a parsed and rewritten file. Specifically: Parse a file, rename the source file to a backup, rewrite the file from the parsed object, check the rewritten file with the given series of test functions, then restore the original by r... | def _rewrite_and_call(self, orig_fname, test_cases): """Parse, rewrite and retest a phyloXML example file.""" infile = open(orig_fname, 'rb') phx = PhyloXMLIO.read(infile) infile.close() outfile = open(DUMMY, 'w+b') PhyloXMLIO.write(phx, outfile) outfile.close() for cls, tests in test_cases: inst = cls('setUp') for tes... | def test_Uri(self): """Instantiation of Uri objects.""" tree = list(PhyloXMLIO.parse(EX_PHYLO))[9] uri = tree.clade.taxonomies[0].uri self.assert_(isinstance(uri, PX.Uri)) self.assertEqual(uri.desc, 'EMBL REPTILE DATABASE') self.assertEqual(uri.value, 'http://www.embl-heidelberg.de/~uetz/families/Varanidae.html') |
self._stash_rewrite_and_call(EX_APAF, ( (ParseTests, [ 'test_read_apaf', 'test_parse_apaf', 'test_shape_apaf']), (TreeTests, ['test_DomainArchitecture']), )) | global EX_APAF orig_fname = EX_APAF try: EX_APAF = DUMMY self._rewrite_and_call(orig_fname, ( (ParseTests, [ 'test_read_apaf', 'test_parse_apaf', 'test_shape_apaf']), (TreeTests, ['test_DomainArchitecture']), )) finally: EX_APAF = orig_fname | def test_apaf(self): """Round-trip parsing and serialization of apaf.xml.""" self._stash_rewrite_and_call(EX_APAF, ( (ParseTests, [ 'test_read_apaf', 'test_parse_apaf', 'test_shape_apaf']), (TreeTests, ['test_DomainArchitecture']), )) |
self._stash_rewrite_and_call(EX_BCL2, ( (ParseTests, [ 'test_read_bcl2', 'test_parse_bcl2', 'test_shape_bcl2']), (TreeTests, ['test_Confidence']), )) | global EX_BCL2 orig_fname = EX_BCL2 try: EX_BCL2 = DUMMY self._rewrite_and_call(orig_fname, ( (ParseTests, [ 'test_read_bcl2', 'test_parse_bcl2', 'test_shape_bcl2']), (TreeTests, ['test_Confidence']), )) finally: EX_BCL2 = orig_fname | def test_bcl2(self): """Round-trip parsing and serialization of bcl_2.xml.""" self._stash_rewrite_and_call(EX_BCL2, ( (ParseTests, [ 'test_read_bcl2', 'test_parse_bcl2', 'test_shape_bcl2']), (TreeTests, ['test_Confidence']), )) |
self._stash_rewrite_and_call(EX_MADE, ( (ParseTests, ['test_read_made', 'test_parse_made']), (TreeTests, ['test_Confidence', 'test_Polygon']), )) | global EX_MADE orig_fname = EX_MADE try: EX_MADE = DUMMY self._rewrite_and_call(orig_fname, ( (ParseTests, ['test_read_made', 'test_parse_made']), (TreeTests, ['test_Confidence', 'test_Polygon']), )) finally: EX_MADE = orig_fname | def test_made(self): """Round-trip parsing and serialization of made_up.xml.""" self._stash_rewrite_and_call(EX_MADE, ( (ParseTests, ['test_read_made', 'test_parse_made']), (TreeTests, ['test_Confidence', 'test_Polygon']), )) |
self._stash_rewrite_and_call(EX_PHYLO, ( (ParseTests, [ 'test_read_phylo', 'test_parse_phylo', 'test_shape_phylo']), (TreeTests, [ 'test_Phyloxml', 'test_Other', 'test_Phylogeny', 'test_Clade', 'test_Annotation', 'test_CladeRelation', 'test_Date', 'test_Distribution', 'test_Events', 'test_Property', 'test_... | global EX_PHYLO orig_fname = EX_PHYLO try: EX_PHYLO = DUMMY self._rewrite_and_call(orig_fname, ( (ParseTests, [ 'test_read_phylo', 'test_parse_phylo', 'test_shape_phylo']), (TreeTests, [ 'test_Phyloxml', 'test_Other', 'test_Phylogeny', 'test_Clade', 'test_Annotation', 'test_CladeRelation', 'test_Date', 'test_D... | def test_phylo(self): """Round-trip parsing and serialization of phyloxml_examples.xml.""" self._stash_rewrite_and_call(EX_PHYLO, ( (ParseTests, [ 'test_read_phylo', 'test_parse_phylo', 'test_shape_phylo']), (TreeTests, [ 'test_Phyloxml', 'test_Other', 'test_Phylogeny', 'test_Clade', 'test_Annotation', 'test_CladeRe... |
self._stash_rewrite_and_call(EX_DOLLO, ( (ParseTests, ['test_read_dollo', 'test_parse_dollo']), (TreeTests, ['test_BinaryCharacters']), )) | global EX_DOLLO orig_fname = EX_DOLLO try: EX_DOLLO = DUMMY self._rewrite_and_call(orig_fname, ( (ParseTests, ['test_read_dollo', 'test_parse_dollo']), (TreeTests, ['test_BinaryCharacters']), )) finally: EX_DOLLO = orig_fname | def test_dollo(self): """Round-trip parsing and serialization of o_tol_332_d_dollo.xml.""" self._stash_rewrite_and_call(EX_DOLLO, ( (ParseTests, ['test_read_dollo', 'test_parse_dollo']), (TreeTests, ['test_BinaryCharacters']), )) |
Both 'color' and 'width' elements apply for the whole clade unless overwritten in-sub clades. | Both 'color' and 'width' elements should be interpreted by client code as applying to the whole clade, including all descendents, unless overwritten in-sub clades. This module doesn't automatically assign these attributes to sub-clades to achieve this cascade -- and neither should you. | def confidence(self): """Equivalent to self.confidences[0] if there is only 1 value. |
@param width: branch width for this clade (including parent branch) | @param width: branch width for this clade (including branch from parent) | def confidence(self): """Equivalent to self.confidences[0] if there is only 1 value. |
The color applies to the whole clade unless overwritten by the color(s) of sub-clades. Color values should be unsigned bytes, or integers from 0 to 255. | The color should be interpreted by client code (e.g. visualization programs) as applying to the whole clade, unless overwritten by the color(s) of sub-clades. Color values must be integers from 0 to 255. | def __init__(self, # Attributes type=None, gained_count=None, lost_count=None, present_count=None, absent_count=None, # Child nodes (flattened into collections) gained=None, lost=None, present=None, absent=None): self.type=type self.gained_count=gained_count self.lost_count=lost_count self.present_count=present_count s... |
answer = SeqFeature(location = self.location._shift(offset), type = self.type, location_operator = self.location_operator, strand = self.strand, id = self.id, ref = self.ref, ref_db = self.ref_db) answer.sub_features = [f._shift(offset) for f in self.sub_features] answer.qualifiers = dict(self.qualifiers.iteritems()... | return SeqFeature(location = self.location._shift(offset), type = self.type, location_operator = self.location_operator, strand = self.strand, id = self.id, qualifiers = dict(self.qualifiers.iteritems()), sub_features = [f._shift(offset) for f in self.sub_features], ref = self.ref, ref_db = self.ref_db) | def _shift(self, offset): """Returns a copy of the feature with its location shifted (PRIVATE). |
self.assertEqual(old.id[:9], new.id) | self.assertTrue(old.id==new.id or old.id[:9]==new.id) | def test_Prank_simple_with_NEXUS_output(self): """Simple round-trip through app with infile, output in NEXUS output.?.??? files written to cwd - no way to redirect """ records = list(SeqIO.parse(open(self.infile1),"fasta")) #Try using keyword argument, cmdline = PrankCommandline(prank_exe, d=self.infile1, noxml=True) #... |
data = ''.join(lines) | try: data = ''.join(lines) except TypeError: data = ''.join(x.decode() for x in lines) | def _open(cgi, params={}, post=False): """Helper function to build the URL and open a handle to it (PRIVATE). Open a handle to Entrez. cgi is the URL for the cgi script to access. params is a dictionary with the options to pass to it. Does some simple error checking, and will raise an IOError if it encounters one. ... |
>>> values[0:5] (840, 65040, 256, 24, 800) | >>> print values[0] 840 >>> print values[1] 65040 >>> print values[2] 256 >>> print values[3] 24 >>> print values[4] 800 | def _sff_file_header(handle): """Read in an SFF file header (PRIVATE). Assumes the handle is at the start of the file, will read forwards though the header and leave the handle pointing at the first record. Returns a tuple of values from the header (header_length, index_offset, index_length, number_of_reads, flows_per... |
def to_string(self,support_as_branchlengths=False,branchlengths_only=False,plain=True,plain_newick=False,ladderize=None): | def to_string(self,support_as_branchlengths=False,branchlengths_only=False,plain=True,plain_newick=False,ladderize=None,ignore_comments=True): | def to_string(self,support_as_branchlengths=False,branchlengths_only=False,plain=True,plain_newick=False,ladderize=None): """Return a paup compatible tree line. to_string(self,support_as_branchlengths=False,branchlengths_only=False,plain=True) """ # if there's a conflict in the arguments, we override plain=True if sup... |
return '' | info_string= '' | def make_info_string(data,terminal=False): """Creates nicely formatted support/branchlengths.""" # CHECK FORMATTING if self.plain: # plain tree only. That's easy. return '' elif self.support_as_branchlengths: # support as branchlengths (eg. PAUP), ignore actual branchlengths if terminal: # terminal branches have 100... |
return ':%1.2f' % self.max_support | info_string= ':%1.2f' % self.max_support elif data.support: info_string= ':%1.2f' % (data.support) | def make_info_string(data,terminal=False): """Creates nicely formatted support/branchlengths.""" # CHECK FORMATTING if self.plain: # plain tree only. That's easy. return '' elif self.support_as_branchlengths: # support as branchlengths (eg. PAUP), ignore actual branchlengths if terminal: # terminal branches have 100... |
return ':%1.2f' % (data.support) | info_string=':0.00' | def make_info_string(data,terminal=False): """Creates nicely formatted support/branchlengths.""" # CHECK FORMATTING if self.plain: # plain tree only. That's easy. return '' elif self.support_as_branchlengths: # support as branchlengths (eg. PAUP), ignore actual branchlengths if terminal: # terminal branches have 100... |
return ':%1.5f' % (data.branchlength) | info_string= ':%1.5f' % (data.branchlength) | def make_info_string(data,terminal=False): """Creates nicely formatted support/branchlengths.""" # CHECK FORMATTING if self.plain: # plain tree only. That's easy. return '' elif self.support_as_branchlengths: # support as branchlengths (eg. PAUP), ignore actual branchlengths if terminal: # terminal branches have 100... |
return '%1.2f:%1.5f' % (data.support,data.branchlength) | info_string= '%1.2f:%1.5f' % (data.support,data.branchlength) | def make_info_string(data,terminal=False): """Creates nicely formatted support/branchlengths.""" # CHECK FORMATTING if self.plain: # plain tree only. That's easy. return '' elif self.support_as_branchlengths: # support as branchlengths (eg. PAUP), ignore actual branchlengths if terminal: # terminal branches have 100... |
return '0.00000:%1.5f' % (data.branchlength) | info_string= '0.00000:%1.5f' % (data.branchlength) | def make_info_string(data,terminal=False): """Creates nicely formatted support/branchlengths.""" # CHECK FORMATTING if self.plain: # plain tree only. That's easy. return '' elif self.support_as_branchlengths: # support as branchlengths (eg. PAUP), ignore actual branchlengths if terminal: # terminal branches have 100... |
return '%1.2f:0.00000' % (data.support) | info_string= '%1.2f:0.00000' % (data.support) | def make_info_string(data,terminal=False): """Creates nicely formatted support/branchlengths.""" # CHECK FORMATTING if self.plain: # plain tree only. That's easy. return '' elif self.support_as_branchlengths: # support as branchlengths (eg. PAUP), ignore actual branchlengths if terminal: # terminal branches have 100... |
return '0.00:0.00000' | info_string= '0.00:0.00000' if not ignore_comments and hasattr(data,'nodecomment'): info_string=str(data.nodecomment)+info_string return info_string | def make_info_string(data,terminal=False): """Creates nicely formatted support/branchlengths.""" # CHECK FORMATTING if self.plain: # plain tree only. That's easy. return '' elif self.support_as_branchlengths: # support as branchlengths (eg. PAUP), ignore actual branchlengths if terminal: # terminal branches have 100... |
id=Id(tree.id)) | id=(tree.id is not None) and Id(str(tree.id)) or None) | def from_tree(self, tree, **kwargs): phy = Phylogeny( root=Clade.from_subtree(tree.root), rooted=tree.rooted, name=tree.name, id=Id(tree.id)) phy.__dict__.update(kwargs) return phy |
clade = cls( branch_length=subtree.branch_length, name=subtree.name, node_id=Id(str(subtree.id))) | clade = cls(branch_length=subtree.branch_length, name=subtree.name) | def from_subtree(cls, subtree, **kwargs): """Create a new Clade from a BaseTree.Subtree object.""" clade = cls( branch_length=subtree.branch_length, name=subtree.name, node_id=Id(str(subtree.id))) clade.clades = [cls.from_subtree(st) for st in subtree.clades] clade.__dict__.update(kwargs) return clade |
@property def id(self): return self.node_id.value | def to_phylogeny(self, **kwargs): """Create a new phylogeny containing just this clade.""" phy = Phylogeny(root=self, date=self.date) phy.__dict__.update(kwargs) return phy | |
file = open(filename,'r') dict = parse_pdb_header(file) | handle = open(filename,'r') data_dict = parse_pdb_header(handle) handle.close() | def _parse_pdb_header_list(header): # database fields dict={'name':"", 'head':'', 'deposition_date' : "1909-01-08", 'release_date' : "1909-01-08", 'structure_method' : "unknown", 'resolution' : 0.0, 'structure_reference' : "unknown", 'journal_reference' : "unknown", 'author' : "", 'compound':{'1':{'misc':''}},'source':... |
for d in dict.keys(): | for k, y in data_dict.iteritems(): | def _parse_pdb_header_list(header): # database fields dict={'name':"", 'head':'', 'deposition_date' : "1909-01-08", 'release_date' : "1909-01-08", 'structure_method' : "unknown", 'resolution' : 0.0, 'structure_reference' : "unknown", 'journal_reference' : "unknown", 'author' : "", 'compound':{'1':{'misc':''}},'source':... |
print d print dict[d] | print k print y | def _parse_pdb_header_list(header): # database fields dict={'name':"", 'head':'', 'deposition_date' : "1909-01-08", 'release_date' : "1909-01-08", 'structure_method' : "unknown", 'resolution' : 0.0, 'structure_reference' : "unknown", 'journal_reference' : "unknown", 'author' : "", 'compound':{'1':{'misc':''}},'source':... |
if isinstance(range_info, LocationParser.Between) \ and range_info.low.val+1 == range_info.high.val: | if isinstance(range_info, LocationParser.Between): if not (range_info.low.val+1 == range_info.high.val \ or range_info.low.val==self._expected_size \ and range_info.high.val==1): raise ValueError(range_info) | def _get_location(self, range_info): """Return a (possibly fuzzy) location from a Range object. |
raw += _bytes_to_string(handle.read(8 + name_length)) | raw += handle.read(8 + name_length) | def _sff_read_raw_record(handle, number_of_flows_per_read): """Extract the next read in the file as a raw (bytes) string (PRIVATE).""" read_header_fmt = '>2HI' read_header_size = struct.calcsize(read_header_fmt) read_flow_fmt = ">%iH" % number_of_flows_per_read read_flow_size = struct.calcsize(read_flow_fmt) raw = han... |
True if RE and other are the same enzyme.""" return other is cls | True if RE and other are the same enzyme. Specifically this checks they are the same Python object. """ return id(cls)==id(other) | def __eq__(cls, other): """RE == other -> bool |
all the other-> True""" | all the other-> True WARNING - This is not the inverse of the __eq__ method. """ | def __ne__(cls, other): """RE != other -> bool. isoschizomer strict, same recognition site, same restriction -> False all the other-> True""" if not isinstance(other, RestrictionType): return True elif cls.charac == other.charac: return False else: return True |
del k, x, enzymes, TYPE, bases, names | del k, enzymes, TYPE, bases, names | def do_not_cut(self, start, end, dct = None): """A.do_not_cut(start, end [, dct]) -> dict. |
align = AlignIO.read(open(cline.outfile),"emboss") | handle = open(cline.outfile) align = AlignIO.read(handle,"emboss") handle.close() | def test_water_file(self): """water with the asis trick, output to a file.""" #Setup, try a mixture of keyword arguments and later additions: cline = WaterCommandline(cmd=exes["water"], gapopen="10", gapextend="0.5") #Try using both human readable names, and the literal ones: cline.set_parameter("asequence", "asis:ACCC... |
align = AlignIO.read(open(filename),"emboss") | handle = open(filename) align = AlignIO.read(handle,"emboss") handle.close() | def test_needle_file(self): """needle with the asis trick, output to a file.""" #Setup, cline = NeedleCommandline(cmd=exes["needle"]) cline.set_parameter("-asequence", "asis:ACCCGGGCGCGGT") cline.set_parameter("-bsequence", "asis:ACCCGAGCGCGGT") cline.set_parameter("-gapopen", "10") cline.set_parameter("-gapextend", "0... |
AlignIO.parse(open(out_file),"emboss"), | AlignIO.parse(handle,"emboss"), | def test_water_file2(self): """water with the asis trick and nucleotide FASTA file, output to a file.""" #Setup, query = "ACACACTCACACACACTTGGTCAGAGATGCTGTGCTTCTTGGAAGCAAGGNCTCAAAGGCAAGGTGCACGCAGAGGGACGTTTGAGTCTGGGATGAAGCATGTNCGTATTATTTATATGATGGAATTTCACGTTTTTATG" out_file = "Emboss/temp_test2.water" in_file = "Fasta/f0... |
AlignIO.parse(open(out_file),"emboss"), | AlignIO.parse(handle,"emboss"), | def test_water_file3(self): """water with the asis trick and GenBank file, output to a file.""" #Setup, query = "TGTTGTAATGTTTTAATGTTTCTTCTCCCTTTAGATGTACTACGTTTGGA" out_file = "Emboss/temp_test3.water" in_file = "GenBank/cor6_6.gb" self.assertTrue(os.path.isfile(in_file)) if os.path.isfile(out_file): os.remove(out_file... |
AlignIO.parse(open(out_file),"emboss"), | AlignIO.parse(handle,"emboss"), | def test_water_file4(self): """water with the asis trick and SwissProt file, output to a file.""" #Setup, query = "DVCTGKALCDPVTQNIKTYPVKIENLRVMI" out_file = "Emboss/temp_test4.water" in_file = "SwissProt/sp004" self.assertTrue(os.path.isfile(in_file)) if os.path.isfile(out_file): os.remove(out_file) cline = WaterComma... |
[_Option(["-sequences","sequences"], ["input"], None, 1, "Sequence to look for the primer pairs in."), _Option(["-primers","primers"], ["input", "file"], None, 1, "File containing the primer pairs to search for."), | [_Option(["-seqall","-sequences","sequences","seqall"], ["input"], None, 1, "Sequence to look for the primer pairs in."), _Option(["-input","-primers","primers","input"], ["input", "file"], None, 1, "File containing the primer pairs to search for."), | def __init__(self, cmd="primersearch", **kwargs): self.parameters = \ [_Option(["-sequences","sequences"], ["input"], None, 1, "Sequence to look for the primer pairs in."), _Option(["-primers","primers"], ["input", "file"], None, 1, "File containing the primer pairs to search for."), #Including -out and out for backwar... |
"Allowed percentage mismatch.")] | "Allowed percentage mismatch (any integer value, default 0)."), _Option(["-snucleotide","snucleotide"], ["input"], None, 0, "Sequences are nucleotide (boolean)"), _Option(["-sprotein","sprotein"], ["input"], None, 0, "Sequences are protein (boolean)"), ] | def __init__(self, cmd="primersearch", **kwargs): self.parameters = \ [_Option(["-sequences","sequences"], ["input"], None, 1, "Sequence to look for the primer pairs in."), _Option(["-primers","primers"], ["input", "file"], None, 1, "File containing the primer pairs to search for."), #Including -out and out for backwar... |
"VRL"]: | "VRL", "XXX"]: | def _get_data_division(self, record): try: division = record.annotations["data_file_division"] except KeyError: division = "UNC" if division in ["PHG", "ENV", "FUN", "HUM", "INV", "MAM", "VRT", "MUS", "PLN", "PRO", "ROD", "SYN", "TGN", "UNC", "VRL"]: #Good, already EMBL style # Division Code # ---... |
qaulity reads. If you have an old Solexa/Illumina file with negative | quality reads. If you have an old Solexa/Illumina file with negative | def FastqIlluminaIterator(handle, alphabet = single_letter_alphabet, title2ids = None): """Parse new Illumina 1.3+ FASTQ like files (which differ in the quality mapping). The optional arguments are the same as those for the FastqPhredIterator. For each sequence in Illumina 1.3+ FASTQ files there is a matching string ... |
>>> from Bio import SeqIO >>> record = SeqIO.read(open("Quality/solexa_faked.fastq"), "fastq-solexa") >>> print record.id, record.seq slxa_0001_1_0001_01 ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN >>> print record.letter_annotations["solexa_quality"] [40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, ... | def FastqIlluminaIterator(handle, alphabet = single_letter_alphabet, title2ids = None): """Parse new Illumina 1.3+ FASTQ like files (which differ in the quality mapping). The optional arguments are the same as those for the FastqPhredIterator. For each sequence in Illumina 1.3+ FASTQ files there is a matching string ... | |
if urlinfo.scheme=='http': | if urlinfo[0]=='http': | def externalEntityRefHandler(self, context, base, systemId, publicId): """The purpose of this function is to load the DTD locally, instead of downloading it from the URL specified in the XML. Using the local DTD results in much faster parsing. If the DTD is not found locally, we try to download it. If new DTDs become a... |
elif urlinfo.scheme=='': | elif urlinfo[0]=='': | def externalEntityRefHandler(self, context, base, systemId, publicId): """The purpose of this function is to load the DTD locally, instead of downloading it from the URL specified in the XML. Using the local DTD results in much faster parsing. If the DTD is not found locally, we try to download it. If new DTDs become a... |
raise ValuError("Incorrect dimension") | raise ValueError("Incorrect dimension") | def _copy_and_check(matrix, desired_shape): # Copy the matrix. matrix = numpy.array(matrix, copy=1) # Check the dimensions. if matrix.shape != desired_shape: raise ValuError("Incorrect dimension") # Make sure it's normalized. if len(matrix.shape) == 1: if numpy.fabs(sum(matrix)-1.0) > 0.01: raise ValueError("matrix not... |
if self._debug : print "Debug: '%s' and '%s'" % (title, "".join(lines)) | if self._debug: print "Debug: '%s'" % "".join(lines) | def next(self): """Return the next record in the file""" line = self._lookahead if not line: return None assert line[0]==">", line lines = [line.rstrip()] line = self.handle.readline() while line: if line[0] == ">": break if line[0] == "#": if self._debug : print "Ignoring comment line" pass else: lines.append(line.rst... |
d2=sum(d*d, 1) | d2=numpy.sum(d*d, 1) | def min_dist(coord, surface): """ Return minimum distance between coord and surface. """ d=surface-coord d2=sum(d*d, 1) return numpy.sqrt(min(d2)) |
key=re.sub("\s.+\s*","",h) tail=re.sub("\A\w+\s+\d*\s*","",h) | key = h[:6].strip() tail = h[10:].strip() | def _parse_pdb_header_list(header): # database fields dict={'name':"", 'head':'', 'deposition_date' : "1909-01-08", 'release_date' : "1909-01-08", 'structure_method' : "unknown", 'resolution' : 0.0, 'structure_reference' : "unknown", 'journal_reference' : "unknown", 'author' : "", 'compound':{'1':{'misc':''}},'source':... |
return self.adaptor.list_bioentry_ids(self.dbid) | return self.keys() | def get_all_primary_ids(self): """All the primary_ids of the sequences in the database (OBSOLETE). |
return self.get_all_primary_ids() | return self.adaptor.list_bioentry_ids(self.dbid) | def keys(self): """List of ids which may not be meaningful outside this database.""" return self.get_all_primary_ids() |
self.assertTrue(rec.id, ids) | self.assertTrue(rec.id in ids) | def check_dict_methods(self, rec_dict, keys, ids): self.assertEqual(set(keys), set(rec_dict.keys())) #This is redundant, I just want to make sure len works: 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): self.asse... |
class Parser(): | class Parser(object): | def UniprotIterator(handle, alphabet=Alphabet.ProteinAlphabet(), return_raw_comments=False): '''Generator Function parses an XML entry at a time from any UniProt XML file returns a SeqRecord for each iteration This generator can be used in Bio.SeqIO return_raw_comments = True --> comment fields are returned as comple... |
seq=Seq(s, ProteinAlphabet) | seq=Seq(s, generic_protein) | def get_sequence(self): """ Return the AA sequence. |
class Primer3Commandline(_EmbossCommandLine): """Commandline object for the Primer3 interface from EMBOSS. """ def __init__(self, cmd="eprimer3", **kwargs): self.parameters = \ [_Option(["-sequence","sequence"], ["input"], None, 1, "Sequence to choose primers from"), _Option(["-task","task"], ["input"], None, 0), _Opti... | def _validate(self): #Check the outfile, filter, or stdout option has been set. #We can't simply do this via the required flag for the outfile #output - this seems the simplest solution. if not (self.outfile or self.filter or self.stdout): raise ValueError("You must either set outfile (output filename), " "or enable fi... | |
% (options)) | % (opts)) | 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() # we ignore * before names if name=='*': name=opts.next_word() if not name: raise NexusError('Formatting error in line: %s ' % rest) name=quotestrip(name) if opts.peek_nonwhit... |
% (qualifier,options)) | % (qualifier, opts)) | 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() # we ignore * before names if name=='*': name=opts.next_word() if not name: raise NexusError('Formatting error in line: %s ' % rest) name=quotestrip(name) if opts.peek_nonwhit... |
if format in _BinaryFormats : handle = open(handle, "wb") else : handle = open(handle, "w") | handle = open(handle, "w") | def write(alignments, handle, format): """Write complete set of alignments to a file. Arguments: - sequences - A list (or iterator) of Alignment objects - handle - File handle object to write to, or filename as string (note older versions of Biopython only took a handle). - format - lower case string describing ... |
pass | parts = data.rstrip(".").split(";") consumer.dblink("%s:%s" % (parts[0].strip(), parts[1].strip())) | def _feed_header_lines(self, consumer, lines): EMBL_INDENT = self.HEADER_WIDTH EMBL_SPACER = " " * EMBL_INDENT consumer_dict = { 'AC' : 'accession', 'SV' : 'version', # SV line removed in June 2006, now part of ID line 'DE' : 'definition', #'RN' : 'reference_num', #'RC' : reference comment... TODO #'RP' : 'reference_b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.