repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
flo-compbio/genometools | genometools/basic/gene_set.py | GeneSet.from_list | def from_list(cls, l):
"""Generate an GeneSet object from a list of strings.
Note: See also :meth:`to_list`.
Parameters
----------
l: list or tuple of str
A list of strings representing gene set ID, name, genes,
source, collection, and description. The genes must be
comma-separated. See also :meth:`to_list`.
Returns
-------
`genometools.basic.GeneSet`
The gene set.
"""
id_ = l[0]
name = l[3]
genes = l[4].split(',')
src = l[1] or None
coll = l[2] or None
desc = l[5] or None
return cls(id_, name, genes, src, coll, desc) | python | def from_list(cls, l):
"""Generate an GeneSet object from a list of strings.
Note: See also :meth:`to_list`.
Parameters
----------
l: list or tuple of str
A list of strings representing gene set ID, name, genes,
source, collection, and description. The genes must be
comma-separated. See also :meth:`to_list`.
Returns
-------
`genometools.basic.GeneSet`
The gene set.
"""
id_ = l[0]
name = l[3]
genes = l[4].split(',')
src = l[1] or None
coll = l[2] or None
desc = l[5] or None
return cls(id_, name, genes, src, coll, desc) | [
"def",
"from_list",
"(",
"cls",
",",
"l",
")",
":",
"id_",
"=",
"l",
"[",
"0",
"]",
"name",
"=",
"l",
"[",
"3",
"]",
"genes",
"=",
"l",
"[",
"4",
"]",
".",
"split",
"(",
"','",
")",
"src",
"=",
"l",
"[",
"1",
"]",
"or",
"None",
"coll",
... | Generate an GeneSet object from a list of strings.
Note: See also :meth:`to_list`.
Parameters
----------
l: list or tuple of str
A list of strings representing gene set ID, name, genes,
source, collection, and description. The genes must be
comma-separated. See also :meth:`to_list`.
Returns
-------
`genometools.basic.GeneSet`
The gene set. | [
"Generate",
"an",
"GeneSet",
"object",
"from",
"a",
"list",
"of",
"strings",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/basic/gene_set.py#L187-L212 |
acorg/dark-matter | dark/sequence.py | findPrimer | def findPrimer(primer, seq):
"""
Look for a primer sequence.
@param primer: A C{str} primer sequence.
@param seq: A BioPython C{Bio.Seq} sequence.
@return: A C{list} of zero-based offsets into the sequence at which the
primer can be found. If no instances are found, return an empty
C{list}.
"""
offsets = []
seq = seq.upper()
primer = primer.upper()
primerLen = len(primer)
discarded = 0
offset = seq.find(primer)
while offset > -1:
offsets.append(discarded + offset)
seq = seq[offset + primerLen:]
discarded += offset + primerLen
offset = seq.find(primer)
return offsets | python | def findPrimer(primer, seq):
"""
Look for a primer sequence.
@param primer: A C{str} primer sequence.
@param seq: A BioPython C{Bio.Seq} sequence.
@return: A C{list} of zero-based offsets into the sequence at which the
primer can be found. If no instances are found, return an empty
C{list}.
"""
offsets = []
seq = seq.upper()
primer = primer.upper()
primerLen = len(primer)
discarded = 0
offset = seq.find(primer)
while offset > -1:
offsets.append(discarded + offset)
seq = seq[offset + primerLen:]
discarded += offset + primerLen
offset = seq.find(primer)
return offsets | [
"def",
"findPrimer",
"(",
"primer",
",",
"seq",
")",
":",
"offsets",
"=",
"[",
"]",
"seq",
"=",
"seq",
".",
"upper",
"(",
")",
"primer",
"=",
"primer",
".",
"upper",
"(",
")",
"primerLen",
"=",
"len",
"(",
"primer",
")",
"discarded",
"=",
"0",
"o... | Look for a primer sequence.
@param primer: A C{str} primer sequence.
@param seq: A BioPython C{Bio.Seq} sequence.
@return: A C{list} of zero-based offsets into the sequence at which the
primer can be found. If no instances are found, return an empty
C{list}. | [
"Look",
"for",
"a",
"primer",
"sequence",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/sequence.py#L4-L28 |
acorg/dark-matter | dark/sequence.py | findPrimerBidi | def findPrimerBidi(primer, seq):
"""
Look for a primer in a sequence and its reverse complement.
@param primer: A C{str} primer sequence.
@param seq: A BioPython C{Bio.Seq} sequence.
@return: A C{tuple} of two lists. The first contains (zero-based)
ascending offsets into the sequence at which the primer can be found.
The second is a similar list ascending offsets into the original
sequence where the primer matches the reverse complemented of the
sequence. If no instances are found, the corresponding list in the
returned tuple must be empty.
"""
# Note that we reverse complement the primer to find the reverse
# matches. This is much simpler than reverse complementing the sequence
# because it allows us to use findPrimer and to deal with overlapping
# matches correctly.
forward = findPrimer(primer, seq)
reverse = findPrimer(reverse_complement(primer), seq)
return forward, reverse | python | def findPrimerBidi(primer, seq):
"""
Look for a primer in a sequence and its reverse complement.
@param primer: A C{str} primer sequence.
@param seq: A BioPython C{Bio.Seq} sequence.
@return: A C{tuple} of two lists. The first contains (zero-based)
ascending offsets into the sequence at which the primer can be found.
The second is a similar list ascending offsets into the original
sequence where the primer matches the reverse complemented of the
sequence. If no instances are found, the corresponding list in the
returned tuple must be empty.
"""
# Note that we reverse complement the primer to find the reverse
# matches. This is much simpler than reverse complementing the sequence
# because it allows us to use findPrimer and to deal with overlapping
# matches correctly.
forward = findPrimer(primer, seq)
reverse = findPrimer(reverse_complement(primer), seq)
return forward, reverse | [
"def",
"findPrimerBidi",
"(",
"primer",
",",
"seq",
")",
":",
"# Note that we reverse complement the primer to find the reverse",
"# matches. This is much simpler than reverse complementing the sequence",
"# because it allows us to use findPrimer and to deal with overlapping",
"# matches corre... | Look for a primer in a sequence and its reverse complement.
@param primer: A C{str} primer sequence.
@param seq: A BioPython C{Bio.Seq} sequence.
@return: A C{tuple} of two lists. The first contains (zero-based)
ascending offsets into the sequence at which the primer can be found.
The second is a similar list ascending offsets into the original
sequence where the primer matches the reverse complemented of the
sequence. If no instances are found, the corresponding list in the
returned tuple must be empty. | [
"Look",
"for",
"a",
"primer",
"in",
"a",
"sequence",
"and",
"its",
"reverse",
"complement",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/sequence.py#L31-L51 |
acorg/dark-matter | dark/sequence.py | findPrimerBidiLimits | def findPrimerBidiLimits(primer, seq):
"""
Report the extreme (inner) offsets of primer in a sequence and its
reverse complement.
@param primer: A C{str} primer sequence.
@param seq: A BioPython C{Bio.Seq} sequence.
@return: A C{tuple} of two C{int} offsets. The first is a (zero-based)
offset into the sequence that is beyond the first instance (if any)
of the primer. The second is an offset into the original sequence of
the beginning of the last instance of the primer in the reverse
complemented sequence.
In other words, if you wanted to chop all instances of a primer
out of a sequence from the start and the end (when reverse
complemented) you'd call this function and do something like this:
start, end = findPrimerBidiLimits(primer, seq)
seq = seq[start:end]
"""
forward, reverse = findPrimerBidi(primer, seq)
if forward:
start = forward[-1] + len(primer)
end = len(seq)
for offset in reverse:
if offset >= start:
end = offset
break
else:
start = 0
end = reverse[0] if reverse else len(seq)
return start, end | python | def findPrimerBidiLimits(primer, seq):
"""
Report the extreme (inner) offsets of primer in a sequence and its
reverse complement.
@param primer: A C{str} primer sequence.
@param seq: A BioPython C{Bio.Seq} sequence.
@return: A C{tuple} of two C{int} offsets. The first is a (zero-based)
offset into the sequence that is beyond the first instance (if any)
of the primer. The second is an offset into the original sequence of
the beginning of the last instance of the primer in the reverse
complemented sequence.
In other words, if you wanted to chop all instances of a primer
out of a sequence from the start and the end (when reverse
complemented) you'd call this function and do something like this:
start, end = findPrimerBidiLimits(primer, seq)
seq = seq[start:end]
"""
forward, reverse = findPrimerBidi(primer, seq)
if forward:
start = forward[-1] + len(primer)
end = len(seq)
for offset in reverse:
if offset >= start:
end = offset
break
else:
start = 0
end = reverse[0] if reverse else len(seq)
return start, end | [
"def",
"findPrimerBidiLimits",
"(",
"primer",
",",
"seq",
")",
":",
"forward",
",",
"reverse",
"=",
"findPrimerBidi",
"(",
"primer",
",",
"seq",
")",
"if",
"forward",
":",
"start",
"=",
"forward",
"[",
"-",
"1",
"]",
"+",
"len",
"(",
"primer",
")",
"... | Report the extreme (inner) offsets of primer in a sequence and its
reverse complement.
@param primer: A C{str} primer sequence.
@param seq: A BioPython C{Bio.Seq} sequence.
@return: A C{tuple} of two C{int} offsets. The first is a (zero-based)
offset into the sequence that is beyond the first instance (if any)
of the primer. The second is an offset into the original sequence of
the beginning of the last instance of the primer in the reverse
complemented sequence.
In other words, if you wanted to chop all instances of a primer
out of a sequence from the start and the end (when reverse
complemented) you'd call this function and do something like this:
start, end = findPrimerBidiLimits(primer, seq)
seq = seq[start:end] | [
"Report",
"the",
"extreme",
"(",
"inner",
")",
"offsets",
"of",
"primer",
"in",
"a",
"sequence",
"and",
"its",
"reverse",
"complement",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/sequence.py#L54-L87 |
acorg/dark-matter | dark/utils.py | numericallySortFilenames | def numericallySortFilenames(names):
"""
Sort (ascending) a list of file names by their numerical prefixes.
The number sorted on is the numeric prefix of the basename of
the given filename. E.g., '../output/1.json.bz2' will sort before
'../output/10.json.bz2'.
@param: A C{list} of file names, each of whose basename starts with a
string of digits.
@return: The sorted C{list} of full file names.
"""
def numericPrefix(name):
"""
Find any numeric prefix of C{name} and return it as an C{int}.
@param: A C{str} file name, whose name possibly starts with digits.
@return: The C{int} number at the start of the name, else 0 if
there are no leading digits in the name.
"""
count = 0
for ch in name:
if ch in string.digits:
count += 1
else:
break
return 0 if count == 0 else int(name[0:count])
return sorted(names, key=lambda name: numericPrefix(basename(name))) | python | def numericallySortFilenames(names):
"""
Sort (ascending) a list of file names by their numerical prefixes.
The number sorted on is the numeric prefix of the basename of
the given filename. E.g., '../output/1.json.bz2' will sort before
'../output/10.json.bz2'.
@param: A C{list} of file names, each of whose basename starts with a
string of digits.
@return: The sorted C{list} of full file names.
"""
def numericPrefix(name):
"""
Find any numeric prefix of C{name} and return it as an C{int}.
@param: A C{str} file name, whose name possibly starts with digits.
@return: The C{int} number at the start of the name, else 0 if
there are no leading digits in the name.
"""
count = 0
for ch in name:
if ch in string.digits:
count += 1
else:
break
return 0 if count == 0 else int(name[0:count])
return sorted(names, key=lambda name: numericPrefix(basename(name))) | [
"def",
"numericallySortFilenames",
"(",
"names",
")",
":",
"def",
"numericPrefix",
"(",
"name",
")",
":",
"\"\"\"\n Find any numeric prefix of C{name} and return it as an C{int}.\n\n @param: A C{str} file name, whose name possibly starts with digits.\n @return: The C{int... | Sort (ascending) a list of file names by their numerical prefixes.
The number sorted on is the numeric prefix of the basename of
the given filename. E.g., '../output/1.json.bz2' will sort before
'../output/10.json.bz2'.
@param: A C{list} of file names, each of whose basename starts with a
string of digits.
@return: The sorted C{list} of full file names. | [
"Sort",
"(",
"ascending",
")",
"a",
"list",
"of",
"file",
"names",
"by",
"their",
"numerical",
"prefixes",
".",
"The",
"number",
"sorted",
"on",
"is",
"the",
"numeric",
"prefix",
"of",
"the",
"basename",
"of",
"the",
"given",
"filename",
".",
"E",
".",
... | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/utils.py#L13-L41 |
acorg/dark-matter | dark/utils.py | asHandle | 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}.
"""
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('.bz2'):
if six.PY3:
yield bz2.open(fileNameOrHandle, mode='rt', encoding='UTF-8')
else:
yield bz2.BZ2File(fileNameOrHandle)
else:
with open(fileNameOrHandle) as fp:
yield fp
else:
yield fileNameOrHandle | python | 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}.
"""
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('.bz2'):
if six.PY3:
yield bz2.open(fileNameOrHandle, mode='rt', encoding='UTF-8')
else:
yield bz2.BZ2File(fileNameOrHandle)
else:
with open(fileNameOrHandle) as fp:
yield fp
else:
yield fileNameOrHandle | [
"def",
"asHandle",
"(",
"fileNameOrHandle",
",",
"mode",
"=",
"'r'",
")",
":",
"if",
"isinstance",
"(",
"fileNameOrHandle",
",",
"six",
".",
"string_types",
")",
":",
"if",
"fileNameOrHandle",
".",
"endswith",
"(",
"'.gz'",
")",
":",
"if",
"six",
".",
"P... | 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}. | [
"Decorator",
"for",
"file",
"opening",
"that",
"makes",
"it",
"easy",
"to",
"open",
"compressed",
"files",
".",
"Based",
"on",
"L",
"{",
"Bio",
".",
"File",
".",
"as_handle",
"}",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/utils.py#L106-L130 |
acorg/dark-matter | dark/utils.py | parseRangeString | 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 in the specified set.
"""
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:
start, end = end, start
if convertToZeroBased:
result.update(range(start - 1, end))
else:
result.update(range(start, end + 1))
else:
raise ValueError(
'Illegal range %r. Ranges must single numbers or '
'number-number.' % _range)
return result | python | 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 in the specified set.
"""
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:
start, end = end, start
if convertToZeroBased:
result.update(range(start - 1, end))
else:
result.update(range(start, end + 1))
else:
raise ValueError(
'Illegal range %r. Ranges must single numbers or '
'number-number.' % _range)
return result | [
"def",
"parseRangeString",
"(",
"s",
",",
"convertToZeroBased",
"=",
"False",
")",
":",
"result",
"=",
"set",
"(",
")",
"for",
"_range",
"in",
"s",
".",
"split",
"(",
"','",
")",
":",
"match",
"=",
"_rangeRegex",
".",
"match",
"(",
"_range",
")",
"if... | 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 in the specified set. | [
"Parse",
"a",
"range",
"string",
"of",
"the",
"form",
"1",
"-",
"5",
"12",
"100",
"-",
"200",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/utils.py#L136-L168 |
acorg/dark-matter | dark/utils.py | nucleotidesToStr | 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 for each.
"""
result = []
for offset in sorted(nucleotides):
result.append(
'%s%d: %s' % (prefix, offset,
baseCountsToStr(nucleotides[offset])))
return '\n'.join(result) | python | 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 for each.
"""
result = []
for offset in sorted(nucleotides):
result.append(
'%s%d: %s' % (prefix, offset,
baseCountsToStr(nucleotides[offset])))
return '\n'.join(result) | [
"def",
"nucleotidesToStr",
"(",
"nucleotides",
",",
"prefix",
"=",
"''",
")",
":",
"result",
"=",
"[",
"]",
"for",
"offset",
"in",
"sorted",
"(",
"nucleotides",
")",
":",
"result",
".",
"append",
"(",
"'%s%d: %s'",
"%",
"(",
"prefix",
",",
"offset",
",... | 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 for each. | [
"Convert",
"offsets",
"and",
"base",
"counts",
"to",
"a",
"string",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/utils.py#L201-L216 |
acorg/dark-matter | dark/utils.py | countPrint | 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 C{len1}.
@return: A C{str} for printing.
"""
def percentage(a, b):
"""
What percent of a is b?
@param a: a numeric value.
@param b: a numeric value.
@return: the C{float} percentage.
"""
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))
else:
return ('%s: %d/%d (%.2f%%) of sequence 1, '
'%d/%d (%.2f%%) of sequence 2' % (
mesg,
count, len1, percentage(count, len1),
count, len2, percentage(count, len2))) | python | 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 C{len1}.
@return: A C{str} for printing.
"""
def percentage(a, b):
"""
What percent of a is b?
@param a: a numeric value.
@param b: a numeric value.
@return: the C{float} percentage.
"""
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))
else:
return ('%s: %d/%d (%.2f%%) of sequence 1, '
'%d/%d (%.2f%%) of sequence 2' % (
mesg,
count, len1, percentage(count, len1),
count, len2, percentage(count, len2))) | [
"def",
"countPrint",
"(",
"mesg",
",",
"count",
",",
"len1",
",",
"len2",
"=",
"None",
")",
":",
"def",
"percentage",
"(",
"a",
",",
"b",
")",
":",
"\"\"\"\n What percent of a is b?\n\n @param a: a numeric value.\n @param b: a numeric value.\n ... | 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 C{len1}.
@return: A C{str} for printing. | [
"Format",
"a",
"message",
"followed",
"by",
"an",
"integer",
"count",
"and",
"a",
"percentage",
"(",
"or",
"two",
"if",
"the",
"sequence",
"lengths",
"are",
"unequal",
")",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/utils.py#L219-L253 |
flo-compbio/genometools | genometools/gcloud/tasks/util.py | upload_scripts | def upload_scripts(client, script_dir, overwrite=True):
"""Uploads general-purpose scripts to a Google Storage bucket.
TODO: docstring"""
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.split(os.sep)[depth:])
for f in files:
local_path = os.path.join(root, f)
if rel_path:
remote_path = '/'.join([script_prefix, rel_path, f])
else:
remote_path = '/'.join([script_prefix, f])
_LOGGER.info('Uploading "%s"...', remote_path)
storage.upload_file(client, script_bucket, local_path, remote_path,
overwrite=overwrite) | python | def upload_scripts(client, script_dir, overwrite=True):
"""Uploads general-purpose scripts to a Google Storage bucket.
TODO: docstring"""
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.split(os.sep)[depth:])
for f in files:
local_path = os.path.join(root, f)
if rel_path:
remote_path = '/'.join([script_prefix, rel_path, f])
else:
remote_path = '/'.join([script_prefix, f])
_LOGGER.info('Uploading "%s"...', remote_path)
storage.upload_file(client, script_bucket, local_path, remote_path,
overwrite=overwrite) | [
"def",
"upload_scripts",
"(",
"client",
",",
"script_dir",
",",
"overwrite",
"=",
"True",
")",
":",
"local_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"genometools",
".",
"_root",
",",
"'data'",
",",
"'gcloud'",
",",
"'scripts'",
")",
"match",
"=",
... | Uploads general-purpose scripts to a Google Storage bucket.
TODO: docstring | [
"Uploads",
"general",
"-",
"purpose",
"scripts",
"to",
"a",
"Google",
"Storage",
"bucket",
".",
"TODO",
":",
"docstring"
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gcloud/tasks/util.py#L22-L44 |
acorg/dark-matter | dark/diamond/alignments.py | DiamondReadsAlignments._getReader | 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).
"""
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) | python | 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).
"""
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",
")",
":",
"if",
"filename",
".",
"endswith",
"(",
"'.json'",
")",
"or",
"filename",
".",
"endswith",
"(",
"'.json.bz2'",
")",
":",
"return",
"JSONRecordsReader",
"(",
"filename",
",",
"s... | 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). | [
"Obtain",
"a",
"JSON",
"record",
"reader",
"for",
"DIAMOND",
"records",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/diamond/alignments.py#L84-L95 |
acorg/dark-matter | dark/diamond/alignments.py | DiamondReadsAlignments.iter | def iter(self):
"""
Extract DIAMOND records and yield C{ReadAlignments} instances.
@return: A generator that yields C{ReadAlignments} instances.
"""
# 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
for filename in self.filenames:
if first:
# The first file has already been opened, in __init__.
first = False
reader = self._reader
else:
reader = self._getReader(filename, self.scoreClass)
for readAlignments in reader.readAlignments(reads):
yield readAlignments
# Any remaining query reads must have had no subject matches.
for read in reads:
yield ReadAlignments(read, []) | python | def iter(self):
"""
Extract DIAMOND records and yield C{ReadAlignments} instances.
@return: A generator that yields C{ReadAlignments} instances.
"""
# 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
for filename in self.filenames:
if first:
# The first file has already been opened, in __init__.
first = False
reader = self._reader
else:
reader = self._getReader(filename, self.scoreClass)
for readAlignments in reader.readAlignments(reads):
yield readAlignments
# Any remaining query reads must have had no subject matches.
for read in reads:
yield ReadAlignments(read, []) | [
"def",
"iter",
"(",
"self",
")",
":",
"# 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",
... | Extract DIAMOND records and yield C{ReadAlignments} instances.
@return: A generator that yields C{ReadAlignments} instances. | [
"Extract",
"DIAMOND",
"records",
"and",
"yield",
"C",
"{",
"ReadAlignments",
"}",
"instances",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/diamond/alignments.py#L97-L124 |
acorg/dark-matter | dark/diamond/alignments.py | DiamondReadsAlignments.getSubjectSequence | 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.
"""
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._databaseDirectory,
readClass=AAReadWithX)
else:
# Build a dict to look up subjects.
titles = {}
for read in FastaReads(self._databaseFilename,
readClass=AAReadWithX):
titles[read.id] = read
self._subjectTitleToSubject = titles
return self._subjectTitleToSubject[title] | python | 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.
"""
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._databaseDirectory,
readClass=AAReadWithX)
else:
# Build a dict to look up subjects.
titles = {}
for read in FastaReads(self._databaseFilename,
readClass=AAReadWithX):
titles[read.id] = read
self._subjectTitleToSubject = titles
return self._subjectTitleToSubject[title] | [
"def",
"getSubjectSequence",
"(",
"self",
",",
"title",
")",
":",
"if",
"self",
".",
"_subjectTitleToSubject",
"is",
"None",
":",
"if",
"self",
".",
"_databaseFilename",
"is",
"None",
":",
"# An Sqlite3 database is used to look up subjects.",
"self",
".",
"_subjectT... | 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. | [
"Obtain",
"information",
"about",
"a",
"subject",
"sequence",
"given",
"its",
"title",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/diamond/alignments.py#L126-L150 |
flo-compbio/genometools | genometools/ncbi/sra/util.py | get_project_urls | def get_project_urls(project):
"""Get the URLs for all runs from a given project.
TODO: docstring"""
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)
# compile a list of all files
for folder in run_folders:
files = ftp_host.listdir(folder)
assert len(files) == 1
for f in files:
path = exp_dir + folder + '/' + f
urls.append(path)
return urls | python | def get_project_urls(project):
"""Get the URLs for all runs from a given project.
TODO: docstring"""
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)
# compile a list of all files
for folder in run_folders:
files = ftp_host.listdir(folder)
assert len(files) == 1
for f in files:
path = exp_dir + folder + '/' + f
urls.append(path)
return urls | [
"def",
"get_project_urls",
"(",
"project",
")",
":",
"urls",
"=",
"[",
"]",
"with",
"ftputil",
".",
"FTPHost",
"(",
"sra_host",
",",
"sra_user",
",",
"sra_password",
")",
"as",
"ftp_host",
":",
"download_paths",
"=",
"[",
"]",
"exp_dir",
"=",
"'/sra/sra-in... | Get the URLs for all runs from a given project.
TODO: docstring | [
"Get",
"the",
"URLs",
"for",
"all",
"runs",
"from",
"a",
"given",
"project",
".",
"TODO",
":",
"docstring"
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ncbi/sra/util.py#L27-L46 |
nkavaldj/myhdl_lib | examples/pipeline_control_simple.py | twos_complement | 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-stage pipeline
stage 0: registers input data
stage 1: inverts data coming from stage 0 and registers the inverted data
stage 2: increments data coming from stage 1 and registers the incremented data
Each stage is implemented as a separate process controlled by a central pipeline control unit via an enable signal
The pipeline control unit manages the handshake and synchronizes the operation of the stages
'''
DATA_WIDTH = len(rx_dat)
NUM_STAGES = 3
stage_en = Signal(intbv(0)[NUM_STAGES:])
pipe_ctrl = pipeline_control( rst = rst,
clk = clk,
rx_vld = rx_vld,
rx_rdy = rx_rdy,
tx_vld = tx_vld,
tx_rdy = tx_rdy,
stage_enable = stage_en)
s0_dat = Signal(intbv(0)[DATA_WIDTH:])
@always_seq(clk.posedge, reset=rst)
def stage_0():
''' Register input data'''
if (stage_en[0]):
s0_dat.next = rx_dat
s1_dat = Signal(intbv(0)[DATA_WIDTH:])
@always_seq(clk.posedge, reset=rst)
def stage_1():
''' Invert data'''
if (stage_en[1]):
s1_dat.next = ~s0_dat
s2_dat = Signal(intbv(0)[DATA_WIDTH:])
@always_seq(clk.posedge, reset=rst)
def stage_2():
''' Add one to data'''
if (stage_en[2]):
s2_dat.next = s1_dat + 1
@always_comb
def comb():
tx_dat.next = s2_dat.signed()
return instances() | python | 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-stage pipeline
stage 0: registers input data
stage 1: inverts data coming from stage 0 and registers the inverted data
stage 2: increments data coming from stage 1 and registers the incremented data
Each stage is implemented as a separate process controlled by a central pipeline control unit via an enable signal
The pipeline control unit manages the handshake and synchronizes the operation of the stages
'''
DATA_WIDTH = len(rx_dat)
NUM_STAGES = 3
stage_en = Signal(intbv(0)[NUM_STAGES:])
pipe_ctrl = pipeline_control( rst = rst,
clk = clk,
rx_vld = rx_vld,
rx_rdy = rx_rdy,
tx_vld = tx_vld,
tx_rdy = tx_rdy,
stage_enable = stage_en)
s0_dat = Signal(intbv(0)[DATA_WIDTH:])
@always_seq(clk.posedge, reset=rst)
def stage_0():
''' Register input data'''
if (stage_en[0]):
s0_dat.next = rx_dat
s1_dat = Signal(intbv(0)[DATA_WIDTH:])
@always_seq(clk.posedge, reset=rst)
def stage_1():
''' Invert data'''
if (stage_en[1]):
s1_dat.next = ~s0_dat
s2_dat = Signal(intbv(0)[DATA_WIDTH:])
@always_seq(clk.posedge, reset=rst)
def stage_2():
''' Add one to data'''
if (stage_en[2]):
s2_dat.next = s1_dat + 1
@always_comb
def comb():
tx_dat.next = s2_dat.signed()
return instances() | [
"def",
"twos_complement",
"(",
"rst",
",",
"clk",
",",
"rx_rdy",
",",
"rx_vld",
",",
"rx_dat",
",",
"tx_rdy",
",",
"tx_vld",
",",
"tx_dat",
")",
":",
"DATA_WIDTH",
"=",
"len",
"(",
"rx_dat",
")",
"NUM_STAGES",
"=",
"3",
"stage_en",
"=",
"Signal",
"(",
... | 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-stage pipeline
stage 0: registers input data
stage 1: inverts data coming from stage 0 and registers the inverted data
stage 2: increments data coming from stage 1 and registers the incremented data
Each stage is implemented as a separate process controlled by a central pipeline control unit via an enable signal
The pipeline control unit manages the handshake and synchronizes the operation of the stages | [
"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",
"&",
... | train | https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/examples/pipeline_control_simple.py#L7-L72 |
flo-compbio/genometools | genometools/ncbi/extract_entrez2gene.py | get_argument_parser | 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.
"""
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("""\
Path of gene2accession.gz file (from
ftp://ftp.ncbi.nlm.nih.gov/gene/DATA), or a filtered version
thereof.""")
)
parser.add_argument(
'-o', '--output-file', type=str, required=True,
help=textwrap.dedent("""\
Path of output file. If set to ``-``, print to ``stdout``,
and redirect logging messages to ``stderr``.""")
)
parser.add_argument(
'-l', '--log-file', type=str, default=None,
help='Path of log file. If not specified, print to stdout.'
)
parser.add_argument(
'-q', '--quiet', action='store_true',
help='Suppress all output except warnings and errors.'
)
parser.add_argument(
'-v', '--verbose', action='store_true',
help='Enable verbose output. Ignored if ``--quiet`` is specified.'
)
return parser | python | 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.
"""
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("""\
Path of gene2accession.gz file (from
ftp://ftp.ncbi.nlm.nih.gov/gene/DATA), or a filtered version
thereof.""")
)
parser.add_argument(
'-o', '--output-file', type=str, required=True,
help=textwrap.dedent("""\
Path of output file. If set to ``-``, print to ``stdout``,
and redirect logging messages to ``stderr``.""")
)
parser.add_argument(
'-l', '--log-file', type=str, default=None,
help='Path of log file. If not specified, print to stdout.'
)
parser.add_argument(
'-q', '--quiet', action='store_true',
help='Suppress all output except warnings and errors.'
)
parser.add_argument(
'-v', '--verbose', action='store_true',
help='Enable verbose output. Ignored if ``--quiet`` is specified.'
)
return parser | [
"def",
"get_argument_parser",
"(",
")",
":",
"desc",
"=",
"'Generate a mapping of Entrez IDs to gene symbols.'",
"parser",
"=",
"cli",
".",
"get_argument_parser",
"(",
"desc",
"=",
"desc",
")",
"parser",
".",
"add_argument",
"(",
"'-f'",
",",
"'--gene2acc-file'",
",... | 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. | [
"Creates",
"the",
"argument",
"parser",
"for",
"the",
"extract_entrez2gene",
".",
"py",
"script",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ncbi/extract_entrez2gene.py#L69-L116 |
flo-compbio/genometools | genometools/ncbi/extract_entrez2gene.py | read_gene2acc | 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.
"""
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:
gene2acc[id_].append(symbol)
except KeyError:
gene2acc[id_] = [symbol]
# print (l[0],l[15])
# make sure all EntrezIDs map to a unique gene symbol
n = len(gene2acc)
for k, v in gene2acc.items():
symbols = sorted(set(v))
assert len(symbols) == 1
gene2acc[k] = symbols[0]
all_symbols = sorted(set(gene2acc.values()))
m = len(all_symbols)
logger.info('Found %d Entrez Gene IDs associated with %d gene symbols.',
n, m)
return gene2acc | python | 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.
"""
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:
gene2acc[id_].append(symbol)
except KeyError:
gene2acc[id_] = [symbol]
# print (l[0],l[15])
# make sure all EntrezIDs map to a unique gene symbol
n = len(gene2acc)
for k, v in gene2acc.items():
symbols = sorted(set(v))
assert len(symbols) == 1
gene2acc[k] = symbols[0]
all_symbols = sorted(set(gene2acc.values()))
m = len(all_symbols)
logger.info('Found %d Entrez Gene IDs associated with %d gene symbols.',
n, m)
return gene2acc | [
"def",
"read_gene2acc",
"(",
"file_path",
",",
"logger",
")",
":",
"gene2acc",
"=",
"{",
"}",
"with",
"misc",
".",
"smart_open_read",
"(",
"file_path",
",",
"mode",
"=",
"'rb'",
",",
"try_gzip",
"=",
"True",
")",
"as",
"fh",
":",
"reader",
"=",
"csv",
... | 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. | [
"Extracts",
"Entrez",
"ID",
"-",
">",
"gene",
"symbol",
"mapping",
"from",
"gene2accession",
".",
"gz",
"file",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ncbi/extract_entrez2gene.py#L119-L160 |
flo-compbio/genometools | genometools/ncbi/extract_entrez2gene.py | write_entrez2gene | 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
"""
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 written to file "%s".', file_path) | python | 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
"""
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 written to file "%s".', file_path) | [
"def",
"write_entrez2gene",
"(",
"file_path",
",",
"entrez2gene",
",",
"logger",
")",
":",
"with",
"misc",
".",
"smart_open_write",
"(",
"file_path",
",",
"mode",
"=",
"'wb'",
")",
"as",
"ofh",
":",
"writer",
"=",
"csv",
".",
"writer",
"(",
"ofh",
",",
... | 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 | [
"Writes",
"Entrez",
"ID",
"-",
">",
"gene",
"symbol",
"mapping",
"to",
"a",
"tab",
"-",
"delimited",
"text",
"file",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ncbi/extract_entrez2gene.py#L163-L183 |
flo-compbio/genometools | genometools/ncbi/extract_entrez2gene.py | main | 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
-------
int
Exit code (0 if no error occurred).
Raises
------
SystemError
If the version of the Python interpreter is not >= 2.7.
"""
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()
gene2acc_file = args.gene2acc_file
output_file = args.output_file
log_file = args.log_file
quiet = args.quiet
verbose = args.verbose
# configure logger
log_stream = sys.stdout
if output_file == '-':
log_stream = sys.stderr
logger = misc.get_logger(log_stream=log_stream, log_file=log_file,
quiet=quiet, verbose=verbose)
entrez2gene = read_gene2acc(gene2acc_file, logger)
write_entrez2gene(output_file, entrez2gene, logger)
return 0 | python | 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
-------
int
Exit code (0 if no error occurred).
Raises
------
SystemError
If the version of the Python interpreter is not >= 2.7.
"""
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()
gene2acc_file = args.gene2acc_file
output_file = args.output_file
log_file = args.log_file
quiet = args.quiet
verbose = args.verbose
# configure logger
log_stream = sys.stdout
if output_file == '-':
log_stream = sys.stderr
logger = misc.get_logger(log_stream=log_stream, log_file=log_file,
quiet=quiet, verbose=verbose)
entrez2gene = read_gene2acc(gene2acc_file, logger)
write_entrez2gene(output_file, entrez2gene, logger)
return 0 | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"vinfo",
"=",
"sys",
".",
"version_info",
"if",
"not",
"(",
"vinfo",
">=",
"(",
"2",
",",
"7",
")",
")",
":",
"raise",
"SystemError",
"(",
"'Python interpreter version >= 2.7 required, '",
"'found %d.%d inst... | 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
-------
int
Exit code (0 if no error occurred).
Raises
------
SystemError
If the version of the Python interpreter is not >= 2.7. | [
"Extracts",
"Entrez",
"ID",
"-",
">",
"gene",
"symbol",
"mapping",
"and",
"writes",
"it",
"to",
"a",
"text",
"file",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ncbi/extract_entrez2gene.py#L186-L231 |
acorg/dark-matter | dark/aa.py | find | 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.
"""
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:
abbrev1 = ABBREV3_TO_ABBREV1[s]
elif s in NAMES_TO_ABBREV1:
abbrev1 = NAMES_TO_ABBREV1[s]
else:
# Look for a 3-letter codon.
def findCodon(target):
for abbrev1, codons in CODONS.items():
for codon in codons:
if codon == target:
return abbrev1
abbrev1 = findCodon(origS.upper())
if abbrev1:
return AminoAcid(
NAMES[abbrev1], ABBREV3[abbrev1], abbrev1, CODONS[abbrev1],
PROPERTIES[abbrev1], PROPERTY_DETAILS[abbrev1],
PROPERTY_CLUSTERS[abbrev1]) | python | 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.
"""
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:
abbrev1 = ABBREV3_TO_ABBREV1[s]
elif s in NAMES_TO_ABBREV1:
abbrev1 = NAMES_TO_ABBREV1[s]
else:
# Look for a 3-letter codon.
def findCodon(target):
for abbrev1, codons in CODONS.items():
for codon in codons:
if codon == target:
return abbrev1
abbrev1 = findCodon(origS.upper())
if abbrev1:
return AminoAcid(
NAMES[abbrev1], ABBREV3[abbrev1], abbrev1, CODONS[abbrev1],
PROPERTIES[abbrev1], PROPERTY_DETAILS[abbrev1],
PROPERTY_CLUSTERS[abbrev1]) | [
"def",
"find",
"(",
"s",
")",
":",
"abbrev1",
"=",
"None",
"origS",
"=",
"s",
"if",
"' '",
"in",
"s",
":",
"# Convert first word to title case, others to lower.",
"first",
",",
"rest",
"=",
"s",
".",
"split",
"(",
"' '",
",",
"1",
")",
"s",
"=",
"first... | 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. | [
"Find",
"an",
"amino",
"acid",
"whose",
"name",
"or",
"abbreviation",
"is",
"s",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/aa.py#L982-L1022 |
acorg/dark-matter | dark/aa.py | _propertiesOrClustersForSequence | 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 form of C{PROPERTY_DETAILS} or
C{PROPERTY_CLUSTERS} (see above).
@param missingAAValue: A C{float} value to use for properties when an AA
(e.g., 'X') is not known.
@raise ValueError: If an unknown property is given in C{propertyNames}.
@return: A C{dict} keyed by (lowercase) property name, with values that are
C{list}s of the corresponding property value in C{propertyValues} in
order of sequence position.
"""
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:
raise ValueError(
'Unknown propert%s: %s.' %
('y' if len(unknown) == 1 else 'ies', ', '.join(unknown)))
aas = sequence.sequence.upper()
result = {}
for propertyName in propertyNames:
result[propertyName] = values = []
append = values.append
for aa in aas:
try:
properties = propertyValues[aa]
except KeyError:
# No such AA.
append(missingAAValue)
else:
append(properties[propertyName])
return result | python | 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 form of C{PROPERTY_DETAILS} or
C{PROPERTY_CLUSTERS} (see above).
@param missingAAValue: A C{float} value to use for properties when an AA
(e.g., 'X') is not known.
@raise ValueError: If an unknown property is given in C{propertyNames}.
@return: A C{dict} keyed by (lowercase) property name, with values that are
C{list}s of the corresponding property value in C{propertyValues} in
order of sequence position.
"""
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:
raise ValueError(
'Unknown propert%s: %s.' %
('y' if len(unknown) == 1 else 'ies', ', '.join(unknown)))
aas = sequence.sequence.upper()
result = {}
for propertyName in propertyNames:
result[propertyName] = values = []
append = values.append
for aa in aas:
try:
properties = propertyValues[aa]
except KeyError:
# No such AA.
append(missingAAValue)
else:
append(properties[propertyName])
return result | [
"def",
"_propertiesOrClustersForSequence",
"(",
"sequence",
",",
"propertyNames",
",",
"propertyValues",
",",
"missingAAValue",
")",
":",
"propertyNames",
"=",
"sorted",
"(",
"map",
"(",
"str",
".",
"lower",
",",
"set",
"(",
"propertyNames",
")",
")",
")",
"# ... | 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 form of C{PROPERTY_DETAILS} or
C{PROPERTY_CLUSTERS} (see above).
@param missingAAValue: A C{float} value to use for properties when an AA
(e.g., 'X') is not known.
@raise ValueError: If an unknown property is given in C{propertyNames}.
@return: A C{dict} keyed by (lowercase) property name, with values that are
C{list}s of the corresponding property value in C{propertyValues} in
order of sequence position. | [
"Extract",
"amino",
"acid",
"property",
"values",
"or",
"cluster",
"numbers",
"for",
"a",
"sequence",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/aa.py#L1025-L1069 |
acorg/dark-matter | dark/aa.py | matchToString | 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 with.
@param offsets: If not C{None}, a C{set} of offsets of interest that were
only considered when making C{match}.
@return: A C{str} describing the match.
"""
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, (read1, read2))
result = []
append = result.append
append(countPrint('%sMatches' % indent, matchCount, len1, len2))
mismatchCount = (gapMismatchCount + gapGapMismatchCount +
nonGapMismatchCount)
append(countPrint('%sMismatches' % indent, mismatchCount, len1, len2))
append(countPrint('%s Not involving gaps (i.e., conflicts)' % (indent),
nonGapMismatchCount, len1, len2))
append(countPrint('%s Involving a gap in one sequence' % indent,
gapMismatchCount, len1, len2))
append(countPrint('%s Involving a gap in both sequences' % indent,
gapGapMismatchCount, len1, len2))
for read, key in zip((read1, read2), ('read1', 'read2')):
append('%s Id: %s' % (indent, read.id))
length = len(read)
append('%s Length: %d' % (indent, length))
gapCount = len(aaMatch[key]['gapOffsets'])
append(countPrint('%s Gaps' % indent, gapCount, length))
if gapCount:
append(
'%s Gap locations (1-based): %s' %
(indent,
', '.join(map(lambda offset: str(offset + 1),
sorted(aaMatch[key]['gapOffsets'])))))
extraCount = aaMatch[key]['extraCount']
if extraCount:
append(countPrint('%s Extra nucleotides at end' % indent,
extraCount, length))
return '\n'.join(result) | python | 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 with.
@param offsets: If not C{None}, a C{set} of offsets of interest that were
only considered when making C{match}.
@return: A C{str} describing the match.
"""
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, (read1, read2))
result = []
append = result.append
append(countPrint('%sMatches' % indent, matchCount, len1, len2))
mismatchCount = (gapMismatchCount + gapGapMismatchCount +
nonGapMismatchCount)
append(countPrint('%sMismatches' % indent, mismatchCount, len1, len2))
append(countPrint('%s Not involving gaps (i.e., conflicts)' % (indent),
nonGapMismatchCount, len1, len2))
append(countPrint('%s Involving a gap in one sequence' % indent,
gapMismatchCount, len1, len2))
append(countPrint('%s Involving a gap in both sequences' % indent,
gapGapMismatchCount, len1, len2))
for read, key in zip((read1, read2), ('read1', 'read2')):
append('%s Id: %s' % (indent, read.id))
length = len(read)
append('%s Length: %d' % (indent, length))
gapCount = len(aaMatch[key]['gapOffsets'])
append(countPrint('%s Gaps' % indent, gapCount, length))
if gapCount:
append(
'%s Gap locations (1-based): %s' %
(indent,
', '.join(map(lambda offset: str(offset + 1),
sorted(aaMatch[key]['gapOffsets'])))))
extraCount = aaMatch[key]['extraCount']
if extraCount:
append(countPrint('%s Extra nucleotides at end' % indent,
extraCount, length))
return '\n'.join(result) | [
"def",
"matchToString",
"(",
"aaMatch",
",",
"read1",
",",
"read2",
",",
"indent",
"=",
"''",
",",
"offsets",
"=",
"None",
")",
":",
"match",
"=",
"aaMatch",
"[",
"'match'",
"]",
"matchCount",
"=",
"match",
"[",
"'matchCount'",
"]",
"gapMismatchCount",
"... | 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 with.
@param offsets: If not C{None}, a C{set} of offsets of interest that were
only considered when making C{match}.
@return: A C{str} describing the match. | [
"Format",
"amino",
"acid",
"sequence",
"match",
"as",
"a",
"string",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/aa.py#L1108-L1162 |
acorg/dark-matter | dark/aa.py | compareAaReads | 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 offsets: If not C{None}, a C{set} of offsets of interest. Offsets
not in the set will not be considered.
@return: A C{dict} with information about the match and the individual
sequences (see below).
"""
matchCount = 0
gapMismatchCount = nonGapMismatchCount = gapGapMismatchCount = 0
read1ExtraCount = read2ExtraCount = 0
read1GapOffsets = []
read2GapOffsets = []
for offset, (a, b) in enumerate(zip_longest(read1.sequence.upper(),
read2.sequence.upper())):
# Use 'is not None' in the following to allow an empty offsets set
# to be passed.
if offsets is not None and offset not in offsets:
continue
if a is None:
# b has an extra character at its end (it cannot be None).
assert b is not None
read2ExtraCount += 1
if b in gapChars:
read2GapOffsets.append(offset)
elif b is None:
# a has an extra character at its end.
read1ExtraCount += 1
if a in gapChars:
read1GapOffsets.append(offset)
else:
# We have a character from both sequences (they could still be
# gap characters).
if a in gapChars:
read1GapOffsets.append(offset)
if b in gapChars:
# Both are gaps. This can happen (though hopefully not
# if the sequences were pairwise aligned).
gapGapMismatchCount += 1
read2GapOffsets.append(offset)
else:
# a is a gap, b is not.
gapMismatchCount += 1
else:
if b in gapChars:
# b is a gap, a is not.
gapMismatchCount += 1
read2GapOffsets.append(offset)
else:
# Neither is a gap character.
if a == b:
matchCount += 1
else:
nonGapMismatchCount += 1
return {
'match': {
'matchCount': matchCount,
'gapMismatchCount': gapMismatchCount,
'gapGapMismatchCount': gapGapMismatchCount,
'nonGapMismatchCount': nonGapMismatchCount,
},
'read1': {
'extraCount': read1ExtraCount,
'gapOffsets': read1GapOffsets,
},
'read2': {
'extraCount': read2ExtraCount,
'gapOffsets': read2GapOffsets,
},
} | python | 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 offsets: If not C{None}, a C{set} of offsets of interest. Offsets
not in the set will not be considered.
@return: A C{dict} with information about the match and the individual
sequences (see below).
"""
matchCount = 0
gapMismatchCount = nonGapMismatchCount = gapGapMismatchCount = 0
read1ExtraCount = read2ExtraCount = 0
read1GapOffsets = []
read2GapOffsets = []
for offset, (a, b) in enumerate(zip_longest(read1.sequence.upper(),
read2.sequence.upper())):
# Use 'is not None' in the following to allow an empty offsets set
# to be passed.
if offsets is not None and offset not in offsets:
continue
if a is None:
# b has an extra character at its end (it cannot be None).
assert b is not None
read2ExtraCount += 1
if b in gapChars:
read2GapOffsets.append(offset)
elif b is None:
# a has an extra character at its end.
read1ExtraCount += 1
if a in gapChars:
read1GapOffsets.append(offset)
else:
# We have a character from both sequences (they could still be
# gap characters).
if a in gapChars:
read1GapOffsets.append(offset)
if b in gapChars:
# Both are gaps. This can happen (though hopefully not
# if the sequences were pairwise aligned).
gapGapMismatchCount += 1
read2GapOffsets.append(offset)
else:
# a is a gap, b is not.
gapMismatchCount += 1
else:
if b in gapChars:
# b is a gap, a is not.
gapMismatchCount += 1
read2GapOffsets.append(offset)
else:
# Neither is a gap character.
if a == b:
matchCount += 1
else:
nonGapMismatchCount += 1
return {
'match': {
'matchCount': matchCount,
'gapMismatchCount': gapMismatchCount,
'gapGapMismatchCount': gapGapMismatchCount,
'nonGapMismatchCount': nonGapMismatchCount,
},
'read1': {
'extraCount': read1ExtraCount,
'gapOffsets': read1GapOffsets,
},
'read2': {
'extraCount': read2ExtraCount,
'gapOffsets': read2GapOffsets,
},
} | [
"def",
"compareAaReads",
"(",
"read1",
",",
"read2",
",",
"gapChars",
"=",
"'-'",
",",
"offsets",
"=",
"None",
")",
":",
"matchCount",
"=",
"0",
"gapMismatchCount",
"=",
"nonGapMismatchCount",
"=",
"gapGapMismatchCount",
"=",
"0",
"read1ExtraCount",
"=",
"read... | 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 offsets: If not C{None}, a C{set} of offsets of interest. Offsets
not in the set will not be considered.
@return: A C{dict} with information about the match and the individual
sequences (see below). | [
"Compare",
"two",
"amino",
"acid",
"sequences",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/aa.py#L1165-L1241 |
acorg/dark-matter | bin/noninteractive-alignment-panel.py | parseColors | 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. Note that if read
ids contain spaces you will need to use the latter (i.e. FASTA/Q file
name) approach because C{args.colors} is split on whitespace.
@param args: The argparse C{Namespace} instance holding the other parsed
command line arguments.
@return: A C{dict} whose keys are colors and whose values are sets of
read ids.
"""
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)
else:
reads = FastqReads(filename)
for read in reads:
result[color].add(read.id)
else:
result[color].add(readId)
return result | python | 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. Note that if read
ids contain spaces you will need to use the latter (i.e. FASTA/Q file
name) approach because C{args.colors} is split on whitespace.
@param args: The argparse C{Namespace} instance holding the other parsed
command line arguments.
@return: A C{dict} whose keys are colors and whose values are sets of
read ids.
"""
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)
else:
reads = FastqReads(filename)
for read in reads:
result[color].add(read.id)
else:
result[color].add(readId)
return result | [
"def",
"parseColors",
"(",
"colors",
",",
"args",
")",
":",
"result",
"=",
"defaultdict",
"(",
"set",
")",
"for",
"colorInfo",
"in",
"colors",
":",
"readIds",
"=",
"colorInfo",
".",
"split",
"(",
")",
"color",
"=",
"readIds",
".",
"pop",
"(",
"0",
")... | 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. Note that if read
ids contain spaces you will need to use the latter (i.e. FASTA/Q file
name) approach because C{args.colors} is split on whitespace.
@param args: The argparse C{Namespace} instance holding the other parsed
command line arguments.
@return: A C{dict} whose keys are colors and whose values are sets of
read ids. | [
"Parse",
"read",
"id",
"color",
"specification",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/bin/noninteractive-alignment-panel.py#L35-L65 |
flo-compbio/genometools | genometools/ontology/util.py | download_release | def download_release(download_file, release=None):
"""Downloads the "go-basic.obo" file for the specified release."""
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) | python | def download_release(download_file, release=None):
"""Downloads the "go-basic.obo" file for the specified release."""
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",
")",
":",
"if",
"release",
"is",
"None",
":",
"release",
"=",
"get_latest_release",
"(",
")",
"url",
"=",
"'http://viewvc.geneontology.org/viewvc/GO-SVN/ontology-releases/%s/go-basic.obo'",
"%... | Downloads the "go-basic.obo" file for the specified release. | [
"Downloads",
"the",
"go",
"-",
"basic",
".",
"obo",
"file",
"for",
"the",
"specified",
"release",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ontology/util.py#L53-L59 |
flo-compbio/genometools | genometools/ontology/util.py | get_current_ontology_date | def get_current_ontology_date():
"""Get the release date of the current Gene Ontolgo release."""
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]
break
return date | python | def get_current_ontology_date():
"""Get the release date of the current Gene Ontolgo release."""
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]
break
return date | [
"def",
"get_current_ontology_date",
"(",
")",
":",
"with",
"closing",
"(",
"requests",
".",
"get",
"(",
"'http://geneontology.org/ontology/go-basic.obo'",
",",
"stream",
"=",
"True",
")",
")",
"as",
"r",
":",
"for",
"i",
",",
"l",
"in",
"enumerate",
"(",
"r"... | Get the release date of the current Gene Ontolgo release. | [
"Get",
"the",
"release",
"date",
"of",
"the",
"current",
"Gene",
"Ontolgo",
"release",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ontology/util.py#L62-L73 |
invenia/Arbiter | arbiter/sync.py | execute | def execute(function, name):
"""
Execute a task, returning a TaskResult
"""
try:
return TaskResult(name, True, None, function())
except Exception as exc:
return TaskResult(name, False, exc, None) | python | def execute(function, name):
"""
Execute a task, returning a TaskResult
"""
try:
return TaskResult(name, True, None, function())
except Exception as exc:
return TaskResult(name, False, exc, None) | [
"def",
"execute",
"(",
"function",
",",
"name",
")",
":",
"try",
":",
"return",
"TaskResult",
"(",
"name",
",",
"True",
",",
"None",
",",
"function",
"(",
")",
")",
"except",
"Exception",
"as",
"exc",
":",
"return",
"TaskResult",
"(",
"name",
",",
"F... | Execute a task, returning a TaskResult | [
"Execute",
"a",
"task",
"returning",
"a",
"TaskResult"
] | train | https://github.com/invenia/Arbiter/blob/51008393ae8797da85bcd67807259a157f941dfd/arbiter/sync.py#L19-L26 |
disqus/overseer | overseer/templatetags/overseer_helpers.py | truncatechars | def truncatechars(value, arg):
"""
Truncates a string after a certain number of chars.
Argument: Number of chars to truncate after.
"""
try:
length = int(arg)
except ValueError: # Invalid literal for int().
return value # Fail silently.
if len(value) > length:
return value[:length] + '...'
return value | python | def truncatechars(value, arg):
"""
Truncates a string after a certain number of chars.
Argument: Number of chars to truncate after.
"""
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",
")",
":",
"try",
":",
"length",
"=",
"int",
"(",
"arg",
")",
"except",
"ValueError",
":",
"# Invalid literal for int().",
"return",
"value",
"# Fail silently.",
"if",
"len",
"(",
"value",
")",
">",
"length",
... | Truncates a string after a certain number of chars.
Argument: Number of chars to truncate after. | [
"Truncates",
"a",
"string",
"after",
"a",
"certain",
"number",
"of",
"chars",
"."
] | train | https://github.com/disqus/overseer/blob/b37573aba33b20aa86f89eb0c7e6f4d9905bedef/overseer/templatetags/overseer_helpers.py#L32-L44 |
disqus/overseer | example_project/urls.py | handler500 | def handler500(request):
"""
500 error handler.
Templates: `500.html`
Context: None
"""
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={'request': request})
context = {}
context['request'] = request
t = loader.get_template('500.html') # You need to create a 500.html template.
return HttpResponseServerError(t.render(Context(context))) | python | def handler500(request):
"""
500 error handler.
Templates: `500.html`
Context: None
"""
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={'request': request})
context = {}
context['request'] = request
t = loader.get_template('500.html') # You need to create a 500.html template.
return HttpResponseServerError(t.render(Context(context))) | [
"def",
"handler500",
"(",
"request",
")",
":",
"from",
"django",
".",
"template",
"import",
"Context",
",",
"loader",
"from",
"django",
".",
"http",
"import",
"HttpResponseServerError",
"from",
"overseer",
".",
"context_processors",
"import",
"default",
"import",
... | 500 error handler.
Templates: `500.html`
Context: None | [
"500",
"error",
"handler",
"."
] | train | https://github.com/disqus/overseer/blob/b37573aba33b20aa86f89eb0c7e6f4d9905bedef/example_project/urls.py#L7-L28 |
flo-compbio/genometools | genometools/ensembl/cli/util.py | get_gtf_argument_parser | 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 argument parser.
"""
parser = cli.get_argument_parser(desc=desc)
parser.add_argument(
'-a', '--annotation-file', default='-', type=str,
help=textwrap.dedent("""\
Path of Ensembl gene annotation file (in GTF format). The file
may be gzip'ed. If set to ``-``, read from ``stdin``.""")
)
parser.add_argument(
'-o', '--output-file', required=True, type=str,
help=textwrap.dedent("""\
Path of output file. If set to ``-``, print to ``stdout``,
and redirect logging messages to ``stderr``.""")
)
#parser.add_argument(
# '-s', '--species', type=str,
# choices=sorted(ensembl.SPECIES_CHROMPAT.keys()), default='human',
# help=textwrap.dedent("""\
# Species for which to extract genes. (This parameter is ignored
# if ``--chromosome-pattern`` is specified.)""")
#)
parser.add_argument(
'-c', '--chromosome-pattern', type=str, required=False,
default=None, help=textwrap.dedent("""\
Regular expression that chromosome names have to match. [None]
""")
)
#parser.add_argument(
# '-f', '--field-name', type=str, default=default_field_name,
# help=textwrap.dedent("""\
# Rows in the GTF file that do not contain this value
# in the third column are ignored.""")
#)
cli.add_reporting_args(parser)
return parser | python | 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 argument parser.
"""
parser = cli.get_argument_parser(desc=desc)
parser.add_argument(
'-a', '--annotation-file', default='-', type=str,
help=textwrap.dedent("""\
Path of Ensembl gene annotation file (in GTF format). The file
may be gzip'ed. If set to ``-``, read from ``stdin``.""")
)
parser.add_argument(
'-o', '--output-file', required=True, type=str,
help=textwrap.dedent("""\
Path of output file. If set to ``-``, print to ``stdout``,
and redirect logging messages to ``stderr``.""")
)
#parser.add_argument(
# '-s', '--species', type=str,
# choices=sorted(ensembl.SPECIES_CHROMPAT.keys()), default='human',
# help=textwrap.dedent("""\
# Species for which to extract genes. (This parameter is ignored
# if ``--chromosome-pattern`` is specified.)""")
#)
parser.add_argument(
'-c', '--chromosome-pattern', type=str, required=False,
default=None, help=textwrap.dedent("""\
Regular expression that chromosome names have to match. [None]
""")
)
#parser.add_argument(
# '-f', '--field-name', type=str, default=default_field_name,
# help=textwrap.dedent("""\
# Rows in the GTF file that do not contain this value
# in the third column are ignored.""")
#)
cli.add_reporting_args(parser)
return parser | [
"def",
"get_gtf_argument_parser",
"(",
"desc",
",",
"default_field_name",
"=",
"'gene'",
")",
":",
"parser",
"=",
"cli",
".",
"get_argument_parser",
"(",
"desc",
"=",
"desc",
")",
"parser",
".",
"add_argument",
"(",
"'-a'",
",",
"'--annotation-file'",
",",
"de... | 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 argument parser. | [
"Return",
"an",
"argument",
"parser",
"with",
"basic",
"options",
"for",
"reading",
"GTF",
"files",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ensembl/cli/util.py#L30-L85 |
inveniosoftware/invenio-jsonschemas | invenio_jsonschemas/jsonresolver.py | jsonresolver_loader | def jsonresolver_loader(url_map):
"""JSON resolver plugin that loads the schema endpoint.
Injected into Invenio-Records JSON resolver.
"""
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'])) | python | def jsonresolver_loader(url_map):
"""JSON resolver plugin that loads the schema endpoint.
Injected into Invenio-Records JSON resolver.
"""
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",
")",
":",
"from",
"flask",
"import",
"current_app",
"from",
".",
"import",
"current_jsonschemas",
"url_map",
".",
"add",
"(",
"Rule",
"(",
"\"{0}/<path:path>\"",
".",
"format",
"(",
"current_app",
".",
"config",
"[",... | JSON resolver plugin that loads the schema endpoint.
Injected into Invenio-Records JSON resolver. | [
"JSON",
"resolver",
"plugin",
"that",
"loads",
"the",
"schema",
"endpoint",
"."
] | train | https://github.com/inveniosoftware/invenio-jsonschemas/blob/93019b8fe3bf549335e94c84198c9c0b76d8fde2/invenio_jsonschemas/jsonresolver.py#L18-L28 |
grabbles/grabbit | grabbit/core.py | merge_layouts | 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 updated with all values in the 2nd Layout,
then the result will be updated with values from the 3rd Layout, etc.
This means that order matters: in the event of entity or filename
conflicts, later layouts will take precedence.
'''
layout = layouts[0].clone()
for l in layouts[1:]:
layout.files.update(l.files)
layout.domains.update(l.domains)
for k, v in l.entities.items():
if k not in layout.entities:
layout.entities[k] = v
else:
layout.entities[k].files.update(v.files)
return layout | python | 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 updated with all values in the 2nd Layout,
then the result will be updated with values from the 3rd Layout, etc.
This means that order matters: in the event of entity or filename
conflicts, later layouts will take precedence.
'''
layout = layouts[0].clone()
for l in layouts[1:]:
layout.files.update(l.files)
layout.domains.update(l.domains)
for k, v in l.entities.items():
if k not in layout.entities:
layout.entities[k] = v
else:
layout.entities[k].files.update(v.files)
return layout | [
"def",
"merge_layouts",
"(",
"layouts",
")",
":",
"layout",
"=",
"layouts",
"[",
"0",
"]",
".",
"clone",
"(",
")",
"for",
"l",
"in",
"layouts",
"[",
"1",
":",
"]",
":",
"layout",
".",
"files",
".",
"update",
"(",
"l",
".",
"files",
")",
"layout",... | 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 updated with all values in the 2nd Layout,
then the result will be updated with values from the 3rd Layout, etc.
This means that order matters: in the event of entity or filename
conflicts, later layouts will take precedence. | [
"Utility",
"function",
"for",
"merging",
"multiple",
"layouts",
"."
] | train | https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L1079-L1105 |
grabbles/grabbit | grabbit/core.py | File._matches | 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 match.
regex_search (bool): Whether to require exact match (False) or
regex search (True) when comparing the query string to each
entity.
Returns:
True if _all_ entities and extensions match; False otherwise.
"""
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 None:
domains = listify(domains)
if not set(self.domains) & set(domains):
return False
if entities is not None:
for name, val in entities.items():
if (name not in self.tags) ^ (val is None):
return False
if val is None:
continue
def make_patt(x):
patt = '%s' % x
if isinstance(x, (int, float)):
# allow for leading zeros if a number was specified
# regardless of regex_search
patt = '0*' + patt
if not regex_search:
patt = '^%s$' % patt
return patt
ent_patts = [make_patt(x) for x in listify(val)]
patt = '|'.join(ent_patts)
if re.search(patt, str(self.tags[name].value)) is None:
return False
return True | python | 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 match.
regex_search (bool): Whether to require exact match (False) or
regex search (True) when comparing the query string to each
entity.
Returns:
True if _all_ entities and extensions match; False otherwise.
"""
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 None:
domains = listify(domains)
if not set(self.domains) & set(domains):
return False
if entities is not None:
for name, val in entities.items():
if (name not in self.tags) ^ (val is None):
return False
if val is None:
continue
def make_patt(x):
patt = '%s' % x
if isinstance(x, (int, float)):
# allow for leading zeros if a number was specified
# regardless of regex_search
patt = '0*' + patt
if not regex_search:
patt = '^%s$' % patt
return patt
ent_patts = [make_patt(x) for x in listify(val)]
patt = '|'.join(ent_patts)
if re.search(patt, str(self.tags[name].value)) is None:
return False
return True | [
"def",
"_matches",
"(",
"self",
",",
"entities",
"=",
"None",
",",
"extensions",
"=",
"None",
",",
"domains",
"=",
"None",
",",
"regex_search",
"=",
"False",
")",
":",
"if",
"extensions",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"extensions",
... | 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 match.
regex_search (bool): Whether to require exact match (False) or
regex search (True) when comparing the query string to each
entity.
Returns:
True if _all_ entities and extensions match; False otherwise. | [
"Checks",
"whether",
"the",
"file",
"matches",
"all",
"of",
"the",
"passed",
"entities",
"and",
"extensions",
"."
] | train | https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L35-L88 |
grabbles/grabbit | grabbit/core.py | File.as_named_tuple | 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.
"""
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 cannot be reserved keywords when "
"representing a File as a namedtuple. Replacing "
"entities %s with safe versions %s." % (keys, safe))
entities = dict(zip(keys, self.entities.values()))
_File = namedtuple('File', 'filename ' + ' '.join(entities.keys()))
return _File(filename=self.path, **entities) | python | 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.
"""
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 cannot be reserved keywords when "
"representing a File as a namedtuple. Replacing "
"entities %s with safe versions %s." % (keys, safe))
entities = dict(zip(keys, self.entities.values()))
_File = namedtuple('File', 'filename ' + ' '.join(entities.keys()))
return _File(filename=self.path, **entities) | [
"def",
"as_named_tuple",
"(",
"self",
")",
":",
"keys",
"=",
"list",
"(",
"self",
".",
"entities",
".",
"keys",
"(",
")",
")",
"replaced",
"=",
"[",
"]",
"for",
"i",
",",
"k",
"in",
"enumerate",
"(",
"keys",
")",
":",
"if",
"iskeyword",
"(",
"k",... | Returns the File as a named tuple. The full path plus all entity
key/value pairs are returned as attributes. | [
"Returns",
"the",
"File",
"as",
"a",
"named",
"tuple",
".",
"The",
"full",
"path",
"plus",
"all",
"entity",
"key",
"/",
"value",
"pairs",
"are",
"returned",
"as",
"attributes",
"."
] | train | https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L90-L108 |
grabbles/grabbit | grabbit/core.py | File.copy | 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. '''
new_filename = build_path(self.entities, path_patterns)
if not new_filename:
return None
if new_filename[-1] == os.sep:
new_filename += self.filename
if isabs(self.path) or root is None:
path = self.path
else:
path = join(root, self.path)
if not exists(path):
raise ValueError("Target filename to copy/symlink (%s) doesn't "
"exist." % path)
if symbolic_link:
contents = None
link_to = path
else:
with open(path, 'r') as f:
contents = f.read()
link_to = None
write_contents_to_file(new_filename, contents=contents,
link_to=link_to, content_mode='text', root=root,
conflicts=conflicts) | python | 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. '''
new_filename = build_path(self.entities, path_patterns)
if not new_filename:
return None
if new_filename[-1] == os.sep:
new_filename += self.filename
if isabs(self.path) or root is None:
path = self.path
else:
path = join(root, self.path)
if not exists(path):
raise ValueError("Target filename to copy/symlink (%s) doesn't "
"exist." % path)
if symbolic_link:
contents = None
link_to = path
else:
with open(path, 'r') as f:
contents = f.read()
link_to = None
write_contents_to_file(new_filename, contents=contents,
link_to=link_to, content_mode='text', root=root,
conflicts=conflicts) | [
"def",
"copy",
"(",
"self",
",",
"path_patterns",
",",
"symbolic_link",
"=",
"False",
",",
"root",
"=",
"None",
",",
"conflicts",
"=",
"'fail'",
")",
":",
"new_filename",
"=",
"build_path",
"(",
"self",
".",
"entities",
",",
"path_patterns",
")",
"if",
"... | 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. | [
"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",
"."
] | train | https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L110-L141 |
grabbles/grabbit | grabbit/core.py | Entity.match_file | 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.
"""
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) | python | 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.
"""
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",
")",
":",
"if",
"self",
".",
"map_func",
"is",
"not",
"None",
":",
"val",
"=",
"self",
".",
"map_func",
"(",
"f",
")",
"else",
":",
"m",
"=",
"self",
".",
"regex",
".",... | 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. | [
"Determine",
"whether",
"the",
"passed",
"file",
"matches",
"the",
"Entity",
"."
] | train | https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L261-L276 |
grabbles/grabbit | grabbit/core.py | Layout._get_or_load_domain | 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 information
'''
if isinstance(domain, six.string_types):
if domain in self.domains:
return self.domains[domain]
elif exists(domain):
with open(domain, 'r') as fobj:
domain = json.load(fobj)
else:
raise ValueError("No domain could be found/loaded from input "
"'{}'; value must be either the name of an "
"existing Domain, or a valid path to a "
"configuration file.".format(domain))
# At this point, domain is a dict
name = domain['name']
if name in self.domains:
msg = ("Domain with name '{}' already exists; returning existing "
"Domain configuration.".format(name))
warnings.warn(msg)
return self.domains[name]
entities = domain.get('entities', [])
domain = Domain(domain)
for e in entities:
self.add_entity(domain=domain, **e)
self.domains[name] = domain
return self.domains[name] | python | 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 information
'''
if isinstance(domain, six.string_types):
if domain in self.domains:
return self.domains[domain]
elif exists(domain):
with open(domain, 'r') as fobj:
domain = json.load(fobj)
else:
raise ValueError("No domain could be found/loaded from input "
"'{}'; value must be either the name of an "
"existing Domain, or a valid path to a "
"configuration file.".format(domain))
# At this point, domain is a dict
name = domain['name']
if name in self.domains:
msg = ("Domain with name '{}' already exists; returning existing "
"Domain configuration.".format(name))
warnings.warn(msg)
return self.domains[name]
entities = domain.get('entities', [])
domain = Domain(domain)
for e in entities:
self.add_entity(domain=domain, **e)
self.domains[name] = domain
return self.domains[name] | [
"def",
"_get_or_load_domain",
"(",
"self",
",",
"domain",
")",
":",
"if",
"isinstance",
"(",
"domain",
",",
"six",
".",
"string_types",
")",
":",
"if",
"domain",
"in",
"self",
".",
"domains",
":",
"return",
"self",
".",
"domains",
"[",
"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 information | [
"Return",
"a",
"domain",
"if",
"one",
"already",
"exists",
"or",
"create",
"a",
"new",
"one",
"if",
"not",
"."
] | train | https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L423-L457 |
grabbles/grabbit | grabbit/core.py | Layout._check_inclusions | 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 '''
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 position for global include/exclude
domains = list(domains)
domains.insert(0, self)
for dom in domains:
# If file matches any include regex, then True
if dom.include:
for regex in dom.include:
if re.search(regex, filename):
return True
return False
else:
# If file matches any exclude regex, then False
for regex in dom.exclude:
if re.search(regex, filename, flags=re.UNICODE):
return False
return True | python | 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 '''
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 position for global include/exclude
domains = list(domains)
domains.insert(0, self)
for dom in domains:
# If file matches any include regex, then True
if dom.include:
for regex in dom.include:
if re.search(regex, filename):
return True
return False
else:
# If file matches any exclude regex, then False
for regex in dom.exclude:
if re.search(regex, filename, flags=re.UNICODE):
return False
return True | [
"def",
"_check_inclusions",
"(",
"self",
",",
"f",
",",
"domains",
"=",
"None",
")",
":",
"filename",
"=",
"f",
"if",
"isinstance",
"(",
"f",
",",
"six",
".",
"string_types",
")",
"else",
"f",
".",
"path",
"if",
"domains",
"is",
"None",
":",
"domains... | Check file or directory against regexes in config to determine if
it should be included in the index | [
"Check",
"file",
"or",
"directory",
"against",
"regexes",
"in",
"config",
"to",
"determine",
"if",
"it",
"should",
"be",
"included",
"in",
"the",
"index"
] | train | https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L470-L495 |
grabbles/grabbit | grabbit/core.py | Layout._find_entity | def _find_entity(self, entity):
''' 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. To "
"avoid ambiguity, please prefix the entity "
"name with its domain (e.g., 'bids.%s'." %
(entity, len(_ent), entity))
if _ent:
return _ent[0]
raise ValueError("No entity '%s' found." % entity) | python | def _find_entity(self, entity):
''' 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. To "
"avoid ambiguity, please prefix the entity "
"name with its domain (e.g., 'bids.%s'." %
(entity, len(_ent), entity))
if _ent:
return _ent[0]
raise ValueError("No entity '%s' found." % entity) | [
"def",
"_find_entity",
"(",
"self",
",",
"entity",
")",
":",
"if",
"entity",
"in",
"self",
".",
"entities",
":",
"return",
"self",
".",
"entities",
"[",
"entity",
"]",
"_ent",
"=",
"[",
"e",
"for",
"e",
"in",
"self",
".",
"entities",
".",
"values",
... | Find an Entity instance by name. Checks both name and id fields. | [
"Find",
"an",
"Entity",
"instance",
"by",
"name",
".",
"Checks",
"both",
"name",
"and",
"id",
"fields",
"."
] | train | https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L557-L570 |
grabbles/grabbit | grabbit/core.py | Layout.save_index | 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 within a project.
'''
data = {}
for f in self.files.values():
entities = {v.entity.id: v.value for k, v in f.tags.items()}
data[f.path] = {'domains': f.domains, 'entities': entities}
with open(filename, 'w') as outfile:
json.dump(data, outfile) | python | 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 within a project.
'''
data = {}
for f in self.files.values():
entities = {v.entity.id: v.value for k, v in f.tags.items()}
data[f.path] = {'domains': f.domains, 'entities': entities}
with open(filename, 'w') as outfile:
json.dump(data, outfile) | [
"def",
"save_index",
"(",
"self",
",",
"filename",
")",
":",
"data",
"=",
"{",
"}",
"for",
"f",
"in",
"self",
".",
"files",
".",
"values",
"(",
")",
":",
"entities",
"=",
"{",
"v",
".",
"entity",
".",
"id",
":",
"v",
".",
"value",
"for",
"k",
... | 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 within a project. | [
"Save",
"the",
"current",
"Layout",
"s",
"index",
"to",
"a",
".",
"json",
"file",
"."
] | train | https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L613-L628 |
grabbles/grabbit | grabbit/core.py | Layout.load_index | 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 defined in the config. Default is
False, in which case it is assumed that all entity definitions
in the loaded index are correct and do not need any further
validation.
Note: At the moment, directory-specific config files aren't serialized.
This means reconstructed indexes will only work properly in cases
where there aren't multiple layout specs within a project.
'''
self._reset_index()
with open(filename, 'r') as fobj:
data = json.load(fobj)
for path, file in data.items():
ents, domains = file['entities'], file['domains']
root, f = dirname(path), basename(path)
if reindex:
self._index_file(root, f, domains)
else:
f = self._make_file_object(root, f)
tags = {k: Tag(self.entities[k], v) for k, v in ents.items()}
f.tags = tags
self.files[f.path] = f
for ent, val in f.entities.items():
self.entities[ent].add_file(f.path, val) | python | 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 defined in the config. Default is
False, in which case it is assumed that all entity definitions
in the loaded index are correct and do not need any further
validation.
Note: At the moment, directory-specific config files aren't serialized.
This means reconstructed indexes will only work properly in cases
where there aren't multiple layout specs within a project.
'''
self._reset_index()
with open(filename, 'r') as fobj:
data = json.load(fobj)
for path, file in data.items():
ents, domains = file['entities'], file['domains']
root, f = dirname(path), basename(path)
if reindex:
self._index_file(root, f, domains)
else:
f = self._make_file_object(root, f)
tags = {k: Tag(self.entities[k], v) for k, v in ents.items()}
f.tags = tags
self.files[f.path] = f
for ent, val in f.entities.items():
self.entities[ent].add_file(f.path, val) | [
"def",
"load_index",
"(",
"self",
",",
"filename",
",",
"reindex",
"=",
"False",
")",
":",
"self",
".",
"_reset_index",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"fobj",
":",
"data",
"=",
"json",
".",
"load",
"(",
"fobj",
")... | 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 defined in the config. Default is
False, in which case it is assumed that all entity definitions
in the loaded index are correct and do not need any further
validation.
Note: At the moment, directory-specific config files aren't serialized.
This means reconstructed indexes will only work properly in cases
where there aren't multiple layout specs within a project. | [
"Load",
"the",
"Layout",
"s",
"index",
"from",
"a",
"plaintext",
"file",
"."
] | train | https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L630-L664 |
grabbles/grabbit | grabbit/core.py | Layout.add_entity | def add_entity(self, domain, **kwargs):
''' 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 '%s' specified for Entity "
"'%s', but no entity mapper was passed when "
"initializing the current Layout. Please make"
" sure the 'entity_mapper' argument is set." %
(map_func, kwargs['name']))
map_func = getattr(self.entity_mapper, kwargs['map_func'])
kwargs['map_func'] = map_func
ent = Entity(domain=domain, **kwargs)
domain.add_entity(ent)
if ent.mandatory:
self.mandatory.add(ent.id)
if ent.directory is not None:
ent.directory = ent.directory.replace('{{root}}', self.root)
self.entities[ent.id] = ent
for alias in ent.aliases:
self.entities[alias] = ent
if self.dynamic_getters:
func = partial(getattr(self, 'get'), target=ent.name,
return_type='id')
func_name = inflect.engine().plural(ent.name)
setattr(self, 'get_%s' % func_name, func) | python | def add_entity(self, domain, **kwargs):
''' 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 '%s' specified for Entity "
"'%s', but no entity mapper was passed when "
"initializing the current Layout. Please make"
" sure the 'entity_mapper' argument is set." %
(map_func, kwargs['name']))
map_func = getattr(self.entity_mapper, kwargs['map_func'])
kwargs['map_func'] = map_func
ent = Entity(domain=domain, **kwargs)
domain.add_entity(ent)
if ent.mandatory:
self.mandatory.add(ent.id)
if ent.directory is not None:
ent.directory = ent.directory.replace('{{root}}', self.root)
self.entities[ent.id] = ent
for alias in ent.aliases:
self.entities[alias] = ent
if self.dynamic_getters:
func = partial(getattr(self, 'get'), target=ent.name,
return_type='id')
func_name = inflect.engine().plural(ent.name)
setattr(self, 'get_%s' % func_name, func) | [
"def",
"add_entity",
"(",
"self",
",",
"domain",
",",
"*",
"*",
"kwargs",
")",
":",
"# Set the entity's mapping func if one was specified",
"map_func",
"=",
"kwargs",
".",
"get",
"(",
"'map_func'",
",",
"None",
")",
"if",
"map_func",
"is",
"not",
"None",
"and"... | Add a new Entity to tracking. | [
"Add",
"a",
"new",
"Entity",
"to",
"tracking",
"."
] | train | https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L666-L697 |
grabbles/grabbit | grabbit/core.py | Layout.get | 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': returns a list of matching filenames.
'dir': returns a list of directories.
'id': returns a list of unique IDs. Must be used together with
a valid target.
'obj': returns a list of matching File objects.
target (str): The name of the target entity to get results for
(if return_type is 'dir' or 'id').
extensions (str, list): One or more file extensions to filter on.
Files with any other extensions will be excluded.
domains (list): Optional list of domain names to scan for files.
If None, all available domains are scanned.
regex_search (bool or None): Whether to require exact matching
(False) or regex search (True) when comparing the query string
to each entity. If None (default), uses the value found in
self.
kwargs (dict): Any optional key/values to filter the entities on.
Keys are entity names, values are regexes to filter on. For
example, passing filter={ 'subject': 'sub-[12]'} would return
only files that match the first two subjects.
Returns:
A named tuple (default) or a list (see return_type for details).
"""
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
result.append(file)
# Convert to relative paths if needed
if not self.absolute_paths:
for i, f in enumerate(result):
f = copy(f)
f.path = relpath(f.path, self.root)
result[i] = f
if return_type == 'file':
return natural_sort([f.path for f in result])
if return_type == 'tuple':
result = [r.as_named_tuple() for r in result]
return natural_sort(result, field='filename')
if return_type.startswith('obj'):
return result
else:
valid_entities = self.get_domain_entities(domains)
if target is None:
raise ValueError('If return_type is "id" or "dir", a valid '
'target entity must also be specified.')
result = [x for x in result if target in x.entities]
if return_type == 'id':
result = list(set([x.entities[target] for x in result]))
return natural_sort(result)
elif return_type == 'dir':
template = valid_entities[target].directory
if template is None:
raise ValueError('Return type set to directory, but no '
'directory template is defined for the '
'target entity (\"%s\").' % target)
# Construct regex search pattern from target directory template
to_rep = re.findall('\{(.*?)\}', template)
for ent in to_rep:
patt = valid_entities[ent].pattern
template = template.replace('{%s}' % ent, patt)
template += '[^\%s]*$' % os.path.sep
matches = [f.dirname for f in result
if re.search(template, f.dirname)]
return natural_sort(list(set(matches)))
else:
raise ValueError("Invalid return_type specified (must be one "
"of 'tuple', 'file', 'id', or 'dir'.") | python | 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': returns a list of matching filenames.
'dir': returns a list of directories.
'id': returns a list of unique IDs. Must be used together with
a valid target.
'obj': returns a list of matching File objects.
target (str): The name of the target entity to get results for
(if return_type is 'dir' or 'id').
extensions (str, list): One or more file extensions to filter on.
Files with any other extensions will be excluded.
domains (list): Optional list of domain names to scan for files.
If None, all available domains are scanned.
regex_search (bool or None): Whether to require exact matching
(False) or regex search (True) when comparing the query string
to each entity. If None (default), uses the value found in
self.
kwargs (dict): Any optional key/values to filter the entities on.
Keys are entity names, values are regexes to filter on. For
example, passing filter={ 'subject': 'sub-[12]'} would return
only files that match the first two subjects.
Returns:
A named tuple (default) or a list (see return_type for details).
"""
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
result.append(file)
# Convert to relative paths if needed
if not self.absolute_paths:
for i, f in enumerate(result):
f = copy(f)
f.path = relpath(f.path, self.root)
result[i] = f
if return_type == 'file':
return natural_sort([f.path for f in result])
if return_type == 'tuple':
result = [r.as_named_tuple() for r in result]
return natural_sort(result, field='filename')
if return_type.startswith('obj'):
return result
else:
valid_entities = self.get_domain_entities(domains)
if target is None:
raise ValueError('If return_type is "id" or "dir", a valid '
'target entity must also be specified.')
result = [x for x in result if target in x.entities]
if return_type == 'id':
result = list(set([x.entities[target] for x in result]))
return natural_sort(result)
elif return_type == 'dir':
template = valid_entities[target].directory
if template is None:
raise ValueError('Return type set to directory, but no '
'directory template is defined for the '
'target entity (\"%s\").' % target)
# Construct regex search pattern from target directory template
to_rep = re.findall('\{(.*?)\}', template)
for ent in to_rep:
patt = valid_entities[ent].pattern
template = template.replace('{%s}' % ent, patt)
template += '[^\%s]*$' % os.path.sep
matches = [f.dirname for f in result
if re.search(template, f.dirname)]
return natural_sort(list(set(matches)))
else:
raise ValueError("Invalid return_type specified (must be one "
"of 'tuple', 'file', 'id', or 'dir'.") | [
"def",
"get",
"(",
"self",
",",
"return_type",
"=",
"'tuple'",
",",
"target",
"=",
"None",
",",
"extensions",
"=",
"None",
",",
"domains",
"=",
"None",
",",
"regex_search",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"regex_search",
"is",
"... | 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': returns a list of matching filenames.
'dir': returns a list of directories.
'id': returns a list of unique IDs. Must be used together with
a valid target.
'obj': returns a list of matching File objects.
target (str): The name of the target entity to get results for
(if return_type is 'dir' or 'id').
extensions (str, list): One or more file extensions to filter on.
Files with any other extensions will be excluded.
domains (list): Optional list of domain names to scan for files.
If None, all available domains are scanned.
regex_search (bool or None): Whether to require exact matching
(False) or regex search (True) when comparing the query string
to each entity. If None (default), uses the value found in
self.
kwargs (dict): Any optional key/values to filter the entities on.
Keys are entity names, values are regexes to filter on. For
example, passing filter={ 'subject': 'sub-[12]'} would return
only files that match the first two subjects.
Returns:
A named tuple (default) or a list (see return_type for details). | [
"Retrieve",
"files",
"and",
"/",
"or",
"metadata",
"from",
"the",
"current",
"Layout",
"."
] | train | https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L699-L791 |
grabbles/grabbit | grabbit/core.py | Layout.count | 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 the entity.
"""
return self._find_entity(entity).count(files) | python | 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 the entity.
"""
return self._find_entity(entity).count(files) | [
"def",
"count",
"(",
"self",
",",
"entity",
",",
"files",
"=",
"False",
")",
":",
"return",
"self",
".",
"_find_entity",
"(",
"entity",
")",
".",
"count",
"(",
"files",
")"
] | 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 the entity. | [
"Return",
"the",
"count",
"of",
"unique",
"values",
"or",
"files",
"for",
"the",
"named",
"entity",
"."
] | train | https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L802-L812 |
grabbles/grabbit | grabbit/core.py | Layout.as_data_frame | 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 file, and each column is
a tracked entity. NaNs are injected whenever a file has no
value for a given attribute.
"""
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:
files = self.get(return_type='obj', **kwargs)
else:
files = self.files.values()
data = pd.DataFrame.from_records([f.entities for f in files])
data.insert(0, 'path', [f.path for f in files])
return data | python | 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 file, and each column is
a tracked entity. NaNs are injected whenever a file has no
value for a given attribute.
"""
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:
files = self.get(return_type='obj', **kwargs)
else:
files = self.files.values()
data = pd.DataFrame.from_records([f.entities for f in files])
data.insert(0, 'path', [f.path for f in files])
return data | [
"def",
"as_data_frame",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"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 ha... | 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 file, and each column is
a tracked entity. NaNs are injected whenever a file has no
value for a given attribute. | [
"Return",
"information",
"for",
"all",
"Files",
"tracked",
"in",
"the",
"Layout",
"as",
"a",
"pandas",
"DataFrame",
"."
] | train | https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L814-L839 |
grabbles/grabbit | grabbit/core.py | Layout.get_nearest | def get_nearest(self, path, return_type='file', strict=True, all_=False,
ignore_strict_entities=None, full_search=False, **kwargs):
''' Walk up the file tree from the specified path and return the
nearest matching file(s).
Args:
path (str): The file to search from.
return_type (str): What to return; must be one of 'file' (default)
or 'tuple'.
strict (bool): When True, all entities present in both the input
path and the target file(s) must match perfectly. When False,
files will be ordered by the number of matching entities, and
partial matches will be allowed.
all_ (bool): When True, returns all matching files. When False
(default), only returns the first match.
ignore_strict_entities (list): Optional list of entities to
exclude from strict matching when strict is True. This allows
one to search, e.g., for files of a different type while
matching all other entities perfectly by passing
ignore_strict_entities=['type'].
full_search (bool): If True, searches all indexed files, even if
they don't share a common root with the provided path. If
False, only files that share a common root will be scanned.
kwargs: Optional keywords to pass on to .get().
'''
entities = {}
for ent in self.entities.values():
m = ent.regex.search(path)
if m:
entities[ent.name] = ent._astype(m.group(1))
# Remove any entities we want to ignore when strict matching is on
if strict and ignore_strict_entities is not None:
for k in ignore_strict_entities:
entities.pop(k, None)
results = self.get(return_type='file', **kwargs)
folders = defaultdict(list)
for filename in results:
f = self.get_file(filename)
folders[f.dirname].append(f)
def count_matches(f):
f_ents = f.entities
keys = set(entities.keys()) & set(f_ents.keys())
shared = len(keys)
return [shared, sum([entities[k] == f_ents[k] for k in keys])]
matches = []
search_paths = []
while True:
if path in folders and folders[path]:
search_paths.append(path)
parent = dirname(path)
if parent == path:
break
path = parent
if full_search:
unchecked = set(folders.keys()) - set(search_paths)
search_paths.extend(path for path in unchecked if folders[path])
for path in search_paths:
# Sort by number of matching entities. Also store number of
# common entities, for filtering when strict=True.
num_ents = [[f] + count_matches(f) for f in folders[path]]
# Filter out imperfect matches (i.e., where number of common
# entities does not equal number of matching entities).
if strict:
num_ents = [f for f in num_ents if f[1] == f[2]]
num_ents.sort(key=lambda x: x[2], reverse=True)
if num_ents:
matches.append(num_ents[0][0])
if not all_:
break
matches = [m.path if return_type == 'file' else m.as_named_tuple()
for m in matches]
return matches if all_ else matches[0] if matches else None | python | def get_nearest(self, path, return_type='file', strict=True, all_=False,
ignore_strict_entities=None, full_search=False, **kwargs):
''' Walk up the file tree from the specified path and return the
nearest matching file(s).
Args:
path (str): The file to search from.
return_type (str): What to return; must be one of 'file' (default)
or 'tuple'.
strict (bool): When True, all entities present in both the input
path and the target file(s) must match perfectly. When False,
files will be ordered by the number of matching entities, and
partial matches will be allowed.
all_ (bool): When True, returns all matching files. When False
(default), only returns the first match.
ignore_strict_entities (list): Optional list of entities to
exclude from strict matching when strict is True. This allows
one to search, e.g., for files of a different type while
matching all other entities perfectly by passing
ignore_strict_entities=['type'].
full_search (bool): If True, searches all indexed files, even if
they don't share a common root with the provided path. If
False, only files that share a common root will be scanned.
kwargs: Optional keywords to pass on to .get().
'''
entities = {}
for ent in self.entities.values():
m = ent.regex.search(path)
if m:
entities[ent.name] = ent._astype(m.group(1))
# Remove any entities we want to ignore when strict matching is on
if strict and ignore_strict_entities is not None:
for k in ignore_strict_entities:
entities.pop(k, None)
results = self.get(return_type='file', **kwargs)
folders = defaultdict(list)
for filename in results:
f = self.get_file(filename)
folders[f.dirname].append(f)
def count_matches(f):
f_ents = f.entities
keys = set(entities.keys()) & set(f_ents.keys())
shared = len(keys)
return [shared, sum([entities[k] == f_ents[k] for k in keys])]
matches = []
search_paths = []
while True:
if path in folders and folders[path]:
search_paths.append(path)
parent = dirname(path)
if parent == path:
break
path = parent
if full_search:
unchecked = set(folders.keys()) - set(search_paths)
search_paths.extend(path for path in unchecked if folders[path])
for path in search_paths:
# Sort by number of matching entities. Also store number of
# common entities, for filtering when strict=True.
num_ents = [[f] + count_matches(f) for f in folders[path]]
# Filter out imperfect matches (i.e., where number of common
# entities does not equal number of matching entities).
if strict:
num_ents = [f for f in num_ents if f[1] == f[2]]
num_ents.sort(key=lambda x: x[2], reverse=True)
if num_ents:
matches.append(num_ents[0][0])
if not all_:
break
matches = [m.path if return_type == 'file' else m.as_named_tuple()
for m in matches]
return matches if all_ else matches[0] if matches else None | [
"def",
"get_nearest",
"(",
"self",
",",
"path",
",",
"return_type",
"=",
"'file'",
",",
"strict",
"=",
"True",
",",
"all_",
"=",
"False",
",",
"ignore_strict_entities",
"=",
"None",
",",
"full_search",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"... | Walk up the file tree from the specified path and return the
nearest matching file(s).
Args:
path (str): The file to search from.
return_type (str): What to return; must be one of 'file' (default)
or 'tuple'.
strict (bool): When True, all entities present in both the input
path and the target file(s) must match perfectly. When False,
files will be ordered by the number of matching entities, and
partial matches will be allowed.
all_ (bool): When True, returns all matching files. When False
(default), only returns the first match.
ignore_strict_entities (list): Optional list of entities to
exclude from strict matching when strict is True. This allows
one to search, e.g., for files of a different type while
matching all other entities perfectly by passing
ignore_strict_entities=['type'].
full_search (bool): If True, searches all indexed files, even if
they don't share a common root with the provided path. If
False, only files that share a common root will be scanned.
kwargs: Optional keywords to pass on to .get(). | [
"Walk",
"up",
"the",
"file",
"tree",
"from",
"the",
"specified",
"path",
"and",
"return",
"the",
"nearest",
"matching",
"file",
"(",
"s",
")",
"."
] | train | https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L845-L929 |
grabbles/grabbit | grabbit/core.py | Layout.build_path | 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
current Layout.
- A dict of entities, with entity names in keys and values in
values
path_patterns (list): Optional path patterns to use to construct
the new file path. If None, the Layout-defined patterns will
be used.
strict (bool): If True, all entities must be matched inside a
pattern in order to be a valid match. If False, extra entities
will be ignored so long as all mandatory entities are found.
domains (str, list): Optional name(s) of domain(s) to scan for
path patterns. If None, all domains are scanned. If two or more
domains are provided, the order determines the precedence of
path patterns (i.e., earlier domains will have higher
precedence).
'''
if isinstance(source, six.string_types):
if source not in self.files:
source = join(self.root, source)
source = self.get_file(source)
if isinstance(source, File):
source = source.entities
if path_patterns is None:
if domains is None:
domains = list(self.domains.keys())
path_patterns = []
for dom in listify(domains):
path_patterns.extend(self.domains[dom].path_patterns)
return build_path(source, path_patterns, strict) | python | 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
current Layout.
- A dict of entities, with entity names in keys and values in
values
path_patterns (list): Optional path patterns to use to construct
the new file path. If None, the Layout-defined patterns will
be used.
strict (bool): If True, all entities must be matched inside a
pattern in order to be a valid match. If False, extra entities
will be ignored so long as all mandatory entities are found.
domains (str, list): Optional name(s) of domain(s) to scan for
path patterns. If None, all domains are scanned. If two or more
domains are provided, the order determines the precedence of
path patterns (i.e., earlier domains will have higher
precedence).
'''
if isinstance(source, six.string_types):
if source not in self.files:
source = join(self.root, source)
source = self.get_file(source)
if isinstance(source, File):
source = source.entities
if path_patterns is None:
if domains is None:
domains = list(self.domains.keys())
path_patterns = []
for dom in listify(domains):
path_patterns.extend(self.domains[dom].path_patterns)
return build_path(source, path_patterns, strict) | [
"def",
"build_path",
"(",
"self",
",",
"source",
",",
"path_patterns",
"=",
"None",
",",
"strict",
"=",
"False",
",",
"domains",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"source",
",",
"six",
".",
"string_types",
")",
":",
"if",
"source",
"not",... | 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
current Layout.
- A dict of entities, with entity names in keys and values in
values
path_patterns (list): Optional path patterns to use to construct
the new file path. If None, the Layout-defined patterns will
be used.
strict (bool): If True, all entities must be matched inside a
pattern in order to be a valid match. If False, extra entities
will be ignored so long as all mandatory entities are found.
domains (str, list): Optional name(s) of domain(s) to scan for
path patterns. If None, all domains are scanned. If two or more
domains are provided, the order determines the precedence of
path patterns (i.e., earlier domains will have higher
precedence). | [
"Constructs",
"a",
"target",
"filename",
"for",
"a",
"file",
"or",
"dictionary",
"of",
"entities",
"."
] | train | https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L948-L989 |
grabbles/grabbit | grabbit/core.py | Layout.write_contents_to_file | 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 building
the filename. If None, the Layout-defined patterns will be
used.
contents (object): Contents to write to the generate file path.
Can be any object serializable as text or binary data (as
defined in the content_mode argument).
conflicts (str): One of 'fail', 'skip', 'overwrite', or 'append'
that defines the desired action when the output path already
exists. 'fail' raises an exception; 'skip' does nothing;
'overwrite' overwrites the existing file; 'append' adds a suffix
to each file copy, starting with 1. Default is 'fail'.
strict (bool): If True, all entities must be matched inside a
pattern in order to be a valid match. If False, extra entities
will be ignored so long as all mandatory entities are found.
domains (list): List of Domains to scan for path_patterns. Order
determines precedence (i.e., earlier Domains will be scanned
first). If None, all available domains are included.
index (bool): If True, adds the generated file to the current
index using the domains specified in index_domains.
index_domains (list): List of domain names to attach the generated
file to when indexing. Ignored if index == False. If None,
All available domains are used.
"""
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_to_file(path, contents=contents, link_to=link_to,
content_mode=content_mode, conflicts=conflicts,
root=self.root)
if index:
# TODO: Default to using only domains that have at least one
# tagged entity in the generated file.
if index_domains is None:
index_domains = list(self.domains.keys())
self._index_file(self.root, path, index_domains) | python | 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 building
the filename. If None, the Layout-defined patterns will be
used.
contents (object): Contents to write to the generate file path.
Can be any object serializable as text or binary data (as
defined in the content_mode argument).
conflicts (str): One of 'fail', 'skip', 'overwrite', or 'append'
that defines the desired action when the output path already
exists. 'fail' raises an exception; 'skip' does nothing;
'overwrite' overwrites the existing file; 'append' adds a suffix
to each file copy, starting with 1. Default is 'fail'.
strict (bool): If True, all entities must be matched inside a
pattern in order to be a valid match. If False, extra entities
will be ignored so long as all mandatory entities are found.
domains (list): List of Domains to scan for path_patterns. Order
determines precedence (i.e., earlier Domains will be scanned
first). If None, all available domains are included.
index (bool): If True, adds the generated file to the current
index using the domains specified in index_domains.
index_domains (list): List of domain names to attach the generated
file to when indexing. Ignored if index == False. If None,
All available domains are used.
"""
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_to_file(path, contents=contents, link_to=link_to,
content_mode=content_mode, conflicts=conflicts,
root=self.root)
if index:
# TODO: Default to using only domains that have at least one
# tagged entity in the generated file.
if index_domains is None:
index_domains = list(self.domains.keys())
self._index_file(self.root, path, index_domains) | [
"def",
"write_contents_to_file",
"(",
"self",
",",
"entities",
",",
"path_patterns",
"=",
"None",
",",
"contents",
"=",
"None",
",",
"link_to",
"=",
"None",
",",
"content_mode",
"=",
"'text'",
",",
"conflicts",
"=",
"'fail'",
",",
"strict",
"=",
"False",
"... | 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 building
the filename. If None, the Layout-defined patterns will be
used.
contents (object): Contents to write to the generate file path.
Can be any object serializable as text or binary data (as
defined in the content_mode argument).
conflicts (str): One of 'fail', 'skip', 'overwrite', or 'append'
that defines the desired action when the output path already
exists. 'fail' raises an exception; 'skip' does nothing;
'overwrite' overwrites the existing file; 'append' adds a suffix
to each file copy, starting with 1. Default is 'fail'.
strict (bool): If True, all entities must be matched inside a
pattern in order to be a valid match. If False, extra entities
will be ignored so long as all mandatory entities are found.
domains (list): List of Domains to scan for path_patterns. Order
determines precedence (i.e., earlier Domains will be scanned
first). If None, all available domains are included.
index (bool): If True, adds the generated file to the current
index using the domains specified in index_domains.
index_domains (list): List of domain names to attach the generated
file to when indexing. Ignored if index == False. If None,
All available domains are used. | [
"Write",
"arbitrary",
"data",
"to",
"a",
"file",
"defined",
"by",
"the",
"passed",
"entities",
"and",
"path",
"patterns",
"."
] | train | https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L1024-L1076 |
flo-compbio/genometools | genometools/misc/log.py | configure_logger | 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
The stream to write log messages to. If ``None``, do not write to any
stream. The default value is `sys.stdout`.
log_file: str, optional
The path of a file to write log messages to. If None, do not write to
any file. The default value is ``None``.
log_level: int, optional
A logging level as `defined`__ in Python's logging module. The default
value is `logging.INFO`.
keep_old_handlers: bool, optional
If set to ``True``, keep any pre-existing handlers that are attached to
the logger. The default value is ``False``.
propagate: bool, optional
If set to ``True``, propagate the loggers messages to the parent
logger. The default value is ``False``.
Returns
-------
`logging.Logger`
The logger.
Notes
-----
Note that if ``log_stream`` and ``log_file`` are both ``None``, no handlers
will be created.
__ loglvl_
.. _loglvl: https://docs.python.org/2/library/logging.html#logging-levels
"""
# 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 = []
# create the formatter
log_fmt = '[%(asctime)s] %(levelname)s: %(message)s'
log_datefmt = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter(log_fmt, log_datefmt)
# create and attach the handlers
if log_stream is not None:
# create a StreamHandler
stream_handler = logging.StreamHandler(log_stream)
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
if log_file is not None:
# create a FileHandler
file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
if log_stream is None and log_file is None:
# "no handler" => use NullHandler
logger.addHandler(logging.NullHandler())
return logger | python | 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
The stream to write log messages to. If ``None``, do not write to any
stream. The default value is `sys.stdout`.
log_file: str, optional
The path of a file to write log messages to. If None, do not write to
any file. The default value is ``None``.
log_level: int, optional
A logging level as `defined`__ in Python's logging module. The default
value is `logging.INFO`.
keep_old_handlers: bool, optional
If set to ``True``, keep any pre-existing handlers that are attached to
the logger. The default value is ``False``.
propagate: bool, optional
If set to ``True``, propagate the loggers messages to the parent
logger. The default value is ``False``.
Returns
-------
`logging.Logger`
The logger.
Notes
-----
Note that if ``log_stream`` and ``log_file`` are both ``None``, no handlers
will be created.
__ loglvl_
.. _loglvl: https://docs.python.org/2/library/logging.html#logging-levels
"""
# 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 = []
# create the formatter
log_fmt = '[%(asctime)s] %(levelname)s: %(message)s'
log_datefmt = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter(log_fmt, log_datefmt)
# create and attach the handlers
if log_stream is not None:
# create a StreamHandler
stream_handler = logging.StreamHandler(log_stream)
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
if log_file is not None:
# create a FileHandler
file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
if log_stream is None and log_file is None:
# "no handler" => use NullHandler
logger.addHandler(logging.NullHandler())
return logger | [
"def",
"configure_logger",
"(",
"name",
",",
"log_stream",
"=",
"sys",
".",
"stdout",
",",
"log_file",
"=",
"None",
",",
"log_level",
"=",
"logging",
".",
"INFO",
",",
"keep_old_handlers",
"=",
"False",
",",
"propagate",
"=",
"False",
")",
":",
"# create a... | 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
The stream to write log messages to. If ``None``, do not write to any
stream. The default value is `sys.stdout`.
log_file: str, optional
The path of a file to write log messages to. If None, do not write to
any file. The default value is ``None``.
log_level: int, optional
A logging level as `defined`__ in Python's logging module. The default
value is `logging.INFO`.
keep_old_handlers: bool, optional
If set to ``True``, keep any pre-existing handlers that are attached to
the logger. The default value is ``False``.
propagate: bool, optional
If set to ``True``, propagate the loggers messages to the parent
logger. The default value is ``False``.
Returns
-------
`logging.Logger`
The logger.
Notes
-----
Note that if ``log_stream`` and ``log_file`` are both ``None``, no handlers
will be created.
__ loglvl_
.. _loglvl: https://docs.python.org/2/library/logging.html#logging-levels | [
"Configures",
"and",
"returns",
"a",
"logger",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/misc/log.py#L27-L106 |
flo-compbio/genometools | genometools/misc/log.py | get_logger | def get_logger(name='', log_stream=None, log_file=None,
quiet=False, verbose=False):
"""Convenience function for getting a logger."""
# 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,
log_file=log_file, log_level=log_level)
return new_logger | python | def get_logger(name='', log_stream=None, log_file=None,
quiet=False, verbose=False):
"""Convenience function for getting a logger."""
# 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,
log_file=log_file, log_level=log_level)
return new_logger | [
"def",
"get_logger",
"(",
"name",
"=",
"''",
",",
"log_stream",
"=",
"None",
",",
"log_file",
"=",
"None",
",",
"quiet",
"=",
"False",
",",
"verbose",
"=",
"False",
")",
":",
"# configure root logger",
"log_level",
"=",
"logging",
".",
"INFO",
"if",
"qui... | Convenience function for getting a logger. | [
"Convenience",
"function",
"for",
"getting",
"a",
"logger",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/misc/log.py#L109-L126 |
srevenant/timeinterval | timeinterval/__init__.py | start | 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 unless it is an object will reset each
interval.
The inine test will print "TickTock x.." every second, where x increments.
>>> import time
>>> class Tock(object):
... count = 0
... stop = None
>>> def tick(obj):
... obj.count += 1
... if obj.stop and obj.count == 4:
... obj.stop.set() # shut itself off
... return
... print("TickTock {}..".format(obj.count))
>>> tock = Tock()
>>> tock.stop = start(1000, tick, tock)
>>> time.sleep(6)
TickTock 1..
TickTock 2..
TickTock 3..
"""
stopper = threading.Event()
def interval(seconds, func, *args, **kwargs):
"""outer wrapper"""
def wrapper():
"""inner wrapper"""
if stopper.isSet():
return
interval(seconds, func, *args, **kwargs)
try:
func(*args, **kwargs)
except: # pylint: disable=bare-except
logging.error("Error during interval")
logging.error(traceback.format_exc())
thread = threading.Timer(seconds, wrapper)
thread.daemon = True
thread.start()
interval(milliseconds/1000, func, *args, **kwargs)
return stopper | python | 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 unless it is an object will reset each
interval.
The inine test will print "TickTock x.." every second, where x increments.
>>> import time
>>> class Tock(object):
... count = 0
... stop = None
>>> def tick(obj):
... obj.count += 1
... if obj.stop and obj.count == 4:
... obj.stop.set() # shut itself off
... return
... print("TickTock {}..".format(obj.count))
>>> tock = Tock()
>>> tock.stop = start(1000, tick, tock)
>>> time.sleep(6)
TickTock 1..
TickTock 2..
TickTock 3..
"""
stopper = threading.Event()
def interval(seconds, func, *args, **kwargs):
"""outer wrapper"""
def wrapper():
"""inner wrapper"""
if stopper.isSet():
return
interval(seconds, func, *args, **kwargs)
try:
func(*args, **kwargs)
except: # pylint: disable=bare-except
logging.error("Error during interval")
logging.error(traceback.format_exc())
thread = threading.Timer(seconds, wrapper)
thread.daemon = True
thread.start()
interval(milliseconds/1000, func, *args, **kwargs)
return stopper | [
"def",
"start",
"(",
"milliseconds",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"stopper",
"=",
"threading",
".",
"Event",
"(",
")",
"def",
"interval",
"(",
"seconds",
",",
"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 unless it is an object will reset each
interval.
The inine test will print "TickTock x.." every second, where x increments.
>>> import time
>>> class Tock(object):
... count = 0
... stop = None
>>> def tick(obj):
... obj.count += 1
... if obj.stop and obj.count == 4:
... obj.stop.set() # shut itself off
... return
... print("TickTock {}..".format(obj.count))
>>> tock = Tock()
>>> tock.stop = start(1000, tick, tock)
>>> time.sleep(6)
TickTock 1..
TickTock 2..
TickTock 3.. | [
"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",
... | train | https://github.com/srevenant/timeinterval/blob/61ba4cb23530dc131ff9e2209fb84019663ee7f9/timeinterval/__init__.py#L40-L88 |
acorg/dark-matter | dark/codonDistance.py | codonInformation | 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.
"""
result = defaultdict(list)
for c1 in codons1:
for c2 in codons2:
distance = findDistance(c1, c2)
result[distance].append([c1, c2])
return result | python | 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.
"""
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",
")",
":",
"result",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"c1",
"in",
"codons1",
":",
"for",
"c2",
"in",
"codons2",
":",
"distance",
"=",
"findDistance",
"(",
"c1",
",",
"c2",
")",
"resu... | 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. | [
"Take",
"two",
"C",
"{",
"list",
"}",
"of",
"codons",
"and",
"returns",
"information",
"about",
"the",
"min",
"and",
"max",
"distance",
"between",
"them",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/codonDistance.py#L15-L32 |
vovanec/httputil | examples/http_client.py | example_async_client | def example_async_client(api_client):
"""Example async client.
"""
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()) | python | def example_async_client(api_client):
"""Example async client.
"""
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",
")",
":",
"try",
":",
"pprint",
"(",
"(",
"yield",
"from",
"api_client",
".",
"echo",
"(",
")",
")",
")",
"except",
"errors",
".",
"RequestError",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"'Excepti... | Example async client. | [
"Example",
"async",
"client",
"."
] | train | https://github.com/vovanec/httputil/blob/0b8dab5a23166cceb7dbc2a1dbc802ab5b311347/examples/http_client.py#L65-L74 |
vovanec/httputil | examples/http_client.py | example_sync_client | def example_sync_client(api_client):
"""Example sync client use with.
"""
try:
pprint(api_client.echo())
except errors.RequestError as exc:
log.exception('Exception occurred: %s', exc) | python | def example_sync_client(api_client):
"""Example sync client use with.
"""
try:
pprint(api_client.echo())
except errors.RequestError as exc:
log.exception('Exception occurred: %s', exc) | [
"def",
"example_sync_client",
"(",
"api_client",
")",
":",
"try",
":",
"pprint",
"(",
"api_client",
".",
"echo",
"(",
")",
")",
"except",
"errors",
".",
"RequestError",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"'Exception occurred: %s'",
",",
"exc",
... | Example sync client use with. | [
"Example",
"sync",
"client",
"use",
"with",
"."
] | train | https://github.com/vovanec/httputil/blob/0b8dab5a23166cceb7dbc2a1dbc802ab5b311347/examples/http_client.py#L77-L84 |
vovanec/httputil | examples/http_client.py | main | def main():
"""Run the examples.
"""
logging.basicConfig(level=logging.INFO)
example_sync_client(SyncAPIClient())
example_async_client(AsyncAPIClient())
io_loop = ioloop.IOLoop.current()
io_loop.start() | python | def main():
"""Run the examples.
"""
logging.basicConfig(level=logging.INFO)
example_sync_client(SyncAPIClient())
example_async_client(AsyncAPIClient())
io_loop = ioloop.IOLoop.current()
io_loop.start() | [
"def",
"main",
"(",
")",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"INFO",
")",
"example_sync_client",
"(",
"SyncAPIClient",
"(",
")",
")",
"example_async_client",
"(",
"AsyncAPIClient",
"(",
")",
")",
"io_loop",
"=",
"ioloop",
... | Run the examples. | [
"Run",
"the",
"examples",
"."
] | train | https://github.com/vovanec/httputil/blob/0b8dab5a23166cceb7dbc2a1dbc802ab5b311347/examples/http_client.py#L87-L97 |
flo-compbio/genometools | genometools/ensembl/cli/extract_protein_coding_genes.py | main | 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
-------
int
Exit code (0 if no error occurred).
Raises
------
SystemError
If the version of the Python interpreter is not >= 2.7.
"""
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()
args = parser.parse_args()
input_file = args.annotation_file
output_file = args.output_file
# species = args.species
chrom_pat = args.chromosome_pattern
log_file = args.log_file
quiet = args.quiet
verbose = args.verbose
# configure root logger
log_stream = sys.stdout
if output_file == '-':
# if we print output to stdout, redirect log messages to stderr
log_stream = sys.stderr
logger = misc.get_logger(log_stream=log_stream, log_file=log_file,
quiet=quiet, verbose=verbose)
#if chrom_pat is None:
# chrom_pat = ensembl.SPECIES_CHROMPAT[species]
if chrom_pat is not None:
logger.info('Regular expression used for filtering chromosome names: '
'"%s"', chrom_pat)
if input_file == '-':
input_file = sys.stdin
if output_file == '-':
output_file = sys.stdout
genes = ensembl.get_protein_coding_genes(
input_file,
chromosome_pattern=chrom_pat)
genes.to_csv(output_file, sep='\t', index=False)
return 0 | python | 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
-------
int
Exit code (0 if no error occurred).
Raises
------
SystemError
If the version of the Python interpreter is not >= 2.7.
"""
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()
args = parser.parse_args()
input_file = args.annotation_file
output_file = args.output_file
# species = args.species
chrom_pat = args.chromosome_pattern
log_file = args.log_file
quiet = args.quiet
verbose = args.verbose
# configure root logger
log_stream = sys.stdout
if output_file == '-':
# if we print output to stdout, redirect log messages to stderr
log_stream = sys.stderr
logger = misc.get_logger(log_stream=log_stream, log_file=log_file,
quiet=quiet, verbose=verbose)
#if chrom_pat is None:
# chrom_pat = ensembl.SPECIES_CHROMPAT[species]
if chrom_pat is not None:
logger.info('Regular expression used for filtering chromosome names: '
'"%s"', chrom_pat)
if input_file == '-':
input_file = sys.stdin
if output_file == '-':
output_file = sys.stdout
genes = ensembl.get_protein_coding_genes(
input_file,
chromosome_pattern=chrom_pat)
genes.to_csv(output_file, sep='\t', index=False)
return 0 | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"vinfo",
"=",
"sys",
".",
"version_info",
"if",
"not",
"vinfo",
">=",
"(",
"2",
",",
"7",
")",
":",
"raise",
"SystemError",
"(",
"'Python interpreter version >= 2.7 required, '",
"'found %d.%d instead.'",
"%",... | 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
-------
int
Exit code (0 if no error occurred).
Raises
------
SystemError
If the version of the Python interpreter is not >= 2.7. | [
"Extract",
"protein",
"-",
"coding",
"genes",
"and",
"store",
"in",
"tab",
"-",
"delimited",
"text",
"file",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ensembl/cli/extract_protein_coding_genes.py#L75-L140 |
shmir/PyIxExplorer | ixexplorer/ixe_statistics_view.py | IxePortsStats.read_stats | def read_stats(self, *stats):
""" Read port statistics from chassis.
:param stats: list of requested statistics to read, if empty - read all statistics.
"""
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()})
self.statistics[str(port)] = port_stats
return self.statistics | python | def read_stats(self, *stats):
""" Read port statistics from chassis.
:param stats: list of requested statistics to read, if empty - read all statistics.
"""
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()})
self.statistics[str(port)] = port_stats
return self.statistics | [
"def",
"read_stats",
"(",
"self",
",",
"*",
"stats",
")",
":",
"self",
".",
"statistics",
"=",
"OrderedDict",
"(",
")",
"for",
"port",
"in",
"self",
".",
"ports",
":",
"port_stats",
"=",
"IxeStatTotal",
"(",
"port",
")",
".",
"get_attributes",
"(",
"FL... | Read port statistics from chassis.
:param stats: list of requested statistics to read, if empty - read all statistics. | [
"Read",
"port",
"statistics",
"from",
"chassis",
"."
] | train | https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_statistics_view.py#L195-L207 |
shmir/PyIxExplorer | ixexplorer/ixe_statistics_view.py | IxeStreamsStats.read_stats | def read_stats(self, *stats):
""" Read stream statistics from chassis.
:param stats: list of requested statistics to read, if empty - read all statistics.
"""
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
# Read twice to refresh rate statistics.
for port in self.tx_ports_streams:
port.api.call_rc('streamTransmitStats get {} 1 4096'.format(port.uri))
for rx_port in self.rx_ports:
rx_port.api.call_rc('packetGroupStats get {} 0 65536'.format(rx_port.uri))
time.sleep(sleep_time)
self.statistics = OrderedDict()
for tx_port, streams in self.tx_ports_streams.items():
for stream in streams:
stream_stats = OrderedDict()
tx_port.api.call_rc('streamTransmitStats get {} 1 4096'.format(tx_port.uri))
stream_tx_stats = IxeStreamTxStats(tx_port, stream.index)
stream_stats_tx = {c: v for c, v in stream_tx_stats.get_attributes(FLAG_RDONLY).items()}
stream_stats['tx'] = stream_stats_tx
stream_stat_pgid = IxePacketGroupStream(stream).groupId
stream_stats_pg = pg_stats_dict()
for port in self.session.ports.values():
stream_stats_pg[str(port)] = OrderedDict(zip(stats, [-1] * len(stats)))
for rx_port in self.rx_ports:
if not stream.rx_ports or rx_port in stream.rx_ports:
rx_port.api.call_rc('packetGroupStats get {} 0 65536'.format(rx_port.uri))
pg_stats = IxePgStats(rx_port, stream_stat_pgid)
stream_stats_pg[str(rx_port)] = pg_stats.read_stats(*stats)
stream_stats['rx'] = stream_stats_pg
self.statistics[str(stream)] = stream_stats
return self.statistics | python | def read_stats(self, *stats):
""" Read stream statistics from chassis.
:param stats: list of requested statistics to read, if empty - read all statistics.
"""
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
# Read twice to refresh rate statistics.
for port in self.tx_ports_streams:
port.api.call_rc('streamTransmitStats get {} 1 4096'.format(port.uri))
for rx_port in self.rx_ports:
rx_port.api.call_rc('packetGroupStats get {} 0 65536'.format(rx_port.uri))
time.sleep(sleep_time)
self.statistics = OrderedDict()
for tx_port, streams in self.tx_ports_streams.items():
for stream in streams:
stream_stats = OrderedDict()
tx_port.api.call_rc('streamTransmitStats get {} 1 4096'.format(tx_port.uri))
stream_tx_stats = IxeStreamTxStats(tx_port, stream.index)
stream_stats_tx = {c: v for c, v in stream_tx_stats.get_attributes(FLAG_RDONLY).items()}
stream_stats['tx'] = stream_stats_tx
stream_stat_pgid = IxePacketGroupStream(stream).groupId
stream_stats_pg = pg_stats_dict()
for port in self.session.ports.values():
stream_stats_pg[str(port)] = OrderedDict(zip(stats, [-1] * len(stats)))
for rx_port in self.rx_ports:
if not stream.rx_ports or rx_port in stream.rx_ports:
rx_port.api.call_rc('packetGroupStats get {} 0 65536'.format(rx_port.uri))
pg_stats = IxePgStats(rx_port, stream_stat_pgid)
stream_stats_pg[str(rx_port)] = pg_stats.read_stats(*stats)
stream_stats['rx'] = stream_stats_pg
self.statistics[str(stream)] = stream_stats
return self.statistics | [
"def",
"read_stats",
"(",
"self",
",",
"*",
"stats",
")",
":",
"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",
":"... | Read stream statistics from chassis.
:param stats: list of requested statistics to read, if empty - read all statistics. | [
"Read",
"stream",
"statistics",
"from",
"chassis",
"."
] | train | https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_statistics_view.py#L242-L279 |
nkavaldj/myhdl_lib | myhdl_lib/arbiter.py | arbiter | 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 '''
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:
assert "Arbiter: Unknown arbiter type: {}".format(ARBITER_TYPE)
return _arb | python | 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 '''
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:
assert "Arbiter: Unknown arbiter type: {}".format(ARBITER_TYPE)
return _arb | [
"def",
"arbiter",
"(",
"rst",
",",
"clk",
",",
"req_vec",
",",
"gnt_vec",
"=",
"None",
",",
"gnt_idx",
"=",
"None",
",",
"gnt_vld",
"=",
"None",
",",
"gnt_rdy",
"=",
"None",
",",
"ARBITER_TYPE",
"=",
"\"priority\"",
")",
":",
"if",
"ARBITER_TYPE",
"=="... | Wrapper that provides common interface to all arbiters | [
"Wrapper",
"that",
"provides",
"common",
"interface",
"to",
"all",
"arbiters"
] | train | https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/arbiter.py#L5-L14 |
nkavaldj/myhdl_lib | myhdl_lib/arbiter.py | arbiter_priority | 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_idx - (o) optional, grant index, index of the granted request
gnt_vld - (o) optional, grant valid, indicate that there is a granted request
"""
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):
if ( req_vec[i]==1 ):
gnt_vec_s.next[i] = 1
gnt_idx_s.next = i
gnt_vld_s.next = 1
break
if gnt_vec!=None: _vec = assign(gnt_vec, gnt_vec_s)
if gnt_idx!=None: _idx = assign(gnt_idx, gnt_idx_s)
if gnt_vld!=None: _vld = assign(gnt_vld, gnt_vld_s)
return instances() | python | 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_idx - (o) optional, grant index, index of the granted request
gnt_vld - (o) optional, grant valid, indicate that there is a granted request
"""
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):
if ( req_vec[i]==1 ):
gnt_vec_s.next[i] = 1
gnt_idx_s.next = i
gnt_vld_s.next = 1
break
if gnt_vec!=None: _vec = assign(gnt_vec, gnt_vec_s)
if gnt_idx!=None: _idx = assign(gnt_idx, gnt_idx_s)
if gnt_vld!=None: _vld = assign(gnt_vld, gnt_vld_s)
return instances() | [
"def",
"arbiter_priority",
"(",
"req_vec",
",",
"gnt_vec",
"=",
"None",
",",
"gnt_idx",
"=",
"None",
",",
"gnt_vld",
"=",
"None",
")",
":",
"REQ_NUM",
"=",
"len",
"(",
"req_vec",
")",
"gnt_vec_s",
"=",
"Signal",
"(",
"intbv",
"(",
"0",
")",
"[",
"REQ... | 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_idx - (o) optional, grant index, index of the granted request
gnt_vld - (o) optional, grant valid, indicate that there is a granted request | [
"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",
"... | train | https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/arbiter.py#L17-L45 |
nkavaldj/myhdl_lib | myhdl_lib/arbiter.py | arbiter_roundrobin | 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
gnt_idx - (o) optional, grant index, index of the granted request
gnt_vld - (o) optional, grant valid, indicate that there is a granted request
gnt_rdy - (i) grant ready, indicates that the current grant is consumed and priority should be updated.
The priority is updated only if there is a valid grant when gnt_rdy is activated.
When priority is updated, the currently granted req_vec[gnt_idx] gets the lowest priority and
req_vec[gnt_idx+1] gets the highest priority.
gnt_rdy should be activated in the same clock cycle when output the grant is used
"""
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 (gnt_rdy and gnt_vld_s):
ptr.next = gnt_idx_s
@always_comb
def roundrobin_encoder():
gnt_vec_s.next = 0
gnt_idx_s.next = 0
gnt_vld_s.next = 0
for i in range(REQ_NUM):
if (i>ptr):
if ( req_vec[i]==1 ):
gnt_vec_s.next[i] = 1
gnt_idx_s.next = i
gnt_vld_s.next = 1
return
for i in range(REQ_NUM):
if ( req_vec[i]==1 ):
gnt_vec_s.next[i] = 1
gnt_idx_s.next = i
gnt_vld_s.next = 1
return
if gnt_vec!=None: _vec = assign(gnt_vec, gnt_vec_s)
if gnt_idx!=None: _idx = assign(gnt_idx, gnt_idx_s)
if gnt_vld!=None: _vld = assign(gnt_vld, gnt_vld_s)
return instances() | python | 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
gnt_idx - (o) optional, grant index, index of the granted request
gnt_vld - (o) optional, grant valid, indicate that there is a granted request
gnt_rdy - (i) grant ready, indicates that the current grant is consumed and priority should be updated.
The priority is updated only if there is a valid grant when gnt_rdy is activated.
When priority is updated, the currently granted req_vec[gnt_idx] gets the lowest priority and
req_vec[gnt_idx+1] gets the highest priority.
gnt_rdy should be activated in the same clock cycle when output the grant is used
"""
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 (gnt_rdy and gnt_vld_s):
ptr.next = gnt_idx_s
@always_comb
def roundrobin_encoder():
gnt_vec_s.next = 0
gnt_idx_s.next = 0
gnt_vld_s.next = 0
for i in range(REQ_NUM):
if (i>ptr):
if ( req_vec[i]==1 ):
gnt_vec_s.next[i] = 1
gnt_idx_s.next = i
gnt_vld_s.next = 1
return
for i in range(REQ_NUM):
if ( req_vec[i]==1 ):
gnt_vec_s.next[i] = 1
gnt_idx_s.next = i
gnt_vld_s.next = 1
return
if gnt_vec!=None: _vec = assign(gnt_vec, gnt_vec_s)
if gnt_idx!=None: _idx = assign(gnt_idx, gnt_idx_s)
if gnt_vld!=None: _vld = assign(gnt_vld, gnt_vld_s)
return instances() | [
"def",
"arbiter_roundrobin",
"(",
"rst",
",",
"clk",
",",
"req_vec",
",",
"gnt_vec",
"=",
"None",
",",
"gnt_idx",
"=",
"None",
",",
"gnt_vld",
"=",
"None",
",",
"gnt_rdy",
"=",
"None",
")",
":",
"REQ_NUM",
"=",
"len",
"(",
"req_vec",
")",
"ptr",
"=",... | 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
gnt_idx - (o) optional, grant index, index of the granted request
gnt_vld - (o) optional, grant valid, indicate that there is a granted request
gnt_rdy - (i) grant ready, indicates that the current grant is consumed and priority should be updated.
The priority is updated only if there is a valid grant when gnt_rdy is activated.
When priority is updated, the currently granted req_vec[gnt_idx] gets the lowest priority and
req_vec[gnt_idx+1] gets the highest priority.
gnt_rdy should be activated in the same clock cycle when output the grant is used | [
"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",
... | train | https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/arbiter.py#L48-L97 |
biocommons/bioutils | src/bioutils/digests.py | seq_seqhash | 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)
'eFwawHHdibaZBDcs9kW3gm31h1NNJcQe'
"""
seq = normalize_sequence(seq) if normalize else seq
return str(vmc_digest(seq, digest_size=24)) | python | 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)
'eFwawHHdibaZBDcs9kW3gm31h1NNJcQe'
"""
seq = normalize_sequence(seq) if normalize else seq
return str(vmc_digest(seq, digest_size=24)) | [
"def",
"seq_seqhash",
"(",
"seq",
",",
"normalize",
"=",
"True",
")",
":",
"seq",
"=",
"normalize_sequence",
"(",
"seq",
")",
"if",
"normalize",
"else",
"seq",
"return",
"str",
"(",
"vmc_digest",
"(",
"seq",
",",
"digest_size",
"=",
"24",
")",
")"
] | 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)
'eFwawHHdibaZBDcs9kW3gm31h1NNJcQe' | [
"returns",
"24",
"-",
"byte",
"Truncated",
"Digest",
"sequence",
"seq"
] | train | https://github.com/biocommons/bioutils/blob/88bcbdfa707268fed1110800e91b6d4f8e9475a0/src/bioutils/digests.py#L10-L28 |
biocommons/bioutils | src/bioutils/digests.py | seq_seguid | 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)
'lII0AoG1/I8qKY271rgv5CFZtsU'
"""
seq = normalize_sequence(seq) if normalize else seq
bseq = seq.encode("ascii")
return base64.b64encode(hashlib.sha1(bseq).digest()).decode("ascii").rstrip(
'=') | python | 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)
'lII0AoG1/I8qKY271rgv5CFZtsU'
"""
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",
")",
":",
"seq",
"=",
"normalize_sequence",
"(",
"seq",
")",
"if",
"normalize",
"else",
"seq",
"bseq",
"=",
"seq",
".",
"encode",
"(",
"\"ascii\"",
")",
"return",
"base64",
".",
"b64encode",... | 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)
'lII0AoG1/I8qKY271rgv5CFZtsU' | [
"returns",
"seguid",
"for",
"sequence",
"seq"
] | train | https://github.com/biocommons/bioutils/blob/88bcbdfa707268fed1110800e91b6d4f8e9475a0/src/bioutils/digests.py#L31-L52 |
biocommons/bioutils | src/bioutils/digests.py | seq_md5 | 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'
>>> seq_md5('acgt')
'f1f8f4bf413b16ad135722aa4591043e'
>>> seq_md5('acgt', normalize=False)
'db516c3913e179338b162b2476d1c23f'
"""
seq = normalize_sequence(seq) if normalize else seq
bseq = seq.encode("ascii")
return hashlib.md5(bseq).hexdigest() | python | 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'
>>> seq_md5('acgt')
'f1f8f4bf413b16ad135722aa4591043e'
>>> seq_md5('acgt', normalize=False)
'db516c3913e179338b162b2476d1c23f'
"""
seq = normalize_sequence(seq) if normalize else seq
bseq = seq.encode("ascii")
return hashlib.md5(bseq).hexdigest() | [
"def",
"seq_md5",
"(",
"seq",
",",
"normalize",
"=",
"True",
")",
":",
"seq",
"=",
"normalize_sequence",
"(",
"seq",
")",
"if",
"normalize",
"else",
"seq",
"bseq",
"=",
"seq",
".",
"encode",
"(",
"\"ascii\"",
")",
"return",
"hashlib",
".",
"md5",
"(",
... | 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'
>>> seq_md5('acgt')
'f1f8f4bf413b16ad135722aa4591043e'
>>> seq_md5('acgt', normalize=False)
'db516c3913e179338b162b2476d1c23f' | [
"returns",
"unicode",
"md5",
"as",
"hex",
"digest",
"for",
"sequence",
"seq",
"."
] | train | https://github.com/biocommons/bioutils/blob/88bcbdfa707268fed1110800e91b6d4f8e9475a0/src/bioutils/digests.py#L55-L79 |
biocommons/bioutils | src/bioutils/digests.py | seq_sha1 | 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)
'9482340281b5fc8f2a298dbbd6b82fe42159b6c5'
"""
seq = normalize_sequence(seq) if normalize else seq
bseq = seq.encode("ascii")
return hashlib.sha1(bseq).hexdigest() | python | 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)
'9482340281b5fc8f2a298dbbd6b82fe42159b6c5'
"""
seq = normalize_sequence(seq) if normalize else seq
bseq = seq.encode("ascii")
return hashlib.sha1(bseq).hexdigest() | [
"def",
"seq_sha1",
"(",
"seq",
",",
"normalize",
"=",
"True",
")",
":",
"seq",
"=",
"normalize_sequence",
"(",
"seq",
")",
"if",
"normalize",
"else",
"seq",
"bseq",
"=",
"seq",
".",
"encode",
"(",
"\"ascii\"",
")",
"return",
"hashlib",
".",
"sha1",
"("... | returns unicode sha1 hexdigest for sequence `seq`.
>>> seq_sha1('')
'da39a3ee5e6b4b0d3255bfef95601890afd80709'
>>> seq_sha1('ACGT')
'2108994e17f6cca9ff2352ada92b6511db076034'
>>> seq_sha1('acgt')
'2108994e17f6cca9ff2352ada92b6511db076034'
>>> seq_sha1('acgt', normalize=False)
'9482340281b5fc8f2a298dbbd6b82fe42159b6c5' | [
"returns",
"unicode",
"sha1",
"hexdigest",
"for",
"sequence",
"seq",
"."
] | train | https://github.com/biocommons/bioutils/blob/88bcbdfa707268fed1110800e91b6d4f8e9475a0/src/bioutils/digests.py#L82-L101 |
biocommons/bioutils | src/bioutils/digests.py | seq_sha512 | def seq_sha512(seq, normalize=True):
"""returns unicode sequence sha512 hexdigest for sequence `seq`.
>>> seq_sha512('')
'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e'
>>> seq_sha512('ACGT')
'68a178f7c740c5c240aa67ba41843b119d3bf9f8b0f0ac36cf701d26672964efbd536d197f51ce634fc70634d1eefe575bec34c83247abc52010f6e2bbdb8253'
>>> seq_sha512('acgt')
'68a178f7c740c5c240aa67ba41843b119d3bf9f8b0f0ac36cf701d26672964efbd536d197f51ce634fc70634d1eefe575bec34c83247abc52010f6e2bbdb8253'
>>> seq_sha512('acgt', normalize=False)
'785c1ac071dd89b69904372cf645b7826df587534d25c41edb2862e54fb2940d697218f2883d2bf1a11cdaee658c7f7ab945a1cfd08eb26cbce57ee88790250a'
"""
seq = normalize_sequence(seq) if normalize else seq
bseq = seq.encode("ascii")
return hashlib.sha512(bseq).hexdigest() | python | def seq_sha512(seq, normalize=True):
"""returns unicode sequence sha512 hexdigest for sequence `seq`.
>>> seq_sha512('')
'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e'
>>> seq_sha512('ACGT')
'68a178f7c740c5c240aa67ba41843b119d3bf9f8b0f0ac36cf701d26672964efbd536d197f51ce634fc70634d1eefe575bec34c83247abc52010f6e2bbdb8253'
>>> seq_sha512('acgt')
'68a178f7c740c5c240aa67ba41843b119d3bf9f8b0f0ac36cf701d26672964efbd536d197f51ce634fc70634d1eefe575bec34c83247abc52010f6e2bbdb8253'
>>> seq_sha512('acgt', normalize=False)
'785c1ac071dd89b69904372cf645b7826df587534d25c41edb2862e54fb2940d697218f2883d2bf1a11cdaee658c7f7ab945a1cfd08eb26cbce57ee88790250a'
"""
seq = normalize_sequence(seq) if normalize else seq
bseq = seq.encode("ascii")
return hashlib.sha512(bseq).hexdigest() | [
"def",
"seq_sha512",
"(",
"seq",
",",
"normalize",
"=",
"True",
")",
":",
"seq",
"=",
"normalize_sequence",
"(",
"seq",
")",
"if",
"normalize",
"else",
"seq",
"bseq",
"=",
"seq",
".",
"encode",
"(",
"\"ascii\"",
")",
"return",
"hashlib",
".",
"sha512",
... | returns unicode sequence sha512 hexdigest for sequence `seq`.
>>> seq_sha512('')
'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e'
>>> seq_sha512('ACGT')
'68a178f7c740c5c240aa67ba41843b119d3bf9f8b0f0ac36cf701d26672964efbd536d197f51ce634fc70634d1eefe575bec34c83247abc52010f6e2bbdb8253'
>>> seq_sha512('acgt')
'68a178f7c740c5c240aa67ba41843b119d3bf9f8b0f0ac36cf701d26672964efbd536d197f51ce634fc70634d1eefe575bec34c83247abc52010f6e2bbdb8253'
>>> seq_sha512('acgt', normalize=False)
'785c1ac071dd89b69904372cf645b7826df587534d25c41edb2862e54fb2940d697218f2883d2bf1a11cdaee658c7f7ab945a1cfd08eb26cbce57ee88790250a' | [
"returns",
"unicode",
"sequence",
"sha512",
"hexdigest",
"for",
"sequence",
"seq",
"."
] | train | https://github.com/biocommons/bioutils/blob/88bcbdfa707268fed1110800e91b6d4f8e9475a0/src/bioutils/digests.py#L104-L123 |
biocommons/bioutils | src/bioutils/digests.py | seq_vmc_identifier | 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'}
True
>>> seq_vmc_identifier("acgt") == {'namespace': 'VMC', 'accession': 'GS_aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2'}
True
>>> seq_vmc_identifier("acgt", normalize=False) == {'namespace': 'VMC', 'accession': 'GS_eFwawHHdibaZBDcs9kW3gm31h1NNJcQe'}
True
"""
seq = normalize_sequence(seq) if normalize else seq
return {"namespace": "VMC", "accession": "GS_" + str(vmc_digest(seq))} | python | 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'}
True
>>> seq_vmc_identifier("acgt") == {'namespace': 'VMC', 'accession': 'GS_aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2'}
True
>>> seq_vmc_identifier("acgt", normalize=False) == {'namespace': 'VMC', 'accession': 'GS_eFwawHHdibaZBDcs9kW3gm31h1NNJcQe'}
True
"""
seq = normalize_sequence(seq) if normalize else seq
return {"namespace": "VMC", "accession": "GS_" + str(vmc_digest(seq))} | [
"def",
"seq_vmc_identifier",
"(",
"seq",
",",
"normalize",
"=",
"True",
")",
":",
"seq",
"=",
"normalize_sequence",
"(",
"seq",
")",
"if",
"normalize",
"else",
"seq",
"return",
"{",
"\"namespace\"",
":",
"\"VMC\"",
",",
"\"accession\"",
":",
"\"GS_\"",
"+",
... | 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'}
True
>>> seq_vmc_identifier("acgt") == {'namespace': 'VMC', 'accession': 'GS_aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2'}
True
>>> seq_vmc_identifier("acgt", normalize=False) == {'namespace': 'VMC', 'accession': 'GS_eFwawHHdibaZBDcs9kW3gm31h1NNJcQe'}
True | [
"returns",
"VMC",
"identifier",
"(",
"record",
")",
"for",
"sequence",
"seq"
] | train | https://github.com/biocommons/bioutils/blob/88bcbdfa707268fed1110800e91b6d4f8e9475a0/src/bioutils/digests.py#L148-L167 |
flo-compbio/genometools | genometools/gcloud/tasks/star.py | map_single_end | 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_nmax=None, sort_bam=True, keep_unmapped=False,
self_destruct=True, compressed=True,
**kwargs):
"""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"""
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(
os.path.join('map_single-end.sh'))
startup_script = template.render(
script_dir=script_dir,
index_dir=index_dir,
fastq_files=fastq_files,
output_dir=output_dir,
num_threads=num_threads,
seed_start_lmax=seed_start_lmax,
self_destruct=self_destruct,
mismatch_nmax=mismatch_nmax,
multimap_nmax=multimap_nmax,
splice_min_overhang=splice_min_overhang,
out_mult_nmax=out_mult_nmax,
keep_unmapped=keep_unmapped,
compressed=compressed,
out_sam_type=out_sam_type)
if len(startup_script) > 32768:
raise ValueError('Startup script larger than 32,768 bytes!')
#print(startup_script)
op_name = instance_config.create_instance(
credentials, instance_name, startup_script=startup_script, **kwargs)
return op_name | python | 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_nmax=None, sort_bam=True, keep_unmapped=False,
self_destruct=True, compressed=True,
**kwargs):
"""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"""
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(
os.path.join('map_single-end.sh'))
startup_script = template.render(
script_dir=script_dir,
index_dir=index_dir,
fastq_files=fastq_files,
output_dir=output_dir,
num_threads=num_threads,
seed_start_lmax=seed_start_lmax,
self_destruct=self_destruct,
mismatch_nmax=mismatch_nmax,
multimap_nmax=multimap_nmax,
splice_min_overhang=splice_min_overhang,
out_mult_nmax=out_mult_nmax,
keep_unmapped=keep_unmapped,
compressed=compressed,
out_sam_type=out_sam_type)
if len(startup_script) > 32768:
raise ValueError('Startup script larger than 32,768 bytes!')
#print(startup_script)
op_name = instance_config.create_instance(
credentials, instance_name, startup_script=startup_script, **kwargs)
return op_name | [
"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",
"=",
... | 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 | [
"Maps",
"single",
"-",
"end",
"reads",
"using",
"STAR",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gcloud/tasks/star.py#L39-L93 |
flo-compbio/genometools | genometools/gcloud/tasks/star.py | generate_index | 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_destruct=True,
**kwargs):
"""Generates a STAR index.
Recommended machine type: "n1-highmem-8" (52 GB of RAM, 8 vCPUs)
TODO: docstring"""
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_threads=num_threads,
chromosome_bin_bits=chromosome_bin_bits,
genome_memory_limit=genome_memory_limit,
self_destruct=self_destruct)
op_name = instance_config.create_instance(
credentials, instance_name, startup_script=startup_script, **kwargs)
return op_name | python | 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_destruct=True,
**kwargs):
"""Generates a STAR index.
Recommended machine type: "n1-highmem-8" (52 GB of RAM, 8 vCPUs)
TODO: docstring"""
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_threads=num_threads,
chromosome_bin_bits=chromosome_bin_bits,
genome_memory_limit=genome_memory_limit,
self_destruct=self_destruct)
op_name = instance_config.create_instance(
credentials, instance_name, startup_script=startup_script, **kwargs)
return op_name | [
"def",
"generate_index",
"(",
"credentials",
",",
"instance_config",
",",
"instance_name",
",",
"script_dir",
",",
"genome_file",
",",
"output_dir",
",",
"annotation_file",
"=",
"None",
",",
"splice_overhang",
"=",
"100",
",",
"num_threads",
"=",
"8",
",",
"chro... | Generates a STAR index.
Recommended machine type: "n1-highmem-8" (52 GB of RAM, 8 vCPUs)
TODO: docstring | [
"Generates",
"a",
"STAR",
"index",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gcloud/tasks/star.py#L162-L191 |
nkavaldj/myhdl_lib | myhdl_lib/fifo.py | fifo | def fifo(rst, clk, full, we, din, empty, re, dout, afull=None, aempty=None, afull_th=None, aempty_th=None, ovf=None, udf=None, count=None, count_max=None, depth=None, width=None):
""" Synchronous FIFO
Input interface: full, we, din
Output interface: empty, re, dout
It s possible to set din and dout to None. Then the fifo width will be 0 and the fifo will contain no storage.
Extra interface:
afull (o) - almost full flag, asserted when the number of empty cells <= afull_th
aempty (o) - almost empty flag, asserted when the number of full cells <= aempty_th
afull_th (i) - almost full threshold, in terms of fifo cells; signal or constant; Optional, default depth/2
aempty_th (i) - almost empty threshold, in terms of fifo cells; signal or constant; Optional, default depth/2
count (o) - number of occupied fifo cells
count_max (o) - max number of occupied fifo cells reached since the last reset
ovf (o) - overflow flag, set at the first write in a full fifo, cleared at reset
udf (o) - underflow flag, set at the first read from an empty fifo, cleared at reset
Parameters:
depth - fifo depth, must be >= 1; if not set or set to `None` default value 2 is used
width - data width in bits, must be >= 0; if not set or set to `None` the `din` width is used
"""
if (width == None):
width = 0
if din is not None:
width = len(din)
if (depth == None):
depth = 2
full_flg = Signal(bool(1))
empty_flg = Signal(bool(1))
we_safe = Signal(bool(0))
re_safe = Signal(bool(0))
rd_ptr = Signal(intbv(0, min=0, max=depth))
rd_ptr_new = Signal(intbv(0, min=0, max=depth))
wr_ptr = Signal(intbv(0, min=0, max=depth))
wr_ptr_new = Signal(intbv(0, min=0, max=depth))
@always_comb
def safe_read_write():
full.next = full_flg
empty.next = empty_flg
we_safe.next = we and not full_flg
re_safe.next = re and not empty_flg
#===========================================================================
# Write, Read, Full, Empty
#===========================================================================
@always_comb
def ptrs_new():
rd_ptr_new.next = ((rd_ptr + 1) % depth)
wr_ptr_new.next = ((wr_ptr + 1) % depth)
@always(clk.posedge)
def state_main():
if (rst):
wr_ptr.next = 0
rd_ptr.next = 0
full_flg.next = 0
empty_flg.next = 1
else:
# Write pointer
if (we_safe): wr_ptr.next = wr_ptr_new
# Read pointer
if (re_safe): rd_ptr.next = rd_ptr_new
# Empty flag
if (we_safe):
empty_flg.next = 0
elif (re_safe and (rd_ptr_new == wr_ptr)):
empty_flg.next = 1
# Full flag
if (re_safe):
full_flg.next = 0
elif (we_safe and (wr_ptr_new == rd_ptr)):
full_flg.next = 1
#===========================================================================
# Count, CountMax
#===========================================================================
''' Count '''
if (count != None) or (count_max != None) or (afull != None) or (aempty != None):
count_r = Signal(intbv(0, min=0, max=depth+1))
count_new = Signal(intbv(0, min=-1, max=depth+2))
if (count != None):
assert count.max > depth
@always_comb
def count_out():
count.next = count_r
@always_comb
def count_comb():
if (we_safe and not re_safe):
count_new.next = count_r + 1
elif (not we_safe and re_safe):
count_new.next = count_r - 1
else:
count_new.next = count_r
@always(clk.posedge)
def count_proc():
if (rst):
count_r.next = 0
else:
count_r.next = count_new
''' Count max '''
if (count_max != None):
assert count_max.max > depth
count_max_r = Signal(intbv(0, min=0,max=count_max.max))
@always(clk.posedge)
def count_max_proc():
if (rst):
count_max_r.next = 0
else:
if (count_max_r < count_new):
count_max_r.next = count_new
@always_comb
def count_max_out():
count_max.next = count_max_r
#===========================================================================
# AlmostFull, AlmostEmpty
#===========================================================================
''' AlmostFull flag '''
if (afull != None):
if (afull_th == None):
afull_th = depth//2
@always(clk.posedge)
def afull_proc():
if (rst):
afull.next = 0
else:
afull.next = (count_new >= depth-afull_th)
''' AlmostEmpty flag '''
if (aempty != None):
if (aempty_th == None):
aempty_th = depth//2
@always(clk.posedge)
def aempty_proc():
if (rst):
aempty.next = 1
else:
aempty.next = (count_new <= aempty_th)
#===========================================================================
# Overflow, Underflow
#===========================================================================
''' Overflow flag '''
if (ovf != None):
@always(clk.posedge)
def ovf_proc():
if (rst):
ovf.next = 0
else:
if (we and full_flg ):
ovf.next = 1
''' Underflow flag '''
if (udf != None):
@always(clk.posedge)
def udf_proc():
if (rst):
udf.next = 0
else:
if (re and empty_flg):
udf.next = 1
if width>0:
#===========================================================================
# Memory instance
#===========================================================================
mem_we = Signal(bool(0))
mem_addrw = Signal(intbv(0, min=0, max=depth))
mem_addrr = Signal(intbv(0, min=0, max=depth))
mem_di = Signal(intbv(0)[width:0])
mem_do = Signal(intbv(0)[width:0])
# RAM: Simple-Dual-Port, Asynchronous read
mem = ram_sdp_ar( clk = clk,
we = mem_we,
addrw = mem_addrw,
addrr = mem_addrr,
di = mem_di,
do = mem_do )
@always_comb
def mem_connect():
mem_we.next = we_safe
mem_addrw.next = wr_ptr
mem_addrr.next = rd_ptr
mem_di.next = din
dout.next = mem_do
return instances() | python | def fifo(rst, clk, full, we, din, empty, re, dout, afull=None, aempty=None, afull_th=None, aempty_th=None, ovf=None, udf=None, count=None, count_max=None, depth=None, width=None):
""" Synchronous FIFO
Input interface: full, we, din
Output interface: empty, re, dout
It s possible to set din and dout to None. Then the fifo width will be 0 and the fifo will contain no storage.
Extra interface:
afull (o) - almost full flag, asserted when the number of empty cells <= afull_th
aempty (o) - almost empty flag, asserted when the number of full cells <= aempty_th
afull_th (i) - almost full threshold, in terms of fifo cells; signal or constant; Optional, default depth/2
aempty_th (i) - almost empty threshold, in terms of fifo cells; signal or constant; Optional, default depth/2
count (o) - number of occupied fifo cells
count_max (o) - max number of occupied fifo cells reached since the last reset
ovf (o) - overflow flag, set at the first write in a full fifo, cleared at reset
udf (o) - underflow flag, set at the first read from an empty fifo, cleared at reset
Parameters:
depth - fifo depth, must be >= 1; if not set or set to `None` default value 2 is used
width - data width in bits, must be >= 0; if not set or set to `None` the `din` width is used
"""
if (width == None):
width = 0
if din is not None:
width = len(din)
if (depth == None):
depth = 2
full_flg = Signal(bool(1))
empty_flg = Signal(bool(1))
we_safe = Signal(bool(0))
re_safe = Signal(bool(0))
rd_ptr = Signal(intbv(0, min=0, max=depth))
rd_ptr_new = Signal(intbv(0, min=0, max=depth))
wr_ptr = Signal(intbv(0, min=0, max=depth))
wr_ptr_new = Signal(intbv(0, min=0, max=depth))
@always_comb
def safe_read_write():
full.next = full_flg
empty.next = empty_flg
we_safe.next = we and not full_flg
re_safe.next = re and not empty_flg
#===========================================================================
# Write, Read, Full, Empty
#===========================================================================
@always_comb
def ptrs_new():
rd_ptr_new.next = ((rd_ptr + 1) % depth)
wr_ptr_new.next = ((wr_ptr + 1) % depth)
@always(clk.posedge)
def state_main():
if (rst):
wr_ptr.next = 0
rd_ptr.next = 0
full_flg.next = 0
empty_flg.next = 1
else:
# Write pointer
if (we_safe): wr_ptr.next = wr_ptr_new
# Read pointer
if (re_safe): rd_ptr.next = rd_ptr_new
# Empty flag
if (we_safe):
empty_flg.next = 0
elif (re_safe and (rd_ptr_new == wr_ptr)):
empty_flg.next = 1
# Full flag
if (re_safe):
full_flg.next = 0
elif (we_safe and (wr_ptr_new == rd_ptr)):
full_flg.next = 1
#===========================================================================
# Count, CountMax
#===========================================================================
''' Count '''
if (count != None) or (count_max != None) or (afull != None) or (aempty != None):
count_r = Signal(intbv(0, min=0, max=depth+1))
count_new = Signal(intbv(0, min=-1, max=depth+2))
if (count != None):
assert count.max > depth
@always_comb
def count_out():
count.next = count_r
@always_comb
def count_comb():
if (we_safe and not re_safe):
count_new.next = count_r + 1
elif (not we_safe and re_safe):
count_new.next = count_r - 1
else:
count_new.next = count_r
@always(clk.posedge)
def count_proc():
if (rst):
count_r.next = 0
else:
count_r.next = count_new
''' Count max '''
if (count_max != None):
assert count_max.max > depth
count_max_r = Signal(intbv(0, min=0,max=count_max.max))
@always(clk.posedge)
def count_max_proc():
if (rst):
count_max_r.next = 0
else:
if (count_max_r < count_new):
count_max_r.next = count_new
@always_comb
def count_max_out():
count_max.next = count_max_r
#===========================================================================
# AlmostFull, AlmostEmpty
#===========================================================================
''' AlmostFull flag '''
if (afull != None):
if (afull_th == None):
afull_th = depth//2
@always(clk.posedge)
def afull_proc():
if (rst):
afull.next = 0
else:
afull.next = (count_new >= depth-afull_th)
''' AlmostEmpty flag '''
if (aempty != None):
if (aempty_th == None):
aempty_th = depth//2
@always(clk.posedge)
def aempty_proc():
if (rst):
aempty.next = 1
else:
aempty.next = (count_new <= aempty_th)
#===========================================================================
# Overflow, Underflow
#===========================================================================
''' Overflow flag '''
if (ovf != None):
@always(clk.posedge)
def ovf_proc():
if (rst):
ovf.next = 0
else:
if (we and full_flg ):
ovf.next = 1
''' Underflow flag '''
if (udf != None):
@always(clk.posedge)
def udf_proc():
if (rst):
udf.next = 0
else:
if (re and empty_flg):
udf.next = 1
if width>0:
#===========================================================================
# Memory instance
#===========================================================================
mem_we = Signal(bool(0))
mem_addrw = Signal(intbv(0, min=0, max=depth))
mem_addrr = Signal(intbv(0, min=0, max=depth))
mem_di = Signal(intbv(0)[width:0])
mem_do = Signal(intbv(0)[width:0])
# RAM: Simple-Dual-Port, Asynchronous read
mem = ram_sdp_ar( clk = clk,
we = mem_we,
addrw = mem_addrw,
addrr = mem_addrr,
di = mem_di,
do = mem_do )
@always_comb
def mem_connect():
mem_we.next = we_safe
mem_addrw.next = wr_ptr
mem_addrr.next = rd_ptr
mem_di.next = din
dout.next = mem_do
return instances() | [
"def",
"fifo",
"(",
"rst",
",",
"clk",
",",
"full",
",",
"we",
",",
"din",
",",
"empty",
",",
"re",
",",
"dout",
",",
"afull",
"=",
"None",
",",
"aempty",
"=",
"None",
",",
"afull_th",
"=",
"None",
",",
"aempty_th",
"=",
"None",
",",
"ovf",
"="... | Synchronous FIFO
Input interface: full, we, din
Output interface: empty, re, dout
It s possible to set din and dout to None. Then the fifo width will be 0 and the fifo will contain no storage.
Extra interface:
afull (o) - almost full flag, asserted when the number of empty cells <= afull_th
aempty (o) - almost empty flag, asserted when the number of full cells <= aempty_th
afull_th (i) - almost full threshold, in terms of fifo cells; signal or constant; Optional, default depth/2
aempty_th (i) - almost empty threshold, in terms of fifo cells; signal or constant; Optional, default depth/2
count (o) - number of occupied fifo cells
count_max (o) - max number of occupied fifo cells reached since the last reset
ovf (o) - overflow flag, set at the first write in a full fifo, cleared at reset
udf (o) - underflow flag, set at the first read from an empty fifo, cleared at reset
Parameters:
depth - fifo depth, must be >= 1; if not set or set to `None` default value 2 is used
width - data width in bits, must be >= 0; if not set or set to `None` the `din` width is used | [
"Synchronous",
"FIFO"
] | train | https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/fifo.py#L6-L210 |
flo-compbio/genometools | genometools/ensembl/util.py | get_file_checksums | 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 file names as keys and checksums as
values.
Notes
-----
The checksums contains in Ensembl CHECKSUM files are obtained with the
UNIX `sum` command.
"""
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(ftp_user)
close_connection = True
# download and parse CHECKSUM file
data = []
ftp.retrbinary('RETR %s' % url, data.append)
data = ''.join(d.decode('utf-8') for d in data).split('\n')[:-1]
file_checksums = OrderedDict()
for d in data:
file_name = d[(d.rindex(' ') + 1):]
sum_ = int(d[:d.index(' ')])
file_checksums[file_name] = sum_
logger.debug('Obtained checksums for %d files', len(file_checksums))
# close FTP connection if we opened it
if close_connection:
ftp.close()
return file_checksums | python | 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 file names as keys and checksums as
values.
Notes
-----
The checksums contains in Ensembl CHECKSUM files are obtained with the
UNIX `sum` command.
"""
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(ftp_user)
close_connection = True
# download and parse CHECKSUM file
data = []
ftp.retrbinary('RETR %s' % url, data.append)
data = ''.join(d.decode('utf-8') for d in data).split('\n')[:-1]
file_checksums = OrderedDict()
for d in data:
file_name = d[(d.rindex(' ') + 1):]
sum_ = int(d[:d.index(' ')])
file_checksums[file_name] = sum_
logger.debug('Obtained checksums for %d files', len(file_checksums))
# close FTP connection if we opened it
if close_connection:
ftp.close()
return file_checksums | [
"def",
"get_file_checksums",
"(",
"url",
",",
"ftp",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"url",
",",
"(",
"str",
",",
"_oldstr",
")",
")",
"if",
"ftp",
"is",
"not",
"None",
":",
"assert",
"isinstance",
"(",
"ftp",
",",
"ftplib",
".",
... | 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 file names as keys and checksums as
values.
Notes
-----
The checksums contains in Ensembl CHECKSUM files are obtained with the
UNIX `sum` command. | [
"Download",
"and",
"parse",
"an",
"Ensembl",
"CHECKSUMS",
"file",
"and",
"obtain",
"checksums",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ensembl/util.py#L77-L127 |
grabbles/grabbit | grabbit/utils.py | listify | 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. '''
return obj if isinstance(obj, ignore) else [obj] | python | 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. '''
return obj if isinstance(obj, ignore) else [obj] | [
"def",
"listify",
"(",
"obj",
",",
"ignore",
"=",
"(",
"list",
",",
"tuple",
",",
"type",
"(",
"None",
")",
")",
")",
":",
"return",
"obj",
"if",
"isinstance",
"(",
"obj",
",",
"ignore",
")",
"else",
"[",
"obj",
"]"
] | Wraps all non-list or tuple objects in a list; provides a simple way
to accept flexible arguments. | [
"Wraps",
"all",
"non",
"-",
"list",
"or",
"tuple",
"objects",
"in",
"a",
"list",
";",
"provides",
"a",
"simple",
"way",
"to",
"accept",
"flexible",
"arguments",
"."
] | train | https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/utils.py#L34-L37 |
flo-compbio/genometools | genometools/ncbi/taxonomy.py | _get_divisions | def _get_divisions(taxdump_file):
"""Returns a dictionary mapping division names to division IDs."""
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[:, 1] = df.iloc[:, 1].str.strip('\t')
# generate dictionary
divisions = {}
for _, row in df.iterrows():
divisions[row.iloc[1]] = row.iloc[0]
return divisions | python | def _get_divisions(taxdump_file):
"""Returns a dictionary mapping division names to division IDs."""
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[:, 1] = df.iloc[:, 1].str.strip('\t')
# generate dictionary
divisions = {}
for _, row in df.iterrows():
divisions[row.iloc[1]] = row.iloc[0]
return divisions | [
"def",
"_get_divisions",
"(",
"taxdump_file",
")",
":",
"with",
"tarfile",
".",
"open",
"(",
"taxdump_file",
")",
"as",
"tf",
":",
"with",
"tf",
".",
"extractfile",
"(",
"'division.dmp'",
")",
"as",
"fh",
":",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"fh... | Returns a dictionary mapping division names to division IDs. | [
"Returns",
"a",
"dictionary",
"mapping",
"division",
"names",
"to",
"division",
"IDs",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ncbi/taxonomy.py#L25-L43 |
flo-compbio/genometools | genometools/ncbi/taxonomy.py | _get_species_taxon_ids | def _get_species_taxon_ids(taxdump_file,
select_divisions=None, exclude_divisions=None):
"""Get a list of species taxon IDs (allow filtering by division)."""
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_divisions:
divisions = _get_divisions(taxdump_file)
if select_divisions:
select_division_ids = set([divisions[d] for d in select_divisions])
elif exclude_divisions:
exclude_division_ids = set([divisions[d] for d in exclude_divisions])
with tarfile.open(taxdump_file) as tf:
with tf.extractfile('nodes.dmp') as fh:
df = pd.read_csv(fh, header=None, sep='|', encoding='ascii')
# select only tax_id, rank, and division id columns
df = df.iloc[:, [0, 2, 4]]
if select_division_ids:
# select only species from specified divisions
df = df.loc[df.iloc[:, 2].isin(select_division_ids)]
elif exclude_division_ids:
# exclude species from specified divisions
df = df.loc[~df.iloc[:, 2].isin(exclude_division_ids)]
# remove tab characters flanking each rank name
df.iloc[:, 1] = df.iloc[:, 1].str.strip('\t')
# get taxon IDs for all species
taxon_ids = df.iloc[:, 0].loc[df.iloc[:, 1] == 'species'].values
return taxon_ids | python | def _get_species_taxon_ids(taxdump_file,
select_divisions=None, exclude_divisions=None):
"""Get a list of species taxon IDs (allow filtering by division)."""
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_divisions:
divisions = _get_divisions(taxdump_file)
if select_divisions:
select_division_ids = set([divisions[d] for d in select_divisions])
elif exclude_divisions:
exclude_division_ids = set([divisions[d] for d in exclude_divisions])
with tarfile.open(taxdump_file) as tf:
with tf.extractfile('nodes.dmp') as fh:
df = pd.read_csv(fh, header=None, sep='|', encoding='ascii')
# select only tax_id, rank, and division id columns
df = df.iloc[:, [0, 2, 4]]
if select_division_ids:
# select only species from specified divisions
df = df.loc[df.iloc[:, 2].isin(select_division_ids)]
elif exclude_division_ids:
# exclude species from specified divisions
df = df.loc[~df.iloc[:, 2].isin(exclude_division_ids)]
# remove tab characters flanking each rank name
df.iloc[:, 1] = df.iloc[:, 1].str.strip('\t')
# get taxon IDs for all species
taxon_ids = df.iloc[:, 0].loc[df.iloc[:, 1] == 'species'].values
return taxon_ids | [
"def",
"_get_species_taxon_ids",
"(",
"taxdump_file",
",",
"select_divisions",
"=",
"None",
",",
"exclude_divisions",
"=",
"None",
")",
":",
"if",
"select_divisions",
"and",
"exclude_divisions",
":",
"raise",
"ValueError",
"(",
"'Cannot specify \"select_divisions\" and '"... | Get a list of species taxon IDs (allow filtering by division). | [
"Get",
"a",
"list",
"of",
"species",
"taxon",
"IDs",
"(",
"allow",
"filtering",
"by",
"division",
")",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ncbi/taxonomy.py#L46-L88 |
flo-compbio/genometools | genometools/ncbi/taxonomy.py | get_species | def get_species(taxdump_file, select_divisions=None,
exclude_divisions=None, nrows=None):
"""Get a dataframe with species information."""
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_divisions=exclude_divisions)
select_taxon_ids = set(select_taxon_ids)
with tarfile.open(taxdump_file) as tf:
with tf.extractfile('names.dmp') as fh:
df = pd.read_csv(fh, header=None, sep='|',
encoding='ascii', nrows=nrows)
# only keep information we need
df = df.iloc[:, [0, 1, 3]]
# only select selected species
df = df.loc[df.iloc[:, 0].isin(select_taxon_ids)]
# remove tab characters flanking each "name class" entry
df.iloc[:, 2] = df.iloc[:, 2].str.strip('\t')
# select only "scientific name" and "common name" rows
df = df.loc[df.iloc[:, 2].isin(['scientific name', 'common name'])]
# remove tab characters flanking each "name" entry
df.iloc[:, 1] = df.iloc[:, 1].str.strip('\t')
# collapse common names for each scientific name
common_names = defaultdict(list)
cn = df.loc[df.iloc[:, 2] == 'common name']
for _, row in cn.iterrows():
common_names[row.iloc[0]].append(row.iloc[1])
# build final dataframe (this is very slow)
sn = df.loc[df.iloc[:, 2] == 'scientific name']
species = []
for i, row in sn.iterrows():
species.append([row.iloc[0], row.iloc[1],
'|'.join(common_names[row.iloc[0]])])
species_df = pd.DataFrame(species).set_index(0)
species_df.columns = ['scientific_name', 'common_names']
species_df.index.name = 'taxon_id'
return species_df | python | def get_species(taxdump_file, select_divisions=None,
exclude_divisions=None, nrows=None):
"""Get a dataframe with species information."""
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_divisions=exclude_divisions)
select_taxon_ids = set(select_taxon_ids)
with tarfile.open(taxdump_file) as tf:
with tf.extractfile('names.dmp') as fh:
df = pd.read_csv(fh, header=None, sep='|',
encoding='ascii', nrows=nrows)
# only keep information we need
df = df.iloc[:, [0, 1, 3]]
# only select selected species
df = df.loc[df.iloc[:, 0].isin(select_taxon_ids)]
# remove tab characters flanking each "name class" entry
df.iloc[:, 2] = df.iloc[:, 2].str.strip('\t')
# select only "scientific name" and "common name" rows
df = df.loc[df.iloc[:, 2].isin(['scientific name', 'common name'])]
# remove tab characters flanking each "name" entry
df.iloc[:, 1] = df.iloc[:, 1].str.strip('\t')
# collapse common names for each scientific name
common_names = defaultdict(list)
cn = df.loc[df.iloc[:, 2] == 'common name']
for _, row in cn.iterrows():
common_names[row.iloc[0]].append(row.iloc[1])
# build final dataframe (this is very slow)
sn = df.loc[df.iloc[:, 2] == 'scientific name']
species = []
for i, row in sn.iterrows():
species.append([row.iloc[0], row.iloc[1],
'|'.join(common_names[row.iloc[0]])])
species_df = pd.DataFrame(species).set_index(0)
species_df.columns = ['scientific_name', 'common_names']
species_df.index.name = 'taxon_id'
return species_df | [
"def",
"get_species",
"(",
"taxdump_file",
",",
"select_divisions",
"=",
"None",
",",
"exclude_divisions",
"=",
"None",
",",
"nrows",
"=",
"None",
")",
":",
"if",
"select_divisions",
"and",
"exclude_divisions",
":",
"raise",
"ValueError",
"(",
"'Cannot specify \"s... | Get a dataframe with species information. | [
"Get",
"a",
"dataframe",
"with",
"species",
"information",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ncbi/taxonomy.py#L94-L143 |
shmir/PyIxExplorer | ixexplorer/ixe_object.py | IxeObject.set_attributes | 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.
"""
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) | python | 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.
"""
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",
")",
":",
"auto_set",
"=",
"IxeObject",
".",
"get_auto_set",
"(",
")",
"IxeObject",
".",
"set_auto_set",
"(",
"False",
")",
"for",
"name",
",",
"value",
"in",
"attributes",
".",
"items",
... | 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. | [
"Set",
"group",
"of",
"attributes",
"without",
"calling",
"set",
"between",
"attributes",
"regardless",
"of",
"global",
"auto_set",
"."
] | train | https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_object.py#L64-L78 |
acorg/dark-matter | dark/consensus.py | consensusSequence | def consensusSequence(recordFilename, hitId, fastaFilename, eCutoff=None,
db='nt', actualSequenceId=None):
"""
Build a consensus sequence against a target sequence.
recordFilename: the BLAST XML output file.
hitId: the str sequence id to examine the BLAST output for hits against.
fastaFilename: The name of the FASTA file containing query sequences,
or a list of fasta sequences from SeqIO.parse
eCutoff: converted e values less than this will be ignored.
db: the BLAST db to use to look up the target and, if given, actual
sequence.
actualSequenceId: the str id of the actual sequence (if known).
"""
print('TODO: This function is not finished yet.')
return
start = time()
if isinstance(recordFilename, str):
# TODO: REMOVE THE LIMIT IN THE NEXT LINE!
allhits = findHits(recordFilename, set([hitId]), limit=100)
else:
allhits = recordFilename
sequence = getSequence(hitId, db)
fasta, summary = summarizeHits(allhits, fastaFilename, eCutoff=eCutoff)
minX, maxX = summary['minX'], summary['maxX']
if actualSequenceId:
# UNUSED.
# actualSequence = getSequence(actualSequenceId, db)
pass
print(summary['hitCount'])
print('seq len =', len(sequence))
fasta = summary['fasta']
# The length of the consensus depends on where the query sequences fell
# when aligned with the target. The consensus could extend the target
# at both ends.
consensusLen = maxX - minX
consensus = [None, ] * consensusLen
for item in summary['items']:
print('NEW HSP')
printHSP(item['origHsp']) # TODO: REMOVE ME
hsp = item['hsp']
print('HIT query-start=%d query-stop=%d subj-start=%d subj-stop=%d' % (
hsp['queryStart'], hsp['queryEnd'], hsp['subjectStart'],
hsp['subjectEnd']))
# print ' match: %s%s' % ('.' * hsp['subjectStart'], '-' *
# (hsp['subjectEnd'] - hsp['subjectStart']))
if item['frame']['subject'] > 0:
query = fasta[item['sequenceId']].seq
else:
query = fasta[item['sequenceId']].reverse_complement().seq
print(' target:',
sequence[hsp['queryStart']:hsp['queryEnd']].seq)
print(' query:', query)
match = []
for index in range(hsp['subjectStart'], hsp['subjectEnd']):
queryIndex = index - hsp['queryStart']
match.append('.' if query[queryIndex] == sequence[index] else '*')
print(' match: %s%s' % (
' ' * (hsp['subjectStart'] - hsp['queryStart']), ''.join(match)))
print(' score:', item['convertedE'])
print(' match len:', hsp['subjectEnd'] - hsp['subjectStart'])
print('subject frame:', item['frame']['subject'])
for queryIndex, sequenceIndex in enumerate(
range(hsp['queryStart'], hsp['queryEnd'])):
consensusIndex = sequenceIndex + minX
locus = consensus[consensusIndex]
if locus is None:
consensus[consensusIndex] = locus = defaultdict(int)
locus[query[queryIndex]] += 1
# Print the consensus before the target, if any.
for index in range(minX, 0):
consensusIndex = index - minX
if consensus[consensusIndex]:
print('%d: %r' % (index, consensus[consensusIndex]))
# Print the consensus as it overlaps with the target, if any.
for index in range(0, len(sequence)):
consensusIndex = index - minX
try:
if consensus[consensusIndex]:
print('%d: %r (%s)' % (
index, consensus[index], sequence[index]))
except KeyError:
# There's nothing left in the consensus, so we're done.
break
for index in range(len(sequence), maxX):
consensusIndex = index - minX
if consensus[consensusIndex]:
print('%d: %r' % (index, consensus[consensusIndex]))
stop = time()
report('Consensus sequence generated in %.3f mins.' %
((stop - start) / 60.0))
return summary, consensus | python | def consensusSequence(recordFilename, hitId, fastaFilename, eCutoff=None,
db='nt', actualSequenceId=None):
"""
Build a consensus sequence against a target sequence.
recordFilename: the BLAST XML output file.
hitId: the str sequence id to examine the BLAST output for hits against.
fastaFilename: The name of the FASTA file containing query sequences,
or a list of fasta sequences from SeqIO.parse
eCutoff: converted e values less than this will be ignored.
db: the BLAST db to use to look up the target and, if given, actual
sequence.
actualSequenceId: the str id of the actual sequence (if known).
"""
print('TODO: This function is not finished yet.')
return
start = time()
if isinstance(recordFilename, str):
# TODO: REMOVE THE LIMIT IN THE NEXT LINE!
allhits = findHits(recordFilename, set([hitId]), limit=100)
else:
allhits = recordFilename
sequence = getSequence(hitId, db)
fasta, summary = summarizeHits(allhits, fastaFilename, eCutoff=eCutoff)
minX, maxX = summary['minX'], summary['maxX']
if actualSequenceId:
# UNUSED.
# actualSequence = getSequence(actualSequenceId, db)
pass
print(summary['hitCount'])
print('seq len =', len(sequence))
fasta = summary['fasta']
# The length of the consensus depends on where the query sequences fell
# when aligned with the target. The consensus could extend the target
# at both ends.
consensusLen = maxX - minX
consensus = [None, ] * consensusLen
for item in summary['items']:
print('NEW HSP')
printHSP(item['origHsp']) # TODO: REMOVE ME
hsp = item['hsp']
print('HIT query-start=%d query-stop=%d subj-start=%d subj-stop=%d' % (
hsp['queryStart'], hsp['queryEnd'], hsp['subjectStart'],
hsp['subjectEnd']))
# print ' match: %s%s' % ('.' * hsp['subjectStart'], '-' *
# (hsp['subjectEnd'] - hsp['subjectStart']))
if item['frame']['subject'] > 0:
query = fasta[item['sequenceId']].seq
else:
query = fasta[item['sequenceId']].reverse_complement().seq
print(' target:',
sequence[hsp['queryStart']:hsp['queryEnd']].seq)
print(' query:', query)
match = []
for index in range(hsp['subjectStart'], hsp['subjectEnd']):
queryIndex = index - hsp['queryStart']
match.append('.' if query[queryIndex] == sequence[index] else '*')
print(' match: %s%s' % (
' ' * (hsp['subjectStart'] - hsp['queryStart']), ''.join(match)))
print(' score:', item['convertedE'])
print(' match len:', hsp['subjectEnd'] - hsp['subjectStart'])
print('subject frame:', item['frame']['subject'])
for queryIndex, sequenceIndex in enumerate(
range(hsp['queryStart'], hsp['queryEnd'])):
consensusIndex = sequenceIndex + minX
locus = consensus[consensusIndex]
if locus is None:
consensus[consensusIndex] = locus = defaultdict(int)
locus[query[queryIndex]] += 1
# Print the consensus before the target, if any.
for index in range(minX, 0):
consensusIndex = index - minX
if consensus[consensusIndex]:
print('%d: %r' % (index, consensus[consensusIndex]))
# Print the consensus as it overlaps with the target, if any.
for index in range(0, len(sequence)):
consensusIndex = index - minX
try:
if consensus[consensusIndex]:
print('%d: %r (%s)' % (
index, consensus[index], sequence[index]))
except KeyError:
# There's nothing left in the consensus, so we're done.
break
for index in range(len(sequence), maxX):
consensusIndex = index - minX
if consensus[consensusIndex]:
print('%d: %r' % (index, consensus[consensusIndex]))
stop = time()
report('Consensus sequence generated in %.3f mins.' %
((stop - start) / 60.0))
return summary, consensus | [
"def",
"consensusSequence",
"(",
"recordFilename",
",",
"hitId",
",",
"fastaFilename",
",",
"eCutoff",
"=",
"None",
",",
"db",
"=",
"'nt'",
",",
"actualSequenceId",
"=",
"None",
")",
":",
"print",
"(",
"'TODO: This function is not finished yet.'",
")",
"return",
... | Build a consensus sequence against a target sequence.
recordFilename: the BLAST XML output file.
hitId: the str sequence id to examine the BLAST output for hits against.
fastaFilename: The name of the FASTA file containing query sequences,
or a list of fasta sequences from SeqIO.parse
eCutoff: converted e values less than this will be ignored.
db: the BLAST db to use to look up the target and, if given, actual
sequence.
actualSequenceId: the str id of the actual sequence (if known). | [
"Build",
"a",
"consensus",
"sequence",
"against",
"a",
"target",
"sequence",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/consensus.py#L8-L102 |
jbochi/cep | cep/__init__.py | Correios.detalhe | def detalhe(self, posicao=0):
"""Retorna o detalhe de um CEP da última lista de resultados"""
handle = self._url_open('detalheCEPAction.do', {'Metodo': 'detalhe',
'TipoCep': 2,
'Posicao': posicao + 1,
'CEP': ''})
html = handle.read()
return self._parse_detalhe(html) | python | def detalhe(self, posicao=0):
"""Retorna o detalhe de um CEP da última lista de resultados"""
handle = self._url_open('detalheCEPAction.do', {'Metodo': 'detalhe',
'TipoCep': 2,
'Posicao': posicao + 1,
'CEP': ''})
html = handle.read()
return self._parse_detalhe(html) | [
"def",
"detalhe",
"(",
"self",
",",
"posicao",
"=",
"0",
")",
":",
"handle",
"=",
"self",
".",
"_url_open",
"(",
"'detalheCEPAction.do'",
",",
"{",
"'Metodo'",
":",
"'detalhe'",
",",
"'TipoCep'",
":",
"2",
",",
"'Posicao'",
":",
"posicao",
"+",
"1",
",... | Retorna o detalhe de um CEP da última lista de resultados | [
"Retorna",
"o",
"detalhe",
"de",
"um",
"CEP",
"da",
"última",
"lista",
"de",
"resultados"
] | train | https://github.com/jbochi/cep/blob/8c9c334b63fe1685706065a72c69a66ddaa13392/cep/__init__.py#L72-L79 |
jbochi/cep | cep/__init__.py | Correios.consulta_faixa | def consulta_faixa(self, localidade, uf):
"""Consulta site e retorna faixa para localidade"""
url = 'consultaFaixaCepAction.do'
data = {
'UF': uf,
'Localidade': localidade.encode('cp1252'),
'cfm': '1',
'Metodo': 'listaFaixaCEP',
'TipoConsulta': 'faixaCep',
'StartRow': '1',
'EndRow': '10',
}
html = self._url_open(url, data).read()
return self._parse_faixa(html) | python | def consulta_faixa(self, localidade, uf):
"""Consulta site e retorna faixa para localidade"""
url = 'consultaFaixaCepAction.do'
data = {
'UF': uf,
'Localidade': localidade.encode('cp1252'),
'cfm': '1',
'Metodo': 'listaFaixaCEP',
'TipoConsulta': 'faixaCep',
'StartRow': '1',
'EndRow': '10',
}
html = self._url_open(url, data).read()
return self._parse_faixa(html) | [
"def",
"consulta_faixa",
"(",
"self",
",",
"localidade",
",",
"uf",
")",
":",
"url",
"=",
"'consultaFaixaCepAction.do'",
"data",
"=",
"{",
"'UF'",
":",
"uf",
",",
"'Localidade'",
":",
"localidade",
".",
"encode",
"(",
"'cp1252'",
")",
",",
"'cfm'",
":",
... | Consulta site e retorna faixa para localidade | [
"Consulta",
"site",
"e",
"retorna",
"faixa",
"para",
"localidade"
] | train | https://github.com/jbochi/cep/blob/8c9c334b63fe1685706065a72c69a66ddaa13392/cep/__init__.py#L81-L94 |
jbochi/cep | cep/__init__.py | Correios.consulta | def consulta(self, endereco, primeiro=False,
uf=None, localidade=None, tipo=None, numero=None):
"""Consulta site e retorna lista de resultados"""
if uf is None:
url = 'consultaEnderecoAction.do'
data = {
'relaxation': endereco.encode('ISO-8859-1'),
'TipoCep': 'ALL',
'semelhante': 'N',
'cfm': 1,
'Metodo': 'listaLogradouro',
'TipoConsulta': 'relaxation',
'StartRow': '1',
'EndRow': '10'
}
else:
url = 'consultaLogradouroAction.do'
data = {
'Logradouro': endereco.encode('ISO-8859-1'),
'UF': uf,
'TIPO': tipo,
'Localidade': localidade.encode('ISO-8859-1'),
'Numero': numero,
'cfm': 1,
'Metodo': 'listaLogradouro',
'TipoConsulta': 'logradouro',
'StartRow': '1',
'EndRow': '10'
}
h = self._url_open(url, data)
html = h.read()
if primeiro:
return self.detalhe()
else:
return self._parse_tabela(html) | python | def consulta(self, endereco, primeiro=False,
uf=None, localidade=None, tipo=None, numero=None):
"""Consulta site e retorna lista de resultados"""
if uf is None:
url = 'consultaEnderecoAction.do'
data = {
'relaxation': endereco.encode('ISO-8859-1'),
'TipoCep': 'ALL',
'semelhante': 'N',
'cfm': 1,
'Metodo': 'listaLogradouro',
'TipoConsulta': 'relaxation',
'StartRow': '1',
'EndRow': '10'
}
else:
url = 'consultaLogradouroAction.do'
data = {
'Logradouro': endereco.encode('ISO-8859-1'),
'UF': uf,
'TIPO': tipo,
'Localidade': localidade.encode('ISO-8859-1'),
'Numero': numero,
'cfm': 1,
'Metodo': 'listaLogradouro',
'TipoConsulta': 'logradouro',
'StartRow': '1',
'EndRow': '10'
}
h = self._url_open(url, data)
html = h.read()
if primeiro:
return self.detalhe()
else:
return self._parse_tabela(html) | [
"def",
"consulta",
"(",
"self",
",",
"endereco",
",",
"primeiro",
"=",
"False",
",",
"uf",
"=",
"None",
",",
"localidade",
"=",
"None",
",",
"tipo",
"=",
"None",
",",
"numero",
"=",
"None",
")",
":",
"if",
"uf",
"is",
"None",
":",
"url",
"=",
"'c... | Consulta site e retorna lista de resultados | [
"Consulta",
"site",
"e",
"retorna",
"lista",
"de",
"resultados"
] | train | https://github.com/jbochi/cep/blob/8c9c334b63fe1685706065a72c69a66ddaa13392/cep/__init__.py#L96-L133 |
vovanec/httputil | httputil/request_engines/sync.py | SyncRequestEngine._request | 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
"""
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:
cert = self._client_cert
if self._verify_cert:
verify = True
if self._ca_certs:
verify = self._ca_certs
else:
verify = False
auth = None
if self._username and self._password:
auth = (self._username, self._password)
response = s.request(method, url, data=data,
timeout=self._connect_timeout,
cert=cert,
headers=headers,
verify=verify,
auth=auth)
""":type: requests.models.Response
"""
if 400 <= response.status_code < 500:
raise ClientError(
response.status_code, response.content)
elif response.status_code >= 500:
raise ServerError(
response.status_code, response.content)
try:
if result_callback:
return result_callback(response.content)
except (ValueError, TypeError) as err:
raise MalformedResponse(err) from None
return response.content
except (requests.exceptions.RequestException,
requests.exceptions.BaseHTTPError) as exc:
if self._conn_retries is None or retries_left <= 0:
raise CommunicationError(exc) from None
else:
retries_left -= 1
retry_in = (self._conn_retries - retries_left) * 2
self._log.warning('Server communication error: %s. '
'Retrying in %s seconds.', exc, retry_in)
time.sleep(retry_in)
continue
finally:
s.close() | python | 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
"""
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:
cert = self._client_cert
if self._verify_cert:
verify = True
if self._ca_certs:
verify = self._ca_certs
else:
verify = False
auth = None
if self._username and self._password:
auth = (self._username, self._password)
response = s.request(method, url, data=data,
timeout=self._connect_timeout,
cert=cert,
headers=headers,
verify=verify,
auth=auth)
""":type: requests.models.Response
"""
if 400 <= response.status_code < 500:
raise ClientError(
response.status_code, response.content)
elif response.status_code >= 500:
raise ServerError(
response.status_code, response.content)
try:
if result_callback:
return result_callback(response.content)
except (ValueError, TypeError) as err:
raise MalformedResponse(err) from None
return response.content
except (requests.exceptions.RequestException,
requests.exceptions.BaseHTTPError) as exc:
if self._conn_retries is None or retries_left <= 0:
raise CommunicationError(exc) from None
else:
retries_left -= 1
retry_in = (self._conn_retries - retries_left) * 2
self._log.warning('Server communication error: %s. '
'Retrying in %s seconds.', exc, retry_in)
time.sleep(retry_in)
continue
finally:
s.close() | [
"def",
"_request",
"(",
"self",
",",
"url",
",",
"*",
",",
"method",
"=",
"'GET'",
",",
"headers",
"=",
"None",
",",
"data",
"=",
"None",
",",
"result_callback",
"=",
"None",
")",
":",
"retries_left",
"=",
"self",
".",
"_conn_retries",
"while",
"True",... | 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 | [
"Perform",
"synchronous",
"request",
"."
] | train | https://github.com/vovanec/httputil/blob/0b8dab5a23166cceb7dbc2a1dbc802ab5b311347/httputil/request_engines/sync.py#L51-L121 |
vovanec/httputil | httputil/request_engines/sync.py | SyncRequestEngine._make_session | def _make_session():
"""Create session object.
:rtype: requests.Session
"""
sess = requests.Session()
sess.mount('http://', requests.adapters.HTTPAdapter(max_retries=False))
sess.mount('https://', requests.adapters.HTTPAdapter(max_retries=False))
return sess | python | def _make_session():
"""Create session object.
:rtype: requests.Session
"""
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",
"(",
")",
":",
"sess",
"=",
"requests",
".",
"Session",
"(",
")",
"sess",
".",
"mount",
"(",
"'http://'",
",",
"requests",
".",
"adapters",
".",
"HTTPAdapter",
"(",
"max_retries",
"=",
"False",
")",
")",
"sess",
".",
"mount",
"(... | Create session object.
:rtype: requests.Session | [
"Create",
"session",
"object",
"."
] | train | https://github.com/vovanec/httputil/blob/0b8dab5a23166cceb7dbc2a1dbc802ab5b311347/httputil/request_engines/sync.py#L124-L134 |
flo-compbio/genometools | genometools/gdc/tcga.py | get_clinical_data | 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 the returned data frame, and are identified by
12-character TCGA barcodes.
"""
payload = {
'attachment': 'true',
"filters": json.dumps({
"op": "and",
"content": [
{
"op":"in",
"content":{
"field":"cases.project.program.name",
"value":["TCGA"]}},
{
"op": "in",
"content": {
"field": "project.project_id",
"value": [tcga_id]}}]
}),
'fields': 'case_id',
'expand': 'demographic,diagnoses,family_histories,exposures',
'format': 'JSON',
'pretty': 'true',
'size': 10000,
'filename': 'clinical.project-%s' % tcga_id,
}
r = requests.get('https://gdc-api.nci.nih.gov/cases', params=payload)
j = json.loads(r.content.decode())
clinical = {}
valid = 0
for s in j:
if 'diagnoses' not in s:
continue
valid += 1
assert len(s['diagnoses']) == 1
diag = s['diagnoses'][0]
tcga_id = diag['submitter_id'][:12]
clinical[tcga_id] = diag
logger.info('Found clinical data for %d cases.', valid)
df = pd.DataFrame.from_dict(clinical).T
df.sort_index(inplace=True)
return df | python | 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 the returned data frame, and are identified by
12-character TCGA barcodes.
"""
payload = {
'attachment': 'true',
"filters": json.dumps({
"op": "and",
"content": [
{
"op":"in",
"content":{
"field":"cases.project.program.name",
"value":["TCGA"]}},
{
"op": "in",
"content": {
"field": "project.project_id",
"value": [tcga_id]}}]
}),
'fields': 'case_id',
'expand': 'demographic,diagnoses,family_histories,exposures',
'format': 'JSON',
'pretty': 'true',
'size': 10000,
'filename': 'clinical.project-%s' % tcga_id,
}
r = requests.get('https://gdc-api.nci.nih.gov/cases', params=payload)
j = json.loads(r.content.decode())
clinical = {}
valid = 0
for s in j:
if 'diagnoses' not in s:
continue
valid += 1
assert len(s['diagnoses']) == 1
diag = s['diagnoses'][0]
tcga_id = diag['submitter_id'][:12]
clinical[tcga_id] = diag
logger.info('Found clinical data for %d cases.', valid)
df = pd.DataFrame.from_dict(clinical).T
df.sort_index(inplace=True)
return df | [
"def",
"get_clinical_data",
"(",
"tcga_id",
")",
":",
"payload",
"=",
"{",
"'attachment'",
":",
"'true'",
",",
"\"filters\"",
":",
"json",
".",
"dumps",
"(",
"{",
"\"op\"",
":",
"\"and\"",
",",
"\"content\"",
":",
"[",
"{",
"\"op\"",
":",
"\"in\"",
",",
... | 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 the returned data frame, and are identified by
12-character TCGA barcodes. | [
"Get",
"clinical",
"data",
"for",
"a",
"TCGA",
"project",
".",
"Parameters",
"----------",
"tcga_id",
":",
"str",
"The",
"TCGA",
"project",
"ID",
".",
"Returns",
"-------",
"pandas",
".",
"DataFrame",
"The",
"clinical",
"data",
".",
"abs"
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gdc/tcga.py#L35-L95 |
flo-compbio/genometools | genometools/gdc/tcga.py | get_biospecimen_data | 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 of a sample, and are uniquely identified by a 16-character
barcode. For example, one vial can contain FFPE material and the other
fresh-frozen material from the same sample. Each row in the returned data
frame corresponds to a vial.
"""
payload = {
'attachment': 'true',
"filters": json.dumps({
"op": "and",
"content": [
{
"op":"in",
"content":{
"field":"cases.project.program.name",
"value":["TCGA"]}},
{
"op": "in",
"content": {
"field": "project.project_id",
"value": [tcga_id]}}]
}),
'fields': 'case_id',
'expand': ('samples,samples.portions,'
'samples.portions.analytes,'
'samples.portions.analytes.aliquots,'
'samples.portions.analytes.aliquots.annotations,'
'samples.portions.analytes.annotations,'
'samples.portions.submitter_id,'
'samples.portions.slides,'
'samples.portions.annotations,'
'samples.portions.center'),
'format': 'JSON',
'pretty': 'true',
'size': 10000,
'filename': 'biospecimen.project-%s' % tcga_id,
}
r = requests.get('https://gdc-api.nci.nih.gov/cases', params=payload)
j = json.loads(r.content.decode())
biospec = {}
valid = 0
for case in j:
if 'samples' not in case:
continue
valid += 1
for s in case['samples']:
tcga_id = s['submitter_id'][:16]
del s['portions']
del s['submitter_id']
biospec[tcga_id] = s
logger.info('Found biospecimen data for %d cases.', valid)
df = pd.DataFrame.from_dict(biospec).T
df.sort_index(inplace=True)
return df | python | 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 of a sample, and are uniquely identified by a 16-character
barcode. For example, one vial can contain FFPE material and the other
fresh-frozen material from the same sample. Each row in the returned data
frame corresponds to a vial.
"""
payload = {
'attachment': 'true',
"filters": json.dumps({
"op": "and",
"content": [
{
"op":"in",
"content":{
"field":"cases.project.program.name",
"value":["TCGA"]}},
{
"op": "in",
"content": {
"field": "project.project_id",
"value": [tcga_id]}}]
}),
'fields': 'case_id',
'expand': ('samples,samples.portions,'
'samples.portions.analytes,'
'samples.portions.analytes.aliquots,'
'samples.portions.analytes.aliquots.annotations,'
'samples.portions.analytes.annotations,'
'samples.portions.submitter_id,'
'samples.portions.slides,'
'samples.portions.annotations,'
'samples.portions.center'),
'format': 'JSON',
'pretty': 'true',
'size': 10000,
'filename': 'biospecimen.project-%s' % tcga_id,
}
r = requests.get('https://gdc-api.nci.nih.gov/cases', params=payload)
j = json.loads(r.content.decode())
biospec = {}
valid = 0
for case in j:
if 'samples' not in case:
continue
valid += 1
for s in case['samples']:
tcga_id = s['submitter_id'][:16]
del s['portions']
del s['submitter_id']
biospec[tcga_id] = s
logger.info('Found biospecimen data for %d cases.', valid)
df = pd.DataFrame.from_dict(biospec).T
df.sort_index(inplace=True)
return df | [
"def",
"get_biospecimen_data",
"(",
"tcga_id",
")",
":",
"payload",
"=",
"{",
"'attachment'",
":",
"'true'",
",",
"\"filters\"",
":",
"json",
".",
"dumps",
"(",
"{",
"\"op\"",
":",
"\"and\"",
",",
"\"content\"",
":",
"[",
"{",
"\"op\"",
":",
"\"in\"",
",... | 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 of a sample, and are uniquely identified by a 16-character
barcode. For example, one vial can contain FFPE material and the other
fresh-frozen material from the same sample. Each row in the returned data
frame corresponds to a vial. | [
"Get",
"biospecimen",
"data",
"for",
"a",
"TCGA",
"project",
".",
"Parameters",
"----------",
"tcga_id",
":",
"str",
"The",
"TCGA",
"project",
"ID",
".",
"Returns",
"-------",
"pandas",
".",
"DataFrame",
"The",
"biospecmin",
"data",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gdc/tcga.py#L99-L170 |
flo-compbio/genometools | genometools/gdc/tcga.py | get_masked_cnv_manifest | 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.
"""
payload = {
"filters": json.dumps({
"op": "and",
"content" : [
{
"op":"in",
"content":{
"field":"cases.project.program.name",
"value":["TCGA"]}},
{
"op":"in",
"content":{
"field":"cases.project.project_id",
"value":[tcga_id]}},
{
"op":"in",
"content":{
"field":"files.data_category",
"value":["Copy Number Variation"]}},
{
"op":"in",
"content":{
"field":"files.data_type",
"value":["Masked Copy Number Segment"]}}]
}),
"return_type":"manifest",
"size":10000,
}
r = requests.get('https://gdc-api.nci.nih.gov/files', params=payload)
df = pd.read_csv(io.StringIO(r.text), sep='\t', header=0)
logger.info('Obtained manifest with %d files.', df.shape[0])
return df | python | 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.
"""
payload = {
"filters": json.dumps({
"op": "and",
"content" : [
{
"op":"in",
"content":{
"field":"cases.project.program.name",
"value":["TCGA"]}},
{
"op":"in",
"content":{
"field":"cases.project.project_id",
"value":[tcga_id]}},
{
"op":"in",
"content":{
"field":"files.data_category",
"value":["Copy Number Variation"]}},
{
"op":"in",
"content":{
"field":"files.data_type",
"value":["Masked Copy Number Segment"]}}]
}),
"return_type":"manifest",
"size":10000,
}
r = requests.get('https://gdc-api.nci.nih.gov/files', params=payload)
df = pd.read_csv(io.StringIO(r.text), sep='\t', header=0)
logger.info('Obtained manifest with %d files.', df.shape[0])
return df | [
"def",
"get_masked_cnv_manifest",
"(",
"tcga_id",
")",
":",
"payload",
"=",
"{",
"\"filters\"",
":",
"json",
".",
"dumps",
"(",
"{",
"\"op\"",
":",
"\"and\"",
",",
"\"content\"",
":",
"[",
"{",
"\"op\"",
":",
"\"in\"",
",",
"\"content\"",
":",
"{",
"\"fi... | 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. | [
"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",
".",
... | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gdc/tcga.py#L174-L221 |
flo-compbio/genometools | genometools/gdc/tcga.py | get_file_samples | 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.
"""
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),
}
}),
"fields":"file_id,cases.samples.submitter_id",
"size":10000
}
r = requests.post('https://gdc-api.nci.nih.gov/files', data=payload)
j = json.loads(r.content.decode('utf-8'))
file_samples = OrderedDict()
for hit in j['data']['hits']:
file_id = hit['file_id']
assert len(hit['cases']) == 1
case = hit['cases'][0]
assert len(case['samples']) == 1
sample = case['samples'][0]
sample_barcode = sample['submitter_id']
file_samples[file_id] = sample_barcode
df = pd.DataFrame.from_dict(file_samples, orient='index')
df = df.reset_index()
df.columns = ['file_id', 'sample_barcode']
return df | python | 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.
"""
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),
}
}),
"fields":"file_id,cases.samples.submitter_id",
"size":10000
}
r = requests.post('https://gdc-api.nci.nih.gov/files', data=payload)
j = json.loads(r.content.decode('utf-8'))
file_samples = OrderedDict()
for hit in j['data']['hits']:
file_id = hit['file_id']
assert len(hit['cases']) == 1
case = hit['cases'][0]
assert len(case['samples']) == 1
sample = case['samples'][0]
sample_barcode = sample['submitter_id']
file_samples[file_id] = sample_barcode
df = pd.DataFrame.from_dict(file_samples, orient='index')
df = df.reset_index()
df.columns = ['file_id', 'sample_barcode']
return df | [
"def",
"get_file_samples",
"(",
"file_ids",
")",
":",
"assert",
"isinstance",
"(",
"file_ids",
",",
"Iterable",
")",
"# query TCGA API to get sample barcodes associated with file IDs",
"payload",
"=",
"{",
"\"filters\"",
":",
"json",
".",
"dumps",
"(",
"{",
"\"op\"",
... | 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. | [
"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",... | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gdc/tcga.py#L272-L314 |
flo-compbio/genometools | genometools/gdc/tcga.py | get_unique_sample_files | 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
-------
`pandas.DataFrame`
The filtered data frame.
Notes
-----
In order to remove redundant files in a consistent fashion, the samples are
sorted by file ID, and then the first file for each sample is kept.
"""
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
logger.info('Original number of files: %d', len(df.index))
df.drop_duplicates('sample_barcode', keep='first', inplace=True)
logger.info('Number of files after removing duplicates from different '
'aliquots: %d', len(df.index))
# - some samples also have multiple files corresponding to different vials
# add an auxilliary column that contains the sample barcode without the
# vial tag (first 15 characters)
df['sample_barcode15'] = df['sample_barcode'].apply(lambda x: x[:15])
# use auxilliary column to get rid of duplicate files
df.drop_duplicates('sample_barcode15', keep='first', inplace=True)
logger.info('Number of files after removing duplicates from different '
'vials: %d', len(df.index))
# get rid of auxilliary column
df.drop('sample_barcode15', axis=1, inplace=True)
# restore original order using the (numerical) index
df.sort_index(inplace=True)
# return the filtered data frame
return df | python | 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
-------
`pandas.DataFrame`
The filtered data frame.
Notes
-----
In order to remove redundant files in a consistent fashion, the samples are
sorted by file ID, and then the first file for each sample is kept.
"""
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
logger.info('Original number of files: %d', len(df.index))
df.drop_duplicates('sample_barcode', keep='first', inplace=True)
logger.info('Number of files after removing duplicates from different '
'aliquots: %d', len(df.index))
# - some samples also have multiple files corresponding to different vials
# add an auxilliary column that contains the sample barcode without the
# vial tag (first 15 characters)
df['sample_barcode15'] = df['sample_barcode'].apply(lambda x: x[:15])
# use auxilliary column to get rid of duplicate files
df.drop_duplicates('sample_barcode15', keep='first', inplace=True)
logger.info('Number of files after removing duplicates from different '
'vials: %d', len(df.index))
# get rid of auxilliary column
df.drop('sample_barcode15', axis=1, inplace=True)
# restore original order using the (numerical) index
df.sort_index(inplace=True)
# return the filtered data frame
return df | [
"def",
"get_unique_sample_files",
"(",
"file_samples",
")",
":",
"assert",
"isinstance",
"(",
"file_samples",
",",
"pd",
".",
"DataFrame",
")",
"df",
"=",
"file_samples",
"# use shorter variable name",
"# sort data frame by file ID",
"df",
"=",
"df",
".",
"sort_values... | 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
-------
`pandas.DataFrame`
The filtered data frame.
Notes
-----
In order to remove redundant files in a consistent fashion, the samples are
sorted by file ID, and then the first file for each sample is kept. | [
"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",
"sa... | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gdc/tcga.py#L317-L368 |
flo-compbio/genometools | genometools/gdc/tcga.py | get_fresh_primary_tumors | 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 filtered data frame.
"""
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)
# only keep primary tumors
num_before = len(df.index)
df = df.loc[df['sample_type'] == 'Primary Tumor']
logger.info('Excluded %d files not corresponding to primary tumor '
'samples (out of %d files in total).',
num_before - len(df.index), num_before)
return df | python | 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 filtered data frame.
"""
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)
# only keep primary tumors
num_before = len(df.index)
df = df.loc[df['sample_type'] == 'Primary Tumor']
logger.info('Excluded %d files not corresponding to primary tumor '
'samples (out of %d files in total).',
num_before - len(df.index), num_before)
return df | [
"def",
"get_fresh_primary_tumors",
"(",
"biospecimen",
")",
":",
"df",
"=",
"biospecimen",
"# use shorter variable name",
"# get rid of FFPE samples",
"num_before",
"=",
"len",
"(",
"df",
".",
"index",
")",
"df",
"=",
"df",
".",
"loc",
"[",
"~",
"df",
"[",
"'i... | 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 filtered data frame. | [
"Filter",
"biospecimen",
"data",
"to",
"only",
"keep",
"non",
"-",
"FFPE",
"primary",
"tumor",
"samples",
".",
"Parameters",
"----------",
"biospecimen",
":",
"pandas",
".",
"DataFrame",
"The",
"biospecimen",
"data",
"frame",
".",
"This",
"type",
"of",
"data",... | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gdc/tcga.py#L371-L401 |
acorg/dark-matter | dark/fasta.py | dedupFasta | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"seen",
"=",
"set",
"(",
")",
"add",
"=",
"seen",
".",
"add",
"for",
"read",
"in",
"reads",
":",
"hash_",
"=",
"md5",
"(",
"read",
".",
"sequence",
".",
"encode",
"(",
"'UTF-8'",
")",
")",
".",
"digest... | 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. | [
"Remove",
"sequence",
"duplicates",
"(",
"based",
"on",
"sequence",
")",
"from",
"FASTA",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/fasta.py#L17-L30 |
acorg/dark-matter | dark/fasta.py | dePrefixAndSuffixFasta | def dePrefixAndSuffixFasta(sequences):
"""
sequences: an iterator producing Bio.Seq sequences.
return: a generator of sequences with no duplicates and no fully contained
subsequences.
"""
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 thisSeq:
newHash.update(nucl.encode('UTF-8'))
seen.add(newHash.digest())
# Add suffixes.
for start in range(len(thisSeq) - 1):
seen.add(md5(thisSeq[start + 1:].encode('UTF-8')).digest())
yield s | python | def dePrefixAndSuffixFasta(sequences):
"""
sequences: an iterator producing Bio.Seq sequences.
return: a generator of sequences with no duplicates and no fully contained
subsequences.
"""
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 thisSeq:
newHash.update(nucl.encode('UTF-8'))
seen.add(newHash.digest())
# Add suffixes.
for start in range(len(thisSeq) - 1):
seen.add(md5(thisSeq[start + 1:].encode('UTF-8')).digest())
yield s | [
"def",
"dePrefixAndSuffixFasta",
"(",
"sequences",
")",
":",
"sequences",
"=",
"sorted",
"(",
"sequences",
",",
"key",
"=",
"lambda",
"s",
":",
"len",
"(",
"s",
".",
"seq",
")",
",",
"reverse",
"=",
"True",
")",
"seen",
"=",
"set",
"(",
")",
"for",
... | sequences: an iterator producing Bio.Seq sequences.
return: a generator of sequences with no duplicates and no fully contained
subsequences. | [
"sequences",
":",
"an",
"iterator",
"producing",
"Bio",
".",
"Seq",
"sequences",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/fasta.py#L33-L54 |
acorg/dark-matter | dark/fasta.py | fastaSubtract | 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 suitable for
writing to a file using C{Bio.SeqIO.write}.
"""
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 reads:
assert str(seq.seq) == str(reads[seq.id].seq)
reads.pop(seq.id, None)
return iter(reads.values()) | python | 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 suitable for
writing to a file using C{Bio.SeqIO.write}.
"""
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 reads:
assert str(seq.seq) == str(reads[seq.id].seq)
reads.pop(seq.id, None)
return iter(reads.values()) | [
"def",
"fastaSubtract",
"(",
"fastaFiles",
")",
":",
"reads",
"=",
"{",
"}",
"firstFile",
"=",
"fastaFiles",
".",
"pop",
"(",
"0",
")",
"for",
"seq",
"in",
"SeqIO",
".",
"parse",
"(",
"firstFile",
",",
"'fasta'",
")",
":",
"reads",
"[",
"seq",
".",
... | 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 suitable for
writing to a file using C{Bio.SeqIO.write}. | [
"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",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/fasta.py#L57-L81 |
acorg/dark-matter | dark/fasta.py | combineReads | 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 be used as the sequence
id.
@param readClass: The class of the individual reads.
@param upperCase: If C{True}, reads will be converted to upper case.
@param idPrefix: The C{str} prefix that will be used for the id of the
sequences in C{sequences} that do not have an id specified. A trailing
sequence number will be appended to this prefix. Note that
'command-line-read-', the default id prefix, could collide with ids in
the FASTA file, if given. So output might be ambiguous. That's why we
allow the caller to specify a custom prefix.
@return: A C{FastaReads} instance.
"""
# 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):
# Try splitting the sequence on its last space and using the
# first part of the split as the read id. If there's no space,
# assign a generic id.
parts = sequence.rsplit(' ', 1)
if len(parts) == 2:
readId, sequence = parts
else:
readId = '%s%d' % (idPrefix, count)
if upperCase:
sequence = sequence.upper()
read = readClass(readId, sequence)
reads.add(read)
return reads | python | 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 be used as the sequence
id.
@param readClass: The class of the individual reads.
@param upperCase: If C{True}, reads will be converted to upper case.
@param idPrefix: The C{str} prefix that will be used for the id of the
sequences in C{sequences} that do not have an id specified. A trailing
sequence number will be appended to this prefix. Note that
'command-line-read-', the default id prefix, could collide with ids in
the FASTA file, if given. So output might be ambiguous. That's why we
allow the caller to specify a custom prefix.
@return: A C{FastaReads} instance.
"""
# 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):
# Try splitting the sequence on its last space and using the
# first part of the split as the read id. If there's no space,
# assign a generic id.
parts = sequence.rsplit(' ', 1)
if len(parts) == 2:
readId, sequence = parts
else:
readId = '%s%d' % (idPrefix, count)
if upperCase:
sequence = sequence.upper()
read = readClass(readId, sequence)
reads.add(read)
return reads | [
"def",
"combineReads",
"(",
"filename",
",",
"sequences",
",",
"readClass",
"=",
"DNARead",
",",
"upperCase",
"=",
"False",
",",
"idPrefix",
"=",
"'command-line-read-'",
")",
":",
"# Read sequences from a FASTA file, if given.",
"if",
"filename",
":",
"reads",
"=",
... | 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 be used as the sequence
id.
@param readClass: The class of the individual reads.
@param upperCase: If C{True}, reads will be converted to upper case.
@param idPrefix: The C{str} prefix that will be used for the id of the
sequences in C{sequences} that do not have an id specified. A trailing
sequence number will be appended to this prefix. Note that
'command-line-read-', the default id prefix, could collide with ids in
the FASTA file, if given. So output might be ambiguous. That's why we
allow the caller to specify a custom prefix.
@return: A C{FastaReads} instance. | [
"Combine",
"FASTA",
"reads",
"from",
"a",
"file",
"and",
"/",
"or",
"sequence",
"strings",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/fasta.py#L184-L226 |
acorg/dark-matter | dark/fasta.py | FastaReads.iter | def iter(self):
"""
Iterate over the sequences in the files in self.files_, yielding each
as an instance of the desired read class.
"""
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'):
read = self._readClass(seq.description,
str(seq.seq.upper()))
yield read
count += 1
else:
for seq in SeqIO.parse(fp, 'fasta'):
read = self._readClass(seq.description, str(seq.seq))
yield read
count += 1 | python | def iter(self):
"""
Iterate over the sequences in the files in self.files_, yielding each
as an instance of the desired read class.
"""
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'):
read = self._readClass(seq.description,
str(seq.seq.upper()))
yield read
count += 1
else:
for seq in SeqIO.parse(fp, 'fasta'):
read = self._readClass(seq.description, str(seq.seq))
yield read
count += 1 | [
"def",
"iter",
"(",
"self",
")",
":",
"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",
"... | Iterate over the sequences in the files in self.files_, yielding each
as an instance of the desired read class. | [
"Iterate",
"over",
"the",
"sequences",
"in",
"the",
"files",
"in",
"self",
".",
"files_",
"yielding",
"each",
"as",
"an",
"instance",
"of",
"the",
"desired",
"read",
"class",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/fasta.py#L111-L131 |
acorg/dark-matter | dark/fasta.py | FastaFaiReads.iter | def iter(self):
"""
Iterate over the sequences in the files in self.files_, yielding each
as an instance of the desired read class.
"""
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_])) | python | def iter(self):
"""
Iterate over the sequences in the files in self.files_, yielding each
as an instance of the desired read class.
"""
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",
")",
":",
"if",
"self",
".",
"_upperCase",
":",
"for",
"id_",
"in",
"self",
".",
"_fasta",
":",
"yield",
"self",
".",
"_readClass",
"(",
"id_",
",",
"str",
"(",
"self",
".",
"_fasta",
"[",
"id_",
"]",
")",
".",
"upper"... | Iterate over the sequences in the files in self.files_, yielding each
as an instance of the desired read class. | [
"Iterate",
"over",
"the",
"sequences",
"in",
"the",
"files",
"in",
"self",
".",
"files_",
"yielding",
"each",
"as",
"an",
"instance",
"of",
"the",
"desired",
"read",
"class",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/fasta.py#L168-L178 |
acorg/dark-matter | dark/fasta.py | SqliteIndex._getFilename | 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.
"""
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] | python | 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.
"""
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",
")",
":",
"cur",
"=",
"self",
".",
"_connection",
".",
"cursor",
"(",
")",
"cur",
".",
"execute",
"(",
"'SELECT name FROM files WHERE id = ?'",
",",
"(",
"fileNumber",
",",
")",
")",
"row",
"=",
"cur",... | 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. | [
"Given",
"a",
"file",
"number",
"get",
"its",
"name",
"(",
"if",
"any",
")",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/fasta.py#L265-L279 |
acorg/dark-matter | dark/fasta.py | SqliteIndex._getFileNumber | 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.
"""
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] | python | 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.
"""
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",
")",
":",
"cur",
"=",
"self",
".",
"_connection",
".",
"cursor",
"(",
")",
"cur",
".",
"execute",
"(",
"'SELECT id FROM files WHERE name = ?'",
",",
"(",
"filename",
",",
")",
")",
"row",
"=",
"cur",
... | 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. | [
"Given",
"a",
"file",
"name",
"get",
"its",
"file",
"number",
"(",
"if",
"any",
")",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/fasta.py#L281-L295 |
acorg/dark-matter | dark/fasta.py | SqliteIndex._addFilename | 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.
"""
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)
else:
raise
else:
fileNumber = cur.lastrowid
self._connection.commit()
return fileNumber | python | 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.
"""
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)
else:
raise
else:
fileNumber = cur.lastrowid
self._connection.commit()
return fileNumber | [
"def",
"_addFilename",
"(",
"self",
",",
"filename",
")",
":",
"cur",
"=",
"self",
".",
"_connection",
".",
"cursor",
"(",
")",
"try",
":",
"cur",
".",
"execute",
"(",
"'INSERT INTO files(name) VALUES (?)'",
",",
"(",
"filename",
",",
")",
")",
"except",
... | 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. | [
"Add",
"a",
"new",
"file",
"name",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/fasta.py#L297-L316 |
acorg/dark-matter | dark/fasta.py | SqliteIndex.addFile | 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__} to indicate the
directory containing the original FASTA files, in which case the
basename of the file here provided in C{filename} is used to find
the file in the given directory. This allows the construction of a
sqlite database from the shell in one directory and its use
programmatically from another directory.
@raise ValueError: If a file with this name has already been added or
if the file contains a sequence whose id has already been seen.
@return: The C{int} number of sequences added from the file.
"""
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.')
else:
useBgzf = False
fileNumber = self._addFilename(filename)
connection = self._connection
count = 0
try:
with connection:
if useBgzf:
try:
fp = bgzf.open(filename, 'rb')
except ValueError as e:
if str(e).find('BGZF') > -1:
raise ValueError(
'Compressed FASTA is only supported in BGZF '
'format. Use the samtools bgzip utility '
'(instead of gzip) to compresss your FASTA.')
else:
raise
else:
try:
for line in fp:
if line[0] == '>':
count += 1
id_ = line[1:].rstrip(' \t\n\r')
connection.execute(
'INSERT INTO sequences(id, '
'fileNumber, offset) VALUES (?, ?, ?)',
(id_, fileNumber, fp.tell()))
finally:
fp.close()
else:
with open(filename) as fp:
offset = 0
for line in fp:
offset += len(line)
if line[0] == '>':
count += 1
id_ = line[1:].rstrip(' \t\n\r')
connection.execute(
'INSERT INTO sequences(id, fileNumber, '
'offset) VALUES (?, ?, ?)',
(id_, fileNumber, offset))
except sqlite3.IntegrityError as e:
if str(e).find('UNIQUE constraint failed') > -1:
original = self._find(id_)
if original is None:
# The id must have appeared twice in the current file,
# because we could not look it up in the database
# (i.e., it was INSERTed but not committed).
raise ValueError(
"FASTA sequence id '%s' found twice in file '%s'." %
(id_, filename))
else:
origFilename, _ = original
raise ValueError(
"FASTA sequence id '%s', found in file '%s', was "
"previously added from file '%s'." %
(id_, filename, origFilename))
else:
raise
else:
return count | python | 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__} to indicate the
directory containing the original FASTA files, in which case the
basename of the file here provided in C{filename} is used to find
the file in the given directory. This allows the construction of a
sqlite database from the shell in one directory and its use
programmatically from another directory.
@raise ValueError: If a file with this name has already been added or
if the file contains a sequence whose id has already been seen.
@return: The C{int} number of sequences added from the file.
"""
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.')
else:
useBgzf = False
fileNumber = self._addFilename(filename)
connection = self._connection
count = 0
try:
with connection:
if useBgzf:
try:
fp = bgzf.open(filename, 'rb')
except ValueError as e:
if str(e).find('BGZF') > -1:
raise ValueError(
'Compressed FASTA is only supported in BGZF '
'format. Use the samtools bgzip utility '
'(instead of gzip) to compresss your FASTA.')
else:
raise
else:
try:
for line in fp:
if line[0] == '>':
count += 1
id_ = line[1:].rstrip(' \t\n\r')
connection.execute(
'INSERT INTO sequences(id, '
'fileNumber, offset) VALUES (?, ?, ?)',
(id_, fileNumber, fp.tell()))
finally:
fp.close()
else:
with open(filename) as fp:
offset = 0
for line in fp:
offset += len(line)
if line[0] == '>':
count += 1
id_ = line[1:].rstrip(' \t\n\r')
connection.execute(
'INSERT INTO sequences(id, fileNumber, '
'offset) VALUES (?, ?, ?)',
(id_, fileNumber, offset))
except sqlite3.IntegrityError as e:
if str(e).find('UNIQUE constraint failed') > -1:
original = self._find(id_)
if original is None:
# The id must have appeared twice in the current file,
# because we could not look it up in the database
# (i.e., it was INSERTed but not committed).
raise ValueError(
"FASTA sequence id '%s' found twice in file '%s'." %
(id_, filename))
else:
origFilename, _ = original
raise ValueError(
"FASTA sequence id '%s', found in file '%s', was "
"previously added from file '%s'." %
(id_, filename, origFilename))
else:
raise
else:
return count | [
"def",
"addFile",
"(",
"self",
",",
"filename",
")",
":",
"endswith",
"=",
"filename",
".",
"lower",
"(",
")",
".",
"endswith",
"if",
"endswith",
"(",
"'.bgz'",
")",
"or",
"endswith",
"(",
"'.gz'",
")",
":",
"useBgzf",
"=",
"True",
"elif",
"endswith",
... | 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__} to indicate the
directory containing the original FASTA files, in which case the
basename of the file here provided in C{filename} is used to find
the file in the given directory. This allows the construction of a
sqlite database from the shell in one directory and its use
programmatically from another directory.
@raise ValueError: If a file with this name has already been added or
if the file contains a sequence whose id has already been seen.
@return: The C{int} number of sequences added from the file. | [
"Add",
"a",
"new",
"FASTA",
"file",
"of",
"sequences",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/fasta.py#L318-L404 |
acorg/dark-matter | dark/fasta.py | SqliteIndex._find | 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.
"""
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] | python | 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.
"""
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_",
")",
":",
"cur",
"=",
"self",
".",
"_connection",
".",
"cursor",
"(",
")",
"cur",
".",
"execute",
"(",
"'SELECT fileNumber, offset FROM sequences WHERE id = ?'",
",",
"(",
"id_",
",",
")",
")",
"row",
"=",
"cur",
... | 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. | [
"Find",
"the",
"filename",
"and",
"offset",
"of",
"a",
"sequence",
"given",
"its",
"id",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/fasta.py#L406-L421 |
flo-compbio/genometools | genometools/gtf.py | parse_attributes | 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),
as described in the
`GTF format specification <http://mblab.wustl.edu/GTF22.html>`_.
"""
# 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:
k, v = kv
v = v.strip('"')
attr[k] = v
return attr | python | 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),
as described in the
`GTF format specification <http://mblab.wustl.edu/GTF22.html>`_.
"""
# 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:
k, v = kv
v = v.strip('"')
attr[k] = v
return attr | [
"def",
"parse_attributes",
"(",
"s",
")",
":",
"# 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",
"=",... | 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),
as described in the
`GTF format specification <http://mblab.wustl.edu/GTF22.html>`_. | [
"Parses",
"the",
"attribute",
"string",
"of",
"a",
"GFF",
"/",
"GTF",
"annotation",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gtf.py#L25-L56 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.