code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if isinstance(fileNameOrHandle, six.string_types):
if fileNameOrHandle.endswith('.gz'):
if six.PY3:
yield gzip.open(fileNameOrHandle, mode='rt', encoding='UTF-8')
else:
yield gzip.GzipFile(fileNameOrHandle)
elif fileNameOrHandle.endswith('... | def asHandle(fileNameOrHandle, mode='r') | Decorator for file opening that makes it easy to open compressed files.
Based on L{Bio.File.as_handle}.
@param fileNameOrHandle: Either a C{str} or a file handle.
@return: A generator that can be turned into a context manager via
L{contextlib.contextmanager}. | 1.656347 | 1.700539 | 0.974013 |
result = set()
for _range in s.split(','):
match = _rangeRegex.match(_range)
if match:
start, end = match.groups()
start = int(start)
if end is None:
end = start
else:
end = int(end)
if start > end:... | def parseRangeString(s, convertToZeroBased=False) | Parse a range string of the form 1-5,12,100-200.
@param s: A C{str} specifiying a set of numbers, given in the form of
comma separated numeric ranges or individual indices.
@param convertToZeroBased: If C{True} all indices will have one
subtracted from them.
@return: A C{set} of all C{int}s... | 2.585893 | 2.680196 | 0.964815 |
result = []
for offset in sorted(nucleotides):
result.append(
'%s%d: %s' % (prefix, offset,
baseCountsToStr(nucleotides[offset])))
return '\n'.join(result) | def nucleotidesToStr(nucleotides, prefix='') | Convert offsets and base counts to a string.
@param nucleotides: A C{defaultdict(Counter)} instance, keyed
by C{int} offset, with nucleotides keying the Counters.
@param prefix: A C{str} to put at the start of each line.
@return: A C{str} representation of the offsets and nucleotide
counts ... | 3.647608 | 2.845037 | 1.282095 |
def percentage(a, b):
return 100.0 * a / b if b else 0.0
if count == 0:
return '%s: %d' % (mesg, count)
else:
len2 = len2 or len1
if len1 == len2:
return '%s: %d/%d (%.2f%%)' % (
mesg, count, len1, percentage(count, len1))
el... | def countPrint(mesg, count, len1, len2=None) | Format a message followed by an integer count and a percentage (or
two, if the sequence lengths are unequal).
@param mesg: a C{str} message.
@param count: a numeric value.
@param len1: the C{int} length of sequence 1.
@param len2: the C{int} length of sequence 2. If C{None}, will
default to... | 2.309933 | 2.142476 | 1.07816 |
local_dir = os.path.join(genometools._root, 'data', 'gcloud', 'scripts')
match = _BUCKET_PAT.match(script_dir)
script_bucket = match.group(1)
script_prefix = match.group(2)
depth = len(local_dir.split(os.sep))
for root, dirs, files in os.walk(local_dir):
rel_path = '/'.join(root.s... | def upload_scripts(client, script_dir, overwrite=True) | Uploads general-purpose scripts to a Google Storage bucket.
TODO: docstring | 2.799054 | 2.749659 | 1.017964 |
if filename.endswith('.json') or filename.endswith('.json.bz2'):
return JSONRecordsReader(filename, scoreClass)
else:
raise ValueError(
'Unknown DIAMOND record file suffix for file %r.' % filename) | def _getReader(self, filename, scoreClass) | Obtain a JSON record reader for DIAMOND records.
@param filename: The C{str} file name holding the JSON.
@param scoreClass: A class to hold and compare scores (see scores.py). | 6.643472 | 5.160035 | 1.287486 |
# Note that self._reader is already initialized (in __init__) for
# the first input file. This is less clean than it could be, but it
# makes testing easier, since open() is then only called once for
# each input file.
reads = iter(self.reads)
first = True
... | def iter(self) | Extract DIAMOND records and yield C{ReadAlignments} instances.
@return: A generator that yields C{ReadAlignments} instances. | 7.605566 | 7.196801 | 1.056798 |
if self._subjectTitleToSubject is None:
if self._databaseFilename is None:
# An Sqlite3 database is used to look up subjects.
self._subjectTitleToSubject = SqliteIndex(
self._sqliteDatabaseFilename,
fastaDirectory=self.... | def getSubjectSequence(self, title) | Obtain information about a subject sequence given its title.
@param title: A C{str} sequence title from a DIAMOND hit.
@raise KeyError: If the C{title} is not present in the DIAMOND
database.
@return: An C{AAReadWithX} instance. | 5.598904 | 4.462771 | 1.25458 |
urls = []
with ftputil.FTPHost(sra_host, sra_user, sra_password) as ftp_host:
download_paths = []
exp_dir = '/sra/sra-instant/reads/ByStudy/sra/SRP/%s/%s/' \
%(project[:6], project)
ftp_host.chdir(exp_dir)
run_folders = ftp_host.listdir(ftp_host.curdir)
... | def get_project_urls(project) | Get the URLs for all runs from a given project.
TODO: docstring | 4.125279 | 3.954109 | 1.043289 |
''' Two's complement conversion of a binary number
Input handshake & data
rx_rdy - (o) Ready
rx_vld - (i) Valid
rx_dat - (i) Data
Output handshake & data
tx_rdy - (i) Ready
tx_vld - (o) Valid
tx_dat - (o) Data
Implement... | def twos_complement(rst, clk, rx_rdy, rx_vld, rx_dat, tx_rdy, tx_vld, tx_dat) | Two's complement conversion of a binary number
Input handshake & data
rx_rdy - (o) Ready
rx_vld - (i) Valid
rx_dat - (i) Data
Output handshake & data
tx_rdy - (i) Ready
tx_vld - (o) Valid
tx_dat - (o) Data
Implementation: 3... | 2.839704 | 1.609031 | 1.764854 |
desc = 'Generate a mapping of Entrez IDs to gene symbols.'
parser = cli.get_argument_parser(desc=desc)
parser.add_argument(
'-f', '--gene2acc-file', type=str, required=True,
help=textwrap.dedent()
)
parser.add_argument(
'-o', '--output-file', type=str, required=True,... | def get_argument_parser() | Creates the argument parser for the extract_entrez2gene.py script.
Returns
-------
A fully configured `argparse.ArgumentParser` object.
Notes
-----
This function is used by the `sphinx-argparse` extension for sphinx. | 2.456039 | 2.347145 | 1.046394 |
gene2acc = {}
with misc.smart_open_read(file_path, mode='rb', try_gzip=True) as fh:
reader = csv.reader(fh, dialect='excel-tab')
next(reader) # skip header
for i, l in enumerate(reader):
id_ = int(l[1])
symbol = l[15]
try:
gene2a... | def read_gene2acc(file_path, logger) | Extracts Entrez ID -> gene symbol mapping from gene2accession.gz file.
Parameters
----------
file_path: str
The path of the gene2accession.gz file (or a filtered version thereof).
The file may be gzip'ed.
Returns
-------
dict
A mapping of Entrez IDs to gene symbols. | 3.090697 | 3.149618 | 0.981293 |
with misc.smart_open_write(file_path, mode='wb') as ofh:
writer = csv.writer(ofh, dialect='excel-tab',
lineterminator=os.linesep)
for k in sorted(entrez2gene.keys(), key=lambda x: int(x)):
writer.writerow([k, entrez2gene[k]])
logger.info('Output writt... | def write_entrez2gene(file_path, entrez2gene, logger) | Writes Entrez ID -> gene symbol mapping to a tab-delimited text file.
Parameters
----------
file_path: str
The path of the output file.
entrez2gene: dict
The mapping of Entrez IDs to gene symbols.
Returns
-------
None | 2.850733 | 3.072251 | 0.927897 |
vinfo = sys.version_info
if not (vinfo >= (2, 7)):
raise SystemError('Python interpreter version >= 2.7 required, '
'found %d.%d instead.' % (vinfo.major, vinfo.minor))
if args is None:
parser = get_argument_parser()
args = parser.parse_args()
gen... | def main(args=None) | Extracts Entrez ID -> gene symbol mapping and writes it to a text file.
Parameters
----------
args: argparse.Namespace object, optional
The argument values. If not specified, the values will be obtained by
parsing the command line arguments using the `argparse` module.
Returns
----... | 2.733655 | 2.578086 | 1.060343 |
abbrev1 = None
origS = s
if ' ' in s:
# Convert first word to title case, others to lower.
first, rest = s.split(' ', 1)
s = first.title() + ' ' + rest.lower()
else:
s = s.title()
if s in NAMES:
abbrev1 = s
elif s in ABBREV3_TO_ABBREV1:
abb... | def find(s) | Find an amino acid whose name or abbreviation is s.
@param s: A C{str} amino acid specifier. This may be a full name,
a 3-letter abbreviation or a 1-letter abbreviation. Case is ignored.
return: An L{AminoAcid} instance or C{None} if no matching amino acid can
be located. | 3.386776 | 3.077967 | 1.100329 |
propertyNames = sorted(map(str.lower, set(propertyNames)))
# Make sure all mentioned property names exist for at least one AA.
knownProperties = set()
for names in propertyValues.values():
knownProperties.update(names)
unknown = set(propertyNames) - knownProperties
if unknown:
... | def _propertiesOrClustersForSequence(sequence, propertyNames, propertyValues,
missingAAValue) | Extract amino acid property values or cluster numbers for a sequence.
@param sequence: An C{AARead} (or a subclass) instance.
@param propertyNames: An iterable of C{str} property names (each of which
must be a key of a key in the C{propertyValues} C{dict}).
@param propertyValues: A C{dict} in the f... | 3.085295 | 3.228026 | 0.955784 |
match = aaMatch['match']
matchCount = match['matchCount']
gapMismatchCount = match['gapMismatchCount']
gapGapMismatchCount = match['gapGapMismatchCount']
nonGapMismatchCount = match['nonGapMismatchCount']
if offsets:
len1 = len2 = len(offsets)
else:
len1, len2 = map(len... | def matchToString(aaMatch, read1, read2, indent='', offsets=None) | Format amino acid sequence match as a string.
@param aaMatch: A C{dict} returned by C{compareAaReads}.
@param read1: A C{Read} instance or an instance of one of its subclasses.
@param read2: A C{Read} instance or an instance of one of its subclasses.
@param indent: A C{str} to indent all returned lines... | 2.53641 | 2.547353 | 0.995704 |
matchCount = 0
gapMismatchCount = nonGapMismatchCount = gapGapMismatchCount = 0
read1ExtraCount = read2ExtraCount = 0
read1GapOffsets = []
read2GapOffsets = []
for offset, (a, b) in enumerate(zip_longest(read1.sequence.upper(),
read2.sequence... | def compareAaReads(read1, read2, gapChars='-', offsets=None) | Compare two amino acid sequences.
@param read1: A C{Read} instance or an instance of one of its subclasses.
@param read2: A C{Read} instance or an instance of one of its subclasses.
@param gapChars: An object supporting __contains__ with characters that
should be considered to be gaps.
@param o... | 2.374379 | 2.360411 | 1.005917 |
result = defaultdict(set)
for colorInfo in colors:
readIds = colorInfo.split()
color = readIds.pop(0)
for readId in readIds:
if os.path.isfile(readId):
filename = readId
if args.fasta:
reads = FastaReads(filename)
... | def parseColors(colors, args) | Parse read id color specification.
@param colors: A C{list} of C{str}s. Each item is of the form, e.g.,
'green X Y Z...', where each of X, Y, Z, ... etc. is either a read
id or the name of a FASTA or FASTQ file containing reads whose ids
should be displayed with the corresponding color. Not... | 3.000186 | 2.351615 | 1.275798 |
if release is None:
release = get_latest_release()
url = 'http://viewvc.geneontology.org/viewvc/GO-SVN/ontology-releases/%s/go-basic.obo' % release
#download_file = 'go-basic_%s.obo' % release
misc.http_download(url, download_file) | def download_release(download_file, release=None) | Downloads the "go-basic.obo" file for the specified release. | 5.61873 | 5.4057 | 1.039408 |
with closing(requests.get(
'http://geneontology.org/ontology/go-basic.obo',
stream=True)) as r:
for i, l in enumerate(r.iter_lines(decode_unicode=True)):
if i == 1:
assert l.split(':')[0] == 'data-version'
date = l.split('/')[-1]
... | def get_current_ontology_date() | Get the release date of the current Gene Ontolgo release. | 3.103373 | 3.122932 | 0.993737 |
try:
return TaskResult(name, True, None, function())
except Exception as exc:
return TaskResult(name, False, exc, None) | def execute(function, name) | Execute a task, returning a TaskResult | 4.020552 | 3.099741 | 1.297061 |
try:
length = int(arg)
except ValueError: # Invalid literal for int().
return value # Fail silently.
if len(value) > length:
return value[:length] + '...'
return value | def truncatechars(value, arg) | Truncates a string after a certain number of chars.
Argument: Number of chars to truncate after. | 2.732139 | 3.450941 | 0.791708 |
from django.template import Context, loader
from django.http import HttpResponseServerError
from overseer.context_processors import default
import logging
import sys
try:
context = default(request)
except Exception, e:
logging.error(e, exc_info=sys.exc_info(), extra={'re... | def handler500(request) | 500 error handler.
Templates: `500.html`
Context: None | 3.022784 | 3.094714 | 0.976757 |
parser = cli.get_argument_parser(desc=desc)
parser.add_argument(
'-a', '--annotation-file', default='-', type=str,
help=textwrap.dedent()
)
parser.add_argument(
'-o', '--output-file', required=True, type=str,
help=textwrap.dedent()
)
#parser.add_argument(
... | def get_gtf_argument_parser(desc, default_field_name='gene') | Return an argument parser with basic options for reading GTF files.
Parameters
----------
desc: str
Description of the ArgumentParser
default_field_name: str, optional
Name of field in GTF file to look for.
Returns
-------
`argparse.ArgumentParser` object
The argume... | 2.365559 | 2.546386 | 0.928987 |
from flask import current_app
from . import current_jsonschemas
url_map.add(Rule(
"{0}/<path:path>".format(current_app.config['JSONSCHEMAS_ENDPOINT']),
endpoint=current_jsonschemas.get_schema,
host=current_app.config['JSONSCHEMAS_HOST'])) | def jsonresolver_loader(url_map) | JSON resolver plugin that loads the schema endpoint.
Injected into Invenio-Records JSON resolver. | 3.073122 | 3.00971 | 1.021069 |
''' Utility function for merging multiple layouts.
Args:
layouts (list): A list of BIDSLayout instances to merge.
Returns:
A BIDSLayout containing merged files and entities.
Notes:
Layouts will be merged in the order of the elements in the list. I.e.,
the first Layout wi... | def merge_layouts(layouts) | Utility function for merging multiple layouts.
Args:
layouts (list): A list of BIDSLayout instances to merge.
Returns:
A BIDSLayout containing merged files and entities.
Notes:
Layouts will be merged in the order of the elements in the list. I.e.,
the first Layout will be up... | 3.853365 | 1.573065 | 2.44959 |
if extensions is not None:
if isinstance(extensions, six.string_types):
extensions = [extensions]
extensions = '(' + '|'.join(extensions) + ')$'
if re.search(extensions, self.filename) is None:
return False
if domains is not N... | def _matches(self, entities=None, extensions=None, domains=None,
regex_search=False) | Checks whether the file matches all of the passed entities and
extensions.
Args:
entities (dict): A dictionary of entity names -> regex patterns.
extensions (str, list): One or more file extensions to allow.
domains (str, list): One or more domains the file must matc... | 2.8613 | 2.832196 | 1.010276 |
keys = list(self.entities.keys())
replaced = []
for i, k in enumerate(keys):
if iskeyword(k):
replaced.append(k)
keys[i] = '%s_' % k
if replaced:
safe = ['%s_' % k for k in replaced]
warnings.warn("Entity names ... | def as_named_tuple(self) | Returns the File as a named tuple. The full path plus all entity
key/value pairs are returned as attributes. | 4.033125 | 3.565628 | 1.131112 |
''' Copy the contents of a file to a new location, with target
filename defined by the current File's entities and the specified
path_patterns. '''
new_filename = build_path(self.entities, path_patterns)
if not new_filename:
return None
if new_filename[-1] ==... | def copy(self, path_patterns, symbolic_link=False, root=None,
conflicts='fail') | Copy the contents of a file to a new location, with target
filename defined by the current File's entities and the specified
path_patterns. | 4.080555 | 2.960436 | 1.378363 |
if self.map_func is not None:
val = self.map_func(f)
else:
m = self.regex.search(f.path)
val = m.group(1) if m is not None else None
return self._astype(val) | def match_file(self, f, update_file=False) | Determine whether the passed file matches the Entity.
Args:
f (File): The File instance to match against.
Returns: the matched value if a match was found, otherwise None. | 3.868705 | 3.843089 | 1.006665 |
''' Return a domain if one already exists, or create a new one if not.
Args:
domain (str, dict): Can be one of:
- The name of the Domain to return (fails if none exists)
- A path to the Domain configuration file
- A dictionary containing confi... | def _get_or_load_domain(self, domain) | Return a domain if one already exists, or create a new one if not.
Args:
domain (str, dict): Can be one of:
- The name of the Domain to return (fails if none exists)
- A path to the Domain configuration file
- A dictionary containing configuration inf... | 3.325094 | 2.434081 | 1.366057 |
''' Check file or directory against regexes in config to determine if
it should be included in the index '''
filename = f if isinstance(f, six.string_types) else f.path
if domains is None:
domains = list(self.domains.values())
# Inject the Layout at the first p... | def _check_inclusions(self, f, domains=None) | Check file or directory against regexes in config to determine if
it should be included in the index | 4.426243 | 3.377419 | 1.31054 |
''' Find an Entity instance by name. Checks both name and id fields.'''
if entity in self.entities:
return self.entities[entity]
_ent = [e for e in self.entities.values() if e.name == entity]
if len(_ent) > 1:
raise ValueError("Entity name '%s' matches %d entities... | def _find_entity(self, entity) | Find an Entity instance by name. Checks both name and id fields. | 3.680606 | 3.084674 | 1.193191 |
''' Save the current Layout's index to a .json file.
Args:
filename (str): Filename to write to.
Note: At the moment, this won't serialize directory-specific config
files. This means reconstructed indexes will only work properly in
cases where there aren't multiple ... | def save_index(self, filename) | Save the current Layout's index to a .json file.
Args:
filename (str): Filename to write to.
Note: At the moment, this won't serialize directory-specific config
files. This means reconstructed indexes will only work properly in
cases where there aren't multiple layout specs... | 6.7583 | 2.355242 | 2.869471 |
''' Load the Layout's index from a plaintext file.
Args:
filename (str): Path to the plaintext index file.
reindex (bool): If True, discards entity values provided in the
loaded index and instead re-indexes every file in the loaded
index against t... | def load_index(self, filename, reindex=False) | Load the Layout's index from a plaintext file.
Args:
filename (str): Path to the plaintext index file.
reindex (bool): If True, discards entity values provided in the
loaded index and instead re-indexes every file in the loaded
index against the entities ... | 5.727293 | 2.149096 | 2.664977 |
''' Add a new Entity to tracking. '''
# Set the entity's mapping func if one was specified
map_func = kwargs.get('map_func', None)
if map_func is not None and not callable(kwargs['map_func']):
if self.entity_mapper is None:
raise ValueError("Mapping function ... | def add_entity(self, domain, **kwargs) | Add a new Entity to tracking. | 3.877866 | 3.812025 | 1.017272 |
if regex_search is None:
regex_search = self.regex_search
result = []
filters = {}
filters.update(kwargs)
for filename, file in self.files.items():
if not file._matches(filters, extensions, domains, regex_search):
continue
... | def get(self, return_type='tuple', target=None, extensions=None,
domains=None, regex_search=None, **kwargs) | Retrieve files and/or metadata from the current Layout.
Args:
return_type (str): Type of result to return. Valid values:
'tuple': returns a list of namedtuples containing file name as
well as attribute/value pairs for all named entities.
'file': r... | 3.177787 | 2.977091 | 1.067414 |
return self._find_entity(entity).count(files) | def count(self, entity, files=False) | Return the count of unique values or files for the named entity.
Args:
entity (str): The name of the entity.
files (bool): If True, counts the number of filenames that contain
at least one value of the entity, rather than the number of
unique values of th... | 11.784881 | 23.969133 | 0.491669 |
try:
import pandas as pd
except ImportError:
raise ImportError("What are you doing trying to export a Layout "
"as a pandas DataFrame when you don't have "
"pandas installed? Eh? Eh?")
if kwargs:
... | def as_data_frame(self, **kwargs) | Return information for all Files tracked in the Layout as a pandas
DataFrame.
Args:
kwargs: Optional keyword arguments passed on to get(). This allows
one to easily select only a subset of files for export.
Returns:
A pandas DataFrame, where each row is a... | 4.787098 | 3.603824 | 1.328339 |
''' Constructs a target filename for a file or dictionary of entities.
Args:
source (str, File, dict): The source data to use to construct the
new file path. Must be one of:
- A File object
- A string giving the path of a File contained within... | def build_path(self, source, path_patterns=None, strict=False,
domains=None) | Constructs a target filename for a file or dictionary of entities.
Args:
source (str, File, dict): The source data to use to construct the
new file path. Must be one of:
- A File object
- A string giving the path of a File contained within the
... | 4.278849 | 1.512106 | 2.829728 |
path = self.build_path(entities, path_patterns, strict, domains)
if path is None:
raise ValueError("Cannot construct any valid filename for "
"the passed entities given available path "
"patterns.")
write_contents_t... | def write_contents_to_file(self, entities, path_patterns=None,
contents=None, link_to=None,
content_mode='text', conflicts='fail',
strict=False, domains=None, index=False,
index_domains=None) | Write arbitrary data to a file defined by the passed entities and
path patterns.
Args:
entities (dict): A dictionary of entities, with Entity names in
keys and values for the desired file in values.
path_patterns (list): Optional path patterns to use when buildin... | 3.872812 | 4.153912 | 0.932329 |
# create a child logger
logger = logging.getLogger(name)
# set the logger's level
logger.setLevel(log_level)
# set the logger's propagation attribute
logger.propagate = propagate
if not keep_old_handlers:
# remove previously attached handlers
logger.handlers = []
... | def configure_logger(name, log_stream=sys.stdout, log_file=None,
log_level=logging.INFO, keep_old_handlers=False,
propagate=False) | Configures and returns a logger.
This function serves to simplify the configuration of a logger that
writes to a file and/or to a stream (e.g., stdout).
Parameters
----------
name: str
The name of the logger. Typically set to ``__name__``.
log_stream: a stream object, optional
... | 2.005423 | 2.027444 | 0.989138 |
# configure root logger
log_level = logging.INFO
if quiet:
log_level = logging.WARNING
elif verbose:
log_level = logging.DEBUG
if log_stream is None:
log_stream = sys.stdout
new_logger = configure_logger(name, log_stream=log_stream,
... | def get_logger(name='', log_stream=None, log_file=None,
quiet=False, verbose=False) | Convenience function for getting a logger. | 2.080277 | 2.14018 | 0.972011 |
stopper = threading.Event()
def interval(seconds, func, *args, **kwargs):
def wrapper():
if stopper.isSet():
return
interval(seconds, func, *args, **kwargs)
try:
func(*args, **kwargs)
except: # py... | def start(milliseconds, func, *args, **kwargs) | Call function every interval. Starts the timer at call time.
Although this could also be a decorator, that would not initiate the time at
the same time, so would require additional work.
Arguments following function will be sent to function. Note that these args
are part of the defining state, and un... | 2.564 | 3.227728 | 0.794367 |
result = defaultdict(list)
for c1 in codons1:
for c2 in codons2:
distance = findDistance(c1, c2)
result[distance].append([c1, c2])
return result | def codonInformation(codons1, codons2) | Take two C{list} of codons, and returns information about the min and
max distance between them.
@param codon1: a C{list} of codons.
@param codon2: a C{list} of codons.
@return: a dict whose keys are C{int} distances and whose values are lists
of pairs of codons. | 2.55836 | 2.679897 | 0.954649 |
try:
pprint((yield from api_client.echo()))
except errors.RequestError as exc:
log.exception('Exception occurred: %s', exc)
yield gen.Task(lambda *args, **kwargs: ioloop.IOLoop.current().stop()) | def example_async_client(api_client) | Example async client. | 6.640206 | 6.385595 | 1.039873 |
try:
pprint(api_client.echo())
except errors.RequestError as exc:
log.exception('Exception occurred: %s', exc) | def example_sync_client(api_client) | Example sync client use with. | 8.306467 | 7.486382 | 1.109544 |
logging.basicConfig(level=logging.INFO)
example_sync_client(SyncAPIClient())
example_async_client(AsyncAPIClient())
io_loop = ioloop.IOLoop.current()
io_loop.start() | def main() | Run the examples. | 4.73269 | 4.330826 | 1.092792 |
vinfo = sys.version_info
if not vinfo >= (2, 7):
raise SystemError('Python interpreter version >= 2.7 required, '
'found %d.%d instead.' %(vinfo.major, vinfo.minor))
if args is None:
# parse command-line arguments
parser = get_argument_parser()
... | def main(args=None) | Extract protein-coding genes and store in tab-delimited text file.
Parameters
----------
args: argparse.Namespace object, optional
The argument values. If not specified, the values will be obtained by
parsing the command line arguments using the `argparse` module.
Returns
-------
... | 3.068533 | 2.879325 | 1.065713 |
self.statistics = OrderedDict()
for port in self.ports:
port_stats = IxeStatTotal(port).get_attributes(FLAG_RDONLY, *stats)
port_stats.update({c + '_rate': v for c, v in
IxeStatRate(port).get_attributes(FLAG_RDONLY, *stats).items()})
... | def read_stats(self, *stats) | Read port statistics from chassis.
:param stats: list of requested statistics to read, if empty - read all statistics. | 6.160625 | 5.589444 | 1.102189 |
from ixexplorer.ixe_stream import IxePacketGroupStream
sleep_time = 0.1 # in cases we only want few counters but very fast we need a smaller sleep time
if not stats:
stats = [m.attrname for m in IxePgStats.__tcl_members__ if m.flags & FLAG_RDONLY]
sleep_time = 1... | def read_stats(self, *stats) | Read stream statistics from chassis.
:param stats: list of requested statistics to read, if empty - read all statistics. | 4.042901 | 3.975839 | 1.016867 |
''' Wrapper that provides common interface to all arbiters '''
if ARBITER_TYPE == "priority":
_arb = arbiter_priority(req_vec, gnt_vec, gnt_idx, gnt_vld)
elif (ARBITER_TYPE == "roundrobin"):
_arb = arbiter_roundrobin(rst, clk, req_vec, gnt_vec, gnt_idx, gnt_vld, gnt_rdy)
else:
as... | def arbiter(rst, clk, req_vec, gnt_vec=None, gnt_idx=None, gnt_vld=None, gnt_rdy=None, ARBITER_TYPE="priority") | Wrapper that provides common interface to all arbiters | 2.351908 | 2.094334 | 1.122986 |
REQ_NUM = len(req_vec)
gnt_vec_s = Signal(intbv(0)[REQ_NUM:])
gnt_idx_s = Signal(intbv(0, min=0, max=REQ_NUM))
gnt_vld_s = Signal(bool(0))
@always_comb
def prioroty_encoder():
gnt_vec_s.next = 0
gnt_idx_s.next = 0
gnt_vld_s.next = 0
for i in range(REQ_NUM):
... | def arbiter_priority(req_vec, gnt_vec=None, gnt_idx=None, gnt_vld=None) | Static priority arbiter: grants the request with highest priority, which is the lower index
req_vec - (i) vector of request signals, req_vec[0] is with the highest priority
gnt_vec - (o) optional, vector of grants, one grant per request, only one grant can be active at at time
gnt_id... | 1.924103 | 1.995567 | 0.964189 |
REQ_NUM = len(req_vec)
ptr = Signal(intbv(0, min=0, max=REQ_NUM))
gnt_vec_s = Signal(intbv(0)[REQ_NUM:])
gnt_idx_s = Signal(intbv(0, min=0, max=REQ_NUM))
gnt_vld_s = Signal(bool(0))
@always(clk.posedge)
def ptr_proc():
if (rst):
ptr.next = REQ_NUM-1
elif (g... | def arbiter_roundrobin(rst, clk, req_vec, gnt_vec=None, gnt_idx=None, gnt_vld=None, gnt_rdy=None) | Round Robin arbiter: finds the active request with highest priority and presents its index on the gnt_idx output.
req_vec - (i) vector of request signals, priority changes dynamically
gnt_vec - (o) optional, vector of grants, one grant per request, only one grant can be active at at time
... | 1.839521 | 1.897543 | 0.969422 |
seq = normalize_sequence(seq) if normalize else seq
return str(vmc_digest(seq, digest_size=24)) | def seq_seqhash(seq, normalize=True) | returns 24-byte Truncated Digest sequence `seq`
>>> seq_seqhash("")
'z4PhNX7vuL3xVChQ1m2AB9Yg5AULVxXc'
>>> seq_seqhash("ACGT")
'aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2'
>>> seq_seqhash("acgt")
'aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2'
>>> seq_seqhash("acgt", normalize=False)
'eFwawHHdibaZBDcs9kW3g... | 11.125893 | 11.589757 | 0.959976 |
seq = normalize_sequence(seq) if normalize else seq
bseq = seq.encode("ascii")
return base64.b64encode(hashlib.sha1(bseq).digest()).decode("ascii").rstrip(
'=') | def seq_seguid(seq, normalize=True) | returns seguid for sequence `seq`
This seguid is compatible with BioPython's seguid.
>>> seq_seguid('')
'2jmj7l5rSw0yVb/vlWAYkK/YBwk'
>>> seq_seguid('ACGT')
'IQiZThf2zKn/I1KtqStlEdsHYDQ'
>>> seq_seguid('acgt')
'IQiZThf2zKn/I1KtqStlEdsHYDQ'
>>> seq_seguid('acgt', normalize=False)
... | 4.045317 | 5.699805 | 0.709729 |
seq = normalize_sequence(seq) if normalize else seq
bseq = seq.encode("ascii")
return hashlib.md5(bseq).hexdigest() | def seq_md5(seq, normalize=True) | returns unicode md5 as hex digest for sequence `seq`.
>>> seq_md5('')
'd41d8cd98f00b204e9800998ecf8427e'
>>> seq_md5('ACGT')
'f1f8f4bf413b16ad135722aa4591043e'
>>> seq_md5('ACGT*')
'f1f8f4bf413b16ad135722aa4591043e'
>>> seq_md5(' A C G T ')
'f1f8f4bf413b16ad135722aa4591043e'
>>>... | 3.711205 | 7.223423 | 0.513774 |
seq = normalize_sequence(seq) if normalize else seq
bseq = seq.encode("ascii")
return hashlib.sha1(bseq).hexdigest() | def seq_sha1(seq, normalize=True) | returns unicode sha1 hexdigest for sequence `seq`.
>>> seq_sha1('')
'da39a3ee5e6b4b0d3255bfef95601890afd80709'
>>> seq_sha1('ACGT')
'2108994e17f6cca9ff2352ada92b6511db076034'
>>> seq_sha1('acgt')
'2108994e17f6cca9ff2352ada92b6511db076034'
>>> seq_sha1('acgt', normalize=False)
'948234... | 4.120943 | 5.234412 | 0.787279 |
seq = normalize_sequence(seq) if normalize else seq
bseq = seq.encode("ascii")
return hashlib.sha512(bseq).hexdigest() | def seq_sha512(seq, normalize=True) | returns unicode sequence sha512 hexdigest for sequence `seq`.
>>> seq_sha512('')
'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e'
>>> seq_sha512('ACGT')
'68a178f7c740c5c240aa67ba41843b119d3bf9f8b0f0ac36cf701d26672964efbd... | 3.7439 | 5.007147 | 0.747711 |
seq = normalize_sequence(seq) if normalize else seq
return {"namespace": "VMC", "accession": "GS_" + str(vmc_digest(seq))} | def seq_vmc_identifier(seq, normalize=True) | returns VMC identifier (record) for sequence `seq`
See https://github.com/ga4gh/vmc
>>> seq_vmc_identifier("") == {'namespace': 'VMC', 'accession': 'GS_z4PhNX7vuL3xVChQ1m2AB9Yg5AULVxXc'}
True
>>> seq_vmc_identifier("ACGT") == {'namespace': 'VMC', 'accession': 'GS_aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2'}
... | 8.888083 | 8.082531 | 1.099666 |
if sort_bam:
out_sam_type = 'BAM SortedByCoordinate'
else:
out_sam_type = 'BAM Unsorted'
# template expects a list of FASTQ files
fastq_files = fastq_file
if isinstance(fastq_files, (str, _oldstr)):
fastq_files = [fastq_file]
template = _TEMPLATE_ENV.get_template(... | def map_single_end(credentials, instance_config, instance_name,
script_dir, index_dir, fastq_file, output_dir,
num_threads=None, seed_start_lmax=None,
mismatch_nmax=None, multimap_nmax=None,
splice_min_overhang=None,
out_mult... | Maps single-end reads using STAR.
Reads are expected in FASTQ format. By default, they are also expected to
be compressed with gzip.
- recommended machine type: "n1-standard-16" (60 GB of RAM, 16 vCPUs).
- recommended disk size: depends on size of FASTQ files, at least 128 GB.
TODO: docstring | 2.30914 | 2.392103 | 0.965318 |
template = _TEMPLATE_ENV.get_template(
os.path.join('generate_index.sh'))
startup_script = template.render(
script_dir=script_dir,
genome_file=genome_file,
annotation_file=annotation_file,
splice_overhang=splice_overhang,
output_dir=output_dir,
num_t... | def generate_index(credentials, instance_config, instance_name,
script_dir, genome_file, output_dir, annotation_file=None,
splice_overhang=100,
num_threads=8, chromosome_bin_bits=18,
genome_memory_limit=31000000000,
self_dest... | Generates a STAR index.
Recommended machine type: "n1-highmem-8" (52 GB of RAM, 8 vCPUs)
TODO: docstring | 2.047089 | 2.146283 | 0.953784 |
assert isinstance(url, (str, _oldstr))
if ftp is not None:
assert isinstance(ftp, ftplib.FTP)
# open FTP connection if necessary
close_connection = False
ftp_server = 'ftp.ensembl.org'
ftp_user = 'anonymous'
if ftp is None:
ftp = ftplib.FTP(ftp_server)
ftp.login... | def get_file_checksums(url, ftp=None) | Download and parse an Ensembl CHECKSUMS file and obtain checksums.
Parameters
----------
url : str
The URL of the CHECKSUM file.
ftp : `ftplib.FTP` or `None`, optional
An FTP connection.
Returns
-------
`collections.OrderedDict`
An ordered dictionary containing ... | 2.829237 | 2.626192 | 1.077315 |
''' Wraps all non-list or tuple objects in a list; provides a simple way
to accept flexible arguments. '''
return obj if isinstance(obj, ignore) else [obj] | def listify(obj, ignore=(list, tuple, type(None))) | Wraps all non-list or tuple objects in a list; provides a simple way
to accept flexible arguments. | 9.994981 | 2.890648 | 3.457695 |
with tarfile.open(taxdump_file) as tf:
with tf.extractfile('division.dmp') as fh:
df = pd.read_csv(fh, header=None, sep='|', encoding='ascii')
# only keep division ids and names
df = df.iloc[:, [0, 2]]
# remove tab characters flanking each division name
df.iloc[:,... | def _get_divisions(taxdump_file) | Returns a dictionary mapping division names to division IDs. | 3.328127 | 3.278764 | 1.015055 |
if select_divisions and exclude_divisions:
raise ValueError('Cannot specify "select_divisions" and '
'"exclude_divisions" at the same time.')
select_division_ids = None
exclude_division_ids = None
divisions = None
if select_divisions or exclude_divisi... | def _get_species_taxon_ids(taxdump_file,
select_divisions=None, exclude_divisions=None) | Get a list of species taxon IDs (allow filtering by division). | 2.355994 | 2.375672 | 0.991717 |
if select_divisions and exclude_divisions:
raise ValueError('Cannot specify "select_divisions" and '
'"exclude_divisions" at the same time.')
select_taxon_ids = _get_species_taxon_ids(
taxdump_file,
select_divisions=select_divisions,
exclude_di... | def get_species(taxdump_file, select_divisions=None,
exclude_divisions=None, nrows=None) | Get a dataframe with species information. | 2.421092 | 2.422601 | 0.999377 |
auto_set = IxeObject.get_auto_set()
IxeObject.set_auto_set(False)
for name, value in attributes.items():
setattr(self, name, value)
if auto_set:
self.ix_set()
IxeObject.set_auto_set(auto_set) | def set_attributes(self, **attributes) | Set group of attributes without calling set between attributes regardless of global auto_set.
Set will be called only after all attributes are set based on global auto_set.
:param attributes: dictionary of <attribute, value> to set. | 3.732641 | 3.603015 | 1.035977 |
handle = self._url_open('detalheCEPAction.do', {'Metodo': 'detalhe',
'TipoCep': 2,
'Posicao': posicao + 1,
'CEP': ''})
html = h... | def detalhe(self, posicao=0) | Retorna o detalhe de um CEP da última lista de resultados | 8.676054 | 7.177104 | 1.208852 |
url = 'consultaFaixaCepAction.do'
data = {
'UF': uf,
'Localidade': localidade.encode('cp1252'),
'cfm': '1',
'Metodo': 'listaFaixaCEP',
'TipoConsulta': 'faixaCep',
'StartRow': '1',
'EndRow': '10',
}
... | def consulta_faixa(self, localidade, uf) | Consulta site e retorna faixa para localidade | 5.167487 | 5.050901 | 1.023082 |
if uf is None:
url = 'consultaEnderecoAction.do'
data = {
'relaxation': endereco.encode('ISO-8859-1'),
'TipoCep': 'ALL',
'semelhante': 'N',
'cfm': 1,
'Metodo': 'listaLogradouro',
'Ti... | def consulta(self, endereco, primeiro=False,
uf=None, localidade=None, tipo=None, numero=None) | Consulta site e retorna lista de resultados | 3.175997 | 3.21232 | 0.988692 |
retries_left = self._conn_retries
while True:
s = self._make_session()
try:
cert = None
if self._client_cert and self._client_key:
cert = (self._client_cert, self._client_key)
elif self._client_cert:
... | def _request(self, url, *,
method='GET', headers=None, data=None, result_callback=None) | Perform synchronous request.
:param str url: request URL.
:param str method: request method.
:param object data: JSON-encodable object.
:param object -> object result_callback: result callback.
:rtype: dict
:raise: APIError | 2.089932 | 2.17287 | 0.96183 |
sess = requests.Session()
sess.mount('http://', requests.adapters.HTTPAdapter(max_retries=False))
sess.mount('https://', requests.adapters.HTTPAdapter(max_retries=False))
return sess | def _make_session() | Create session object.
:rtype: requests.Session | 2.537489 | 2.511779 | 1.010236 |
payload = {
'attachment': 'true',
"filters": json.dumps({
"op": "and",
"content": [
{
"op":"in",
"content":{
"field":"cases.project.program.name",
"value":["TCGA"]}},... | def get_clinical_data(tcga_id) | Get clinical data for a TCGA project.
Parameters
----------
tcga_id : str
The TCGA project ID.
Returns
-------
`pandas.DataFrame`
The clinical data.abs
Notes
-----
Clinical data is associated with individual cases (patients). These
correspond to rows in... | 3.090388 | 3.122307 | 0.989777 |
payload = {
'attachment': 'true',
"filters": json.dumps({
"op": "and",
"content": [
{
"op":"in",
"content":{
"field":"cases.project.program.name",
"value":["TCGA"]}},... | def get_biospecimen_data(tcga_id) | Get biospecimen data for a TCGA project.
Parameters
----------
tcga_id : str
The TCGA project ID.
Returns
-------
`pandas.DataFrame`
The biospecmin data.
Notes
-----
Biospecimen data is associated with individual vials. TCGA vials correspond
to portions... | 2.908761 | 2.941077 | 0.989012 |
payload = {
"filters": json.dumps({
"op": "and",
"content" : [
{
"op":"in",
"content":{
"field":"cases.project.program.name",
"value":["TCGA"]}},
{
... | def get_masked_cnv_manifest(tcga_id) | Get manifest for masked TCGA copy-number variation data.
Params
------
tcga_id : str
The TCGA project ID.
download_file : str
The path of the download file.
Returns
-------
`pandas.DataFrame`
The manifest. | 2.413106 | 2.608956 | 0.924932 |
assert isinstance(file_ids, Iterable)
# query TCGA API to get sample barcodes associated with file IDs
payload = {
"filters":json.dumps({
"op":"in",
"content":{
"field":"files.file_id",
"value": list(file_ids),
}
}),
... | def get_file_samples(file_ids) | Get TCGA associated sample barcodes for a list of file IDs.
Params
------
file_ids : Iterable
The file IDs.
Returns
-------
`pandas.Series`
Series containing file IDs as index and corresponding sample barcodes. | 2.394885 | 2.300454 | 1.041049 |
assert isinstance(file_samples, pd.DataFrame)
df = file_samples # use shorter variable name
# sort data frame by file ID
df = df.sort_values('file_id')
# - some samples have multiple files with the same barcode,
# corresponding to different aliquots
# get rid of those duplicates
... | def get_unique_sample_files(file_samples) | Filter file_sample data frame to only keep one file per sample.
Params
------
file_samples : `pandas.DataFrame`
A data frame containing a mapping between file IDs and sample barcodes.
This type of data frame is returned by :meth:`get_file_samples`.
Returns
-------
`... | 3.55621 | 3.408226 | 1.04342 |
df = biospecimen # use shorter variable name
# get rid of FFPE samples
num_before = len(df.index)
df = df.loc[~df['is_ffpe']]
logger.info('Excluded %d files associated with FFPE samples '
'(out of %d files in total).',
num_before - len(df.index), num_before)
... | def get_fresh_primary_tumors(biospecimen) | Filter biospecimen data to only keep non-FFPE primary tumor samples.
Parameters
----------
biospecimen : `pandas.DataFrame`
The biospecimen data frame. This type of data frame is returned by
:meth:`get_biospecimen_data`.
Returns
-------
`pandas.DataFrame`
The fi... | 3.216413 | 3.191179 | 1.007907 |
seen = set()
add = seen.add
for read in reads:
hash_ = md5(read.sequence.encode('UTF-8')).digest()
if hash_ not in seen:
add(hash_)
yield read | def dedupFasta(reads) | Remove sequence duplicates (based on sequence) from FASTA.
@param reads: a C{dark.reads.Reads} instance.
@return: a generator of C{dark.reads.Read} instances with no duplicates. | 3.515949 | 4.095188 | 0.858556 |
sequences = sorted(sequences, key=lambda s: len(s.seq), reverse=True)
seen = set()
for s in sequences:
thisSeq = str(s.seq)
thisHash = md5(thisSeq.encode('UTF-8')).digest()
if thisHash not in seen:
# Add prefixes.
newHash = md5()
for nucl in t... | def dePrefixAndSuffixFasta(sequences) | sequences: an iterator producing Bio.Seq sequences.
return: a generator of sequences with no duplicates and no fully contained
subsequences. | 2.710397 | 2.748515 | 0.986131 |
reads = {}
firstFile = fastaFiles.pop(0)
for seq in SeqIO.parse(firstFile, 'fasta'):
reads[seq.id] = seq
for fastaFile in fastaFiles:
for seq in SeqIO.parse(fastaFile, 'fasta'):
# Make sure that reads with the same id have the same sequence.
if seq.id in rea... | def fastaSubtract(fastaFiles) | Given a list of open file descriptors, each with FASTA content,
remove the reads found in the 2nd, 3rd, etc files from the first file
in the list.
@param fastaFiles: a C{list} of FASTA filenames.
@raises IndexError: if passed an empty list.
@return: An iterator producing C{Bio.SeqRecord} instances ... | 2.441229 | 2.626453 | 0.929478 |
# Read sequences from a FASTA file, if given.
if filename:
reads = FastaReads(filename, readClass=readClass, upperCase=upperCase)
else:
reads = Reads()
# Add any individually specified subject sequences.
if sequences:
for count, sequence in enumerate(sequences, start=1)... | def combineReads(filename, sequences, readClass=DNARead,
upperCase=False, idPrefix='command-line-read-') | Combine FASTA reads from a file and/or sequence strings.
@param filename: A C{str} file name containing FASTA reads.
@param sequences: A C{list} of C{str} sequences. If a sequence
contains spaces, the last field (after splitting on spaces) will be
used as the sequence and the first fields will ... | 3.227001 | 3.253696 | 0.991795 |
count = 0
for _file in self._files:
with asHandle(_file) as fp:
# Duplicate some code here so as not to test
# self._upperCase in the loop.
if self._upperCase:
for seq in SeqIO.parse(fp, 'fasta'):
... | def iter(self) | Iterate over the sequences in the files in self.files_, yielding each
as an instance of the desired read class. | 4.3104 | 3.733465 | 1.154531 |
if self._upperCase:
for id_ in self._fasta:
yield self._readClass(id_, str(self._fasta[id_]).upper())
else:
for id_ in self._fasta:
yield self._readClass(id_, str(self._fasta[id_])) | def iter(self) | Iterate over the sequences in the files in self.files_, yielding each
as an instance of the desired read class. | 4.019165 | 3.059494 | 1.31367 |
cur = self._connection.cursor()
cur.execute('SELECT name FROM files WHERE id = ?', (fileNumber,))
row = cur.fetchone()
if row is None:
return None
else:
return row[0] | def _getFilename(self, fileNumber) | Given a file number, get its name (if any).
@param fileNumber: An C{int} file number.
@return: A C{str} file name or C{None} if a file with that number
has not been added. | 2.458638 | 2.514549 | 0.977765 |
cur = self._connection.cursor()
cur.execute('SELECT id FROM files WHERE name = ?', (filename,))
row = cur.fetchone()
if row is None:
return None
else:
return row[0] | def _getFileNumber(self, filename) | Given a file name, get its file number (if any).
@param filename: A C{str} file name.
@return: An C{int} file number or C{None} if no file with that name
has been added. | 2.401051 | 2.566328 | 0.935598 |
cur = self._connection.cursor()
try:
cur.execute('INSERT INTO files(name) VALUES (?)', (filename,))
except sqlite3.IntegrityError as e:
if str(e).find('UNIQUE constraint failed') > -1:
raise ValueError('Duplicate file name: %r' % filename)
... | def _addFilename(self, filename) | Add a new file name.
@param filename: A C{str} file name.
@raise ValueError: If a file with this name has already been added.
@return: The C{int} id of the newly added file. | 2.675507 | 2.621535 | 1.020588 |
endswith = filename.lower().endswith
if endswith('.bgz') or endswith('.gz'):
useBgzf = True
elif endswith('.bz2'):
raise ValueError(
'Compressed FASTA is only supported in BGZF format. Use '
'bgzip to compresss your FASTA.')
... | def addFile(self, filename) | Add a new FASTA file of sequences.
@param filename: A C{str} file name, with the file in FASTA format.
This file must (obviously) exist at indexing time. When __getitem__
is used to access sequences, it is possible to provide a
C{fastaDirectory} argument to our C{__init__} t... | 2.867843 | 2.756654 | 1.040335 |
cur = self._connection.cursor()
cur.execute(
'SELECT fileNumber, offset FROM sequences WHERE id = ?', (id_,))
row = cur.fetchone()
if row is None:
return None
else:
return self._getFilename(row[0]), row[1] | def _find(self, id_) | Find the filename and offset of a sequence, given its id.
@param id_: A C{str} sequence id.
@return: A 2-tuple, containing the C{str} file name and C{int} offset
within that file of the sequence. | 3.747814 | 3.090882 | 1.212539 |
# use regular expression with negative lookbehind to make sure we don't
# split on escaped semicolons ("\;")
attr_sep = re.compile(r'(?<!\\)\s*;\s*')
attr = {}
atts = attr_sep.split(s)
for a in atts:
#print(a)
kv = a.split(' ', maxsplit=1)
if len(kv) == 2:
... | def parse_attributes(s) | Parses the ``attribute`` string of a GFF/GTF annotation.
Parameters
----------
s : str
The attribute string.
Returns
-------
dict
A dictionary containing attribute name/value pairs.
Notes
-----
The ``attribute`` string is the 9th field of each annotation (row),
... | 3.417763 | 3.484736 | 0.980781 |
if len(record.alignments) == 0:
return 0
if record.descriptions[0].e > 1e-120:
return 0
print(record.query, end=' ')
for i, alignment in enumerate(record.alignments):
print(record.descriptions[i].e, end=' ')
for hspIndex, hsp in enumerate(alignment.hsps, start=1):
... | def printBlastRecordForDerek(record) | This is a hacked version of printBlastRecord that I wrote in
Addenbrookes hospital so Derek could try hacking on the reads
that had low e values. It's called by bin/print-blast-xml-for-derek.py | 2.665288 | 2.579159 | 1.033394 |
match = _PATHOGEN_RE.match(names)
if match:
proteinName = match.group(1).strip()
pathogenName = match.group(2).strip()
else:
proteinName = names
pathogenName = _NO_PATHOGEN_NAME
return proteinName, pathogenName | def splitNames(names) | Split a sequence id string like "Protein name [pathogen name]" into two
pieces using the final square brackets to delimit the pathogen name.
@param names: A C{str} "protein name [pathogen name]" string.
@return: A 2-C{tuple} giving the C{str} protein name and C{str} pathogen
name. If C{names} canno... | 3.290487 | 2.095714 | 1.570103 |
result = Counter()
if filenames:
for filename in filenames:
for protein in FastaReads(filename):
_, pathogenName = splitNames(protein.id)
if pathogenName != _NO_PATHOGEN_NAME:
result[pathogenName] += 1
return result | def getPathogenProteinCounts(filenames) | Get the number of proteins for each pathogen in C{filenames}.
@param filenames: Either C{None} or a C{list} of C{str} FASTA file names.
If C{None} an empty C{Counter} is returned. If FASTA file names are
given, their sequence ids should have the format used in the NCBI
bacterial and viral p... | 5.192555 | 5.230089 | 0.992824 |
pathogenIndex = self._pathogens.setdefault(pathogenName,
len(self._pathogens))
sampleIndex = self._samples.setdefault(sampleName, len(self._samples))
try:
return self._readsFilenames[(pathogenIndex, sampleIndex)]
ex... | def add(self, pathogenName, sampleName) | Add a (pathogen name, sample name) combination and get its FASTA/FASTQ
file name and unique read count. Write the FASTA/FASTQ file if it does
not already exist. Save the unique read count into
C{self._proteinGrouper}.
@param pathogenName: A C{str} pathogen name.
@param sampleNam... | 3.854296 | 3.267469 | 1.179597 |
pathogenIndex = self._pathogens[pathogenName]
sampleIndex = self._samples[sampleName]
return self._readsFilenames[(pathogenIndex, sampleIndex)] | def lookup(self, pathogenName, sampleName) | Look up a pathogen name, sample name combination and get its
FASTA/FASTQ file name and unique read count.
This method should be used instead of C{add} in situations where
you want an exception to be raised if a pathogen/sample combination has
not already been passed to C{add}.
... | 3.981945 | 3.950945 | 1.007846 |
print('\n'.join(
'%d %s' % (index, name) for (index, name) in
sorted((index, name) for (name, index) in self._samples.items())
), file=fp) | def writeSampleIndex(self, fp) | Write a file of sample indices and names, sorted by index.
@param fp: A file-like object, opened for writing. | 3.827097 | 3.488864 | 1.096946 |
print('\n'.join(
'%d %s' % (index, name) for (index, name) in
sorted((index, name) for (name, index) in self._pathogens.items())
), file=fp) | def writePathogenIndex(self, fp) | Write a file of pathogen indices and names, sorted by index.
@param fp: A file-like object, opened for writing. | 3.851636 | 3.427166 | 1.123854 |
return (
'Overall, proteins from %d pathogen%s were found in %d sample%s.' %
(len(self.pathogenNames),
'' if len(self.pathogenNames) == 1 else 's',
len(self.sampleNames),
'' if len(self.sampleNames) == 1 else 's')) | def _title(self) | Create a title summarizing the pathogens and samples.
@return: A C{str} title. | 4.173963 | 3.395485 | 1.229269 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.