本文整理汇总了Python中Bio.File.UndoHandle类的典型用法代码示例。如果您正苦于以下问题:Python UndoHandle类的具体用法?Python UndoHandle怎么用?Python UndoHandle使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了UndoHandle类的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_get_sprot_raw
def test_get_sprot_raw(self):
"""Bio.ExPASy.get_sprot_raw("O23729")"""
identifier = "O23729"
# This is to catch an error page from our proxy:
handle = UndoHandle(ExPASy.get_sprot_raw(identifier))
if _as_string(handle.peekline()).startswith("<!DOCTYPE HTML"):
raise IOError
record = SeqIO.read(handle, "swiss")
handle.close()
self.assertEqual(record.id, identifier)
self.assertEqual(len(record), 394)
self.assertEqual(seguid(record.seq), "5Y08l+HJRDIlhLKzFEfkcKd1dkM")
示例2: extract_organisms
def extract_organisms(file, num_records):
scanner = Fasta._Scanner()
consumer = SpeciesExtractor()
file_to_parse = UndoHandle(open(file, "r"))
for fasta_record in range(num_records):
scanner.feed(file_to_parse, consumer)
file_to_parse.close()
return consumer.species_list
示例3: test_get_sprot_raw
def test_get_sprot_raw(self):
"""Bio.ExPASy.get_sprot_raw("O23729")"""
identifier = "O23729"
try:
#This is to catch an error page from our proxy:
handle = UndoHandle(ExPASy.get_sprot_raw(identifier))
if _as_string(handle.peekline()).startswith("<!DOCTYPE HTML"):
raise IOError
record = SeqIO.read(handle, "swiss")
handle.close()
except IOError:
raise MissingExternalDependencyError(
"internet (or maybe just ExPASy) not available")
self.assertEqual(record.id, identifier)
self.assertEqual(len(record), 394)
self.assertEqual(seguid(record.seq), "5Y08l+HJRDIlhLKzFEfkcKd1dkM")
示例4: __init__
def __init__(self, handle, __parse_hit_table=False):
self.handle = UndoHandle(handle)
self._preamble = self._parse_preamble()
示例5: FastaM10Parser
class FastaM10Parser(object):
"""Parser for Bill Pearson's FASTA suite's -m 10 output."""
def __init__(self, handle, __parse_hit_table=False):
self.handle = UndoHandle(handle)
self._preamble = self._parse_preamble()
def __iter__(self):
for qresult in self._parse_qresult():
# re-set desc, for hsp query description
qresult.description = qresult.description
yield qresult
def _parse_preamble(self):
"""Parses the Fasta preamble for Fasta flavor and version."""
preamble = {}
while True:
self.line = self.handle.readline()
# this should be the line just before the first qresult
if self.line.startswith('Query'):
break
# try to match for version line
elif self.line.startswith(' version'):
preamble['version'] = self.line.split(' ')[2]
else:
# try to match for flavor line
flav_match = re.match(_RE_FLAVS, self.line.lower())
if flav_match:
preamble['program'] = flav_match.group(0)
return preamble
def __parse_hit_table(self):
"""Parses hit table rows."""
# move to the first row
self.line = self.handle.readline()
# parse hit table until we see an empty line
hit_rows = []
while self.line and not self.line.strip():
hit_rows.append(self.line.strip())
self.line = self.handle.readline()
return hit_rows
def _parse_qresult(self):
# initial qresult value
qresult = None
hit_rows = []
# state values
state_QRES_NEW = 1
state_QRES_HITTAB = 3
state_QRES_CONTENT = 5
state_QRES_END = 7
while True:
# one line before the hit table
if self.line.startswith('The best scores are:'):
qres_state = state_QRES_HITTAB
# the end of a query or the file altogether
elif self.line.strip() == '>>>///' or not self.line:
qres_state = state_QRES_END
# the beginning of a new query
elif not self.line.startswith('>>>') and '>>>' in self.line:
qres_state = state_QRES_NEW
# the beginning of the query info and its hits + hsps
elif self.line.startswith('>>>') and not \
self.line.strip() == '>>><<<':
qres_state = state_QRES_CONTENT
# default qres mark
else:
qres_state = None
if qres_state is not None:
if qres_state == state_QRES_HITTAB:
# parse hit table if flag is set
hit_rows = self.__parse_hit_table()
elif qres_state == state_QRES_END:
yield _set_qresult_hits(qresult, hit_rows)
break
elif qres_state == state_QRES_NEW:
# if qresult is filled, yield it first
if qresult is not None:
yield _set_qresult_hits(qresult, hit_rows)
regx = re.search(_RE_ID_DESC_SEQLEN, self.line)
query_id = regx.group(1)
seq_len = regx.group(3)
desc = regx.group(2)
qresult = QueryResult(id=query_id)
qresult.seq_len = int(seq_len)
# get target from the next line
self.line = self.handle.readline()
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
for key, value in self._preamble.items():
setattr(qresult, key, value)
#.........这里部分代码省略.........
示例6: PdbAtomIterator
def PdbAtomIterator(handle):
"""Returns SeqRecord objects for each chain in a PDB file
The sequences are derived from the 3D structure (ATOM records), not the
SEQRES lines in the PDB file header.
Unrecognised three letter amino acid codes (e.g. "CSD") from HETATM entries
are converted to "X" in the sequence.
In addition to information from the PDB header (which is the same for all
records), the following chain specific information is placed in the
annotation:
record.annotations["residues"] = List of residue ID strings
record.annotations["chain"] = Chain ID (typically A, B ,...)
record.annotations["model"] = Model ID (typically zero)
Where amino acids are missing from the structure, as indicated by residue
numbering, the sequence is filled in with 'X' characters to match the size
of the missing region, and None is included as the corresponding entry in
the list record.annotations["residues"].
This function uses the Bio.PDB module to do most of the hard work. The
annotation information could be improved but this extra parsing should be
done in parse_pdb_header, not this module.
"""
# Only import PDB when needed, to avoid/delay NumPy dependency in SeqIO
from Bio.PDB import PDBParser
from Bio.SeqUtils import seq1
from Bio.SCOP.three_to_one_dict import to_one_letter_code
def restype(residue):
"""Return a residue's type as a one-letter code.
Non-standard residues (e.g. CSD, ANP) are returned as 'X'.
"""
return seq1(residue.resname, custom_map=to_one_letter_code)
# Deduce the PDB ID from the PDB header
# ENH: or filename?
from Bio.File import UndoHandle
undo_handle = UndoHandle(handle)
firstline = undo_handle.peekline()
if firstline.startswith("HEADER"):
pdb_id = firstline[62:66]
else:
warnings.warn("First line is not a 'HEADER'; can't determine PDB ID")
pdb_id = '????'
struct = PDBParser().get_structure(pdb_id, undo_handle)
model = struct[0]
for chn_id, chain in sorted(model.child_dict.iteritems()):
# 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(),
custom_map=to_one_letter_code) != "X"]
if not residues:
continue
# Identify missing residues in the structure
# (fill the sequence with 'X' residues in these regions)
gaps = []
rnumbers = [r.id[1] for r in residues]
for i, rnum in enumerate(rnumbers[:-1]):
if rnumbers[i+1] != rnum + 1:
# It's a gap!
gaps.append((i+1, rnum, rnumbers[i+1]))
if gaps:
res_out = []
prev_idx = 0
for i, pregap, postgap in gaps:
if postgap > pregap:
gapsize = postgap - pregap - 1
res_out.extend(map(restype, residues[prev_idx:i]))
prev_idx = i
res_out.append('X'*gapsize)
# Last segment
res_out.extend(map(restype, residues[prev_idx:]))
else:
warnings.warn("Ignoring out-of-order residues after a gap",
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]))
else:
# No gaps
res_out = map(restype, residues)
record_id = "%s:%s" % (pdb_id, chn_id)
# ENH - model number in SeqRecord id if multiple models?
# id = "Chain%s" % str(chain.id)
# if len(structure) > 1 :
# id = ("Model%s|" % str(model.id)) + id
record = SeqRecord(Seq(''.join(res_out), generic_protein),
id=record_id,
description=record_id,
)
# The PDB header was loaded as a dictionary, so let's reuse it all
record.annotations = struct.header.copy()
# Plus some chain specifics:
#.........这里部分代码省略.........
示例7: PdbAtomIterator
def PdbAtomIterator(handle):
"""Return SeqRecord objects for each chain in a PDB file.
The sequences are derived from the 3D structure (ATOM records), not the
SEQRES lines in the PDB file header.
Unrecognised three letter amino acid codes (e.g. "CSD") from HETATM entries
are converted to "X" in the sequence.
In addition to information from the PDB header (which is the same for all
records), the following chain specific information is placed in the
annotation:
record.annotations["residues"] = List of residue ID strings
record.annotations["chain"] = Chain ID (typically A, B ,...)
record.annotations["model"] = Model ID (typically zero)
Where amino acids are missing from the structure, as indicated by residue
numbering, the sequence is filled in with 'X' characters to match the size
of the missing region, and None is included as the corresponding entry in
the list record.annotations["residues"].
This function uses the Bio.PDB module to do most of the hard work. The
annotation information could be improved but this extra parsing should be
done in parse_pdb_header, not this module.
This gets called internally via Bio.SeqIO for the atom based interpretation
of the PDB file format:
>>> from Bio import SeqIO
>>> for record in SeqIO.parse("PDB/1A8O.pdb", "pdb-atom"):
... print("Record id %s, chain %s" % (record.id, record.annotations["chain"]))
...
Record id 1A8O:A, chain A
Equivalently,
>>> with open("PDB/1A8O.pdb") as handle:
... for record in PdbAtomIterator(handle):
... print("Record id %s, chain %s" % (record.id, record.annotations["chain"]))
...
Record id 1A8O:A, chain A
"""
# TODO - Add record.annotations to the doctest, esp the residues (not working?)
# Only import PDB when needed, to avoid/delay NumPy dependency in SeqIO
from Bio.PDB import PDBParser
# Deduce the PDB ID from the PDB header
# ENH: or filename?
from Bio.File import UndoHandle
undo_handle = UndoHandle(handle)
firstline = undo_handle.peekline()
# check if file is empty
if firstline == '':
raise ValueError("Empty file.")
if firstline.startswith("HEADER"):
pdb_id = firstline[62:66]
else:
warnings.warn("First line is not a 'HEADER'; can't determine PDB ID. "
"Line: %r" % firstline, BiopythonParserWarning)
pdb_id = '????'
struct = PDBParser().get_structure(pdb_id, undo_handle)
for record in AtomIterator(pdb_id, struct):
# The PDB header was loaded as a dictionary, so let's reuse it all
record.annotations.update(struct.header)
# ENH - add letter annotations -- per-residue info, e.g. numbers
yield record
示例8: __init__
def __init__(self, handle, __parse_hit_table=False):
"""Initialize the class."""
self.handle = UndoHandle(handle)
self._preamble = self._parse_preamble()